createVerticesFromQuantizedTerrainMesh.js 915 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651
  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. /*
  171. I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  172. so it's better encapsulated. Now you can have multiple random number generators
  173. and they won't stomp all over eachother's state.
  174. If you want to use this as a substitute for Math.random(), use the random()
  175. method like so:
  176. var m = new MersenneTwister();
  177. var randomNumber = m.random();
  178. You can also call the other genrand_{foo}() methods on the instance.
  179. If you want to use a specific seed in order to get a repeatable random
  180. sequence, pass an integer into the constructor:
  181. var m = new MersenneTwister(123);
  182. and that will always produce the same random sequence.
  183. Sean McCullough (banksean@gmail.com)
  184. */
  185. /*
  186. A C-program for MT19937, with initialization improved 2002/1/26.
  187. Coded by Takuji Nishimura and Makoto Matsumoto.
  188. Before using, initialize the state by using init_genrand(seed)
  189. or init_by_array(init_key, key_length).
  190. */
  191. /**
  192. @license
  193. mersenne-twister.js - https://gist.github.com/banksean/300494
  194. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  195. All rights reserved.
  196. Redistribution and use in source and binary forms, with or without
  197. modification, are permitted provided that the following conditions
  198. are met:
  199. 1. Redistributions of source code must retain the above copyright
  200. notice, this list of conditions and the following disclaimer.
  201. 2. Redistributions in binary form must reproduce the above copyright
  202. notice, this list of conditions and the following disclaimer in the
  203. documentation and/or other materials provided with the distribution.
  204. 3. The names of its contributors may not be used to endorse or promote
  205. products derived from this software without specific prior written
  206. permission.
  207. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  208. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  209. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  210. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  211. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  212. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  213. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  214. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  215. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  216. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  217. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  218. */
  219. /*
  220. Any feedback is very welcome.
  221. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  222. email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
  223. */
  224. define('ThirdParty/mersenne-twister',[],function() {
  225. var MersenneTwister = function(seed) {
  226. if (seed == undefined) {
  227. seed = new Date().getTime();
  228. }
  229. /* Period parameters */
  230. this.N = 624;
  231. this.M = 397;
  232. this.MATRIX_A = 0x9908b0df; /* constant vector a */
  233. this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  234. this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
  235. this.mt = new Array(this.N); /* the array for the state vector */
  236. this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
  237. this.init_genrand(seed);
  238. }
  239. /* initializes mt[N] with a seed */
  240. MersenneTwister.prototype.init_genrand = function(s) {
  241. this.mt[0] = s >>> 0;
  242. for (this.mti=1; this.mti<this.N; this.mti++) {
  243. var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
  244. this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  245. + this.mti;
  246. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  247. /* In the previous versions, MSBs of the seed affect */
  248. /* only MSBs of the array mt[]. */
  249. /* 2002/01/09 modified by Makoto Matsumoto */
  250. this.mt[this.mti] >>>= 0;
  251. /* for >32 bit machines */
  252. }
  253. }
  254. /* initialize by an array with array-length */
  255. /* init_key is the array for initializing keys */
  256. /* key_length is its length */
  257. /* slight change for C++, 2004/2/26 */
  258. //MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  259. // var i, j, k;
  260. // this.init_genrand(19650218);
  261. // i=1; j=0;
  262. // k = (this.N>key_length ? this.N : key_length);
  263. // for (; k; k--) {
  264. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
  265. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
  266. // + init_key[j] + j; /* non linear */
  267. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  268. // i++; j++;
  269. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  270. // if (j>=key_length) j=0;
  271. // }
  272. // for (k=this.N-1; k; k--) {
  273. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  274. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
  275. // - i; /* non linear */
  276. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  277. // i++;
  278. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  279. // }
  280. //
  281. // this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
  282. //}
  283. /* generates a random number on [0,0xffffffff]-interval */
  284. MersenneTwister.prototype.genrand_int32 = function() {
  285. var y;
  286. var mag01 = new Array(0x0, this.MATRIX_A);
  287. /* mag01[x] = x * MATRIX_A for x=0,1 */
  288. if (this.mti >= this.N) { /* generate N words at one time */
  289. var kk;
  290. if (this.mti == this.N+1) /* if init_genrand() has not been called, */
  291. this.init_genrand(5489); /* a default initial seed is used */
  292. for (kk=0;kk<this.N-this.M;kk++) {
  293. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  294. this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
  295. }
  296. for (;kk<this.N-1;kk++) {
  297. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  298. this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
  299. }
  300. y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
  301. this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
  302. this.mti = 0;
  303. }
  304. y = this.mt[this.mti++];
  305. /* Tempering */
  306. y ^= (y >>> 11);
  307. y ^= (y << 7) & 0x9d2c5680;
  308. y ^= (y << 15) & 0xefc60000;
  309. y ^= (y >>> 18);
  310. return y >>> 0;
  311. }
  312. /* generates a random number on [0,0x7fffffff]-interval */
  313. //MersenneTwister.prototype.genrand_int31 = function() {
  314. // return (this.genrand_int32()>>>1);
  315. //}
  316. /* generates a random number on [0,1]-real-interval */
  317. //MersenneTwister.prototype.genrand_real1 = function() {
  318. // return this.genrand_int32()*(1.0/4294967295.0);
  319. // /* divided by 2^32-1 */
  320. //}
  321. /* generates a random number on [0,1)-real-interval */
  322. MersenneTwister.prototype.random = function() {
  323. return this.genrand_int32()*(1.0/4294967296.0);
  324. /* divided by 2^32 */
  325. }
  326. /* generates a random number on (0,1)-real-interval */
  327. //MersenneTwister.prototype.genrand_real3 = function() {
  328. // return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
  329. // /* divided by 2^32 */
  330. //}
  331. /* generates a random number on [0,1) with 53-bit resolution*/
  332. //MersenneTwister.prototype.genrand_res53 = function() {
  333. // var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
  334. // return(a*67108864.0+b)*(1.0/9007199254740992.0);
  335. //}
  336. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  337. return MersenneTwister;
  338. });
  339. /*global define*/
  340. define('Core/Math',[
  341. '../ThirdParty/mersenne-twister',
  342. './defaultValue',
  343. './defined',
  344. './DeveloperError'
  345. ], function(
  346. MersenneTwister,
  347. defaultValue,
  348. defined,
  349. DeveloperError) {
  350. 'use strict';
  351. /**
  352. * Math functions.
  353. *
  354. * @exports CesiumMath
  355. */
  356. var CesiumMath = {};
  357. /**
  358. * 0.1
  359. * @type {Number}
  360. * @constant
  361. */
  362. CesiumMath.EPSILON1 = 0.1;
  363. /**
  364. * 0.01
  365. * @type {Number}
  366. * @constant
  367. */
  368. CesiumMath.EPSILON2 = 0.01;
  369. /**
  370. * 0.001
  371. * @type {Number}
  372. * @constant
  373. */
  374. CesiumMath.EPSILON3 = 0.001;
  375. /**
  376. * 0.0001
  377. * @type {Number}
  378. * @constant
  379. */
  380. CesiumMath.EPSILON4 = 0.0001;
  381. /**
  382. * 0.00001
  383. * @type {Number}
  384. * @constant
  385. */
  386. CesiumMath.EPSILON5 = 0.00001;
  387. /**
  388. * 0.000001
  389. * @type {Number}
  390. * @constant
  391. */
  392. CesiumMath.EPSILON6 = 0.000001;
  393. /**
  394. * 0.0000001
  395. * @type {Number}
  396. * @constant
  397. */
  398. CesiumMath.EPSILON7 = 0.0000001;
  399. /**
  400. * 0.00000001
  401. * @type {Number}
  402. * @constant
  403. */
  404. CesiumMath.EPSILON8 = 0.00000001;
  405. /**
  406. * 0.000000001
  407. * @type {Number}
  408. * @constant
  409. */
  410. CesiumMath.EPSILON9 = 0.000000001;
  411. /**
  412. * 0.0000000001
  413. * @type {Number}
  414. * @constant
  415. */
  416. CesiumMath.EPSILON10 = 0.0000000001;
  417. /**
  418. * 0.00000000001
  419. * @type {Number}
  420. * @constant
  421. */
  422. CesiumMath.EPSILON11 = 0.00000000001;
  423. /**
  424. * 0.000000000001
  425. * @type {Number}
  426. * @constant
  427. */
  428. CesiumMath.EPSILON12 = 0.000000000001;
  429. /**
  430. * 0.0000000000001
  431. * @type {Number}
  432. * @constant
  433. */
  434. CesiumMath.EPSILON13 = 0.0000000000001;
  435. /**
  436. * 0.00000000000001
  437. * @type {Number}
  438. * @constant
  439. */
  440. CesiumMath.EPSILON14 = 0.00000000000001;
  441. /**
  442. * 0.000000000000001
  443. * @type {Number}
  444. * @constant
  445. */
  446. CesiumMath.EPSILON15 = 0.000000000000001;
  447. /**
  448. * 0.0000000000000001
  449. * @type {Number}
  450. * @constant
  451. */
  452. CesiumMath.EPSILON16 = 0.0000000000000001;
  453. /**
  454. * 0.00000000000000001
  455. * @type {Number}
  456. * @constant
  457. */
  458. CesiumMath.EPSILON17 = 0.00000000000000001;
  459. /**
  460. * 0.000000000000000001
  461. * @type {Number}
  462. * @constant
  463. */
  464. CesiumMath.EPSILON18 = 0.000000000000000001;
  465. /**
  466. * 0.0000000000000000001
  467. * @type {Number}
  468. * @constant
  469. */
  470. CesiumMath.EPSILON19 = 0.0000000000000000001;
  471. /**
  472. * 0.00000000000000000001
  473. * @type {Number}
  474. * @constant
  475. */
  476. CesiumMath.EPSILON20 = 0.00000000000000000001;
  477. /**
  478. * 3.986004418e14
  479. * @type {Number}
  480. * @constant
  481. */
  482. CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
  483. /**
  484. * Radius of the sun in meters: 6.955e8
  485. * @type {Number}
  486. * @constant
  487. */
  488. CesiumMath.SOLAR_RADIUS = 6.955e8;
  489. /**
  490. * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
  491. * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
  492. * Celestial Mechanics 82: 83-110, 2002.
  493. * @type {Number}
  494. * @constant
  495. */
  496. CesiumMath.LUNAR_RADIUS = 1737400.0;
  497. /**
  498. * 64 * 1024
  499. * @type {Number}
  500. * @constant
  501. */
  502. CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
  503. /**
  504. * Returns the sign of the value; 1 if the value is positive, -1 if the value is
  505. * negative, or 0 if the value is 0.
  506. *
  507. * @param {Number} value The value to return the sign of.
  508. * @returns {Number} The sign of value.
  509. */
  510. CesiumMath.sign = function(value) {
  511. if (value > 0) {
  512. return 1;
  513. }
  514. if (value < 0) {
  515. return -1;
  516. }
  517. return 0;
  518. };
  519. /**
  520. * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
  521. * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
  522. * 0.0 when the input value is 0.0.
  523. * @param {Number} value The value to return the sign of.
  524. * @returns {Number} The sign of value.
  525. */
  526. CesiumMath.signNotZero = function(value) {
  527. return value < 0.0 ? -1.0 : 1.0;
  528. };
  529. /**
  530. * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
  531. * @param {Number} value The scalar value in the range [-1.0, 1.0]
  532. * @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
  533. * @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
  534. *
  535. * @see CesiumMath.fromSNorm
  536. */
  537. CesiumMath.toSNorm = function(value, rangeMax) {
  538. rangeMax = defaultValue(rangeMax, 255);
  539. return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMax);
  540. };
  541. /**
  542. * Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
  543. * @param {Number} value SNORM value in the range [0, 255]
  544. * @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
  545. * @returns {Number} Scalar in the range [-1.0, 1.0].
  546. *
  547. * @see CesiumMath.toSNorm
  548. */
  549. CesiumMath.fromSNorm = function(value, rangeMax) {
  550. rangeMax = defaultValue(rangeMax, 255);
  551. return CesiumMath.clamp(value, 0.0, rangeMax) / rangeMax * 2.0 - 1.0;
  552. };
  553. /**
  554. * Returns the hyperbolic sine of a number.
  555. * The hyperbolic sine of <em>value</em> is defined to be
  556. * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
  557. * where <i>e</i> is Euler's number, approximately 2.71828183.
  558. *
  559. * <p>Special cases:
  560. * <ul>
  561. * <li>If the argument is NaN, then the result is NaN.</li>
  562. *
  563. * <li>If the argument is infinite, then the result is an infinity
  564. * with the same sign as the argument.</li>
  565. *
  566. * <li>If the argument is zero, then the result is a zero with the
  567. * same sign as the argument.</li>
  568. * </ul>
  569. *</p>
  570. *
  571. * @param {Number} value The number whose hyperbolic sine is to be returned.
  572. * @returns {Number} The hyperbolic sine of <code>value</code>.
  573. */
  574. CesiumMath.sinh = function(value) {
  575. var part1 = Math.pow(Math.E, value);
  576. var part2 = Math.pow(Math.E, -1.0 * value);
  577. return (part1 - part2) * 0.5;
  578. };
  579. /**
  580. * Returns the hyperbolic cosine of a number.
  581. * The hyperbolic cosine of <strong>value</strong> is defined to be
  582. * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
  583. * where <i>e</i> is Euler's number, approximately 2.71828183.
  584. *
  585. * <p>Special cases:
  586. * <ul>
  587. * <li>If the argument is NaN, then the result is NaN.</li>
  588. *
  589. * <li>If the argument is infinite, then the result is positive infinity.</li>
  590. *
  591. * <li>If the argument is zero, then the result is 1.0.</li>
  592. * </ul>
  593. *</p>
  594. *
  595. * @param {Number} value The number whose hyperbolic cosine is to be returned.
  596. * @returns {Number} The hyperbolic cosine of <code>value</code>.
  597. */
  598. CesiumMath.cosh = function(value) {
  599. var part1 = Math.pow(Math.E, value);
  600. var part2 = Math.pow(Math.E, -1.0 * value);
  601. return (part1 + part2) * 0.5;
  602. };
  603. /**
  604. * Computes the linear interpolation of two values.
  605. *
  606. * @param {Number} p The start value to interpolate.
  607. * @param {Number} q The end value to interpolate.
  608. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  609. * @returns {Number} The linearly interpolated value.
  610. *
  611. * @example
  612. * var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
  613. */
  614. CesiumMath.lerp = function(p, q, time) {
  615. return ((1.0 - time) * p) + (time * q);
  616. };
  617. /**
  618. * pi
  619. *
  620. * @type {Number}
  621. * @constant
  622. */
  623. CesiumMath.PI = Math.PI;
  624. /**
  625. * 1/pi
  626. *
  627. * @type {Number}
  628. * @constant
  629. */
  630. CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
  631. /**
  632. * pi/2
  633. *
  634. * @type {Number}
  635. * @constant
  636. */
  637. CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
  638. /**
  639. * pi/3
  640. *
  641. * @type {Number}
  642. * @constant
  643. */
  644. CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
  645. /**
  646. * pi/4
  647. *
  648. * @type {Number}
  649. * @constant
  650. */
  651. CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
  652. /**
  653. * pi/6
  654. *
  655. * @type {Number}
  656. * @constant
  657. */
  658. CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
  659. /**
  660. * 3pi/2
  661. *
  662. * @type {Number}
  663. * @constant
  664. */
  665. CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
  666. /**
  667. * 2pi
  668. *
  669. * @type {Number}
  670. * @constant
  671. */
  672. CesiumMath.TWO_PI = 2.0 * Math.PI;
  673. /**
  674. * 1/2pi
  675. *
  676. * @type {Number}
  677. * @constant
  678. */
  679. CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
  680. /**
  681. * The number of radians in a degree.
  682. *
  683. * @type {Number}
  684. * @constant
  685. * @default Math.PI / 180.0
  686. */
  687. CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
  688. /**
  689. * The number of degrees in a radian.
  690. *
  691. * @type {Number}
  692. * @constant
  693. * @default 180.0 / Math.PI
  694. */
  695. CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
  696. /**
  697. * The number of radians in an arc second.
  698. *
  699. * @type {Number}
  700. * @constant
  701. * @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
  702. */
  703. CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  704. /**
  705. * Converts degrees to radians.
  706. * @param {Number} degrees The angle to convert in degrees.
  707. * @returns {Number} The corresponding angle in radians.
  708. */
  709. CesiumMath.toRadians = function(degrees) {
  710. if (!defined(degrees)) {
  711. throw new DeveloperError('degrees is required.');
  712. }
  713. return degrees * CesiumMath.RADIANS_PER_DEGREE;
  714. };
  715. /**
  716. * Converts radians to degrees.
  717. * @param {Number} radians The angle to convert in radians.
  718. * @returns {Number} The corresponding angle in degrees.
  719. */
  720. CesiumMath.toDegrees = function(radians) {
  721. if (!defined(radians)) {
  722. throw new DeveloperError('radians is required.');
  723. }
  724. return radians * CesiumMath.DEGREES_PER_RADIAN;
  725. };
  726. /**
  727. * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  728. *
  729. * @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  730. * @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  731. *
  732. * @example
  733. * // Convert 270 degrees to -90 degrees longitude
  734. * var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
  735. */
  736. CesiumMath.convertLongitudeRange = function(angle) {
  737. if (!defined(angle)) {
  738. throw new DeveloperError('angle is required.');
  739. }
  740. var twoPi = CesiumMath.TWO_PI;
  741. var simplified = angle - Math.floor(angle / twoPi) * twoPi;
  742. if (simplified < -Math.PI) {
  743. return simplified + twoPi;
  744. }
  745. if (simplified >= Math.PI) {
  746. return simplified - twoPi;
  747. }
  748. return simplified;
  749. };
  750. /**
  751. * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  752. * Useful for sanitizing data before use in objects requiring correct range.
  753. *
  754. * @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  755. * @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  756. *
  757. * @example
  758. * // Clamp 108 degrees latitude to 90 degrees latitude
  759. * var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
  760. */
  761. CesiumMath.clampToLatitudeRange = function(angle) {
  762. if (!defined(angle)) {
  763. throw new DeveloperError('angle is required.');
  764. }
  765. return CesiumMath.clamp(angle, -1*CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
  766. };
  767. /**
  768. * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
  769. *
  770. * @param {Number} angle in radians
  771. * @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
  772. */
  773. CesiumMath.negativePiToPi = function(x) {
  774. if (!defined(x)) {
  775. throw new DeveloperError('x is required.');
  776. }
  777. return CesiumMath.zeroToTwoPi(x + CesiumMath.PI) - CesiumMath.PI;
  778. };
  779. /**
  780. * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
  781. *
  782. * @param {Number} angle in radians
  783. * @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
  784. */
  785. CesiumMath.zeroToTwoPi = function(x) {
  786. if (!defined(x)) {
  787. throw new DeveloperError('x is required.');
  788. }
  789. var mod = CesiumMath.mod(x, CesiumMath.TWO_PI);
  790. if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(x) > CesiumMath.EPSILON14) {
  791. return CesiumMath.TWO_PI;
  792. }
  793. return mod;
  794. };
  795. /**
  796. * The modulo operation that also works for negative dividends.
  797. *
  798. * @param {Number} m The dividend.
  799. * @param {Number} n The divisor.
  800. * @returns {Number} The remainder.
  801. */
  802. CesiumMath.mod = function(m, n) {
  803. if (!defined(m)) {
  804. throw new DeveloperError('m is required.');
  805. }
  806. if (!defined(n)) {
  807. throw new DeveloperError('n is required.');
  808. }
  809. return ((m % n) + n) % n;
  810. };
  811. /**
  812. * Determines if two values are equal using an absolute or relative tolerance test. This is useful
  813. * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
  814. * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
  815. * Use this test if you are unsure of the magnitudes of left and right.
  816. *
  817. * @param {Number} left The first value to compare.
  818. * @param {Number} right The other value to compare.
  819. * @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
  820. * @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
  821. * @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
  822. *
  823. * @example
  824. * var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
  825. * var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
  826. * var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
  827. * var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
  828. */
  829. CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  830. if (!defined(left)) {
  831. throw new DeveloperError('left is required.');
  832. }
  833. if (!defined(right)) {
  834. throw new DeveloperError('right is required.');
  835. }
  836. if (!defined(relativeEpsilon)) {
  837. throw new DeveloperError('relativeEpsilon is required.');
  838. }
  839. absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
  840. var absDiff = Math.abs(left - right);
  841. return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
  842. };
  843. var factorials = [1];
  844. /**
  845. * Computes the factorial of the provided number.
  846. *
  847. * @param {Number} n The number whose factorial is to be computed.
  848. * @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
  849. *
  850. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  851. *
  852. *
  853. * @example
  854. * //Compute 7!, which is equal to 5040
  855. * var computedFactorial = Cesium.Math.factorial(7);
  856. *
  857. * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
  858. */
  859. CesiumMath.factorial = function(n) {
  860. if (typeof n !== 'number' || n < 0) {
  861. throw new DeveloperError('A number greater than or equal to 0 is required.');
  862. }
  863. var length = factorials.length;
  864. if (n >= length) {
  865. var sum = factorials[length - 1];
  866. for (var i = length; i <= n; i++) {
  867. factorials.push(sum * i);
  868. }
  869. }
  870. return factorials[n];
  871. };
  872. /**
  873. * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
  874. *
  875. * @param {Number} [n] The number to be incremented.
  876. * @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
  877. * @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
  878. * @returns {Number} The incremented number.
  879. *
  880. * @exception {DeveloperError} Maximum value must be greater than minimum value.
  881. *
  882. * @example
  883. * var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
  884. * var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
  885. */
  886. CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
  887. minimumValue = defaultValue(minimumValue, 0.0);
  888. if (!defined(n)) {
  889. throw new DeveloperError('n is required.');
  890. }
  891. if (maximumValue <= minimumValue) {
  892. throw new DeveloperError('maximumValue must be greater than minimumValue.');
  893. }
  894. ++n;
  895. if (n > maximumValue) {
  896. n = minimumValue;
  897. }
  898. return n;
  899. };
  900. /**
  901. * Determines if a positive integer is a power of two.
  902. *
  903. * @param {Number} n The positive integer to test.
  904. * @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
  905. *
  906. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  907. *
  908. * @example
  909. * var t = Cesium.Math.isPowerOfTwo(16); // true
  910. * var f = Cesium.Math.isPowerOfTwo(20); // false
  911. */
  912. CesiumMath.isPowerOfTwo = function(n) {
  913. if (typeof n !== 'number' || n < 0) {
  914. throw new DeveloperError('A number greater than or equal to 0 is required.');
  915. }
  916. return (n !== 0) && ((n & (n - 1)) === 0);
  917. };
  918. /**
  919. * Computes the next power-of-two integer greater than or equal to the provided positive integer.
  920. *
  921. * @param {Number} n The positive integer to test.
  922. * @returns {Number} The next power-of-two integer.
  923. *
  924. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  925. *
  926. * @example
  927. * var n = Cesium.Math.nextPowerOfTwo(29); // 32
  928. * var m = Cesium.Math.nextPowerOfTwo(32); // 32
  929. */
  930. CesiumMath.nextPowerOfTwo = function(n) {
  931. if (typeof n !== 'number' || n < 0) {
  932. throw new DeveloperError('A number greater than or equal to 0 is required.');
  933. }
  934. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  935. --n;
  936. n |= n >> 1;
  937. n |= n >> 2;
  938. n |= n >> 4;
  939. n |= n >> 8;
  940. n |= n >> 16;
  941. ++n;
  942. return n;
  943. };
  944. /**
  945. * Constraint a value to lie between two values.
  946. *
  947. * @param {Number} value The value to constrain.
  948. * @param {Number} min The minimum value.
  949. * @param {Number} max The maximum value.
  950. * @returns {Number} The value clamped so that min <= value <= max.
  951. */
  952. CesiumMath.clamp = function(value, min, max) {
  953. if (!defined(value)) {
  954. throw new DeveloperError('value is required');
  955. }
  956. if (!defined(min)) {
  957. throw new DeveloperError('min is required.');
  958. }
  959. if (!defined(max)) {
  960. throw new DeveloperError('max is required.');
  961. }
  962. return value < min ? min : value > max ? max : value;
  963. };
  964. var randomNumberGenerator = new MersenneTwister();
  965. /**
  966. * Sets the seed used by the random number generator
  967. * in {@link CesiumMath#nextRandomNumber}.
  968. *
  969. * @param {Number} seed An integer used as the seed.
  970. */
  971. CesiumMath.setRandomNumberSeed = function(seed) {
  972. if (!defined(seed)) {
  973. throw new DeveloperError('seed is required.');
  974. }
  975. randomNumberGenerator = new MersenneTwister(seed);
  976. };
  977. /**
  978. * Generates a random number in the range of [0.0, 1.0)
  979. * using a Mersenne twister.
  980. *
  981. * @returns {Number} A random number in the range of [0.0, 1.0).
  982. *
  983. * @see CesiumMath.setRandomNumberSeed
  984. * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
  985. */
  986. CesiumMath.nextRandomNumber = function() {
  987. return randomNumberGenerator.random();
  988. };
  989. /**
  990. * Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  991. * so that the function will never return NaN.
  992. *
  993. * @param {Number} value The value for which to compute acos.
  994. * @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,
  995. * whichever is closer, if the value is outside the range.
  996. */
  997. CesiumMath.acosClamped = function(value) {
  998. if (!defined(value)) {
  999. throw new DeveloperError('value is required.');
  1000. }
  1001. return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  1002. };
  1003. /**
  1004. * Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1005. * so that the function will never return NaN.
  1006. *
  1007. * @param {Number} value The value for which to compute asin.
  1008. * @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,
  1009. * whichever is closer, if the value is outside the range.
  1010. */
  1011. CesiumMath.asinClamped = function(value) {
  1012. if (!defined(value)) {
  1013. throw new DeveloperError('value is required.');
  1014. }
  1015. return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  1016. };
  1017. /**
  1018. * Finds the chord length between two points given the circle's radius and the angle between the points.
  1019. *
  1020. * @param {Number} angle The angle between the two points.
  1021. * @param {Number} radius The radius of the circle.
  1022. * @returns {Number} The chord length.
  1023. */
  1024. CesiumMath.chordLength = function(angle, radius) {
  1025. if (!defined(angle)) {
  1026. throw new DeveloperError('angle is required.');
  1027. }
  1028. if (!defined(radius)) {
  1029. throw new DeveloperError('radius is required.');
  1030. }
  1031. return 2.0 * radius * Math.sin(angle * 0.5);
  1032. };
  1033. /**
  1034. * Finds the logarithm of a number to a base.
  1035. *
  1036. * @param {Number} number The number.
  1037. * @param {Number} base The base.
  1038. * @returns {Number} The result.
  1039. */
  1040. CesiumMath.logBase = function(number, base) {
  1041. if (!defined(number)) {
  1042. throw new DeveloperError('number is required.');
  1043. }
  1044. if (!defined(base)) {
  1045. throw new DeveloperError('base is required.');
  1046. }
  1047. return Math.log(number) / Math.log(base);
  1048. };
  1049. /**
  1050. * @private
  1051. */
  1052. CesiumMath.fog = function(distanceToCamera, density) {
  1053. var scalar = distanceToCamera * density;
  1054. return 1.0 - Math.exp(-(scalar * scalar));
  1055. };
  1056. return CesiumMath;
  1057. });
  1058. /*global define*/
  1059. define('Core/Cartesian2',[
  1060. './defaultValue',
  1061. './defined',
  1062. './DeveloperError',
  1063. './freezeObject',
  1064. './Math'
  1065. ], function(
  1066. defaultValue,
  1067. defined,
  1068. DeveloperError,
  1069. freezeObject,
  1070. CesiumMath) {
  1071. 'use strict';
  1072. /**
  1073. * A 2D Cartesian point.
  1074. * @alias Cartesian2
  1075. * @constructor
  1076. *
  1077. * @param {Number} [x=0.0] The X component.
  1078. * @param {Number} [y=0.0] The Y component.
  1079. *
  1080. * @see Cartesian3
  1081. * @see Cartesian4
  1082. * @see Packable
  1083. */
  1084. function Cartesian2(x, y) {
  1085. /**
  1086. * The X component.
  1087. * @type {Number}
  1088. * @default 0.0
  1089. */
  1090. this.x = defaultValue(x, 0.0);
  1091. /**
  1092. * The Y component.
  1093. * @type {Number}
  1094. * @default 0.0
  1095. */
  1096. this.y = defaultValue(y, 0.0);
  1097. }
  1098. /**
  1099. * Creates a Cartesian2 instance from x and y coordinates.
  1100. *
  1101. * @param {Number} x The x coordinate.
  1102. * @param {Number} y The y coordinate.
  1103. * @param {Cartesian2} [result] The object onto which to store the result.
  1104. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1105. */
  1106. Cartesian2.fromElements = function(x, y, result) {
  1107. if (!defined(result)) {
  1108. return new Cartesian2(x, y);
  1109. }
  1110. result.x = x;
  1111. result.y = y;
  1112. return result;
  1113. };
  1114. /**
  1115. * Duplicates a Cartesian2 instance.
  1116. *
  1117. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  1118. * @param {Cartesian2} [result] The object onto which to store the result.
  1119. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1120. */
  1121. Cartesian2.clone = function(cartesian, result) {
  1122. if (!defined(cartesian)) {
  1123. return undefined;
  1124. }
  1125. if (!defined(result)) {
  1126. return new Cartesian2(cartesian.x, cartesian.y);
  1127. }
  1128. result.x = cartesian.x;
  1129. result.y = cartesian.y;
  1130. return result;
  1131. };
  1132. /**
  1133. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  1134. * x and y properties of the Cartesian3 and drops z.
  1135. * @function
  1136. *
  1137. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  1138. * @param {Cartesian2} [result] The object onto which to store the result.
  1139. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1140. */
  1141. Cartesian2.fromCartesian3 = Cartesian2.clone;
  1142. /**
  1143. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  1144. * x and y properties of the Cartesian4 and drops z and w.
  1145. * @function
  1146. *
  1147. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  1148. * @param {Cartesian2} [result] The object onto which to store the result.
  1149. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1150. */
  1151. Cartesian2.fromCartesian4 = Cartesian2.clone;
  1152. /**
  1153. * The number of elements used to pack the object into an array.
  1154. * @type {Number}
  1155. */
  1156. Cartesian2.packedLength = 2;
  1157. /**
  1158. * Stores the provided instance into the provided array.
  1159. *
  1160. * @param {Cartesian2} value The value to pack.
  1161. * @param {Number[]} array The array to pack into.
  1162. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1163. *
  1164. * @returns {Number[]} The array that was packed into
  1165. */
  1166. Cartesian2.pack = function(value, array, startingIndex) {
  1167. if (!defined(value)) {
  1168. throw new DeveloperError('value is required');
  1169. }
  1170. if (!defined(array)) {
  1171. throw new DeveloperError('array is required');
  1172. }
  1173. startingIndex = defaultValue(startingIndex, 0);
  1174. array[startingIndex++] = value.x;
  1175. array[startingIndex] = value.y;
  1176. return array;
  1177. };
  1178. /**
  1179. * Retrieves an instance from a packed array.
  1180. *
  1181. * @param {Number[]} array The packed array.
  1182. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1183. * @param {Cartesian2} [result] The object into which to store the result.
  1184. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1185. */
  1186. Cartesian2.unpack = function(array, startingIndex, result) {
  1187. if (!defined(array)) {
  1188. throw new DeveloperError('array is required');
  1189. }
  1190. startingIndex = defaultValue(startingIndex, 0);
  1191. if (!defined(result)) {
  1192. result = new Cartesian2();
  1193. }
  1194. result.x = array[startingIndex++];
  1195. result.y = array[startingIndex];
  1196. return result;
  1197. };
  1198. /**
  1199. * Flattens an array of Cartesian2s into and array of components.
  1200. *
  1201. * @param {Cartesian2[]} array The array of cartesians to pack.
  1202. * @param {Number[]} result The array onto which to store the result.
  1203. * @returns {Number[]} The packed array.
  1204. */
  1205. Cartesian2.packArray = function(array, result) {
  1206. if (!defined(array)) {
  1207. throw new DeveloperError('array is required');
  1208. }
  1209. var length = array.length;
  1210. if (!defined(result)) {
  1211. result = new Array(length * 2);
  1212. } else {
  1213. result.length = length * 2;
  1214. }
  1215. for (var i = 0; i < length; ++i) {
  1216. Cartesian2.pack(array[i], result, i * 2);
  1217. }
  1218. return result;
  1219. };
  1220. /**
  1221. * Unpacks an array of cartesian components into and array of Cartesian2s.
  1222. *
  1223. * @param {Number[]} array The array of components to unpack.
  1224. * @param {Cartesian2[]} result The array onto which to store the result.
  1225. * @returns {Cartesian2[]} The unpacked array.
  1226. */
  1227. Cartesian2.unpackArray = function(array, result) {
  1228. if (!defined(array)) {
  1229. throw new DeveloperError('array is required');
  1230. }
  1231. var length = array.length;
  1232. if (!defined(result)) {
  1233. result = new Array(length / 2);
  1234. } else {
  1235. result.length = length / 2;
  1236. }
  1237. for (var i = 0; i < length; i += 2) {
  1238. var index = i / 2;
  1239. result[index] = Cartesian2.unpack(array, i, result[index]);
  1240. }
  1241. return result;
  1242. };
  1243. /**
  1244. * Creates a Cartesian2 from two consecutive elements in an array.
  1245. * @function
  1246. *
  1247. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  1248. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1249. * @param {Cartesian2} [result] The object onto which to store the result.
  1250. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1251. *
  1252. * @example
  1253. * // Create a Cartesian2 with (1.0, 2.0)
  1254. * var v = [1.0, 2.0];
  1255. * var p = Cesium.Cartesian2.fromArray(v);
  1256. *
  1257. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  1258. * var v2 = [0.0, 0.0, 1.0, 2.0];
  1259. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  1260. */
  1261. Cartesian2.fromArray = Cartesian2.unpack;
  1262. /**
  1263. * Computes the value of the maximum component for the supplied Cartesian.
  1264. *
  1265. * @param {Cartesian2} cartesian The cartesian to use.
  1266. * @returns {Number} The value of the maximum component.
  1267. */
  1268. Cartesian2.maximumComponent = function(cartesian) {
  1269. if (!defined(cartesian)) {
  1270. throw new DeveloperError('cartesian is required');
  1271. }
  1272. return Math.max(cartesian.x, cartesian.y);
  1273. };
  1274. /**
  1275. * Computes the value of the minimum component for the supplied Cartesian.
  1276. *
  1277. * @param {Cartesian2} cartesian The cartesian to use.
  1278. * @returns {Number} The value of the minimum component.
  1279. */
  1280. Cartesian2.minimumComponent = function(cartesian) {
  1281. if (!defined(cartesian)) {
  1282. throw new DeveloperError('cartesian is required');
  1283. }
  1284. return Math.min(cartesian.x, cartesian.y);
  1285. };
  1286. /**
  1287. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1288. *
  1289. * @param {Cartesian2} first A cartesian to compare.
  1290. * @param {Cartesian2} second A cartesian to compare.
  1291. * @param {Cartesian2} result The object into which to store the result.
  1292. * @returns {Cartesian2} A cartesian with the minimum components.
  1293. */
  1294. Cartesian2.minimumByComponent = function(first, second, result) {
  1295. if (!defined(first)) {
  1296. throw new DeveloperError('first is required.');
  1297. }
  1298. if (!defined(second)) {
  1299. throw new DeveloperError('second is required.');
  1300. }
  1301. if (!defined(result)) {
  1302. throw new DeveloperError('result is required.');
  1303. }
  1304. result.x = Math.min(first.x, second.x);
  1305. result.y = Math.min(first.y, second.y);
  1306. return result;
  1307. };
  1308. /**
  1309. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1310. *
  1311. * @param {Cartesian2} first A cartesian to compare.
  1312. * @param {Cartesian2} second A cartesian to compare.
  1313. * @param {Cartesian2} result The object into which to store the result.
  1314. * @returns {Cartesian2} A cartesian with the maximum components.
  1315. */
  1316. Cartesian2.maximumByComponent = function(first, second, result) {
  1317. if (!defined(first)) {
  1318. throw new DeveloperError('first is required.');
  1319. }
  1320. if (!defined(second)) {
  1321. throw new DeveloperError('second is required.');
  1322. }
  1323. if (!defined(result)) {
  1324. throw new DeveloperError('result is required.');
  1325. }
  1326. result.x = Math.max(first.x, second.x);
  1327. result.y = Math.max(first.y, second.y);
  1328. return result;
  1329. };
  1330. /**
  1331. * Computes the provided Cartesian's squared magnitude.
  1332. *
  1333. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1334. * @returns {Number} The squared magnitude.
  1335. */
  1336. Cartesian2.magnitudeSquared = function(cartesian) {
  1337. if (!defined(cartesian)) {
  1338. throw new DeveloperError('cartesian is required');
  1339. }
  1340. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  1341. };
  1342. /**
  1343. * Computes the Cartesian's magnitude (length).
  1344. *
  1345. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  1346. * @returns {Number} The magnitude.
  1347. */
  1348. Cartesian2.magnitude = function(cartesian) {
  1349. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  1350. };
  1351. var distanceScratch = new Cartesian2();
  1352. /**
  1353. * Computes the distance between two points.
  1354. *
  1355. * @param {Cartesian2} left The first point to compute the distance from.
  1356. * @param {Cartesian2} right The second point to compute the distance to.
  1357. * @returns {Number} The distance between two points.
  1358. *
  1359. * @example
  1360. * // Returns 1.0
  1361. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  1362. */
  1363. Cartesian2.distance = function(left, right) {
  1364. if (!defined(left) || !defined(right)) {
  1365. throw new DeveloperError('left and right are required.');
  1366. }
  1367. Cartesian2.subtract(left, right, distanceScratch);
  1368. return Cartesian2.magnitude(distanceScratch);
  1369. };
  1370. /**
  1371. * Computes the squared distance between two points. Comparing squared distances
  1372. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  1373. *
  1374. * @param {Cartesian2} left The first point to compute the distance from.
  1375. * @param {Cartesian2} right The second point to compute the distance to.
  1376. * @returns {Number} The distance between two points.
  1377. *
  1378. * @example
  1379. * // Returns 4.0, not 2.0
  1380. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  1381. */
  1382. Cartesian2.distanceSquared = function(left, right) {
  1383. if (!defined(left) || !defined(right)) {
  1384. throw new DeveloperError('left and right are required.');
  1385. }
  1386. Cartesian2.subtract(left, right, distanceScratch);
  1387. return Cartesian2.magnitudeSquared(distanceScratch);
  1388. };
  1389. /**
  1390. * Computes the normalized form of the supplied Cartesian.
  1391. *
  1392. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  1393. * @param {Cartesian2} result The object onto which to store the result.
  1394. * @returns {Cartesian2} The modified result parameter.
  1395. */
  1396. Cartesian2.normalize = function(cartesian, result) {
  1397. if (!defined(cartesian)) {
  1398. throw new DeveloperError('cartesian is required');
  1399. }
  1400. if (!defined(result)) {
  1401. throw new DeveloperError('result is required');
  1402. }
  1403. var magnitude = Cartesian2.magnitude(cartesian);
  1404. result.x = cartesian.x / magnitude;
  1405. result.y = cartesian.y / magnitude;
  1406. if (isNaN(result.x) || isNaN(result.y)) {
  1407. throw new DeveloperError('normalized result is not a number');
  1408. }
  1409. return result;
  1410. };
  1411. /**
  1412. * Computes the dot (scalar) product of two Cartesians.
  1413. *
  1414. * @param {Cartesian2} left The first Cartesian.
  1415. * @param {Cartesian2} right The second Cartesian.
  1416. * @returns {Number} The dot product.
  1417. */
  1418. Cartesian2.dot = function(left, right) {
  1419. if (!defined(left)) {
  1420. throw new DeveloperError('left is required');
  1421. }
  1422. if (!defined(right)) {
  1423. throw new DeveloperError('right is required');
  1424. }
  1425. return left.x * right.x + left.y * right.y;
  1426. };
  1427. /**
  1428. * Computes the componentwise product of two Cartesians.
  1429. *
  1430. * @param {Cartesian2} left The first Cartesian.
  1431. * @param {Cartesian2} right The second Cartesian.
  1432. * @param {Cartesian2} result The object onto which to store the result.
  1433. * @returns {Cartesian2} The modified result parameter.
  1434. */
  1435. Cartesian2.multiplyComponents = function(left, right, result) {
  1436. if (!defined(left)) {
  1437. throw new DeveloperError('left is required');
  1438. }
  1439. if (!defined(right)) {
  1440. throw new DeveloperError('right is required');
  1441. }
  1442. if (!defined(result)) {
  1443. throw new DeveloperError('result is required');
  1444. }
  1445. result.x = left.x * right.x;
  1446. result.y = left.y * right.y;
  1447. return result;
  1448. };
  1449. /**
  1450. * Computes the componentwise quotient of two Cartesians.
  1451. *
  1452. * @param {Cartesian2} left The first Cartesian.
  1453. * @param {Cartesian2} right The second Cartesian.
  1454. * @param {Cartesian2} result The object onto which to store the result.
  1455. * @returns {Cartesian2} The modified result parameter.
  1456. */
  1457. Cartesian2.divideComponents = function(left, right, result) {
  1458. if (!defined(left)) {
  1459. throw new DeveloperError('left is required');
  1460. }
  1461. if (!defined(right)) {
  1462. throw new DeveloperError('right is required');
  1463. }
  1464. if (!defined(result)) {
  1465. throw new DeveloperError('result is required');
  1466. }
  1467. result.x = left.x / right.x;
  1468. result.y = left.y / right.y;
  1469. return result;
  1470. };
  1471. /**
  1472. * Computes the componentwise sum of two Cartesians.
  1473. *
  1474. * @param {Cartesian2} left The first Cartesian.
  1475. * @param {Cartesian2} right The second Cartesian.
  1476. * @param {Cartesian2} result The object onto which to store the result.
  1477. * @returns {Cartesian2} The modified result parameter.
  1478. */
  1479. Cartesian2.add = function(left, right, result) {
  1480. if (!defined(left)) {
  1481. throw new DeveloperError('left is required');
  1482. }
  1483. if (!defined(right)) {
  1484. throw new DeveloperError('right is required');
  1485. }
  1486. if (!defined(result)) {
  1487. throw new DeveloperError('result is required');
  1488. }
  1489. result.x = left.x + right.x;
  1490. result.y = left.y + right.y;
  1491. return result;
  1492. };
  1493. /**
  1494. * Computes the componentwise difference of two Cartesians.
  1495. *
  1496. * @param {Cartesian2} left The first Cartesian.
  1497. * @param {Cartesian2} right The second Cartesian.
  1498. * @param {Cartesian2} result The object onto which to store the result.
  1499. * @returns {Cartesian2} The modified result parameter.
  1500. */
  1501. Cartesian2.subtract = function(left, right, result) {
  1502. if (!defined(left)) {
  1503. throw new DeveloperError('left is required');
  1504. }
  1505. if (!defined(right)) {
  1506. throw new DeveloperError('right is required');
  1507. }
  1508. if (!defined(result)) {
  1509. throw new DeveloperError('result is required');
  1510. }
  1511. result.x = left.x - right.x;
  1512. result.y = left.y - right.y;
  1513. return result;
  1514. };
  1515. /**
  1516. * Multiplies the provided Cartesian componentwise by the provided scalar.
  1517. *
  1518. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  1519. * @param {Number} scalar The scalar to multiply with.
  1520. * @param {Cartesian2} result The object onto which to store the result.
  1521. * @returns {Cartesian2} The modified result parameter.
  1522. */
  1523. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  1524. if (!defined(cartesian)) {
  1525. throw new DeveloperError('cartesian is required');
  1526. }
  1527. if (typeof scalar !== 'number') {
  1528. throw new DeveloperError('scalar is required and must be a number.');
  1529. }
  1530. if (!defined(result)) {
  1531. throw new DeveloperError('result is required');
  1532. }
  1533. result.x = cartesian.x * scalar;
  1534. result.y = cartesian.y * scalar;
  1535. return result;
  1536. };
  1537. /**
  1538. * Divides the provided Cartesian componentwise by the provided scalar.
  1539. *
  1540. * @param {Cartesian2} cartesian The Cartesian to be divided.
  1541. * @param {Number} scalar The scalar to divide by.
  1542. * @param {Cartesian2} result The object onto which to store the result.
  1543. * @returns {Cartesian2} The modified result parameter.
  1544. */
  1545. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  1546. if (!defined(cartesian)) {
  1547. throw new DeveloperError('cartesian is required');
  1548. }
  1549. if (typeof scalar !== 'number') {
  1550. throw new DeveloperError('scalar is required and must be a number.');
  1551. }
  1552. if (!defined(result)) {
  1553. throw new DeveloperError('result is required');
  1554. }
  1555. result.x = cartesian.x / scalar;
  1556. result.y = cartesian.y / scalar;
  1557. return result;
  1558. };
  1559. /**
  1560. * Negates the provided Cartesian.
  1561. *
  1562. * @param {Cartesian2} cartesian The Cartesian to be negated.
  1563. * @param {Cartesian2} result The object onto which to store the result.
  1564. * @returns {Cartesian2} The modified result parameter.
  1565. */
  1566. Cartesian2.negate = function(cartesian, result) {
  1567. if (!defined(cartesian)) {
  1568. throw new DeveloperError('cartesian is required');
  1569. }
  1570. if (!defined(result)) {
  1571. throw new DeveloperError('result is required');
  1572. }
  1573. result.x = -cartesian.x;
  1574. result.y = -cartesian.y;
  1575. return result;
  1576. };
  1577. /**
  1578. * Computes the absolute value of the provided Cartesian.
  1579. *
  1580. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  1581. * @param {Cartesian2} result The object onto which to store the result.
  1582. * @returns {Cartesian2} The modified result parameter.
  1583. */
  1584. Cartesian2.abs = function(cartesian, result) {
  1585. if (!defined(cartesian)) {
  1586. throw new DeveloperError('cartesian is required');
  1587. }
  1588. if (!defined(result)) {
  1589. throw new DeveloperError('result is required');
  1590. }
  1591. result.x = Math.abs(cartesian.x);
  1592. result.y = Math.abs(cartesian.y);
  1593. return result;
  1594. };
  1595. var lerpScratch = new Cartesian2();
  1596. /**
  1597. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  1598. *
  1599. * @param {Cartesian2} start The value corresponding to t at 0.0.
  1600. * @param {Cartesian2} end The value corresponding to t at 1.0.
  1601. * @param {Number} t The point along t at which to interpolate.
  1602. * @param {Cartesian2} result The object onto which to store the result.
  1603. * @returns {Cartesian2} The modified result parameter.
  1604. */
  1605. Cartesian2.lerp = function(start, end, t, result) {
  1606. if (!defined(start)) {
  1607. throw new DeveloperError('start is required.');
  1608. }
  1609. if (!defined(end)) {
  1610. throw new DeveloperError('end is required.');
  1611. }
  1612. if (typeof t !== 'number') {
  1613. throw new DeveloperError('t is required and must be a number.');
  1614. }
  1615. if (!defined(result)) {
  1616. throw new DeveloperError('result is required.');
  1617. }
  1618. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  1619. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  1620. return Cartesian2.add(lerpScratch, result, result);
  1621. };
  1622. var angleBetweenScratch = new Cartesian2();
  1623. var angleBetweenScratch2 = new Cartesian2();
  1624. /**
  1625. * Returns the angle, in radians, between the provided Cartesians.
  1626. *
  1627. * @param {Cartesian2} left The first Cartesian.
  1628. * @param {Cartesian2} right The second Cartesian.
  1629. * @returns {Number} The angle between the Cartesians.
  1630. */
  1631. Cartesian2.angleBetween = function(left, right) {
  1632. if (!defined(left)) {
  1633. throw new DeveloperError('left is required');
  1634. }
  1635. if (!defined(right)) {
  1636. throw new DeveloperError('right is required');
  1637. }
  1638. Cartesian2.normalize(left, angleBetweenScratch);
  1639. Cartesian2.normalize(right, angleBetweenScratch2);
  1640. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  1641. };
  1642. var mostOrthogonalAxisScratch = new Cartesian2();
  1643. /**
  1644. * Returns the axis that is most orthogonal to the provided Cartesian.
  1645. *
  1646. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  1647. * @param {Cartesian2} result The object onto which to store the result.
  1648. * @returns {Cartesian2} The most orthogonal axis.
  1649. */
  1650. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  1651. if (!defined(cartesian)) {
  1652. throw new DeveloperError('cartesian is required.');
  1653. }
  1654. if (!defined(result)) {
  1655. throw new DeveloperError('result is required.');
  1656. }
  1657. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  1658. Cartesian2.abs(f, f);
  1659. if (f.x <= f.y) {
  1660. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  1661. } else {
  1662. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  1663. }
  1664. return result;
  1665. };
  1666. /**
  1667. * Compares the provided Cartesians componentwise and returns
  1668. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1669. *
  1670. * @param {Cartesian2} [left] The first Cartesian.
  1671. * @param {Cartesian2} [right] The second Cartesian.
  1672. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1673. */
  1674. Cartesian2.equals = function(left, right) {
  1675. return (left === right) ||
  1676. ((defined(left)) &&
  1677. (defined(right)) &&
  1678. (left.x === right.x) &&
  1679. (left.y === right.y));
  1680. };
  1681. /**
  1682. * @private
  1683. */
  1684. Cartesian2.equalsArray = function(cartesian, array, offset) {
  1685. return cartesian.x === array[offset] &&
  1686. cartesian.y === array[offset + 1];
  1687. };
  1688. /**
  1689. * Compares the provided Cartesians componentwise and returns
  1690. * <code>true</code> if they pass an absolute or relative tolerance test,
  1691. * <code>false</code> otherwise.
  1692. *
  1693. * @param {Cartesian2} [left] The first Cartesian.
  1694. * @param {Cartesian2} [right] The second Cartesian.
  1695. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  1696. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  1697. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1698. */
  1699. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  1700. return (left === right) ||
  1701. (defined(left) &&
  1702. defined(right) &&
  1703. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  1704. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  1705. };
  1706. /**
  1707. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  1708. *
  1709. * @type {Cartesian2}
  1710. * @constant
  1711. */
  1712. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  1713. /**
  1714. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  1715. *
  1716. * @type {Cartesian2}
  1717. * @constant
  1718. */
  1719. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  1720. /**
  1721. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  1722. *
  1723. * @type {Cartesian2}
  1724. * @constant
  1725. */
  1726. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  1727. /**
  1728. * Duplicates this Cartesian2 instance.
  1729. *
  1730. * @param {Cartesian2} [result] The object onto which to store the result.
  1731. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  1732. */
  1733. Cartesian2.prototype.clone = function(result) {
  1734. return Cartesian2.clone(this, result);
  1735. };
  1736. /**
  1737. * Compares this Cartesian against the provided Cartesian componentwise and returns
  1738. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1739. *
  1740. * @param {Cartesian2} [right] The right hand side Cartesian.
  1741. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1742. */
  1743. Cartesian2.prototype.equals = function(right) {
  1744. return Cartesian2.equals(this, right);
  1745. };
  1746. /**
  1747. * Compares this Cartesian against the provided Cartesian componentwise and returns
  1748. * <code>true</code> if they pass an absolute or relative tolerance test,
  1749. * <code>false</code> otherwise.
  1750. *
  1751. * @param {Cartesian2} [right] The right hand side Cartesian.
  1752. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  1753. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  1754. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  1755. */
  1756. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  1757. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  1758. };
  1759. /**
  1760. * Creates a string representing this Cartesian in the format '(x, y)'.
  1761. *
  1762. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  1763. */
  1764. Cartesian2.prototype.toString = function() {
  1765. return '(' + this.x + ', ' + this.y + ')';
  1766. };
  1767. return Cartesian2;
  1768. });
  1769. /*global define*/
  1770. define('Core/isArray',[
  1771. './defined'
  1772. ], function(
  1773. defined) {
  1774. 'use strict';
  1775. /**
  1776. * Tests an object to see if it is an array.
  1777. * @exports isArray
  1778. *
  1779. * @param {Object} value The value to test.
  1780. * @returns {Boolean} true if the value is an array, false otherwise.
  1781. */
  1782. var isArray = Array.isArray;
  1783. if (!defined(isArray)) {
  1784. isArray = function(value) {
  1785. return Object.prototype.toString.call(value) === '[object Array]';
  1786. };
  1787. }
  1788. return isArray;
  1789. });
  1790. /*global define*/
  1791. define('Core/Check',[
  1792. './defaultValue',
  1793. './defined',
  1794. './DeveloperError',
  1795. './isArray'
  1796. ], function(
  1797. defaultValue,
  1798. defined,
  1799. DeveloperError,
  1800. isArray) {
  1801. 'use strict';
  1802. /**
  1803. * Contains functions for checking that supplied arguments are of a specified type
  1804. * or meet specified conditions
  1805. * @private
  1806. */
  1807. var Check = {};
  1808. /**
  1809. * Contains type checking functions, all using the typeof operator
  1810. */
  1811. Check.typeOf = {};
  1812. /**
  1813. * Contains functions for checking numeric conditions such as minimum and maximum values
  1814. */
  1815. Check.numeric = {};
  1816. function getUndefinedErrorMessage(name) {
  1817. return name + ' was required but undefined.';
  1818. }
  1819. function getFailedTypeErrorMessage(actual, expected, name) {
  1820. return 'Expected ' + name + ' to be typeof ' + expected + ', got ' + actual;
  1821. }
  1822. /**
  1823. * Throws if test is not defined
  1824. *
  1825. * @param {*} test The value that is to be checked
  1826. * @param {String} name The name of the variable being tested
  1827. * @exception {DeveloperError} test must be defined
  1828. */
  1829. Check.defined = function (test, name) {
  1830. if (!defined(test)) {
  1831. throw new DeveloperError(getUndefinedErrorMessage(name));
  1832. }
  1833. };
  1834. /**
  1835. * Throws if test is greater than maximum
  1836. *
  1837. * @param {Number} test The value to test
  1838. * @param {Number} maximum The maximum allowed value
  1839. * @exception {DeveloperError} test must not be greater than maximum
  1840. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  1841. */
  1842. Check.numeric.maximum = function (test, maximum) {
  1843. Check.typeOf.number(test);
  1844. Check.typeOf.number(maximum);
  1845. if (test > maximum) {
  1846. throw new DeveloperError('Expected ' + test + ' to be at most ' + maximum);
  1847. }
  1848. };
  1849. /**
  1850. * Throws if test is less than minimum
  1851. *
  1852. * @param {Number} test The value to test
  1853. * @param {Number} minimum The minimum allowed value
  1854. * @exception {DeveloperError} test must not be less than mininum
  1855. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  1856. */
  1857. Check.numeric.minimum = function (test, minimum) {
  1858. Check.typeOf.number(test);
  1859. Check.typeOf.number(minimum);
  1860. if (test < minimum) {
  1861. throw new DeveloperError('Expected ' + test + ' to be at least ' + minimum);
  1862. }
  1863. };
  1864. /**
  1865. * Throws if test is not typeof 'function'
  1866. *
  1867. * @param {*} test The value to test
  1868. * @param {String} name The name of the variable being tested
  1869. * @exception {DeveloperError} test must be typeof 'function'
  1870. */
  1871. Check.typeOf.function = function (test, name) {
  1872. if (typeof test !== 'function') {
  1873. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'function', name));
  1874. }
  1875. };
  1876. /**
  1877. * Throws if test is not typeof 'string'
  1878. *
  1879. * @param {*} test The value to test
  1880. * @param {String} name The name of the variable being tested
  1881. * @exception {DeveloperError} test must be typeof 'string'
  1882. */
  1883. Check.typeOf.string = function (test, name) {
  1884. if (typeof test !== 'string') {
  1885. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'string', name));
  1886. }
  1887. };
  1888. /**
  1889. * Throws if test is not typeof 'number'
  1890. *
  1891. * @param {*} test The value to test
  1892. * @param {String} name The name of the variable being tested
  1893. * @exception {DeveloperError} test must be typeof 'number'
  1894. */
  1895. Check.typeOf.number = function (test, name) {
  1896. if (typeof test !== 'number') {
  1897. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'number', name));
  1898. }
  1899. };
  1900. /**
  1901. * Throws if test is not typeof 'object'
  1902. *
  1903. * @param {*} test The value to test
  1904. * @param {String} name The name of the variable being tested
  1905. * @exception {DeveloperError} test must be typeof 'object'
  1906. */
  1907. Check.typeOf.object = function (test, name) {
  1908. if (typeof test !== 'object') {
  1909. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'object', name));
  1910. }
  1911. };
  1912. /**
  1913. * Throws if test is not typeof 'boolean'
  1914. *
  1915. * @param {*} test The value to test
  1916. * @param {String} name The name of the variable being tested
  1917. * @exception {DeveloperError} test must be typeof 'boolean'
  1918. */
  1919. Check.typeOf.boolean = function (test, name) {
  1920. if (typeof test !== 'boolean') {
  1921. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'boolean', name));
  1922. }
  1923. };
  1924. return Check;
  1925. });
  1926. /*global define*/
  1927. define('Core/Cartesian3',[
  1928. './Check',
  1929. './defaultValue',
  1930. './defined',
  1931. './DeveloperError',
  1932. './freezeObject',
  1933. './Math'
  1934. ], function(
  1935. Check,
  1936. defaultValue,
  1937. defined,
  1938. DeveloperError,
  1939. freezeObject,
  1940. CesiumMath) {
  1941. 'use strict';
  1942. /**
  1943. * A 3D Cartesian point.
  1944. * @alias Cartesian3
  1945. * @constructor
  1946. *
  1947. * @param {Number} [x=0.0] The X component.
  1948. * @param {Number} [y=0.0] The Y component.
  1949. * @param {Number} [z=0.0] The Z component.
  1950. *
  1951. * @see Cartesian2
  1952. * @see Cartesian4
  1953. * @see Packable
  1954. */
  1955. function Cartesian3(x, y, z) {
  1956. /**
  1957. * The X component.
  1958. * @type {Number}
  1959. * @default 0.0
  1960. */
  1961. this.x = defaultValue(x, 0.0);
  1962. /**
  1963. * The Y component.
  1964. * @type {Number}
  1965. * @default 0.0
  1966. */
  1967. this.y = defaultValue(y, 0.0);
  1968. /**
  1969. * The Z component.
  1970. * @type {Number}
  1971. * @default 0.0
  1972. */
  1973. this.z = defaultValue(z, 0.0);
  1974. }
  1975. /**
  1976. * Converts the provided Spherical into Cartesian3 coordinates.
  1977. *
  1978. * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
  1979. * @param {Cartesian3} [result] The object onto which to store the result.
  1980. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1981. */
  1982. Cartesian3.fromSpherical = function(spherical, result) {
  1983. Check.typeOf.object(spherical, 'spherical');
  1984. if (!defined(result)) {
  1985. result = new Cartesian3();
  1986. }
  1987. var clock = spherical.clock;
  1988. var cone = spherical.cone;
  1989. var magnitude = defaultValue(spherical.magnitude, 1.0);
  1990. var radial = magnitude * Math.sin(cone);
  1991. result.x = radial * Math.cos(clock);
  1992. result.y = radial * Math.sin(clock);
  1993. result.z = magnitude * Math.cos(cone);
  1994. return result;
  1995. };
  1996. /**
  1997. * Creates a Cartesian3 instance from x, y and z coordinates.
  1998. *
  1999. * @param {Number} x The x coordinate.
  2000. * @param {Number} y The y coordinate.
  2001. * @param {Number} z The z coordinate.
  2002. * @param {Cartesian3} [result] The object onto which to store the result.
  2003. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2004. */
  2005. Cartesian3.fromElements = function(x, y, z, result) {
  2006. if (!defined(result)) {
  2007. return new Cartesian3(x, y, z);
  2008. }
  2009. result.x = x;
  2010. result.y = y;
  2011. result.z = z;
  2012. return result;
  2013. };
  2014. /**
  2015. * Duplicates a Cartesian3 instance.
  2016. *
  2017. * @param {Cartesian3} cartesian The Cartesian to duplicate.
  2018. * @param {Cartesian3} [result] The object onto which to store the result.
  2019. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
  2020. */
  2021. Cartesian3.clone = function(cartesian, result) {
  2022. if (!defined(cartesian)) {
  2023. return undefined;
  2024. }
  2025. if (!defined(result)) {
  2026. return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
  2027. }
  2028. result.x = cartesian.x;
  2029. result.y = cartesian.y;
  2030. result.z = cartesian.z;
  2031. return result;
  2032. };
  2033. /**
  2034. * Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
  2035. * x, y, and z properties of the Cartesian4 and drops w.
  2036. * @function
  2037. *
  2038. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
  2039. * @param {Cartesian3} [result] The object onto which to store the result.
  2040. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2041. */
  2042. Cartesian3.fromCartesian4 = Cartesian3.clone;
  2043. /**
  2044. * The number of elements used to pack the object into an array.
  2045. * @type {Number}
  2046. */
  2047. Cartesian3.packedLength = 3;
  2048. /**
  2049. * Stores the provided instance into the provided array.
  2050. *
  2051. * @param {Cartesian3} value The value to pack.
  2052. * @param {Number[]} array The array to pack into.
  2053. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2054. *
  2055. * @returns {Number[]} The array that was packed into
  2056. */
  2057. Cartesian3.pack = function(value, array, startingIndex) {
  2058. Check.typeOf.object(value, 'value');
  2059. Check.defined(array, 'array');
  2060. startingIndex = defaultValue(startingIndex, 0);
  2061. array[startingIndex++] = value.x;
  2062. array[startingIndex++] = value.y;
  2063. array[startingIndex] = value.z;
  2064. return array;
  2065. };
  2066. /**
  2067. * Retrieves an instance from a packed array.
  2068. *
  2069. * @param {Number[]} array The packed array.
  2070. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2071. * @param {Cartesian3} [result] The object into which to store the result.
  2072. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2073. */
  2074. Cartesian3.unpack = function(array, startingIndex, result) {
  2075. Check.defined(array, 'array');
  2076. startingIndex = defaultValue(startingIndex, 0);
  2077. if (!defined(result)) {
  2078. result = new Cartesian3();
  2079. }
  2080. result.x = array[startingIndex++];
  2081. result.y = array[startingIndex++];
  2082. result.z = array[startingIndex];
  2083. return result;
  2084. };
  2085. /**
  2086. * Flattens an array of Cartesian3s into an array of components.
  2087. *
  2088. * @param {Cartesian3[]} array The array of cartesians to pack.
  2089. * @param {Number[]} result The array onto which to store the result.
  2090. * @returns {Number[]} The packed array.
  2091. */
  2092. Cartesian3.packArray = function(array, result) {
  2093. Check.defined(array, 'array');
  2094. var length = array.length;
  2095. if (!defined(result)) {
  2096. result = new Array(length * 3);
  2097. } else {
  2098. result.length = length * 3;
  2099. }
  2100. for (var i = 0; i < length; ++i) {
  2101. Cartesian3.pack(array[i], result, i * 3);
  2102. }
  2103. return result;
  2104. };
  2105. /**
  2106. * Unpacks an array of cartesian components into an array of Cartesian3s.
  2107. *
  2108. * @param {Number[]} array The array of components to unpack.
  2109. * @param {Cartesian3[]} result The array onto which to store the result.
  2110. * @returns {Cartesian3[]} The unpacked array.
  2111. */
  2112. Cartesian3.unpackArray = function(array, result) {
  2113. Check.defined(array, 'array');
  2114. Check.numeric.minimum(array.length, 3);
  2115. if (array.length % 3 !== 0) {
  2116. throw new DeveloperError('array length must be a multiple of 3.');
  2117. }
  2118. var length = array.length;
  2119. if (!defined(result)) {
  2120. result = new Array(length / 3);
  2121. } else {
  2122. result.length = length / 3;
  2123. }
  2124. for (var i = 0; i < length; i += 3) {
  2125. var index = i / 3;
  2126. result[index] = Cartesian3.unpack(array, i, result[index]);
  2127. }
  2128. return result;
  2129. };
  2130. /**
  2131. * Creates a Cartesian3 from three consecutive elements in an array.
  2132. * @function
  2133. *
  2134. * @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
  2135. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  2136. * @param {Cartesian3} [result] The object onto which to store the result.
  2137. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2138. *
  2139. * @example
  2140. * // Create a Cartesian3 with (1.0, 2.0, 3.0)
  2141. * var v = [1.0, 2.0, 3.0];
  2142. * var p = Cesium.Cartesian3.fromArray(v);
  2143. *
  2144. * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
  2145. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
  2146. * var p2 = Cesium.Cartesian3.fromArray(v2, 2);
  2147. */
  2148. Cartesian3.fromArray = Cartesian3.unpack;
  2149. /**
  2150. * Computes the value of the maximum component for the supplied Cartesian.
  2151. *
  2152. * @param {Cartesian3} cartesian The cartesian to use.
  2153. * @returns {Number} The value of the maximum component.
  2154. */
  2155. Cartesian3.maximumComponent = function(cartesian) {
  2156. Check.typeOf.object(cartesian, 'cartesian');
  2157. return Math.max(cartesian.x, cartesian.y, cartesian.z);
  2158. };
  2159. /**
  2160. * Computes the value of the minimum component for the supplied Cartesian.
  2161. *
  2162. * @param {Cartesian3} cartesian The cartesian to use.
  2163. * @returns {Number} The value of the minimum component.
  2164. */
  2165. Cartesian3.minimumComponent = function(cartesian) {
  2166. Check.typeOf.object(cartesian, 'cartesian');
  2167. return Math.min(cartesian.x, cartesian.y, cartesian.z);
  2168. };
  2169. /**
  2170. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  2171. *
  2172. * @param {Cartesian3} first A cartesian to compare.
  2173. * @param {Cartesian3} second A cartesian to compare.
  2174. * @param {Cartesian3} result The object into which to store the result.
  2175. * @returns {Cartesian3} A cartesian with the minimum components.
  2176. */
  2177. Cartesian3.minimumByComponent = function(first, second, result) {
  2178. Check.typeOf.object(first, 'first');
  2179. Check.typeOf.object(second, 'second');
  2180. Check.typeOf.object(result, 'result');
  2181. result.x = Math.min(first.x, second.x);
  2182. result.y = Math.min(first.y, second.y);
  2183. result.z = Math.min(first.z, second.z);
  2184. return result;
  2185. };
  2186. /**
  2187. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  2188. *
  2189. * @param {Cartesian3} first A cartesian to compare.
  2190. * @param {Cartesian3} second A cartesian to compare.
  2191. * @param {Cartesian3} result The object into which to store the result.
  2192. * @returns {Cartesian3} A cartesian with the maximum components.
  2193. */
  2194. Cartesian3.maximumByComponent = function(first, second, result) {
  2195. Check.typeOf.object(first, 'first');
  2196. Check.typeOf.object(second, 'second');
  2197. Check.typeOf.object(result, 'result');
  2198. result.x = Math.max(first.x, second.x);
  2199. result.y = Math.max(first.y, second.y);
  2200. result.z = Math.max(first.z, second.z);
  2201. return result;
  2202. };
  2203. /**
  2204. * Computes the provided Cartesian's squared magnitude.
  2205. *
  2206. * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
  2207. * @returns {Number} The squared magnitude.
  2208. */
  2209. Cartesian3.magnitudeSquared = function(cartesian) {
  2210. Check.typeOf.object(cartesian, 'cartesian');
  2211. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
  2212. };
  2213. /**
  2214. * Computes the Cartesian's magnitude (length).
  2215. *
  2216. * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
  2217. * @returns {Number} The magnitude.
  2218. */
  2219. Cartesian3.magnitude = function(cartesian) {
  2220. return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  2221. };
  2222. var distanceScratch = new Cartesian3();
  2223. /**
  2224. * Computes the distance between two points.
  2225. *
  2226. * @param {Cartesian3} left The first point to compute the distance from.
  2227. * @param {Cartesian3} right The second point to compute the distance to.
  2228. * @returns {Number} The distance between two points.
  2229. *
  2230. * @example
  2231. * // Returns 1.0
  2232. * var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
  2233. */
  2234. Cartesian3.distance = function(left, right) {
  2235. Check.typeOf.object(left, 'left');
  2236. Check.typeOf.object(right, 'right');
  2237. Cartesian3.subtract(left, right, distanceScratch);
  2238. return Cartesian3.magnitude(distanceScratch);
  2239. };
  2240. /**
  2241. * Computes the squared distance between two points. Comparing squared distances
  2242. * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
  2243. *
  2244. * @param {Cartesian3} left The first point to compute the distance from.
  2245. * @param {Cartesian3} right The second point to compute the distance to.
  2246. * @returns {Number} The distance between two points.
  2247. *
  2248. * @example
  2249. * // Returns 4.0, not 2.0
  2250. * var d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
  2251. */
  2252. Cartesian3.distanceSquared = function(left, right) {
  2253. Check.typeOf.object(left, 'left');
  2254. Check.typeOf.object(right, 'right');
  2255. Cartesian3.subtract(left, right, distanceScratch);
  2256. return Cartesian3.magnitudeSquared(distanceScratch);
  2257. };
  2258. /**
  2259. * Computes the normalized form of the supplied Cartesian.
  2260. *
  2261. * @param {Cartesian3} cartesian The Cartesian to be normalized.
  2262. * @param {Cartesian3} result The object onto which to store the result.
  2263. * @returns {Cartesian3} The modified result parameter.
  2264. */
  2265. Cartesian3.normalize = function(cartesian, result) {
  2266. Check.typeOf.object(cartesian, 'cartesian');
  2267. Check.typeOf.object(result, 'result');
  2268. var magnitude = Cartesian3.magnitude(cartesian);
  2269. result.x = cartesian.x / magnitude;
  2270. result.y = cartesian.y / magnitude;
  2271. result.z = cartesian.z / magnitude;
  2272. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
  2273. throw new DeveloperError('normalized result is not a number');
  2274. }
  2275. return result;
  2276. };
  2277. /**
  2278. * Computes the dot (scalar) product of two Cartesians.
  2279. *
  2280. * @param {Cartesian3} left The first Cartesian.
  2281. * @param {Cartesian3} right The second Cartesian.
  2282. * @returns {Number} The dot product.
  2283. */
  2284. Cartesian3.dot = function(left, right) {
  2285. Check.typeOf.object(left, 'left');
  2286. Check.typeOf.object(right, 'right');
  2287. return left.x * right.x + left.y * right.y + left.z * right.z;
  2288. };
  2289. /**
  2290. * Computes the componentwise product of two Cartesians.
  2291. *
  2292. * @param {Cartesian3} left The first Cartesian.
  2293. * @param {Cartesian3} right The second Cartesian.
  2294. * @param {Cartesian3} result The object onto which to store the result.
  2295. * @returns {Cartesian3} The modified result parameter.
  2296. */
  2297. Cartesian3.multiplyComponents = function(left, right, result) {
  2298. Check.typeOf.object(left, 'left');
  2299. Check.typeOf.object(right, 'right');
  2300. Check.typeOf.object(result, 'result');
  2301. result.x = left.x * right.x;
  2302. result.y = left.y * right.y;
  2303. result.z = left.z * right.z;
  2304. return result;
  2305. };
  2306. /**
  2307. * Computes the componentwise quotient of two Cartesians.
  2308. *
  2309. * @param {Cartesian3} left The first Cartesian.
  2310. * @param {Cartesian3} right The second Cartesian.
  2311. * @param {Cartesian3} result The object onto which to store the result.
  2312. * @returns {Cartesian3} The modified result parameter.
  2313. */
  2314. Cartesian3.divideComponents = function(left, right, result) {
  2315. if (!defined(left)) {
  2316. throw new DeveloperError('left is required');
  2317. }
  2318. if (!defined(right)) {
  2319. throw new DeveloperError('right is required');
  2320. }
  2321. if (!defined(result)) {
  2322. throw new DeveloperError('result is required');
  2323. }
  2324. result.x = left.x / right.x;
  2325. result.y = left.y / right.y;
  2326. result.z = left.z / right.z;
  2327. return result;
  2328. };
  2329. /**
  2330. * Computes the componentwise sum of two Cartesians.
  2331. *
  2332. * @param {Cartesian3} left The first Cartesian.
  2333. * @param {Cartesian3} right The second Cartesian.
  2334. * @param {Cartesian3} result The object onto which to store the result.
  2335. * @returns {Cartesian3} The modified result parameter.
  2336. */
  2337. Cartesian3.add = function(left, right, result) {
  2338. Check.typeOf.object(left, 'left');
  2339. Check.typeOf.object(right, 'right');
  2340. Check.typeOf.object(result, 'result');
  2341. result.x = left.x + right.x;
  2342. result.y = left.y + right.y;
  2343. result.z = left.z + right.z;
  2344. return result;
  2345. };
  2346. /**
  2347. * Computes the componentwise difference of two Cartesians.
  2348. *
  2349. * @param {Cartesian3} left The first Cartesian.
  2350. * @param {Cartesian3} right The second Cartesian.
  2351. * @param {Cartesian3} result The object onto which to store the result.
  2352. * @returns {Cartesian3} The modified result parameter.
  2353. */
  2354. Cartesian3.subtract = function(left, right, result) {
  2355. Check.typeOf.object(left, 'left');
  2356. Check.typeOf.object(right, 'right');
  2357. Check.typeOf.object(result, 'result');
  2358. result.x = left.x - right.x;
  2359. result.y = left.y - right.y;
  2360. result.z = left.z - right.z;
  2361. return result;
  2362. };
  2363. /**
  2364. * Multiplies the provided Cartesian componentwise by the provided scalar.
  2365. *
  2366. * @param {Cartesian3} cartesian The Cartesian to be scaled.
  2367. * @param {Number} scalar The scalar to multiply with.
  2368. * @param {Cartesian3} result The object onto which to store the result.
  2369. * @returns {Cartesian3} The modified result parameter.
  2370. */
  2371. Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
  2372. Check.typeOf.object(cartesian, 'cartesian');
  2373. Check.typeOf.number(scalar, 'scalar');
  2374. Check.typeOf.object(result, 'result');
  2375. result.x = cartesian.x * scalar;
  2376. result.y = cartesian.y * scalar;
  2377. result.z = cartesian.z * scalar;
  2378. return result;
  2379. };
  2380. /**
  2381. * Divides the provided Cartesian componentwise by the provided scalar.
  2382. *
  2383. * @param {Cartesian3} cartesian The Cartesian to be divided.
  2384. * @param {Number} scalar The scalar to divide by.
  2385. * @param {Cartesian3} result The object onto which to store the result.
  2386. * @returns {Cartesian3} The modified result parameter.
  2387. */
  2388. Cartesian3.divideByScalar = function(cartesian, scalar, result) {
  2389. Check.typeOf.object(cartesian, 'cartesian');
  2390. Check.typeOf.number(scalar, 'scalar');
  2391. Check.typeOf.object(result, 'result');
  2392. result.x = cartesian.x / scalar;
  2393. result.y = cartesian.y / scalar;
  2394. result.z = cartesian.z / scalar;
  2395. return result;
  2396. };
  2397. /**
  2398. * Negates the provided Cartesian.
  2399. *
  2400. * @param {Cartesian3} cartesian The Cartesian to be negated.
  2401. * @param {Cartesian3} result The object onto which to store the result.
  2402. * @returns {Cartesian3} The modified result parameter.
  2403. */
  2404. Cartesian3.negate = function(cartesian, result) {
  2405. Check.typeOf.object(cartesian, 'cartesian');
  2406. Check.typeOf.object(result, 'result');
  2407. result.x = -cartesian.x;
  2408. result.y = -cartesian.y;
  2409. result.z = -cartesian.z;
  2410. return result;
  2411. };
  2412. /**
  2413. * Computes the absolute value of the provided Cartesian.
  2414. *
  2415. * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
  2416. * @param {Cartesian3} result The object onto which to store the result.
  2417. * @returns {Cartesian3} The modified result parameter.
  2418. */
  2419. Cartesian3.abs = function(cartesian, result) {
  2420. Check.typeOf.object(cartesian, 'cartesian');
  2421. Check.typeOf.object(result, 'result');
  2422. result.x = Math.abs(cartesian.x);
  2423. result.y = Math.abs(cartesian.y);
  2424. result.z = Math.abs(cartesian.z);
  2425. return result;
  2426. };
  2427. var lerpScratch = new Cartesian3();
  2428. /**
  2429. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  2430. *
  2431. * @param {Cartesian3} start The value corresponding to t at 0.0.
  2432. * @param {Cartesian3} end The value corresponding to t at 1.0.
  2433. * @param {Number} t The point along t at which to interpolate.
  2434. * @param {Cartesian3} result The object onto which to store the result.
  2435. * @returns {Cartesian3} The modified result parameter.
  2436. */
  2437. Cartesian3.lerp = function(start, end, t, result) {
  2438. Check.typeOf.object(start, 'start');
  2439. Check.typeOf.object(end, 'end');
  2440. Check.typeOf.number(t, 't');
  2441. Check.typeOf.object(result, 'result');
  2442. Cartesian3.multiplyByScalar(end, t, lerpScratch);
  2443. result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
  2444. return Cartesian3.add(lerpScratch, result, result);
  2445. };
  2446. var angleBetweenScratch = new Cartesian3();
  2447. var angleBetweenScratch2 = new Cartesian3();
  2448. /**
  2449. * Returns the angle, in radians, between the provided Cartesians.
  2450. *
  2451. * @param {Cartesian3} left The first Cartesian.
  2452. * @param {Cartesian3} right The second Cartesian.
  2453. * @returns {Number} The angle between the Cartesians.
  2454. */
  2455. Cartesian3.angleBetween = function(left, right) {
  2456. Check.typeOf.object(left, 'left');
  2457. Check.typeOf.object(right, 'right');
  2458. Cartesian3.normalize(left, angleBetweenScratch);
  2459. Cartesian3.normalize(right, angleBetweenScratch2);
  2460. var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
  2461. var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
  2462. return Math.atan2(sine, cosine);
  2463. };
  2464. var mostOrthogonalAxisScratch = new Cartesian3();
  2465. /**
  2466. * Returns the axis that is most orthogonal to the provided Cartesian.
  2467. *
  2468. * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
  2469. * @param {Cartesian3} result The object onto which to store the result.
  2470. * @returns {Cartesian3} The most orthogonal axis.
  2471. */
  2472. Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
  2473. Check.typeOf.object(cartesian, 'cartesian');
  2474. Check.typeOf.object(result, 'result');
  2475. var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
  2476. Cartesian3.abs(f, f);
  2477. if (f.x <= f.y) {
  2478. if (f.x <= f.z) {
  2479. result = Cartesian3.clone(Cartesian3.UNIT_X, result);
  2480. } else {
  2481. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  2482. }
  2483. } else {
  2484. if (f.y <= f.z) {
  2485. result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
  2486. } else {
  2487. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  2488. }
  2489. }
  2490. return result;
  2491. };
  2492. /**
  2493. * Compares the provided Cartesians componentwise and returns
  2494. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2495. *
  2496. * @param {Cartesian3} [left] The first Cartesian.
  2497. * @param {Cartesian3} [right] The second Cartesian.
  2498. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2499. */
  2500. Cartesian3.equals = function(left, right) {
  2501. return (left === right) ||
  2502. ((defined(left)) &&
  2503. (defined(right)) &&
  2504. (left.x === right.x) &&
  2505. (left.y === right.y) &&
  2506. (left.z === right.z));
  2507. };
  2508. /**
  2509. * @private
  2510. */
  2511. Cartesian3.equalsArray = function(cartesian, array, offset) {
  2512. return cartesian.x === array[offset] &&
  2513. cartesian.y === array[offset + 1] &&
  2514. cartesian.z === array[offset + 2];
  2515. };
  2516. /**
  2517. * Compares the provided Cartesians componentwise and returns
  2518. * <code>true</code> if they pass an absolute or relative tolerance test,
  2519. * <code>false</code> otherwise.
  2520. *
  2521. * @param {Cartesian3} [left] The first Cartesian.
  2522. * @param {Cartesian3} [right] The second Cartesian.
  2523. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2524. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2525. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2526. */
  2527. Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  2528. return (left === right) ||
  2529. (defined(left) &&
  2530. defined(right) &&
  2531. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  2532. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  2533. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
  2534. };
  2535. /**
  2536. * Computes the cross (outer) product of two Cartesians.
  2537. *
  2538. * @param {Cartesian3} left The first Cartesian.
  2539. * @param {Cartesian3} right The second Cartesian.
  2540. * @param {Cartesian3} result The object onto which to store the result.
  2541. * @returns {Cartesian3} The cross product.
  2542. */
  2543. Cartesian3.cross = function(left, right, result) {
  2544. Check.typeOf.object(left, 'left');
  2545. Check.typeOf.object(right, 'right');
  2546. Check.typeOf.object(result, 'result');
  2547. var leftX = left.x;
  2548. var leftY = left.y;
  2549. var leftZ = left.z;
  2550. var rightX = right.x;
  2551. var rightY = right.y;
  2552. var rightZ = right.z;
  2553. var x = leftY * rightZ - leftZ * rightY;
  2554. var y = leftZ * rightX - leftX * rightZ;
  2555. var z = leftX * rightY - leftY * rightX;
  2556. result.x = x;
  2557. result.y = y;
  2558. result.z = z;
  2559. return result;
  2560. };
  2561. /**
  2562. * Returns a Cartesian3 position from longitude and latitude values given in degrees.
  2563. *
  2564. * @param {Number} longitude The longitude, in degrees
  2565. * @param {Number} latitude The latitude, in degrees
  2566. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2567. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2568. * @param {Cartesian3} [result] The object onto which to store the result.
  2569. * @returns {Cartesian3} The position
  2570. *
  2571. * @example
  2572. * var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
  2573. */
  2574. Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
  2575. Check.typeOf.number(longitude, 'longitude');
  2576. Check.typeOf.number(latitude, 'latitude');
  2577. longitude = CesiumMath.toRadians(longitude);
  2578. latitude = CesiumMath.toRadians(latitude);
  2579. return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
  2580. };
  2581. var scratchN = new Cartesian3();
  2582. var scratchK = new Cartesian3();
  2583. var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
  2584. /**
  2585. * Returns a Cartesian3 position from longitude and latitude values given in radians.
  2586. *
  2587. * @param {Number} longitude The longitude, in radians
  2588. * @param {Number} latitude The latitude, in radians
  2589. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2590. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2591. * @param {Cartesian3} [result] The object onto which to store the result.
  2592. * @returns {Cartesian3} The position
  2593. *
  2594. * @example
  2595. * var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
  2596. */
  2597. Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
  2598. Check.typeOf.number(longitude, 'longitude');
  2599. Check.typeOf.number(latitude, 'latitude');
  2600. height = defaultValue(height, 0.0);
  2601. var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
  2602. var cosLatitude = Math.cos(latitude);
  2603. scratchN.x = cosLatitude * Math.cos(longitude);
  2604. scratchN.y = cosLatitude * Math.sin(longitude);
  2605. scratchN.z = Math.sin(latitude);
  2606. scratchN = Cartesian3.normalize(scratchN, scratchN);
  2607. Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
  2608. var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
  2609. scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
  2610. scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
  2611. if (!defined(result)) {
  2612. result = new Cartesian3();
  2613. }
  2614. return Cartesian3.add(scratchK, scratchN, result);
  2615. };
  2616. /**
  2617. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
  2618. *
  2619. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  2620. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  2621. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2622. * @returns {Cartesian3[]} The array of positions.
  2623. *
  2624. * @example
  2625. * var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
  2626. */
  2627. Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
  2628. Check.defined(coordinates, 'coordinates');
  2629. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  2630. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  2631. }
  2632. var length = coordinates.length;
  2633. if (!defined(result)) {
  2634. result = new Array(length / 2);
  2635. } else {
  2636. result.length = length / 2;
  2637. }
  2638. for (var i = 0; i < length; i += 2) {
  2639. var longitude = coordinates[i];
  2640. var latitude = coordinates[i + 1];
  2641. var index = i / 2;
  2642. result[index] = Cartesian3.fromDegrees(longitude, latitude, 0, ellipsoid, result[index]);
  2643. }
  2644. return result;
  2645. };
  2646. /**
  2647. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
  2648. *
  2649. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  2650. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  2651. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2652. * @returns {Cartesian3[]} The array of positions.
  2653. *
  2654. * @example
  2655. * var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
  2656. */
  2657. Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
  2658. Check.defined(coordinates, 'coordinates');
  2659. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  2660. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  2661. }
  2662. var length = coordinates.length;
  2663. if (!defined(result)) {
  2664. result = new Array(length / 2);
  2665. } else {
  2666. result.length = length / 2;
  2667. }
  2668. for (var i = 0; i < length; i += 2) {
  2669. var longitude = coordinates[i];
  2670. var latitude = coordinates[i + 1];
  2671. var index = i / 2;
  2672. result[index] = Cartesian3.fromRadians(longitude, latitude, 0, ellipsoid, result[index]);
  2673. }
  2674. return result;
  2675. };
  2676. /**
  2677. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
  2678. *
  2679. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  2680. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2681. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2682. * @returns {Cartesian3[]} The array of positions.
  2683. *
  2684. * @example
  2685. * var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
  2686. */
  2687. Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
  2688. Check.defined(coordinates, 'coordinates');
  2689. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  2690. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  2691. }
  2692. var length = coordinates.length;
  2693. if (!defined(result)) {
  2694. result = new Array(length / 3);
  2695. } else {
  2696. result.length = length / 3;
  2697. }
  2698. for (var i = 0; i < length; i += 3) {
  2699. var longitude = coordinates[i];
  2700. var latitude = coordinates[i + 1];
  2701. var height = coordinates[i + 2];
  2702. var index = i / 3;
  2703. result[index] = Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result[index]);
  2704. }
  2705. return result;
  2706. };
  2707. /**
  2708. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
  2709. *
  2710. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  2711. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2712. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2713. * @returns {Cartesian3[]} The array of positions.
  2714. *
  2715. * @example
  2716. * var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
  2717. */
  2718. Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
  2719. Check.defined(coordinates, 'coordinates');
  2720. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  2721. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  2722. }
  2723. var length = coordinates.length;
  2724. if (!defined(result)) {
  2725. result = new Array(length / 3);
  2726. } else {
  2727. result.length = length / 3;
  2728. }
  2729. for (var i = 0; i < length; i += 3) {
  2730. var longitude = coordinates[i];
  2731. var latitude = coordinates[i + 1];
  2732. var height = coordinates[i + 2];
  2733. var index = i / 3;
  2734. result[index] = Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result[index]);
  2735. }
  2736. return result;
  2737. };
  2738. /**
  2739. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
  2740. *
  2741. * @type {Cartesian3}
  2742. * @constant
  2743. */
  2744. Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
  2745. /**
  2746. * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
  2747. *
  2748. * @type {Cartesian3}
  2749. * @constant
  2750. */
  2751. Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
  2752. /**
  2753. * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
  2754. *
  2755. * @type {Cartesian3}
  2756. * @constant
  2757. */
  2758. Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
  2759. /**
  2760. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
  2761. *
  2762. * @type {Cartesian3}
  2763. * @constant
  2764. */
  2765. Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
  2766. /**
  2767. * Duplicates this Cartesian3 instance.
  2768. *
  2769. * @param {Cartesian3} [result] The object onto which to store the result.
  2770. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2771. */
  2772. Cartesian3.prototype.clone = function(result) {
  2773. return Cartesian3.clone(this, result);
  2774. };
  2775. /**
  2776. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2777. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2778. *
  2779. * @param {Cartesian3} [right] The right hand side Cartesian.
  2780. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2781. */
  2782. Cartesian3.prototype.equals = function(right) {
  2783. return Cartesian3.equals(this, right);
  2784. };
  2785. /**
  2786. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2787. * <code>true</code> if they pass an absolute or relative tolerance test,
  2788. * <code>false</code> otherwise.
  2789. *
  2790. * @param {Cartesian3} [right] The right hand side Cartesian.
  2791. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2792. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2793. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2794. */
  2795. Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  2796. return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  2797. };
  2798. /**
  2799. * Creates a string representing this Cartesian in the format '(x, y, z)'.
  2800. *
  2801. * @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
  2802. */
  2803. Cartesian3.prototype.toString = function() {
  2804. return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
  2805. };
  2806. return Cartesian3;
  2807. });
  2808. /*global define*/
  2809. define('Core/AttributeCompression',[
  2810. './Cartesian2',
  2811. './Cartesian3',
  2812. './defined',
  2813. './DeveloperError',
  2814. './Math'
  2815. ], function(
  2816. Cartesian2,
  2817. Cartesian3,
  2818. defined,
  2819. DeveloperError,
  2820. CesiumMath) {
  2821. 'use strict';
  2822. /**
  2823. * Attribute compression and decompression functions.
  2824. *
  2825. * @exports AttributeCompression
  2826. *
  2827. * @private
  2828. */
  2829. var AttributeCompression = {};
  2830. /**
  2831. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  2832. *
  2833. * Oct encoding is a compact representation of unit length vectors.
  2834. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  2835. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  2836. *
  2837. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  2838. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  2839. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  2840. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  2841. *
  2842. * @exception {DeveloperError} vector must be normalized.
  2843. *
  2844. * @see AttributeCompression.octDecodeInRange
  2845. */
  2846. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  2847. if (!defined(vector)) {
  2848. throw new DeveloperError('vector is required.');
  2849. }
  2850. if (!defined(result)) {
  2851. throw new DeveloperError('result is required.');
  2852. }
  2853. var magSquared = Cartesian3.magnitudeSquared(vector);
  2854. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  2855. throw new DeveloperError('vector must be normalized.');
  2856. }
  2857. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  2858. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  2859. if (vector.z < 0) {
  2860. var x = result.x;
  2861. var y = result.y;
  2862. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  2863. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  2864. }
  2865. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  2866. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  2867. return result;
  2868. };
  2869. /**
  2870. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  2871. *
  2872. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  2873. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  2874. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  2875. *
  2876. * @exception {DeveloperError} vector must be normalized.
  2877. *
  2878. * @see AttributeCompression.octEncodeInRange
  2879. * @see AttributeCompression.octDecode
  2880. */
  2881. AttributeCompression.octEncode = function(vector, result) {
  2882. return AttributeCompression.octEncodeInRange(vector, 255, result);
  2883. };
  2884. /**
  2885. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  2886. *
  2887. * @param {Number} x The x component of the oct-encoded unit length vector.
  2888. * @param {Number} y The y component of the oct-encoded unit length vector.
  2889. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  2890. * @param {Cartesian3} result The decoded and normalized vector
  2891. * @returns {Cartesian3} The decoded and normalized vector.
  2892. *
  2893. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  2894. *
  2895. * @see AttributeCompression.octEncodeInRange
  2896. */
  2897. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  2898. if (!defined(result)) {
  2899. throw new DeveloperError('result is required.');
  2900. }
  2901. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  2902. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  2903. }
  2904. result.x = CesiumMath.fromSNorm(x, rangeMax);
  2905. result.y = CesiumMath.fromSNorm(y, rangeMax);
  2906. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  2907. if (result.z < 0.0)
  2908. {
  2909. var oldVX = result.x;
  2910. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  2911. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  2912. }
  2913. return Cartesian3.normalize(result, result);
  2914. };
  2915. /**
  2916. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  2917. *
  2918. * @param {Number} x The x component of the oct-encoded unit length vector.
  2919. * @param {Number} y The y component of the oct-encoded unit length vector.
  2920. * @param {Cartesian3} result The decoded and normalized vector.
  2921. * @returns {Cartesian3} The decoded and normalized vector.
  2922. *
  2923. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  2924. *
  2925. * @see AttributeCompression.octDecodeInRange
  2926. */
  2927. AttributeCompression.octDecode = function(x, y, result) {
  2928. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  2929. };
  2930. /**
  2931. * Packs an oct encoded vector into a single floating-point number.
  2932. *
  2933. * @param {Cartesian2} encoded The oct encoded vector.
  2934. * @returns {Number} The oct encoded vector packed into a single float.
  2935. *
  2936. */
  2937. AttributeCompression.octPackFloat = function(encoded) {
  2938. if (!defined(encoded)) {
  2939. throw new DeveloperError('encoded is required.');
  2940. }
  2941. return 256.0 * encoded.x + encoded.y;
  2942. };
  2943. var scratchEncodeCart2 = new Cartesian2();
  2944. /**
  2945. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  2946. * stores those values in a single float-point number.
  2947. *
  2948. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  2949. * @returns {Number} The 2 byte oct-encoded unit length vector.
  2950. *
  2951. * @exception {DeveloperError} vector must be normalized.
  2952. */
  2953. AttributeCompression.octEncodeFloat = function(vector) {
  2954. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  2955. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  2956. };
  2957. /**
  2958. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  2959. *
  2960. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  2961. * @param {Cartesian3} result The decoded and normalized vector
  2962. * @returns {Cartesian3} The decoded and normalized vector.
  2963. *
  2964. */
  2965. AttributeCompression.octDecodeFloat = function(value, result) {
  2966. if (!defined(value)) {
  2967. throw new DeveloperError('value is required.');
  2968. }
  2969. var temp = value / 256.0;
  2970. var x = Math.floor(temp);
  2971. var y = (temp - x) * 256.0;
  2972. return AttributeCompression.octDecode(x, y, result);
  2973. };
  2974. /**
  2975. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  2976. * packs those into two floating-point numbers.
  2977. *
  2978. * @param {Cartesian3} v1 A normalized vector to be compressed.
  2979. * @param {Cartesian3} v2 A normalized vector to be compressed.
  2980. * @param {Cartesian3} v3 A normalized vector to be compressed.
  2981. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  2982. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  2983. *
  2984. */
  2985. AttributeCompression.octPack = function(v1, v2, v3, result) {
  2986. if (!defined(v1)) {
  2987. throw new DeveloperError('v1 is required.');
  2988. }
  2989. if (!defined(v2)) {
  2990. throw new DeveloperError('v2 is required.');
  2991. }
  2992. if (!defined(v3)) {
  2993. throw new DeveloperError('v3 is required.');
  2994. }
  2995. if (!defined(result)) {
  2996. throw new DeveloperError('result is required.');
  2997. }
  2998. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  2999. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  3000. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  3001. result.x = 65536.0 * encoded3.x + encoded1;
  3002. result.y = 65536.0 * encoded3.y + encoded2;
  3003. return result;
  3004. };
  3005. /**
  3006. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  3007. *
  3008. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  3009. * @param {Cartesian3} v1 One decoded and normalized vector.
  3010. * @param {Cartesian3} v2 One decoded and normalized vector.
  3011. * @param {Cartesian3} v3 One decoded and normalized vector.
  3012. */
  3013. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  3014. if (!defined(packed)) {
  3015. throw new DeveloperError('packed is required.');
  3016. }
  3017. if (!defined(v1)) {
  3018. throw new DeveloperError('v1 is required.');
  3019. }
  3020. if (!defined(v2)) {
  3021. throw new DeveloperError('v2 is required.');
  3022. }
  3023. if (!defined(v3)) {
  3024. throw new DeveloperError('v3 is required.');
  3025. }
  3026. var temp = packed.x / 65536.0;
  3027. var x = Math.floor(temp);
  3028. var encodedFloat1 = (temp - x) * 65536.0;
  3029. temp = packed.y / 65536.0;
  3030. var y = Math.floor(temp);
  3031. var encodedFloat2 = (temp - y) * 65536.0;
  3032. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  3033. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  3034. AttributeCompression.octDecode(x, y, v3);
  3035. };
  3036. /**
  3037. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  3038. *
  3039. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  3040. * @returns {Number} The packed texture coordinates.
  3041. *
  3042. */
  3043. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  3044. if (!defined(textureCoordinates)) {
  3045. throw new DeveloperError('textureCoordinates is required.');
  3046. }
  3047. // Move x and y to the range 0-4095;
  3048. var x = (textureCoordinates.x * 4095.0) | 0;
  3049. var y = (textureCoordinates.y * 4095.0) | 0;
  3050. return 4096.0 * x + y;
  3051. };
  3052. /**
  3053. * Decompresses texture coordinates that were packed into a single float.
  3054. *
  3055. * @param {Number} compressed The compressed texture coordinates.
  3056. * @param {Cartesian2} result The decompressed texture coordinates.
  3057. * @returns {Cartesian2} The modified result parameter.
  3058. *
  3059. */
  3060. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  3061. if (!defined(compressed)) {
  3062. throw new DeveloperError('compressed is required.');
  3063. }
  3064. if (!defined(result)) {
  3065. throw new DeveloperError('result is required.');
  3066. }
  3067. var temp = compressed / 4096.0;
  3068. var xZeroTo4095 = Math.floor(temp);
  3069. result.x = xZeroTo4095 / 4095.0;
  3070. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  3071. return result;
  3072. };
  3073. return AttributeCompression;
  3074. });
  3075. /*global define*/
  3076. define('Core/Intersect',[
  3077. './freezeObject'
  3078. ], function(
  3079. freezeObject) {
  3080. 'use strict';
  3081. /**
  3082. * This enumerated type is used in determining where, relative to the frustum, an
  3083. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3084. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3085. * outside of the frustum's 6 planes (OUTSIDE).
  3086. *
  3087. * @exports Intersect
  3088. */
  3089. var Intersect = {
  3090. /**
  3091. * Represents that an object is not contained within the frustum.
  3092. *
  3093. * @type {Number}
  3094. * @constant
  3095. */
  3096. OUTSIDE : -1,
  3097. /**
  3098. * Represents that an object intersects one of the frustum's planes.
  3099. *
  3100. * @type {Number}
  3101. * @constant
  3102. */
  3103. INTERSECTING : 0,
  3104. /**
  3105. * Represents that an object is fully within the frustum.
  3106. *
  3107. * @type {Number}
  3108. * @constant
  3109. */
  3110. INSIDE : 1
  3111. };
  3112. return freezeObject(Intersect);
  3113. });
  3114. /*global define*/
  3115. define('Core/AxisAlignedBoundingBox',[
  3116. './Cartesian3',
  3117. './defaultValue',
  3118. './defined',
  3119. './DeveloperError',
  3120. './Intersect'
  3121. ], function(
  3122. Cartesian3,
  3123. defaultValue,
  3124. defined,
  3125. DeveloperError,
  3126. Intersect) {
  3127. 'use strict';
  3128. /**
  3129. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  3130. * @alias AxisAlignedBoundingBox
  3131. * @constructor
  3132. *
  3133. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  3134. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  3135. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  3136. *
  3137. * @see BoundingSphere
  3138. * @see BoundingRectangle
  3139. */
  3140. function AxisAlignedBoundingBox(minimum, maximum, center) {
  3141. /**
  3142. * The minimum point defining the bounding box.
  3143. * @type {Cartesian3}
  3144. * @default {@link Cartesian3.ZERO}
  3145. */
  3146. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  3147. /**
  3148. * The maximum point defining the bounding box.
  3149. * @type {Cartesian3}
  3150. * @default {@link Cartesian3.ZERO}
  3151. */
  3152. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  3153. //If center was not defined, compute it.
  3154. if (!defined(center)) {
  3155. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  3156. Cartesian3.multiplyByScalar(center, 0.5, center);
  3157. } else {
  3158. center = Cartesian3.clone(center);
  3159. }
  3160. /**
  3161. * The center point of the bounding box.
  3162. * @type {Cartesian3}
  3163. */
  3164. this.center = center;
  3165. }
  3166. /**
  3167. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  3168. * finding the points spaced the farthest apart on the x, y, and z axes.
  3169. *
  3170. * @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.
  3171. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3172. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  3173. *
  3174. * @example
  3175. * // Compute an axis aligned bounding box enclosing two points.
  3176. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  3177. */
  3178. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  3179. if (!defined(result)) {
  3180. result = new AxisAlignedBoundingBox();
  3181. }
  3182. if (!defined(positions) || positions.length === 0) {
  3183. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  3184. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  3185. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  3186. return result;
  3187. }
  3188. var minimumX = positions[0].x;
  3189. var minimumY = positions[0].y;
  3190. var minimumZ = positions[0].z;
  3191. var maximumX = positions[0].x;
  3192. var maximumY = positions[0].y;
  3193. var maximumZ = positions[0].z;
  3194. var length = positions.length;
  3195. for ( var i = 1; i < length; i++) {
  3196. var p = positions[i];
  3197. var x = p.x;
  3198. var y = p.y;
  3199. var z = p.z;
  3200. minimumX = Math.min(x, minimumX);
  3201. maximumX = Math.max(x, maximumX);
  3202. minimumY = Math.min(y, minimumY);
  3203. maximumY = Math.max(y, maximumY);
  3204. minimumZ = Math.min(z, minimumZ);
  3205. maximumZ = Math.max(z, maximumZ);
  3206. }
  3207. var minimum = result.minimum;
  3208. minimum.x = minimumX;
  3209. minimum.y = minimumY;
  3210. minimum.z = minimumZ;
  3211. var maximum = result.maximum;
  3212. maximum.x = maximumX;
  3213. maximum.y = maximumY;
  3214. maximum.z = maximumZ;
  3215. var center = Cartesian3.add(minimum, maximum, result.center);
  3216. Cartesian3.multiplyByScalar(center, 0.5, center);
  3217. return result;
  3218. };
  3219. /**
  3220. * Duplicates a AxisAlignedBoundingBox instance.
  3221. *
  3222. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  3223. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3224. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  3225. */
  3226. AxisAlignedBoundingBox.clone = function(box, result) {
  3227. if (!defined(box)) {
  3228. return undefined;
  3229. }
  3230. if (!defined(result)) {
  3231. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  3232. }
  3233. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  3234. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  3235. result.center = Cartesian3.clone(box.center, result.center);
  3236. return result;
  3237. };
  3238. /**
  3239. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  3240. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3241. *
  3242. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  3243. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  3244. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3245. */
  3246. AxisAlignedBoundingBox.equals = function(left, right) {
  3247. return (left === right) ||
  3248. ((defined(left)) &&
  3249. (defined(right)) &&
  3250. Cartesian3.equals(left.center, right.center) &&
  3251. Cartesian3.equals(left.minimum, right.minimum) &&
  3252. Cartesian3.equals(left.maximum, right.maximum));
  3253. };
  3254. var intersectScratch = new Cartesian3();
  3255. /**
  3256. * Determines which side of a plane a box is located.
  3257. *
  3258. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  3259. * @param {Plane} plane The plane to test against.
  3260. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  3261. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  3262. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  3263. * intersects the plane.
  3264. */
  3265. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  3266. if (!defined(box)) {
  3267. throw new DeveloperError('box is required.');
  3268. }
  3269. if (!defined(plane)) {
  3270. throw new DeveloperError('plane is required.');
  3271. }
  3272. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  3273. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  3274. var normal = plane.normal;
  3275. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  3276. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  3277. if (s - e > 0) {
  3278. return Intersect.INSIDE;
  3279. }
  3280. if (s + e < 0) {
  3281. //Not in front because normals point inward
  3282. return Intersect.OUTSIDE;
  3283. }
  3284. return Intersect.INTERSECTING;
  3285. };
  3286. /**
  3287. * Duplicates this AxisAlignedBoundingBox instance.
  3288. *
  3289. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3290. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  3291. */
  3292. AxisAlignedBoundingBox.prototype.clone = function(result) {
  3293. return AxisAlignedBoundingBox.clone(this, result);
  3294. };
  3295. /**
  3296. * Determines which side of a plane this box is located.
  3297. *
  3298. * @param {Plane} plane The plane to test against.
  3299. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  3300. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  3301. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  3302. * intersects the plane.
  3303. */
  3304. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  3305. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  3306. };
  3307. /**
  3308. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  3309. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3310. *
  3311. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  3312. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3313. */
  3314. AxisAlignedBoundingBox.prototype.equals = function(right) {
  3315. return AxisAlignedBoundingBox.equals(this, right);
  3316. };
  3317. return AxisAlignedBoundingBox;
  3318. });
  3319. /*global define*/
  3320. define('Core/scaleToGeodeticSurface',[
  3321. './Cartesian3',
  3322. './defined',
  3323. './DeveloperError',
  3324. './Math'
  3325. ], function(
  3326. Cartesian3,
  3327. defined,
  3328. DeveloperError,
  3329. CesiumMath) {
  3330. 'use strict';
  3331. var scaleToGeodeticSurfaceIntersection = new Cartesian3();
  3332. var scaleToGeodeticSurfaceGradient = new Cartesian3();
  3333. /**
  3334. * Scales the provided Cartesian position along the geodetic surface normal
  3335. * so that it is on the surface of this ellipsoid. If the position is
  3336. * at the center of the ellipsoid, this function returns undefined.
  3337. *
  3338. * @param {Cartesian3} cartesian The Cartesian position to scale.
  3339. * @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
  3340. * @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
  3341. * @param {Number} centerToleranceSquared Tolerance for closeness to the center.
  3342. * @param {Cartesian3} [result] The object onto which to store the result.
  3343. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  3344. *
  3345. * @exports scaleToGeodeticSurface
  3346. *
  3347. * @private
  3348. */
  3349. function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
  3350. if (!defined(cartesian)) {
  3351. throw new DeveloperError('cartesian is required.');
  3352. }
  3353. if (!defined(oneOverRadii)) {
  3354. throw new DeveloperError('oneOverRadii is required.');
  3355. }
  3356. if (!defined(oneOverRadiiSquared)) {
  3357. throw new DeveloperError('oneOverRadiiSquared is required.');
  3358. }
  3359. if (!defined(centerToleranceSquared)) {
  3360. throw new DeveloperError('centerToleranceSquared is required.');
  3361. }
  3362. var positionX = cartesian.x;
  3363. var positionY = cartesian.y;
  3364. var positionZ = cartesian.z;
  3365. var oneOverRadiiX = oneOverRadii.x;
  3366. var oneOverRadiiY = oneOverRadii.y;
  3367. var oneOverRadiiZ = oneOverRadii.z;
  3368. var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  3369. var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  3370. var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  3371. // Compute the squared ellipsoid norm.
  3372. var squaredNorm = x2 + y2 + z2;
  3373. var ratio = Math.sqrt(1.0 / squaredNorm);
  3374. // As an initial approximation, assume that the radial intersection is the projection point.
  3375. var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
  3376. // If the position is near the center, the iteration will not converge.
  3377. if (squaredNorm < centerToleranceSquared) {
  3378. return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
  3379. }
  3380. var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  3381. var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  3382. var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  3383. // Use the gradient at the intersection point in place of the true unit normal.
  3384. // The difference in magnitude will be absorbed in the multiplier.
  3385. var gradient = scaleToGeodeticSurfaceGradient;
  3386. gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
  3387. gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
  3388. gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
  3389. // Compute the initial guess at the normal vector multiplier, lambda.
  3390. var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
  3391. var correction = 0.0;
  3392. var func;
  3393. var denominator;
  3394. var xMultiplier;
  3395. var yMultiplier;
  3396. var zMultiplier;
  3397. var xMultiplier2;
  3398. var yMultiplier2;
  3399. var zMultiplier2;
  3400. var xMultiplier3;
  3401. var yMultiplier3;
  3402. var zMultiplier3;
  3403. do {
  3404. lambda -= correction;
  3405. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  3406. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  3407. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  3408. xMultiplier2 = xMultiplier * xMultiplier;
  3409. yMultiplier2 = yMultiplier * yMultiplier;
  3410. zMultiplier2 = zMultiplier * zMultiplier;
  3411. xMultiplier3 = xMultiplier2 * xMultiplier;
  3412. yMultiplier3 = yMultiplier2 * yMultiplier;
  3413. zMultiplier3 = zMultiplier2 * zMultiplier;
  3414. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  3415. // "denominator" here refers to the use of this expression in the velocity and acceleration
  3416. // computations in the sections to follow.
  3417. denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  3418. var derivative = -2.0 * denominator;
  3419. correction = func / derivative;
  3420. } while (Math.abs(func) > CesiumMath.EPSILON12);
  3421. if (!defined(result)) {
  3422. return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
  3423. }
  3424. result.x = positionX * xMultiplier;
  3425. result.y = positionY * yMultiplier;
  3426. result.z = positionZ * zMultiplier;
  3427. return result;
  3428. }
  3429. return scaleToGeodeticSurface;
  3430. });
  3431. /*global define*/
  3432. define('Core/Cartographic',[
  3433. './Cartesian3',
  3434. './defaultValue',
  3435. './defined',
  3436. './DeveloperError',
  3437. './freezeObject',
  3438. './Math',
  3439. './scaleToGeodeticSurface'
  3440. ], function(
  3441. Cartesian3,
  3442. defaultValue,
  3443. defined,
  3444. DeveloperError,
  3445. freezeObject,
  3446. CesiumMath,
  3447. scaleToGeodeticSurface) {
  3448. 'use strict';
  3449. /**
  3450. * A position defined by longitude, latitude, and height.
  3451. * @alias Cartographic
  3452. * @constructor
  3453. *
  3454. * @param {Number} [longitude=0.0] The longitude, in radians.
  3455. * @param {Number} [latitude=0.0] The latitude, in radians.
  3456. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  3457. *
  3458. * @see Ellipsoid
  3459. */
  3460. function Cartographic(longitude, latitude, height) {
  3461. /**
  3462. * The longitude, in radians.
  3463. * @type {Number}
  3464. * @default 0.0
  3465. */
  3466. this.longitude = defaultValue(longitude, 0.0);
  3467. /**
  3468. * The latitude, in radians.
  3469. * @type {Number}
  3470. * @default 0.0
  3471. */
  3472. this.latitude = defaultValue(latitude, 0.0);
  3473. /**
  3474. * The height, in meters, above the ellipsoid.
  3475. * @type {Number}
  3476. * @default 0.0
  3477. */
  3478. this.height = defaultValue(height, 0.0);
  3479. }
  3480. /**
  3481. * Creates a new Cartographic instance from longitude and latitude
  3482. * specified in radians.
  3483. *
  3484. * @param {Number} longitude The longitude, in radians.
  3485. * @param {Number} latitude The latitude, in radians.
  3486. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  3487. * @param {Cartographic} [result] The object onto which to store the result.
  3488. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  3489. */
  3490. Cartographic.fromRadians = function(longitude, latitude, height, result) {
  3491. if (!defined(longitude)) {
  3492. throw new DeveloperError('longitude is required.');
  3493. }
  3494. if (!defined(latitude)) {
  3495. throw new DeveloperError('latitude is required.');
  3496. }
  3497. height = defaultValue(height, 0.0);
  3498. if (!defined(result)) {
  3499. return new Cartographic(longitude, latitude, height);
  3500. }
  3501. result.longitude = longitude;
  3502. result.latitude = latitude;
  3503. result.height = height;
  3504. return result;
  3505. };
  3506. /**
  3507. * Creates a new Cartographic instance from longitude and latitude
  3508. * specified in degrees. The values in the resulting object will
  3509. * be in radians.
  3510. *
  3511. * @param {Number} longitude The longitude, in degrees.
  3512. * @param {Number} latitude The latitude, in degrees.
  3513. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  3514. * @param {Cartographic} [result] The object onto which to store the result.
  3515. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  3516. */
  3517. Cartographic.fromDegrees = function(longitude, latitude, height, result) {
  3518. if (!defined(longitude)) {
  3519. throw new DeveloperError('longitude is required.');
  3520. }
  3521. if (!defined(latitude)) {
  3522. throw new DeveloperError('latitude is required.');
  3523. }
  3524. longitude = CesiumMath.toRadians(longitude);
  3525. latitude = CesiumMath.toRadians(latitude);
  3526. return Cartographic.fromRadians(longitude, latitude, height, result);
  3527. };
  3528. var cartesianToCartographicN = new Cartesian3();
  3529. var cartesianToCartographicP = new Cartesian3();
  3530. var cartesianToCartographicH = new Cartesian3();
  3531. var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
  3532. var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
  3533. var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;
  3534. /**
  3535. * Creates a new Cartographic instance from a Cartesian position. The values in the
  3536. * resulting object will be in radians.
  3537. *
  3538. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  3539. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  3540. * @param {Cartographic} [result] The object onto which to store the result.
  3541. * @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.
  3542. */
  3543. Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
  3544. var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
  3545. var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
  3546. var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
  3547. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  3548. var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);
  3549. if (!defined(p)) {
  3550. return undefined;
  3551. }
  3552. var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
  3553. n = Cartesian3.normalize(n, n);
  3554. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  3555. var longitude = Math.atan2(n.y, n.x);
  3556. var latitude = Math.asin(n.z);
  3557. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  3558. if (!defined(result)) {
  3559. return new Cartographic(longitude, latitude, height);
  3560. }
  3561. result.longitude = longitude;
  3562. result.latitude = latitude;
  3563. result.height = height;
  3564. return result;
  3565. };
  3566. /**
  3567. * Duplicates a Cartographic instance.
  3568. *
  3569. * @param {Cartographic} cartographic The cartographic to duplicate.
  3570. * @param {Cartographic} [result] The object onto which to store the result.
  3571. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
  3572. */
  3573. Cartographic.clone = function(cartographic, result) {
  3574. if (!defined(cartographic)) {
  3575. return undefined;
  3576. }
  3577. if (!defined(result)) {
  3578. return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
  3579. }
  3580. result.longitude = cartographic.longitude;
  3581. result.latitude = cartographic.latitude;
  3582. result.height = cartographic.height;
  3583. return result;
  3584. };
  3585. /**
  3586. * Compares the provided cartographics componentwise and returns
  3587. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3588. *
  3589. * @param {Cartographic} [left] The first cartographic.
  3590. * @param {Cartographic} [right] The second cartographic.
  3591. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3592. */
  3593. Cartographic.equals = function(left, right) {
  3594. return (left === right) ||
  3595. ((defined(left)) &&
  3596. (defined(right)) &&
  3597. (left.longitude === right.longitude) &&
  3598. (left.latitude === right.latitude) &&
  3599. (left.height === right.height));
  3600. };
  3601. /**
  3602. * Compares the provided cartographics componentwise and returns
  3603. * <code>true</code> if they are within the provided epsilon,
  3604. * <code>false</code> otherwise.
  3605. *
  3606. * @param {Cartographic} [left] The first cartographic.
  3607. * @param {Cartographic} [right] The second cartographic.
  3608. * @param {Number} epsilon The epsilon to use for equality testing.
  3609. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3610. */
  3611. Cartographic.equalsEpsilon = function(left, right, epsilon) {
  3612. if (typeof epsilon !== 'number') {
  3613. throw new DeveloperError('epsilon is required and must be a number.');
  3614. }
  3615. return (left === right) ||
  3616. ((defined(left)) &&
  3617. (defined(right)) &&
  3618. (Math.abs(left.longitude - right.longitude) <= epsilon) &&
  3619. (Math.abs(left.latitude - right.latitude) <= epsilon) &&
  3620. (Math.abs(left.height - right.height) <= epsilon));
  3621. };
  3622. /**
  3623. * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
  3624. *
  3625. * @type {Cartographic}
  3626. * @constant
  3627. */
  3628. Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
  3629. /**
  3630. * Duplicates this instance.
  3631. *
  3632. * @param {Cartographic} [result] The object onto which to store the result.
  3633. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  3634. */
  3635. Cartographic.prototype.clone = function(result) {
  3636. return Cartographic.clone(this, result);
  3637. };
  3638. /**
  3639. * Compares the provided against this cartographic componentwise and returns
  3640. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3641. *
  3642. * @param {Cartographic} [right] The second cartographic.
  3643. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3644. */
  3645. Cartographic.prototype.equals = function(right) {
  3646. return Cartographic.equals(this, right);
  3647. };
  3648. /**
  3649. * Compares the provided against this cartographic componentwise and returns
  3650. * <code>true</code> if they are within the provided epsilon,
  3651. * <code>false</code> otherwise.
  3652. *
  3653. * @param {Cartographic} [right] The second cartographic.
  3654. * @param {Number} epsilon The epsilon to use for equality testing.
  3655. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3656. */
  3657. Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
  3658. return Cartographic.equalsEpsilon(this, right, epsilon);
  3659. };
  3660. /**
  3661. * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
  3662. *
  3663. * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
  3664. */
  3665. Cartographic.prototype.toString = function() {
  3666. return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
  3667. };
  3668. return Cartographic;
  3669. });
  3670. /*global define*/
  3671. define('Core/defineProperties',[
  3672. './defined'
  3673. ], function(
  3674. defined) {
  3675. 'use strict';
  3676. var definePropertyWorks = (function() {
  3677. try {
  3678. return 'x' in Object.defineProperty({}, 'x', {});
  3679. } catch (e) {
  3680. return false;
  3681. }
  3682. })();
  3683. /**
  3684. * Defines properties on an object, using Object.defineProperties if available,
  3685. * otherwise returns the object unchanged. This function should be used in
  3686. * setup code to prevent errors from completely halting JavaScript execution
  3687. * in legacy browsers.
  3688. *
  3689. * @private
  3690. *
  3691. * @exports defineProperties
  3692. */
  3693. var defineProperties = Object.defineProperties;
  3694. if (!definePropertyWorks || !defined(defineProperties)) {
  3695. defineProperties = function(o) {
  3696. return o;
  3697. };
  3698. }
  3699. return defineProperties;
  3700. });
  3701. /*global define*/
  3702. define('Core/Ellipsoid',[
  3703. './Cartesian3',
  3704. './Cartographic',
  3705. './defaultValue',
  3706. './defined',
  3707. './defineProperties',
  3708. './DeveloperError',
  3709. './freezeObject',
  3710. './Math',
  3711. './scaleToGeodeticSurface'
  3712. ], function(
  3713. Cartesian3,
  3714. Cartographic,
  3715. defaultValue,
  3716. defined,
  3717. defineProperties,
  3718. DeveloperError,
  3719. freezeObject,
  3720. CesiumMath,
  3721. scaleToGeodeticSurface) {
  3722. 'use strict';
  3723. function initialize(ellipsoid, x, y, z) {
  3724. x = defaultValue(x, 0.0);
  3725. y = defaultValue(y, 0.0);
  3726. z = defaultValue(z, 0.0);
  3727. if (x < 0.0 || y < 0.0 || z < 0.0) {
  3728. throw new DeveloperError('All radii components must be greater than or equal to zero.');
  3729. }
  3730. ellipsoid._radii = new Cartesian3(x, y, z);
  3731. ellipsoid._radiiSquared = new Cartesian3(x * x,
  3732. y * y,
  3733. z * z);
  3734. ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
  3735. y * y * y * y,
  3736. z * z * z * z);
  3737. ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
  3738. y === 0.0 ? 0.0 : 1.0 / y,
  3739. z === 0.0 ? 0.0 : 1.0 / z);
  3740. ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
  3741. y === 0.0 ? 0.0 : 1.0 / (y * y),
  3742. z === 0.0 ? 0.0 : 1.0 / (z * z));
  3743. ellipsoid._minimumRadius = Math.min(x, y, z);
  3744. ellipsoid._maximumRadius = Math.max(x, y, z);
  3745. ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
  3746. if (ellipsoid._radiiSquared.z !== 0) {
  3747. ellipsoid._sqauredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
  3748. }
  3749. }
  3750. /**
  3751. * A quadratic surface defined in Cartesian coordinates by the equation
  3752. * <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
  3753. * by Cesium to represent the shape of planetary bodies.
  3754. *
  3755. * Rather than constructing this object directly, one of the provided
  3756. * constants is normally used.
  3757. * @alias Ellipsoid
  3758. * @constructor
  3759. *
  3760. * @param {Number} [x=0] The radius in the x direction.
  3761. * @param {Number} [y=0] The radius in the y direction.
  3762. * @param {Number} [z=0] The radius in the z direction.
  3763. *
  3764. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  3765. *
  3766. * @see Ellipsoid.fromCartesian3
  3767. * @see Ellipsoid.WGS84
  3768. * @see Ellipsoid.UNIT_SPHERE
  3769. */
  3770. function Ellipsoid(x, y, z) {
  3771. this._radii = undefined;
  3772. this._radiiSquared = undefined;
  3773. this._radiiToTheFourth = undefined;
  3774. this._oneOverRadii = undefined;
  3775. this._oneOverRadiiSquared = undefined;
  3776. this._minimumRadius = undefined;
  3777. this._maximumRadius = undefined;
  3778. this._centerToleranceSquared = undefined;
  3779. this._sqauredXOverSquaredZ = undefined;
  3780. initialize(this, x, y, z);
  3781. }
  3782. defineProperties(Ellipsoid.prototype, {
  3783. /**
  3784. * Gets the radii of the ellipsoid.
  3785. * @memberof Ellipsoid.prototype
  3786. * @type {Cartesian3}
  3787. * @readonly
  3788. */
  3789. radii : {
  3790. get: function() {
  3791. return this._radii;
  3792. }
  3793. },
  3794. /**
  3795. * Gets the squared radii of the ellipsoid.
  3796. * @memberof Ellipsoid.prototype
  3797. * @type {Cartesian3}
  3798. * @readonly
  3799. */
  3800. radiiSquared : {
  3801. get : function() {
  3802. return this._radiiSquared;
  3803. }
  3804. },
  3805. /**
  3806. * Gets the radii of the ellipsoid raise to the fourth power.
  3807. * @memberof Ellipsoid.prototype
  3808. * @type {Cartesian3}
  3809. * @readonly
  3810. */
  3811. radiiToTheFourth : {
  3812. get : function() {
  3813. return this._radiiToTheFourth;
  3814. }
  3815. },
  3816. /**
  3817. * Gets one over the radii of the ellipsoid.
  3818. * @memberof Ellipsoid.prototype
  3819. * @type {Cartesian3}
  3820. * @readonly
  3821. */
  3822. oneOverRadii : {
  3823. get : function() {
  3824. return this._oneOverRadii;
  3825. }
  3826. },
  3827. /**
  3828. * Gets one over the squared radii of the ellipsoid.
  3829. * @memberof Ellipsoid.prototype
  3830. * @type {Cartesian3}
  3831. * @readonly
  3832. */
  3833. oneOverRadiiSquared : {
  3834. get : function() {
  3835. return this._oneOverRadiiSquared;
  3836. }
  3837. },
  3838. /**
  3839. * Gets the minimum radius of the ellipsoid.
  3840. * @memberof Ellipsoid.prototype
  3841. * @type {Number}
  3842. * @readonly
  3843. */
  3844. minimumRadius : {
  3845. get : function() {
  3846. return this._minimumRadius;
  3847. }
  3848. },
  3849. /**
  3850. * Gets the maximum radius of the ellipsoid.
  3851. * @memberof Ellipsoid.prototype
  3852. * @type {Number}
  3853. * @readonly
  3854. */
  3855. maximumRadius : {
  3856. get : function() {
  3857. return this._maximumRadius;
  3858. }
  3859. }
  3860. });
  3861. /**
  3862. * Duplicates an Ellipsoid instance.
  3863. *
  3864. * @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
  3865. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  3866. * instance should be created.
  3867. * @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
  3868. */
  3869. Ellipsoid.clone = function(ellipsoid, result) {
  3870. if (!defined(ellipsoid)) {
  3871. return undefined;
  3872. }
  3873. var radii = ellipsoid._radii;
  3874. if (!defined(result)) {
  3875. return new Ellipsoid(radii.x, radii.y, radii.z);
  3876. }
  3877. Cartesian3.clone(radii, result._radii);
  3878. Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
  3879. Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
  3880. Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
  3881. Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
  3882. result._minimumRadius = ellipsoid._minimumRadius;
  3883. result._maximumRadius = ellipsoid._maximumRadius;
  3884. result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
  3885. return result;
  3886. };
  3887. /**
  3888. * Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
  3889. *
  3890. * @param {Cartesian3} [radii=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
  3891. * @returns {Ellipsoid} A new Ellipsoid instance.
  3892. *
  3893. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  3894. *
  3895. * @see Ellipsoid.WGS84
  3896. * @see Ellipsoid.UNIT_SPHERE
  3897. */
  3898. Ellipsoid.fromCartesian3 = function(cartesian, result) {
  3899. if (!defined(result)) {
  3900. result = new Ellipsoid();
  3901. }
  3902. if (!defined(cartesian)) {
  3903. return result;
  3904. }
  3905. initialize(result, cartesian.x, cartesian.y, cartesian.z);
  3906. return result;
  3907. };
  3908. /**
  3909. * An Ellipsoid instance initialized to the WGS84 standard.
  3910. *
  3911. * @type {Ellipsoid}
  3912. * @constant
  3913. */
  3914. Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
  3915. /**
  3916. * An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
  3917. *
  3918. * @type {Ellipsoid}
  3919. * @constant
  3920. */
  3921. Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
  3922. /**
  3923. * An Ellipsoid instance initialized to a sphere with the lunar radius.
  3924. *
  3925. * @type {Ellipsoid}
  3926. * @constant
  3927. */
  3928. Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
  3929. /**
  3930. * Duplicates an Ellipsoid instance.
  3931. *
  3932. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  3933. * instance should be created.
  3934. * @returns {Ellipsoid} The cloned Ellipsoid.
  3935. */
  3936. Ellipsoid.prototype.clone = function(result) {
  3937. return Ellipsoid.clone(this, result);
  3938. };
  3939. /**
  3940. * The number of elements used to pack the object into an array.
  3941. * @type {Number}
  3942. */
  3943. Ellipsoid.packedLength = Cartesian3.packedLength;
  3944. /**
  3945. * Stores the provided instance into the provided array.
  3946. *
  3947. * @param {Ellipsoid} value The value to pack.
  3948. * @param {Number[]} array The array to pack into.
  3949. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3950. *
  3951. * @returns {Number[]} The array that was packed into
  3952. */
  3953. Ellipsoid.pack = function(value, array, startingIndex) {
  3954. if (!defined(value)) {
  3955. throw new DeveloperError('value is required');
  3956. }
  3957. if (!defined(array)) {
  3958. throw new DeveloperError('array is required');
  3959. }
  3960. startingIndex = defaultValue(startingIndex, 0);
  3961. Cartesian3.pack(value._radii, array, startingIndex);
  3962. return array;
  3963. };
  3964. /**
  3965. * Retrieves an instance from a packed array.
  3966. *
  3967. * @param {Number[]} array The packed array.
  3968. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3969. * @param {Ellipsoid} [result] The object into which to store the result.
  3970. * @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
  3971. */
  3972. Ellipsoid.unpack = function(array, startingIndex, result) {
  3973. if (!defined(array)) {
  3974. throw new DeveloperError('array is required');
  3975. }
  3976. startingIndex = defaultValue(startingIndex, 0);
  3977. var radii = Cartesian3.unpack(array, startingIndex);
  3978. return Ellipsoid.fromCartesian3(radii, result);
  3979. };
  3980. /**
  3981. * Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
  3982. * @function
  3983. *
  3984. * @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
  3985. * @param {Cartesian3} [result] The object onto which to store the result.
  3986. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  3987. */
  3988. Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
  3989. /**
  3990. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  3991. *
  3992. * @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
  3993. * @param {Cartesian3} [result] The object onto which to store the result.
  3994. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  3995. */
  3996. Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
  3997. if (!defined(cartographic)) {
  3998. throw new DeveloperError('cartographic is required.');
  3999. }
  4000. var longitude = cartographic.longitude;
  4001. var latitude = cartographic.latitude;
  4002. var cosLatitude = Math.cos(latitude);
  4003. var x = cosLatitude * Math.cos(longitude);
  4004. var y = cosLatitude * Math.sin(longitude);
  4005. var z = Math.sin(latitude);
  4006. if (!defined(result)) {
  4007. result = new Cartesian3();
  4008. }
  4009. result.x = x;
  4010. result.y = y;
  4011. result.z = z;
  4012. return Cartesian3.normalize(result, result);
  4013. };
  4014. /**
  4015. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  4016. *
  4017. * @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
  4018. * @param {Cartesian3} [result] The object onto which to store the result.
  4019. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  4020. */
  4021. Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
  4022. if (!defined(result)) {
  4023. result = new Cartesian3();
  4024. }
  4025. result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
  4026. return Cartesian3.normalize(result, result);
  4027. };
  4028. var cartographicToCartesianNormal = new Cartesian3();
  4029. var cartographicToCartesianK = new Cartesian3();
  4030. /**
  4031. * Converts the provided cartographic to Cartesian representation.
  4032. *
  4033. * @param {Cartographic} cartographic The cartographic position.
  4034. * @param {Cartesian3} [result] The object onto which to store the result.
  4035. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  4036. *
  4037. * @example
  4038. * //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
  4039. * var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
  4040. * var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
  4041. */
  4042. Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
  4043. //`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
  4044. var n = cartographicToCartesianNormal;
  4045. var k = cartographicToCartesianK;
  4046. this.geodeticSurfaceNormalCartographic(cartographic, n);
  4047. Cartesian3.multiplyComponents(this._radiiSquared, n, k);
  4048. var gamma = Math.sqrt(Cartesian3.dot(n, k));
  4049. Cartesian3.divideByScalar(k, gamma, k);
  4050. Cartesian3.multiplyByScalar(n, cartographic.height, n);
  4051. if (!defined(result)) {
  4052. result = new Cartesian3();
  4053. }
  4054. return Cartesian3.add(k, n, result);
  4055. };
  4056. /**
  4057. * Converts the provided array of cartographics to an array of Cartesians.
  4058. *
  4059. * @param {Cartographic[]} cartographics An array of cartographic positions.
  4060. * @param {Cartesian3[]} [result] The object onto which to store the result.
  4061. * @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
  4062. *
  4063. * @example
  4064. * //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
  4065. * var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
  4066. * new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
  4067. * new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
  4068. * var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
  4069. */
  4070. Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
  4071. if (!defined(cartographics)) {
  4072. throw new DeveloperError('cartographics is required.');
  4073. }
  4074. var length = cartographics.length;
  4075. if (!defined(result)) {
  4076. result = new Array(length);
  4077. } else {
  4078. result.length = length;
  4079. }
  4080. for ( var i = 0; i < length; i++) {
  4081. result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
  4082. }
  4083. return result;
  4084. };
  4085. var cartesianToCartographicN = new Cartesian3();
  4086. var cartesianToCartographicP = new Cartesian3();
  4087. var cartesianToCartographicH = new Cartesian3();
  4088. /**
  4089. * Converts the provided cartesian to cartographic representation.
  4090. * The cartesian is undefined at the center of the ellipsoid.
  4091. *
  4092. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  4093. * @param {Cartographic} [result] The object onto which to store the result.
  4094. * @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.
  4095. *
  4096. * @example
  4097. * //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
  4098. * var position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
  4099. * var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
  4100. */
  4101. Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
  4102. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  4103. var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
  4104. if (!defined(p)) {
  4105. return undefined;
  4106. }
  4107. var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
  4108. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  4109. var longitude = Math.atan2(n.y, n.x);
  4110. var latitude = Math.asin(n.z);
  4111. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  4112. if (!defined(result)) {
  4113. return new Cartographic(longitude, latitude, height);
  4114. }
  4115. result.longitude = longitude;
  4116. result.latitude = latitude;
  4117. result.height = height;
  4118. return result;
  4119. };
  4120. /**
  4121. * Converts the provided array of cartesians to an array of cartographics.
  4122. *
  4123. * @param {Cartesian3[]} cartesians An array of Cartesian positions.
  4124. * @param {Cartographic[]} [result] The object onto which to store the result.
  4125. * @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
  4126. *
  4127. * @example
  4128. * //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
  4129. * var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
  4130. * new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
  4131. * new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
  4132. * var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
  4133. */
  4134. Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
  4135. if (!defined(cartesians)) {
  4136. throw new DeveloperError('cartesians is required.');
  4137. }
  4138. var length = cartesians.length;
  4139. if (!defined(result)) {
  4140. result = new Array(length);
  4141. } else {
  4142. result.length = length;
  4143. }
  4144. for ( var i = 0; i < length; ++i) {
  4145. result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
  4146. }
  4147. return result;
  4148. };
  4149. /**
  4150. * Scales the provided Cartesian position along the geodetic surface normal
  4151. * so that it is on the surface of this ellipsoid. If the position is
  4152. * at the center of the ellipsoid, this function returns undefined.
  4153. *
  4154. * @param {Cartesian3} cartesian The Cartesian position to scale.
  4155. * @param {Cartesian3} [result] The object onto which to store the result.
  4156. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  4157. */
  4158. Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
  4159. return scaleToGeodeticSurface(cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result);
  4160. };
  4161. /**
  4162. * Scales the provided Cartesian position along the geocentric surface normal
  4163. * so that it is on the surface of this ellipsoid.
  4164. *
  4165. * @param {Cartesian3} cartesian The Cartesian position to scale.
  4166. * @param {Cartesian3} [result] The object onto which to store the result.
  4167. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  4168. */
  4169. Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
  4170. if (!defined(cartesian)) {
  4171. throw new DeveloperError('cartesian is required.');
  4172. }
  4173. if (!defined(result)) {
  4174. result = new Cartesian3();
  4175. }
  4176. var positionX = cartesian.x;
  4177. var positionY = cartesian.y;
  4178. var positionZ = cartesian.z;
  4179. var oneOverRadiiSquared = this._oneOverRadiiSquared;
  4180. var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
  4181. (positionY * positionY) * oneOverRadiiSquared.y +
  4182. (positionZ * positionZ) * oneOverRadiiSquared.z);
  4183. return Cartesian3.multiplyByScalar(cartesian, beta, result);
  4184. };
  4185. /**
  4186. * Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
  4187. * its components by the result of {@link Ellipsoid#oneOverRadii}.
  4188. *
  4189. * @param {Cartesian3} position The position to transform.
  4190. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  4191. * return a new instance.
  4192. * @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
  4193. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  4194. */
  4195. Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
  4196. if (!defined(result)) {
  4197. result = new Cartesian3();
  4198. }
  4199. return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
  4200. };
  4201. /**
  4202. * Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
  4203. * its components by the result of {@link Ellipsoid#radii}.
  4204. *
  4205. * @param {Cartesian3} position The position to transform.
  4206. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  4207. * return a new instance.
  4208. * @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
  4209. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  4210. */
  4211. Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
  4212. if (!defined(result)) {
  4213. result = new Cartesian3();
  4214. }
  4215. return Cartesian3.multiplyComponents(position, this._radii, result);
  4216. };
  4217. /**
  4218. * Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
  4219. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4220. *
  4221. * @param {Ellipsoid} [right] The other Ellipsoid.
  4222. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4223. */
  4224. Ellipsoid.prototype.equals = function(right) {
  4225. return (this === right) ||
  4226. (defined(right) &&
  4227. Cartesian3.equals(this._radii, right._radii));
  4228. };
  4229. /**
  4230. * Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  4231. *
  4232. * @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  4233. */
  4234. Ellipsoid.prototype.toString = function() {
  4235. return this._radii.toString();
  4236. };
  4237. /**
  4238. * Computes a point which is the intersection of the surface normal with the z-axis.
  4239. *
  4240. * @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
  4241. * @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
  4242. * 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.
  4243. * In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
  4244. * Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
  4245. * @param {Cartesian} [result] The cartesian to which to copy the result, or undefined to create and
  4246. * return a new instance.
  4247. * @returns {Cartesian | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
  4248. *
  4249. * @exception {DeveloperError} position is required.
  4250. * @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
  4251. * @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
  4252. */
  4253. Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
  4254. if (!defined(position)) {
  4255. throw new DeveloperError('position is required.');
  4256. }
  4257. if (!CesiumMath.equalsEpsilon(this._radii.x, this._radii.y, CesiumMath.EPSILON15)) {
  4258. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  4259. }
  4260. if (this._radii.z === 0) {
  4261. throw new DeveloperError('Ellipsoid.radii.z must be greater than 0');
  4262. }
  4263. buffer = defaultValue(buffer, 0.0);
  4264. var sqauredXOverSquaredZ = this._sqauredXOverSquaredZ;
  4265. if (!defined(result)) {
  4266. result = new Cartesian3();
  4267. }
  4268. result.x = 0.0;
  4269. result.y = 0.0;
  4270. result.z = position.z * (1 - sqauredXOverSquaredZ);
  4271. if (Math.abs(result.z) >= this._radii.z - buffer) {
  4272. return undefined;
  4273. }
  4274. return result;
  4275. };
  4276. return Ellipsoid;
  4277. });
  4278. /*global define*/
  4279. define('Core/GeographicProjection',[
  4280. './Cartesian3',
  4281. './Cartographic',
  4282. './defaultValue',
  4283. './defined',
  4284. './defineProperties',
  4285. './DeveloperError',
  4286. './Ellipsoid'
  4287. ], function(
  4288. Cartesian3,
  4289. Cartographic,
  4290. defaultValue,
  4291. defined,
  4292. defineProperties,
  4293. DeveloperError,
  4294. Ellipsoid) {
  4295. 'use strict';
  4296. /**
  4297. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  4298. * them by the {@link Ellipsoid#maximumRadius}. This projection
  4299. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  4300. * is also known as EPSG:4326.
  4301. *
  4302. * @alias GeographicProjection
  4303. * @constructor
  4304. *
  4305. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  4306. *
  4307. * @see WebMercatorProjection
  4308. */
  4309. function GeographicProjection(ellipsoid) {
  4310. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  4311. this._semimajorAxis = this._ellipsoid.maximumRadius;
  4312. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  4313. }
  4314. defineProperties(GeographicProjection.prototype, {
  4315. /**
  4316. * Gets the {@link Ellipsoid}.
  4317. *
  4318. * @memberof GeographicProjection.prototype
  4319. *
  4320. * @type {Ellipsoid}
  4321. * @readonly
  4322. */
  4323. ellipsoid : {
  4324. get : function() {
  4325. return this._ellipsoid;
  4326. }
  4327. }
  4328. });
  4329. /**
  4330. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  4331. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  4332. * ellipsoid. Z is the unmodified height.
  4333. *
  4334. * @param {Cartographic} cartographic The coordinates to project.
  4335. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  4336. * undefined, a new instance is created and returned.
  4337. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  4338. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  4339. * created and returned.
  4340. */
  4341. GeographicProjection.prototype.project = function(cartographic, result) {
  4342. // Actually this is the special case of equidistant cylindrical called the plate carree
  4343. var semimajorAxis = this._semimajorAxis;
  4344. var x = cartographic.longitude * semimajorAxis;
  4345. var y = cartographic.latitude * semimajorAxis;
  4346. var z = cartographic.height;
  4347. if (!defined(result)) {
  4348. return new Cartesian3(x, y, z);
  4349. }
  4350. result.x = x;
  4351. result.y = y;
  4352. result.z = z;
  4353. return result;
  4354. };
  4355. /**
  4356. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  4357. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  4358. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  4359. *
  4360. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  4361. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  4362. * undefined, a new instance is created and returned.
  4363. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  4364. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  4365. * created and returned.
  4366. */
  4367. GeographicProjection.prototype.unproject = function(cartesian, result) {
  4368. if (!defined(cartesian)) {
  4369. throw new DeveloperError('cartesian is required');
  4370. }
  4371. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  4372. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  4373. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  4374. var height = cartesian.z;
  4375. if (!defined(result)) {
  4376. return new Cartographic(longitude, latitude, height);
  4377. }
  4378. result.longitude = longitude;
  4379. result.latitude = latitude;
  4380. result.height = height;
  4381. return result;
  4382. };
  4383. return GeographicProjection;
  4384. });
  4385. /*global define*/
  4386. define('Core/Interval',[
  4387. './defaultValue'
  4388. ], function(
  4389. defaultValue) {
  4390. 'use strict';
  4391. /**
  4392. * Represents the closed interval [start, stop].
  4393. * @alias Interval
  4394. * @constructor
  4395. *
  4396. * @param {Number} [start=0.0] The beginning of the interval.
  4397. * @param {Number} [stop=0.0] The end of the interval.
  4398. */
  4399. function Interval(start, stop) {
  4400. /**
  4401. * The beginning of the interval.
  4402. * @type {Number}
  4403. * @default 0.0
  4404. */
  4405. this.start = defaultValue(start, 0.0);
  4406. /**
  4407. * The end of the interval.
  4408. * @type {Number}
  4409. * @default 0.0
  4410. */
  4411. this.stop = defaultValue(stop, 0.0);
  4412. }
  4413. return Interval;
  4414. });
  4415. /*global define*/
  4416. define('Core/Matrix3',[
  4417. './Cartesian3',
  4418. './defaultValue',
  4419. './defined',
  4420. './defineProperties',
  4421. './DeveloperError',
  4422. './freezeObject',
  4423. './Math'
  4424. ], function(
  4425. Cartesian3,
  4426. defaultValue,
  4427. defined,
  4428. defineProperties,
  4429. DeveloperError,
  4430. freezeObject,
  4431. CesiumMath) {
  4432. 'use strict';
  4433. /**
  4434. * A 3x3 matrix, indexable as a column-major order array.
  4435. * Constructor parameters are in row-major order for code readability.
  4436. * @alias Matrix3
  4437. * @constructor
  4438. *
  4439. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  4440. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  4441. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  4442. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  4443. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  4444. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  4445. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  4446. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  4447. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  4448. *
  4449. * @see Matrix3.fromColumnMajorArray
  4450. * @see Matrix3.fromRowMajorArray
  4451. * @see Matrix3.fromQuaternion
  4452. * @see Matrix3.fromScale
  4453. * @see Matrix3.fromUniformScale
  4454. * @see Matrix2
  4455. * @see Matrix4
  4456. */
  4457. function Matrix3(column0Row0, column1Row0, column2Row0,
  4458. column0Row1, column1Row1, column2Row1,
  4459. column0Row2, column1Row2, column2Row2) {
  4460. this[0] = defaultValue(column0Row0, 0.0);
  4461. this[1] = defaultValue(column0Row1, 0.0);
  4462. this[2] = defaultValue(column0Row2, 0.0);
  4463. this[3] = defaultValue(column1Row0, 0.0);
  4464. this[4] = defaultValue(column1Row1, 0.0);
  4465. this[5] = defaultValue(column1Row2, 0.0);
  4466. this[6] = defaultValue(column2Row0, 0.0);
  4467. this[7] = defaultValue(column2Row1, 0.0);
  4468. this[8] = defaultValue(column2Row2, 0.0);
  4469. }
  4470. /**
  4471. * The number of elements used to pack the object into an array.
  4472. * @type {Number}
  4473. */
  4474. Matrix3.packedLength = 9;
  4475. /**
  4476. * Stores the provided instance into the provided array.
  4477. *
  4478. * @param {Matrix3} value The value to pack.
  4479. * @param {Number[]} array The array to pack into.
  4480. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4481. *
  4482. * @returns {Number[]} The array that was packed into
  4483. */
  4484. Matrix3.pack = function(value, array, startingIndex) {
  4485. if (!defined(value)) {
  4486. throw new DeveloperError('value is required');
  4487. }
  4488. if (!defined(array)) {
  4489. throw new DeveloperError('array is required');
  4490. }
  4491. startingIndex = defaultValue(startingIndex, 0);
  4492. array[startingIndex++] = value[0];
  4493. array[startingIndex++] = value[1];
  4494. array[startingIndex++] = value[2];
  4495. array[startingIndex++] = value[3];
  4496. array[startingIndex++] = value[4];
  4497. array[startingIndex++] = value[5];
  4498. array[startingIndex++] = value[6];
  4499. array[startingIndex++] = value[7];
  4500. array[startingIndex++] = value[8];
  4501. return array;
  4502. };
  4503. /**
  4504. * Retrieves an instance from a packed array.
  4505. *
  4506. * @param {Number[]} array The packed array.
  4507. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4508. * @param {Matrix3} [result] The object into which to store the result.
  4509. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  4510. */
  4511. Matrix3.unpack = function(array, startingIndex, result) {
  4512. if (!defined(array)) {
  4513. throw new DeveloperError('array is required');
  4514. }
  4515. startingIndex = defaultValue(startingIndex, 0);
  4516. if (!defined(result)) {
  4517. result = new Matrix3();
  4518. }
  4519. result[0] = array[startingIndex++];
  4520. result[1] = array[startingIndex++];
  4521. result[2] = array[startingIndex++];
  4522. result[3] = array[startingIndex++];
  4523. result[4] = array[startingIndex++];
  4524. result[5] = array[startingIndex++];
  4525. result[6] = array[startingIndex++];
  4526. result[7] = array[startingIndex++];
  4527. result[8] = array[startingIndex++];
  4528. return result;
  4529. };
  4530. /**
  4531. * Duplicates a Matrix3 instance.
  4532. *
  4533. * @param {Matrix3} matrix The matrix to duplicate.
  4534. * @param {Matrix3} [result] The object onto which to store the result.
  4535. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  4536. */
  4537. Matrix3.clone = function(values, result) {
  4538. if (!defined(values)) {
  4539. return undefined;
  4540. }
  4541. if (!defined(result)) {
  4542. return new Matrix3(values[0], values[3], values[6],
  4543. values[1], values[4], values[7],
  4544. values[2], values[5], values[8]);
  4545. }
  4546. result[0] = values[0];
  4547. result[1] = values[1];
  4548. result[2] = values[2];
  4549. result[3] = values[3];
  4550. result[4] = values[4];
  4551. result[5] = values[5];
  4552. result[6] = values[6];
  4553. result[7] = values[7];
  4554. result[8] = values[8];
  4555. return result;
  4556. };
  4557. /**
  4558. * Creates a Matrix3 from 9 consecutive elements in an array.
  4559. *
  4560. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  4561. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  4562. * @param {Matrix3} [result] The object onto which to store the result.
  4563. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  4564. *
  4565. * @example
  4566. * // Create the Matrix3:
  4567. * // [1.0, 2.0, 3.0]
  4568. * // [1.0, 2.0, 3.0]
  4569. * // [1.0, 2.0, 3.0]
  4570. *
  4571. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  4572. * var m = Cesium.Matrix3.fromArray(v);
  4573. *
  4574. * // Create same Matrix3 with using an offset into an array
  4575. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  4576. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  4577. */
  4578. Matrix3.fromArray = function(array, startingIndex, result) {
  4579. if (!defined(array)) {
  4580. throw new DeveloperError('array is required');
  4581. }
  4582. startingIndex = defaultValue(startingIndex, 0);
  4583. if (!defined(result)) {
  4584. result = new Matrix3();
  4585. }
  4586. result[0] = array[startingIndex];
  4587. result[1] = array[startingIndex + 1];
  4588. result[2] = array[startingIndex + 2];
  4589. result[3] = array[startingIndex + 3];
  4590. result[4] = array[startingIndex + 4];
  4591. result[5] = array[startingIndex + 5];
  4592. result[6] = array[startingIndex + 6];
  4593. result[7] = array[startingIndex + 7];
  4594. result[8] = array[startingIndex + 8];
  4595. return result;
  4596. };
  4597. /**
  4598. * Creates a Matrix3 instance from a column-major order array.
  4599. *
  4600. * @param {Number[]} values The column-major order array.
  4601. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4602. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4603. */
  4604. Matrix3.fromColumnMajorArray = function(values, result) {
  4605. if (!defined(values)) {
  4606. throw new DeveloperError('values parameter is required');
  4607. }
  4608. return Matrix3.clone(values, result);
  4609. };
  4610. /**
  4611. * Creates a Matrix3 instance from a row-major order array.
  4612. * The resulting matrix will be in column-major order.
  4613. *
  4614. * @param {Number[]} values The row-major order array.
  4615. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4616. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4617. */
  4618. Matrix3.fromRowMajorArray = function(values, result) {
  4619. if (!defined(values)) {
  4620. throw new DeveloperError('values is required.');
  4621. }
  4622. if (!defined(result)) {
  4623. return new Matrix3(values[0], values[1], values[2],
  4624. values[3], values[4], values[5],
  4625. values[6], values[7], values[8]);
  4626. }
  4627. result[0] = values[0];
  4628. result[1] = values[3];
  4629. result[2] = values[6];
  4630. result[3] = values[1];
  4631. result[4] = values[4];
  4632. result[5] = values[7];
  4633. result[6] = values[2];
  4634. result[7] = values[5];
  4635. result[8] = values[8];
  4636. return result;
  4637. };
  4638. /**
  4639. * Computes a 3x3 rotation matrix from the provided quaternion.
  4640. *
  4641. * @param {Quaternion} quaternion the quaternion to use.
  4642. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4643. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  4644. */
  4645. Matrix3.fromQuaternion = function(quaternion, result) {
  4646. if (!defined(quaternion)) {
  4647. throw new DeveloperError('quaternion is required');
  4648. }
  4649. var x2 = quaternion.x * quaternion.x;
  4650. var xy = quaternion.x * quaternion.y;
  4651. var xz = quaternion.x * quaternion.z;
  4652. var xw = quaternion.x * quaternion.w;
  4653. var y2 = quaternion.y * quaternion.y;
  4654. var yz = quaternion.y * quaternion.z;
  4655. var yw = quaternion.y * quaternion.w;
  4656. var z2 = quaternion.z * quaternion.z;
  4657. var zw = quaternion.z * quaternion.w;
  4658. var w2 = quaternion.w * quaternion.w;
  4659. var m00 = x2 - y2 - z2 + w2;
  4660. var m01 = 2.0 * (xy - zw);
  4661. var m02 = 2.0 * (xz + yw);
  4662. var m10 = 2.0 * (xy + zw);
  4663. var m11 = -x2 + y2 - z2 + w2;
  4664. var m12 = 2.0 * (yz - xw);
  4665. var m20 = 2.0 * (xz - yw);
  4666. var m21 = 2.0 * (yz + xw);
  4667. var m22 = -x2 - y2 + z2 + w2;
  4668. if (!defined(result)) {
  4669. return new Matrix3(m00, m01, m02,
  4670. m10, m11, m12,
  4671. m20, m21, m22);
  4672. }
  4673. result[0] = m00;
  4674. result[1] = m10;
  4675. result[2] = m20;
  4676. result[3] = m01;
  4677. result[4] = m11;
  4678. result[5] = m21;
  4679. result[6] = m02;
  4680. result[7] = m12;
  4681. result[8] = m22;
  4682. return result;
  4683. };
  4684. /**
  4685. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  4686. *
  4687. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  4688. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4689. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  4690. */
  4691. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  4692. if (!defined(headingPitchRoll)) {
  4693. throw new DeveloperError('headingPitchRoll is required');
  4694. }
  4695. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  4696. var cosPsi = Math.cos(-headingPitchRoll.heading);
  4697. var cosPhi = Math.cos(headingPitchRoll.roll);
  4698. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  4699. var sinPsi = Math.sin(-headingPitchRoll.heading);
  4700. var sinPhi = Math.sin(headingPitchRoll.roll);
  4701. var m00 = cosTheta * cosPsi;
  4702. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  4703. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  4704. var m10 = cosTheta * sinPsi;
  4705. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  4706. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  4707. var m20 = -sinTheta;
  4708. var m21 = sinPhi * cosTheta;
  4709. var m22 = cosPhi * cosTheta;
  4710. if (!defined(result)) {
  4711. return new Matrix3(m00, m01, m02,
  4712. m10, m11, m12,
  4713. m20, m21, m22);
  4714. }
  4715. result[0] = m00;
  4716. result[1] = m10;
  4717. result[2] = m20;
  4718. result[3] = m01;
  4719. result[4] = m11;
  4720. result[5] = m21;
  4721. result[6] = m02;
  4722. result[7] = m12;
  4723. result[8] = m22;
  4724. return result;
  4725. };
  4726. /**
  4727. * Computes a Matrix3 instance representing a non-uniform scale.
  4728. *
  4729. * @param {Cartesian3} scale The x, y, and z scale factors.
  4730. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4731. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4732. *
  4733. * @example
  4734. * // Creates
  4735. * // [7.0, 0.0, 0.0]
  4736. * // [0.0, 8.0, 0.0]
  4737. * // [0.0, 0.0, 9.0]
  4738. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  4739. */
  4740. Matrix3.fromScale = function(scale, result) {
  4741. if (!defined(scale)) {
  4742. throw new DeveloperError('scale is required.');
  4743. }
  4744. if (!defined(result)) {
  4745. return new Matrix3(
  4746. scale.x, 0.0, 0.0,
  4747. 0.0, scale.y, 0.0,
  4748. 0.0, 0.0, scale.z);
  4749. }
  4750. result[0] = scale.x;
  4751. result[1] = 0.0;
  4752. result[2] = 0.0;
  4753. result[3] = 0.0;
  4754. result[4] = scale.y;
  4755. result[5] = 0.0;
  4756. result[6] = 0.0;
  4757. result[7] = 0.0;
  4758. result[8] = scale.z;
  4759. return result;
  4760. };
  4761. /**
  4762. * Computes a Matrix3 instance representing a uniform scale.
  4763. *
  4764. * @param {Number} scale The uniform scale factor.
  4765. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4766. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4767. *
  4768. * @example
  4769. * // Creates
  4770. * // [2.0, 0.0, 0.0]
  4771. * // [0.0, 2.0, 0.0]
  4772. * // [0.0, 0.0, 2.0]
  4773. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  4774. */
  4775. Matrix3.fromUniformScale = function(scale, result) {
  4776. if (typeof scale !== 'number') {
  4777. throw new DeveloperError('scale is required.');
  4778. }
  4779. if (!defined(result)) {
  4780. return new Matrix3(
  4781. scale, 0.0, 0.0,
  4782. 0.0, scale, 0.0,
  4783. 0.0, 0.0, scale);
  4784. }
  4785. result[0] = scale;
  4786. result[1] = 0.0;
  4787. result[2] = 0.0;
  4788. result[3] = 0.0;
  4789. result[4] = scale;
  4790. result[5] = 0.0;
  4791. result[6] = 0.0;
  4792. result[7] = 0.0;
  4793. result[8] = scale;
  4794. return result;
  4795. };
  4796. /**
  4797. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  4798. *
  4799. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  4800. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4801. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4802. *
  4803. * @example
  4804. * // Creates
  4805. * // [0.0, -9.0, 8.0]
  4806. * // [9.0, 0.0, -7.0]
  4807. * // [-8.0, 7.0, 0.0]
  4808. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  4809. */
  4810. Matrix3.fromCrossProduct = function(vector, result) {
  4811. if (!defined(vector)) {
  4812. throw new DeveloperError('vector is required.');
  4813. }
  4814. if (!defined(result)) {
  4815. return new Matrix3(
  4816. 0.0, -vector.z, vector.y,
  4817. vector.z, 0.0, -vector.x,
  4818. -vector.y, vector.x, 0.0);
  4819. }
  4820. result[0] = 0.0;
  4821. result[1] = vector.z;
  4822. result[2] = -vector.y;
  4823. result[3] = -vector.z;
  4824. result[4] = 0.0;
  4825. result[5] = vector.x;
  4826. result[6] = vector.y;
  4827. result[7] = -vector.x;
  4828. result[8] = 0.0;
  4829. return result;
  4830. };
  4831. /**
  4832. * Creates a rotation matrix around the x-axis.
  4833. *
  4834. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  4835. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4836. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4837. *
  4838. * @example
  4839. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  4840. * var p = new Cesium.Cartesian3(5, 6, 7);
  4841. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  4842. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  4843. */
  4844. Matrix3.fromRotationX = function(angle, result) {
  4845. if (!defined(angle)) {
  4846. throw new DeveloperError('angle is required.');
  4847. }
  4848. var cosAngle = Math.cos(angle);
  4849. var sinAngle = Math.sin(angle);
  4850. if (!defined(result)) {
  4851. return new Matrix3(
  4852. 1.0, 0.0, 0.0,
  4853. 0.0, cosAngle, -sinAngle,
  4854. 0.0, sinAngle, cosAngle);
  4855. }
  4856. result[0] = 1.0;
  4857. result[1] = 0.0;
  4858. result[2] = 0.0;
  4859. result[3] = 0.0;
  4860. result[4] = cosAngle;
  4861. result[5] = sinAngle;
  4862. result[6] = 0.0;
  4863. result[7] = -sinAngle;
  4864. result[8] = cosAngle;
  4865. return result;
  4866. };
  4867. /**
  4868. * Creates a rotation matrix around the y-axis.
  4869. *
  4870. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  4871. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4872. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4873. *
  4874. * @example
  4875. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  4876. * var p = new Cesium.Cartesian3(5, 6, 7);
  4877. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  4878. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  4879. */
  4880. Matrix3.fromRotationY = function(angle, result) {
  4881. if (!defined(angle)) {
  4882. throw new DeveloperError('angle is required.');
  4883. }
  4884. var cosAngle = Math.cos(angle);
  4885. var sinAngle = Math.sin(angle);
  4886. if (!defined(result)) {
  4887. return new Matrix3(
  4888. cosAngle, 0.0, sinAngle,
  4889. 0.0, 1.0, 0.0,
  4890. -sinAngle, 0.0, cosAngle);
  4891. }
  4892. result[0] = cosAngle;
  4893. result[1] = 0.0;
  4894. result[2] = -sinAngle;
  4895. result[3] = 0.0;
  4896. result[4] = 1.0;
  4897. result[5] = 0.0;
  4898. result[6] = sinAngle;
  4899. result[7] = 0.0;
  4900. result[8] = cosAngle;
  4901. return result;
  4902. };
  4903. /**
  4904. * Creates a rotation matrix around the z-axis.
  4905. *
  4906. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  4907. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  4908. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  4909. *
  4910. * @example
  4911. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  4912. * var p = new Cesium.Cartesian3(5, 6, 7);
  4913. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  4914. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  4915. */
  4916. Matrix3.fromRotationZ = function(angle, result) {
  4917. if (!defined(angle)) {
  4918. throw new DeveloperError('angle is required.');
  4919. }
  4920. var cosAngle = Math.cos(angle);
  4921. var sinAngle = Math.sin(angle);
  4922. if (!defined(result)) {
  4923. return new Matrix3(
  4924. cosAngle, -sinAngle, 0.0,
  4925. sinAngle, cosAngle, 0.0,
  4926. 0.0, 0.0, 1.0);
  4927. }
  4928. result[0] = cosAngle;
  4929. result[1] = sinAngle;
  4930. result[2] = 0.0;
  4931. result[3] = -sinAngle;
  4932. result[4] = cosAngle;
  4933. result[5] = 0.0;
  4934. result[6] = 0.0;
  4935. result[7] = 0.0;
  4936. result[8] = 1.0;
  4937. return result;
  4938. };
  4939. /**
  4940. * Creates an Array from the provided Matrix3 instance.
  4941. * The array will be in column-major order.
  4942. *
  4943. * @param {Matrix3} matrix The matrix to use..
  4944. * @param {Number[]} [result] The Array onto which to store the result.
  4945. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  4946. */
  4947. Matrix3.toArray = function(matrix, result) {
  4948. if (!defined(matrix)) {
  4949. throw new DeveloperError('matrix is required');
  4950. }
  4951. if (!defined(result)) {
  4952. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  4953. }
  4954. result[0] = matrix[0];
  4955. result[1] = matrix[1];
  4956. result[2] = matrix[2];
  4957. result[3] = matrix[3];
  4958. result[4] = matrix[4];
  4959. result[5] = matrix[5];
  4960. result[6] = matrix[6];
  4961. result[7] = matrix[7];
  4962. result[8] = matrix[8];
  4963. return result;
  4964. };
  4965. /**
  4966. * Computes the array index of the element at the provided row and column.
  4967. *
  4968. * @param {Number} row The zero-based index of the row.
  4969. * @param {Number} column The zero-based index of the column.
  4970. * @returns {Number} The index of the element at the provided row and column.
  4971. *
  4972. * @exception {DeveloperError} row must be 0, 1, or 2.
  4973. * @exception {DeveloperError} column must be 0, 1, or 2.
  4974. *
  4975. * @example
  4976. * var myMatrix = new Cesium.Matrix3();
  4977. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  4978. * var column1Row0 = myMatrix[column1Row0Index]
  4979. * myMatrix[column1Row0Index] = 10.0;
  4980. */
  4981. Matrix3.getElementIndex = function(column, row) {
  4982. if (typeof row !== 'number' || row < 0 || row > 2) {
  4983. throw new DeveloperError('row must be 0, 1, or 2.');
  4984. }
  4985. if (typeof column !== 'number' || column < 0 || column > 2) {
  4986. throw new DeveloperError('column must be 0, 1, or 2.');
  4987. }
  4988. return column * 3 + row;
  4989. };
  4990. /**
  4991. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  4992. *
  4993. * @param {Matrix3} matrix The matrix to use.
  4994. * @param {Number} index The zero-based index of the column to retrieve.
  4995. * @param {Cartesian3} result The object onto which to store the result.
  4996. * @returns {Cartesian3} The modified result parameter.
  4997. *
  4998. * @exception {DeveloperError} index must be 0, 1, or 2.
  4999. */
  5000. Matrix3.getColumn = function(matrix, index, result) {
  5001. if (!defined(matrix)) {
  5002. throw new DeveloperError('matrix is required.');
  5003. }
  5004. if (typeof index !== 'number' || index < 0 || index > 2) {
  5005. throw new DeveloperError('index must be 0, 1, or 2.');
  5006. }
  5007. if (!defined(result)) {
  5008. throw new DeveloperError('result is required');
  5009. }
  5010. var startIndex = index * 3;
  5011. var x = matrix[startIndex];
  5012. var y = matrix[startIndex + 1];
  5013. var z = matrix[startIndex + 2];
  5014. result.x = x;
  5015. result.y = y;
  5016. result.z = z;
  5017. return result;
  5018. };
  5019. /**
  5020. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  5021. *
  5022. * @param {Matrix3} matrix The matrix to use.
  5023. * @param {Number} index The zero-based index of the column to set.
  5024. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  5025. * @param {Matrix3} result The object onto which to store the result.
  5026. * @returns {Matrix3} The modified result parameter.
  5027. *
  5028. * @exception {DeveloperError} index must be 0, 1, or 2.
  5029. */
  5030. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  5031. if (!defined(matrix)) {
  5032. throw new DeveloperError('matrix is required');
  5033. }
  5034. if (!defined(cartesian)) {
  5035. throw new DeveloperError('cartesian is required');
  5036. }
  5037. if (typeof index !== 'number' || index < 0 || index > 2) {
  5038. throw new DeveloperError('index must be 0, 1, or 2.');
  5039. }
  5040. if (!defined(result)) {
  5041. throw new DeveloperError('result is required');
  5042. }
  5043. result = Matrix3.clone(matrix, result);
  5044. var startIndex = index * 3;
  5045. result[startIndex] = cartesian.x;
  5046. result[startIndex + 1] = cartesian.y;
  5047. result[startIndex + 2] = cartesian.z;
  5048. return result;
  5049. };
  5050. /**
  5051. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  5052. *
  5053. * @param {Matrix3} matrix The matrix to use.
  5054. * @param {Number} index The zero-based index of the row to retrieve.
  5055. * @param {Cartesian3} result The object onto which to store the result.
  5056. * @returns {Cartesian3} The modified result parameter.
  5057. *
  5058. * @exception {DeveloperError} index must be 0, 1, or 2.
  5059. */
  5060. Matrix3.getRow = function(matrix, index, result) {
  5061. if (!defined(matrix)) {
  5062. throw new DeveloperError('matrix is required.');
  5063. }
  5064. if (typeof index !== 'number' || index < 0 || index > 2) {
  5065. throw new DeveloperError('index must be 0, 1, or 2.');
  5066. }
  5067. if (!defined(result)) {
  5068. throw new DeveloperError('result is required');
  5069. }
  5070. var x = matrix[index];
  5071. var y = matrix[index + 3];
  5072. var z = matrix[index + 6];
  5073. result.x = x;
  5074. result.y = y;
  5075. result.z = z;
  5076. return result;
  5077. };
  5078. /**
  5079. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  5080. *
  5081. * @param {Matrix3} matrix The matrix to use.
  5082. * @param {Number} index The zero-based index of the row to set.
  5083. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  5084. * @param {Matrix3} result The object onto which to store the result.
  5085. * @returns {Matrix3} The modified result parameter.
  5086. *
  5087. * @exception {DeveloperError} index must be 0, 1, or 2.
  5088. */
  5089. Matrix3.setRow = function(matrix, index, cartesian, result) {
  5090. if (!defined(matrix)) {
  5091. throw new DeveloperError('matrix is required');
  5092. }
  5093. if (!defined(cartesian)) {
  5094. throw new DeveloperError('cartesian is required');
  5095. }
  5096. if (typeof index !== 'number' || index < 0 || index > 2) {
  5097. throw new DeveloperError('index must be 0, 1, or 2.');
  5098. }
  5099. if (!defined(result)) {
  5100. throw new DeveloperError('result is required');
  5101. }
  5102. result = Matrix3.clone(matrix, result);
  5103. result[index] = cartesian.x;
  5104. result[index + 3] = cartesian.y;
  5105. result[index + 6] = cartesian.z;
  5106. return result;
  5107. };
  5108. var scratchColumn = new Cartesian3();
  5109. /**
  5110. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  5111. *
  5112. * @param {Matrix3} matrix The matrix.
  5113. * @param {Cartesian3} result The object onto which to store the result.
  5114. * @returns {Cartesian3} The modified result parameter.
  5115. */
  5116. Matrix3.getScale = function(matrix, result) {
  5117. if (!defined(matrix)) {
  5118. throw new DeveloperError('matrix is required.');
  5119. }
  5120. if (!defined(result)) {
  5121. throw new DeveloperError('result is required');
  5122. }
  5123. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  5124. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  5125. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  5126. return result;
  5127. };
  5128. var scratchScale = new Cartesian3();
  5129. /**
  5130. * Computes the maximum scale assuming the matrix is an affine transformation.
  5131. * The maximum scale is the maximum length of the column vectors.
  5132. *
  5133. * @param {Matrix3} matrix The matrix.
  5134. * @returns {Number} The maximum scale.
  5135. */
  5136. Matrix3.getMaximumScale = function(matrix) {
  5137. Matrix3.getScale(matrix, scratchScale);
  5138. return Cartesian3.maximumComponent(scratchScale);
  5139. };
  5140. /**
  5141. * Computes the product of two matrices.
  5142. *
  5143. * @param {Matrix3} left The first matrix.
  5144. * @param {Matrix3} right The second matrix.
  5145. * @param {Matrix3} result The object onto which to store the result.
  5146. * @returns {Matrix3} The modified result parameter.
  5147. */
  5148. Matrix3.multiply = function(left, right, result) {
  5149. if (!defined(left)) {
  5150. throw new DeveloperError('left is required');
  5151. }
  5152. if (!defined(right)) {
  5153. throw new DeveloperError('right is required');
  5154. }
  5155. if (!defined(result)) {
  5156. throw new DeveloperError('result is required');
  5157. }
  5158. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  5159. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  5160. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  5161. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  5162. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  5163. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  5164. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  5165. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  5166. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  5167. result[0] = column0Row0;
  5168. result[1] = column0Row1;
  5169. result[2] = column0Row2;
  5170. result[3] = column1Row0;
  5171. result[4] = column1Row1;
  5172. result[5] = column1Row2;
  5173. result[6] = column2Row0;
  5174. result[7] = column2Row1;
  5175. result[8] = column2Row2;
  5176. return result;
  5177. };
  5178. /**
  5179. * Computes the sum of two matrices.
  5180. *
  5181. * @param {Matrix3} left The first matrix.
  5182. * @param {Matrix3} right The second matrix.
  5183. * @param {Matrix3} result The object onto which to store the result.
  5184. * @returns {Matrix3} The modified result parameter.
  5185. */
  5186. Matrix3.add = function(left, right, result) {
  5187. if (!defined(left)) {
  5188. throw new DeveloperError('left is required');
  5189. }
  5190. if (!defined(right)) {
  5191. throw new DeveloperError('right is required');
  5192. }
  5193. if (!defined(result)) {
  5194. throw new DeveloperError('result is required');
  5195. }
  5196. result[0] = left[0] + right[0];
  5197. result[1] = left[1] + right[1];
  5198. result[2] = left[2] + right[2];
  5199. result[3] = left[3] + right[3];
  5200. result[4] = left[4] + right[4];
  5201. result[5] = left[5] + right[5];
  5202. result[6] = left[6] + right[6];
  5203. result[7] = left[7] + right[7];
  5204. result[8] = left[8] + right[8];
  5205. return result;
  5206. };
  5207. /**
  5208. * Computes the difference of two matrices.
  5209. *
  5210. * @param {Matrix3} left The first matrix.
  5211. * @param {Matrix3} right The second matrix.
  5212. * @param {Matrix3} result The object onto which to store the result.
  5213. * @returns {Matrix3} The modified result parameter.
  5214. */
  5215. Matrix3.subtract = function(left, right, result) {
  5216. if (!defined(left)) {
  5217. throw new DeveloperError('left is required');
  5218. }
  5219. if (!defined(right)) {
  5220. throw new DeveloperError('right is required');
  5221. }
  5222. if (!defined(result)) {
  5223. throw new DeveloperError('result is required');
  5224. }
  5225. result[0] = left[0] - right[0];
  5226. result[1] = left[1] - right[1];
  5227. result[2] = left[2] - right[2];
  5228. result[3] = left[3] - right[3];
  5229. result[4] = left[4] - right[4];
  5230. result[5] = left[5] - right[5];
  5231. result[6] = left[6] - right[6];
  5232. result[7] = left[7] - right[7];
  5233. result[8] = left[8] - right[8];
  5234. return result;
  5235. };
  5236. /**
  5237. * Computes the product of a matrix and a column vector.
  5238. *
  5239. * @param {Matrix3} matrix The matrix.
  5240. * @param {Cartesian3} cartesian The column.
  5241. * @param {Cartesian3} result The object onto which to store the result.
  5242. * @returns {Cartesian3} The modified result parameter.
  5243. */
  5244. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  5245. if (!defined(matrix)) {
  5246. throw new DeveloperError('matrix is required');
  5247. }
  5248. if (!defined(cartesian)) {
  5249. throw new DeveloperError('cartesian is required');
  5250. }
  5251. if (!defined(result)) {
  5252. throw new DeveloperError('result is required');
  5253. }
  5254. var vX = cartesian.x;
  5255. var vY = cartesian.y;
  5256. var vZ = cartesian.z;
  5257. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  5258. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  5259. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  5260. result.x = x;
  5261. result.y = y;
  5262. result.z = z;
  5263. return result;
  5264. };
  5265. /**
  5266. * Computes the product of a matrix and a scalar.
  5267. *
  5268. * @param {Matrix3} matrix The matrix.
  5269. * @param {Number} scalar The number to multiply by.
  5270. * @param {Matrix3} result The object onto which to store the result.
  5271. * @returns {Matrix3} The modified result parameter.
  5272. */
  5273. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  5274. if (!defined(matrix)) {
  5275. throw new DeveloperError('matrix is required');
  5276. }
  5277. if (typeof scalar !== 'number') {
  5278. throw new DeveloperError('scalar must be a number');
  5279. }
  5280. if (!defined(result)) {
  5281. throw new DeveloperError('result is required');
  5282. }
  5283. result[0] = matrix[0] * scalar;
  5284. result[1] = matrix[1] * scalar;
  5285. result[2] = matrix[2] * scalar;
  5286. result[3] = matrix[3] * scalar;
  5287. result[4] = matrix[4] * scalar;
  5288. result[5] = matrix[5] * scalar;
  5289. result[6] = matrix[6] * scalar;
  5290. result[7] = matrix[7] * scalar;
  5291. result[8] = matrix[8] * scalar;
  5292. return result;
  5293. };
  5294. /**
  5295. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  5296. *
  5297. * @param {Matrix3} matrix The matrix on the left-hand side.
  5298. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  5299. * @param {Matrix3} result The object onto which to store the result.
  5300. * @returns {Matrix3} The modified result parameter.
  5301. *
  5302. *
  5303. * @example
  5304. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  5305. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  5306. *
  5307. * @see Matrix3.fromScale
  5308. * @see Matrix3.multiplyByUniformScale
  5309. */
  5310. Matrix3.multiplyByScale = function(matrix, scale, result) {
  5311. if (!defined(matrix)) {
  5312. throw new DeveloperError('matrix is required');
  5313. }
  5314. if (!defined(scale)) {
  5315. throw new DeveloperError('scale is required');
  5316. }
  5317. if (!defined(result)) {
  5318. throw new DeveloperError('result is required');
  5319. }
  5320. result[0] = matrix[0] * scale.x;
  5321. result[1] = matrix[1] * scale.x;
  5322. result[2] = matrix[2] * scale.x;
  5323. result[3] = matrix[3] * scale.y;
  5324. result[4] = matrix[4] * scale.y;
  5325. result[5] = matrix[5] * scale.y;
  5326. result[6] = matrix[6] * scale.z;
  5327. result[7] = matrix[7] * scale.z;
  5328. result[8] = matrix[8] * scale.z;
  5329. return result;
  5330. };
  5331. /**
  5332. * Creates a negated copy of the provided matrix.
  5333. *
  5334. * @param {Matrix3} matrix The matrix to negate.
  5335. * @param {Matrix3} result The object onto which to store the result.
  5336. * @returns {Matrix3} The modified result parameter.
  5337. */
  5338. Matrix3.negate = function(matrix, result) {
  5339. if (!defined(matrix)) {
  5340. throw new DeveloperError('matrix is required');
  5341. }
  5342. if (!defined(result)) {
  5343. throw new DeveloperError('result is required');
  5344. }
  5345. result[0] = -matrix[0];
  5346. result[1] = -matrix[1];
  5347. result[2] = -matrix[2];
  5348. result[3] = -matrix[3];
  5349. result[4] = -matrix[4];
  5350. result[5] = -matrix[5];
  5351. result[6] = -matrix[6];
  5352. result[7] = -matrix[7];
  5353. result[8] = -matrix[8];
  5354. return result;
  5355. };
  5356. /**
  5357. * Computes the transpose of the provided matrix.
  5358. *
  5359. * @param {Matrix3} matrix The matrix to transpose.
  5360. * @param {Matrix3} result The object onto which to store the result.
  5361. * @returns {Matrix3} The modified result parameter.
  5362. */
  5363. Matrix3.transpose = function(matrix, result) {
  5364. if (!defined(matrix)) {
  5365. throw new DeveloperError('matrix is required');
  5366. }
  5367. if (!defined(result)) {
  5368. throw new DeveloperError('result is required');
  5369. }
  5370. var column0Row0 = matrix[0];
  5371. var column0Row1 = matrix[3];
  5372. var column0Row2 = matrix[6];
  5373. var column1Row0 = matrix[1];
  5374. var column1Row1 = matrix[4];
  5375. var column1Row2 = matrix[7];
  5376. var column2Row0 = matrix[2];
  5377. var column2Row1 = matrix[5];
  5378. var column2Row2 = matrix[8];
  5379. result[0] = column0Row0;
  5380. result[1] = column0Row1;
  5381. result[2] = column0Row2;
  5382. result[3] = column1Row0;
  5383. result[4] = column1Row1;
  5384. result[5] = column1Row2;
  5385. result[6] = column2Row0;
  5386. result[7] = column2Row1;
  5387. result[8] = column2Row2;
  5388. return result;
  5389. };
  5390. function computeFrobeniusNorm(matrix) {
  5391. var norm = 0.0;
  5392. for (var i = 0; i < 9; ++i) {
  5393. var temp = matrix[i];
  5394. norm += temp * temp;
  5395. }
  5396. return Math.sqrt(norm);
  5397. }
  5398. var rowVal = [1, 0, 0];
  5399. var colVal = [2, 2, 1];
  5400. function offDiagonalFrobeniusNorm(matrix) {
  5401. // Computes the "off-diagonal" Frobenius norm.
  5402. // Assumes matrix is symmetric.
  5403. var norm = 0.0;
  5404. for (var i = 0; i < 3; ++i) {
  5405. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  5406. norm += 2.0 * temp * temp;
  5407. }
  5408. return Math.sqrt(norm);
  5409. }
  5410. function shurDecomposition(matrix, result) {
  5411. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  5412. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  5413. //
  5414. // The routine takes a matrix, which is assumed to be symmetric, and
  5415. // finds the largest off-diagonal term, and then creates
  5416. // a matrix (result) which can be used to help reduce it
  5417. var tolerance = CesiumMath.EPSILON15;
  5418. var maxDiagonal = 0.0;
  5419. var rotAxis = 1;
  5420. // find pivot (rotAxis) based on max diagonal of matrix
  5421. for (var i = 0; i < 3; ++i) {
  5422. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  5423. if (temp > maxDiagonal) {
  5424. rotAxis = i;
  5425. maxDiagonal = temp;
  5426. }
  5427. }
  5428. var c = 1.0;
  5429. var s = 0.0;
  5430. var p = rowVal[rotAxis];
  5431. var q = colVal[rotAxis];
  5432. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  5433. var qq = matrix[Matrix3.getElementIndex(q, q)];
  5434. var pp = matrix[Matrix3.getElementIndex(p, p)];
  5435. var qp = matrix[Matrix3.getElementIndex(q, p)];
  5436. var tau = (qq - pp) / 2.0 / qp;
  5437. var t;
  5438. if (tau < 0.0) {
  5439. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  5440. } else {
  5441. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  5442. }
  5443. c = 1.0 / Math.sqrt(1.0 + t * t);
  5444. s = t * c;
  5445. }
  5446. result = Matrix3.clone(Matrix3.IDENTITY, result);
  5447. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  5448. result[Matrix3.getElementIndex(q, p)] = s;
  5449. result[Matrix3.getElementIndex(p, q)] = -s;
  5450. return result;
  5451. }
  5452. var jMatrix = new Matrix3();
  5453. var jMatrixTranspose = new Matrix3();
  5454. /**
  5455. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  5456. * <p>
  5457. * Returns a diagonal matrix and unitary matrix such that:
  5458. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  5459. * </p>
  5460. * <p>
  5461. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  5462. * of the unitary matrix are the corresponding eigenvectors.
  5463. * </p>
  5464. *
  5465. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  5466. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  5467. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  5468. *
  5469. * @example
  5470. * var a = //... symetric matrix
  5471. * var result = {
  5472. * unitary : new Cesium.Matrix3(),
  5473. * diagonal : new Cesium.Matrix3()
  5474. * };
  5475. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  5476. *
  5477. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  5478. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  5479. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  5480. *
  5481. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  5482. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  5483. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  5484. */
  5485. Matrix3.computeEigenDecomposition = function(matrix, result) {
  5486. if (!defined(matrix)) {
  5487. throw new DeveloperError('matrix is required.');
  5488. }
  5489. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  5490. // section 8.4.3 The Classical Jacobi Algorithm
  5491. var tolerance = CesiumMath.EPSILON20;
  5492. var maxSweeps = 10;
  5493. var count = 0;
  5494. var sweep = 0;
  5495. if (!defined(result)) {
  5496. result = {};
  5497. }
  5498. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  5499. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  5500. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  5501. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  5502. shurDecomposition(diagMatrix, jMatrix);
  5503. Matrix3.transpose(jMatrix, jMatrixTranspose);
  5504. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  5505. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  5506. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  5507. if (++count > 2) {
  5508. ++sweep;
  5509. count = 0;
  5510. }
  5511. }
  5512. return result;
  5513. };
  5514. /**
  5515. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  5516. *
  5517. * @param {Matrix3} matrix The matrix with signed elements.
  5518. * @param {Matrix3} result The object onto which to store the result.
  5519. * @returns {Matrix3} The modified result parameter.
  5520. */
  5521. Matrix3.abs = function(matrix, result) {
  5522. if (!defined(matrix)) {
  5523. throw new DeveloperError('matrix is required');
  5524. }
  5525. if (!defined(result)) {
  5526. throw new DeveloperError('result is required');
  5527. }
  5528. result[0] = Math.abs(matrix[0]);
  5529. result[1] = Math.abs(matrix[1]);
  5530. result[2] = Math.abs(matrix[2]);
  5531. result[3] = Math.abs(matrix[3]);
  5532. result[4] = Math.abs(matrix[4]);
  5533. result[5] = Math.abs(matrix[5]);
  5534. result[6] = Math.abs(matrix[6]);
  5535. result[7] = Math.abs(matrix[7]);
  5536. result[8] = Math.abs(matrix[8]);
  5537. return result;
  5538. };
  5539. /**
  5540. * Computes the determinant of the provided matrix.
  5541. *
  5542. * @param {Matrix3} matrix The matrix to use.
  5543. * @returns {Number} The value of the determinant of the matrix.
  5544. */
  5545. Matrix3.determinant = function(matrix) {
  5546. if (!defined(matrix)) {
  5547. throw new DeveloperError('matrix is required');
  5548. }
  5549. var m11 = matrix[0];
  5550. var m21 = matrix[3];
  5551. var m31 = matrix[6];
  5552. var m12 = matrix[1];
  5553. var m22 = matrix[4];
  5554. var m32 = matrix[7];
  5555. var m13 = matrix[2];
  5556. var m23 = matrix[5];
  5557. var m33 = matrix[8];
  5558. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  5559. };
  5560. /**
  5561. * Computes the inverse of the provided matrix.
  5562. *
  5563. * @param {Matrix3} matrix The matrix to invert.
  5564. * @param {Matrix3} result The object onto which to store the result.
  5565. * @returns {Matrix3} The modified result parameter.
  5566. *
  5567. * @exception {DeveloperError} matrix is not invertible.
  5568. */
  5569. Matrix3.inverse = function(matrix, result) {
  5570. if (!defined(matrix)) {
  5571. throw new DeveloperError('matrix is required');
  5572. }
  5573. if (!defined(result)) {
  5574. throw new DeveloperError('result is required');
  5575. }
  5576. var m11 = matrix[0];
  5577. var m21 = matrix[1];
  5578. var m31 = matrix[2];
  5579. var m12 = matrix[3];
  5580. var m22 = matrix[4];
  5581. var m32 = matrix[5];
  5582. var m13 = matrix[6];
  5583. var m23 = matrix[7];
  5584. var m33 = matrix[8];
  5585. var determinant = Matrix3.determinant(matrix);
  5586. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  5587. throw new DeveloperError('matrix is not invertible');
  5588. }
  5589. result[0] = m22 * m33 - m23 * m32;
  5590. result[1] = m23 * m31 - m21 * m33;
  5591. result[2] = m21 * m32 - m22 * m31;
  5592. result[3] = m13 * m32 - m12 * m33;
  5593. result[4] = m11 * m33 - m13 * m31;
  5594. result[5] = m12 * m31 - m11 * m32;
  5595. result[6] = m12 * m23 - m13 * m22;
  5596. result[7] = m13 * m21 - m11 * m23;
  5597. result[8] = m11 * m22 - m12 * m21;
  5598. var scale = 1.0 / determinant;
  5599. return Matrix3.multiplyByScalar(result, scale, result);
  5600. };
  5601. /**
  5602. * Compares the provided matrices componentwise and returns
  5603. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5604. *
  5605. * @param {Matrix3} [left] The first matrix.
  5606. * @param {Matrix3} [right] The second matrix.
  5607. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5608. */
  5609. Matrix3.equals = function(left, right) {
  5610. return (left === right) ||
  5611. (defined(left) &&
  5612. defined(right) &&
  5613. left[0] === right[0] &&
  5614. left[1] === right[1] &&
  5615. left[2] === right[2] &&
  5616. left[3] === right[3] &&
  5617. left[4] === right[4] &&
  5618. left[5] === right[5] &&
  5619. left[6] === right[6] &&
  5620. left[7] === right[7] &&
  5621. left[8] === right[8]);
  5622. };
  5623. /**
  5624. * Compares the provided matrices componentwise and returns
  5625. * <code>true</code> if they are within the provided epsilon,
  5626. * <code>false</code> otherwise.
  5627. *
  5628. * @param {Matrix3} [left] The first matrix.
  5629. * @param {Matrix3} [right] The second matrix.
  5630. * @param {Number} epsilon The epsilon to use for equality testing.
  5631. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  5632. */
  5633. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  5634. if (typeof epsilon !== 'number') {
  5635. throw new DeveloperError('epsilon must be a number');
  5636. }
  5637. return (left === right) ||
  5638. (defined(left) &&
  5639. defined(right) &&
  5640. Math.abs(left[0] - right[0]) <= epsilon &&
  5641. Math.abs(left[1] - right[1]) <= epsilon &&
  5642. Math.abs(left[2] - right[2]) <= epsilon &&
  5643. Math.abs(left[3] - right[3]) <= epsilon &&
  5644. Math.abs(left[4] - right[4]) <= epsilon &&
  5645. Math.abs(left[5] - right[5]) <= epsilon &&
  5646. Math.abs(left[6] - right[6]) <= epsilon &&
  5647. Math.abs(left[7] - right[7]) <= epsilon &&
  5648. Math.abs(left[8] - right[8]) <= epsilon);
  5649. };
  5650. /**
  5651. * An immutable Matrix3 instance initialized to the identity matrix.
  5652. *
  5653. * @type {Matrix3}
  5654. * @constant
  5655. */
  5656. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  5657. 0.0, 1.0, 0.0,
  5658. 0.0, 0.0, 1.0));
  5659. /**
  5660. * An immutable Matrix3 instance initialized to the zero matrix.
  5661. *
  5662. * @type {Matrix3}
  5663. * @constant
  5664. */
  5665. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  5666. 0.0, 0.0, 0.0,
  5667. 0.0, 0.0, 0.0));
  5668. /**
  5669. * The index into Matrix3 for column 0, row 0.
  5670. *
  5671. * @type {Number}
  5672. * @constant
  5673. */
  5674. Matrix3.COLUMN0ROW0 = 0;
  5675. /**
  5676. * The index into Matrix3 for column 0, row 1.
  5677. *
  5678. * @type {Number}
  5679. * @constant
  5680. */
  5681. Matrix3.COLUMN0ROW1 = 1;
  5682. /**
  5683. * The index into Matrix3 for column 0, row 2.
  5684. *
  5685. * @type {Number}
  5686. * @constant
  5687. */
  5688. Matrix3.COLUMN0ROW2 = 2;
  5689. /**
  5690. * The index into Matrix3 for column 1, row 0.
  5691. *
  5692. * @type {Number}
  5693. * @constant
  5694. */
  5695. Matrix3.COLUMN1ROW0 = 3;
  5696. /**
  5697. * The index into Matrix3 for column 1, row 1.
  5698. *
  5699. * @type {Number}
  5700. * @constant
  5701. */
  5702. Matrix3.COLUMN1ROW1 = 4;
  5703. /**
  5704. * The index into Matrix3 for column 1, row 2.
  5705. *
  5706. * @type {Number}
  5707. * @constant
  5708. */
  5709. Matrix3.COLUMN1ROW2 = 5;
  5710. /**
  5711. * The index into Matrix3 for column 2, row 0.
  5712. *
  5713. * @type {Number}
  5714. * @constant
  5715. */
  5716. Matrix3.COLUMN2ROW0 = 6;
  5717. /**
  5718. * The index into Matrix3 for column 2, row 1.
  5719. *
  5720. * @type {Number}
  5721. * @constant
  5722. */
  5723. Matrix3.COLUMN2ROW1 = 7;
  5724. /**
  5725. * The index into Matrix3 for column 2, row 2.
  5726. *
  5727. * @type {Number}
  5728. * @constant
  5729. */
  5730. Matrix3.COLUMN2ROW2 = 8;
  5731. defineProperties(Matrix3.prototype, {
  5732. /**
  5733. * Gets the number of items in the collection.
  5734. * @memberof Matrix3.prototype
  5735. *
  5736. * @type {Number}
  5737. */
  5738. length : {
  5739. get : function() {
  5740. return Matrix3.packedLength;
  5741. }
  5742. }
  5743. });
  5744. /**
  5745. * Duplicates the provided Matrix3 instance.
  5746. *
  5747. * @param {Matrix3} [result] The object onto which to store the result.
  5748. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5749. */
  5750. Matrix3.prototype.clone = function(result) {
  5751. return Matrix3.clone(this, result);
  5752. };
  5753. /**
  5754. * Compares this matrix to the provided matrix componentwise and returns
  5755. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5756. *
  5757. * @param {Matrix3} [right] The right hand side matrix.
  5758. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5759. */
  5760. Matrix3.prototype.equals = function(right) {
  5761. return Matrix3.equals(this, right);
  5762. };
  5763. /**
  5764. * @private
  5765. */
  5766. Matrix3.equalsArray = function(matrix, array, offset) {
  5767. return matrix[0] === array[offset] &&
  5768. matrix[1] === array[offset + 1] &&
  5769. matrix[2] === array[offset + 2] &&
  5770. matrix[3] === array[offset + 3] &&
  5771. matrix[4] === array[offset + 4] &&
  5772. matrix[5] === array[offset + 5] &&
  5773. matrix[6] === array[offset + 6] &&
  5774. matrix[7] === array[offset + 7] &&
  5775. matrix[8] === array[offset + 8];
  5776. };
  5777. /**
  5778. * Compares this matrix to the provided matrix componentwise and returns
  5779. * <code>true</code> if they are within the provided epsilon,
  5780. * <code>false</code> otherwise.
  5781. *
  5782. * @param {Matrix3} [right] The right hand side matrix.
  5783. * @param {Number} epsilon The epsilon to use for equality testing.
  5784. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  5785. */
  5786. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  5787. return Matrix3.equalsEpsilon(this, right, epsilon);
  5788. };
  5789. /**
  5790. * Creates a string representing this Matrix with each row being
  5791. * on a separate line and in the format '(column0, column1, column2)'.
  5792. *
  5793. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  5794. */
  5795. Matrix3.prototype.toString = function() {
  5796. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  5797. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  5798. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  5799. };
  5800. return Matrix3;
  5801. });
  5802. /*global define*/
  5803. define('Core/Cartesian4',[
  5804. './defaultValue',
  5805. './defined',
  5806. './DeveloperError',
  5807. './freezeObject',
  5808. './Math'
  5809. ], function(
  5810. defaultValue,
  5811. defined,
  5812. DeveloperError,
  5813. freezeObject,
  5814. CesiumMath) {
  5815. 'use strict';
  5816. /**
  5817. * A 4D Cartesian point.
  5818. * @alias Cartesian4
  5819. * @constructor
  5820. *
  5821. * @param {Number} [x=0.0] The X component.
  5822. * @param {Number} [y=0.0] The Y component.
  5823. * @param {Number} [z=0.0] The Z component.
  5824. * @param {Number} [w=0.0] The W component.
  5825. *
  5826. * @see Cartesian2
  5827. * @see Cartesian3
  5828. * @see Packable
  5829. */
  5830. function Cartesian4(x, y, z, w) {
  5831. /**
  5832. * The X component.
  5833. * @type {Number}
  5834. * @default 0.0
  5835. */
  5836. this.x = defaultValue(x, 0.0);
  5837. /**
  5838. * The Y component.
  5839. * @type {Number}
  5840. * @default 0.0
  5841. */
  5842. this.y = defaultValue(y, 0.0);
  5843. /**
  5844. * The Z component.
  5845. * @type {Number}
  5846. * @default 0.0
  5847. */
  5848. this.z = defaultValue(z, 0.0);
  5849. /**
  5850. * The W component.
  5851. * @type {Number}
  5852. * @default 0.0
  5853. */
  5854. this.w = defaultValue(w, 0.0);
  5855. }
  5856. /**
  5857. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  5858. *
  5859. * @param {Number} x The x coordinate.
  5860. * @param {Number} y The y coordinate.
  5861. * @param {Number} z The z coordinate.
  5862. * @param {Number} w The w coordinate.
  5863. * @param {Cartesian4} [result] The object onto which to store the result.
  5864. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5865. */
  5866. Cartesian4.fromElements = function(x, y, z, w, result) {
  5867. if (!defined(result)) {
  5868. return new Cartesian4(x, y, z, w);
  5869. }
  5870. result.x = x;
  5871. result.y = y;
  5872. result.z = z;
  5873. result.w = w;
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  5878. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  5879. *
  5880. * @param {Color} color The source color.
  5881. * @param {Cartesian4} [result] The object onto which to store the result.
  5882. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5883. */
  5884. Cartesian4.fromColor = function(color, result) {
  5885. if (!defined(color)) {
  5886. throw new DeveloperError('color is required');
  5887. }
  5888. if (!defined(result)) {
  5889. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  5890. }
  5891. result.x = color.red;
  5892. result.y = color.green;
  5893. result.z = color.blue;
  5894. result.w = color.alpha;
  5895. return result;
  5896. };
  5897. /**
  5898. * Duplicates a Cartesian4 instance.
  5899. *
  5900. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  5901. * @param {Cartesian4} [result] The object onto which to store the result.
  5902. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  5903. */
  5904. Cartesian4.clone = function(cartesian, result) {
  5905. if (!defined(cartesian)) {
  5906. return undefined;
  5907. }
  5908. if (!defined(result)) {
  5909. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  5910. }
  5911. result.x = cartesian.x;
  5912. result.y = cartesian.y;
  5913. result.z = cartesian.z;
  5914. result.w = cartesian.w;
  5915. return result;
  5916. };
  5917. /**
  5918. * The number of elements used to pack the object into an array.
  5919. * @type {Number}
  5920. */
  5921. Cartesian4.packedLength = 4;
  5922. /**
  5923. * Stores the provided instance into the provided array.
  5924. *
  5925. * @param {Cartesian4} value The value to pack.
  5926. * @param {Number[]} array The array to pack into.
  5927. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5928. *
  5929. * @returns {Number[]} The array that was packed into
  5930. */
  5931. Cartesian4.pack = function(value, array, startingIndex) {
  5932. if (!defined(value)) {
  5933. throw new DeveloperError('value is required');
  5934. }
  5935. if (!defined(array)) {
  5936. throw new DeveloperError('array is required');
  5937. }
  5938. startingIndex = defaultValue(startingIndex, 0);
  5939. array[startingIndex++] = value.x;
  5940. array[startingIndex++] = value.y;
  5941. array[startingIndex++] = value.z;
  5942. array[startingIndex] = value.w;
  5943. return array;
  5944. };
  5945. /**
  5946. * Retrieves an instance from a packed array.
  5947. *
  5948. * @param {Number[]} array The packed array.
  5949. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5950. * @param {Cartesian4} [result] The object into which to store the result.
  5951. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5952. */
  5953. Cartesian4.unpack = function(array, startingIndex, result) {
  5954. if (!defined(array)) {
  5955. throw new DeveloperError('array is required');
  5956. }
  5957. startingIndex = defaultValue(startingIndex, 0);
  5958. if (!defined(result)) {
  5959. result = new Cartesian4();
  5960. }
  5961. result.x = array[startingIndex++];
  5962. result.y = array[startingIndex++];
  5963. result.z = array[startingIndex++];
  5964. result.w = array[startingIndex];
  5965. return result;
  5966. };
  5967. /**
  5968. * Flattens an array of Cartesian4s into and array of components.
  5969. *
  5970. * @param {Cartesian4[]} array The array of cartesians to pack.
  5971. * @param {Number[]} result The array onto which to store the result.
  5972. * @returns {Number[]} The packed array.
  5973. */
  5974. Cartesian4.packArray = function(array, result) {
  5975. if (!defined(array)) {
  5976. throw new DeveloperError('array is required');
  5977. }
  5978. var length = array.length;
  5979. if (!defined(result)) {
  5980. result = new Array(length * 4);
  5981. } else {
  5982. result.length = length * 4;
  5983. }
  5984. for (var i = 0; i < length; ++i) {
  5985. Cartesian4.pack(array[i], result, i * 4);
  5986. }
  5987. return result;
  5988. };
  5989. /**
  5990. * Unpacks an array of cartesian components into and array of Cartesian4s.
  5991. *
  5992. * @param {Number[]} array The array of components to unpack.
  5993. * @param {Cartesian4[]} result The array onto which to store the result.
  5994. * @returns {Cartesian4[]} The unpacked array.
  5995. */
  5996. Cartesian4.unpackArray = function(array, result) {
  5997. if (!defined(array)) {
  5998. throw new DeveloperError('array is required');
  5999. }
  6000. var length = array.length;
  6001. if (!defined(result)) {
  6002. result = new Array(length / 4);
  6003. } else {
  6004. result.length = length / 4;
  6005. }
  6006. for (var i = 0; i < length; i += 4) {
  6007. var index = i / 4;
  6008. result[index] = Cartesian4.unpack(array, i, result[index]);
  6009. }
  6010. return result;
  6011. };
  6012. /**
  6013. * Creates a Cartesian4 from four consecutive elements in an array.
  6014. * @function
  6015. *
  6016. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  6017. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  6018. * @param {Cartesian4} [result] The object onto which to store the result.
  6019. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6020. *
  6021. * @example
  6022. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  6023. * var v = [1.0, 2.0, 3.0, 4.0];
  6024. * var p = Cesium.Cartesian4.fromArray(v);
  6025. *
  6026. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  6027. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  6028. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  6029. */
  6030. Cartesian4.fromArray = Cartesian4.unpack;
  6031. /**
  6032. * Computes the value of the maximum component for the supplied Cartesian.
  6033. *
  6034. * @param {Cartesian4} cartesian The cartesian to use.
  6035. * @returns {Number} The value of the maximum component.
  6036. */
  6037. Cartesian4.maximumComponent = function(cartesian) {
  6038. if (!defined(cartesian)) {
  6039. throw new DeveloperError('cartesian is required');
  6040. }
  6041. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6042. };
  6043. /**
  6044. * Computes the value of the minimum component for the supplied Cartesian.
  6045. *
  6046. * @param {Cartesian4} cartesian The cartesian to use.
  6047. * @returns {Number} The value of the minimum component.
  6048. */
  6049. Cartesian4.minimumComponent = function(cartesian) {
  6050. if (!defined(cartesian)) {
  6051. throw new DeveloperError('cartesian is required');
  6052. }
  6053. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6054. };
  6055. /**
  6056. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  6057. *
  6058. * @param {Cartesian4} first A cartesian to compare.
  6059. * @param {Cartesian4} second A cartesian to compare.
  6060. * @param {Cartesian4} result The object into which to store the result.
  6061. * @returns {Cartesian4} A cartesian with the minimum components.
  6062. */
  6063. Cartesian4.minimumByComponent = function(first, second, result) {
  6064. if (!defined(first)) {
  6065. throw new DeveloperError('first is required.');
  6066. }
  6067. if (!defined(second)) {
  6068. throw new DeveloperError('second is required.');
  6069. }
  6070. if (!defined(result)) {
  6071. throw new DeveloperError('result is required.');
  6072. }
  6073. result.x = Math.min(first.x, second.x);
  6074. result.y = Math.min(first.y, second.y);
  6075. result.z = Math.min(first.z, second.z);
  6076. result.w = Math.min(first.w, second.w);
  6077. return result;
  6078. };
  6079. /**
  6080. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  6081. *
  6082. * @param {Cartesian4} first A cartesian to compare.
  6083. * @param {Cartesian4} second A cartesian to compare.
  6084. * @param {Cartesian4} result The object into which to store the result.
  6085. * @returns {Cartesian4} A cartesian with the maximum components.
  6086. */
  6087. Cartesian4.maximumByComponent = function(first, second, result) {
  6088. if (!defined(first)) {
  6089. throw new DeveloperError('first is required.');
  6090. }
  6091. if (!defined(second)) {
  6092. throw new DeveloperError('second is required.');
  6093. }
  6094. if (!defined(result)) {
  6095. throw new DeveloperError('result is required.');
  6096. }
  6097. result.x = Math.max(first.x, second.x);
  6098. result.y = Math.max(first.y, second.y);
  6099. result.z = Math.max(first.z, second.z);
  6100. result.w = Math.max(first.w, second.w);
  6101. return result;
  6102. };
  6103. /**
  6104. * Computes the provided Cartesian's squared magnitude.
  6105. *
  6106. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  6107. * @returns {Number} The squared magnitude.
  6108. */
  6109. Cartesian4.magnitudeSquared = function(cartesian) {
  6110. if (!defined(cartesian)) {
  6111. throw new DeveloperError('cartesian is required');
  6112. }
  6113. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  6114. };
  6115. /**
  6116. * Computes the Cartesian's magnitude (length).
  6117. *
  6118. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  6119. * @returns {Number} The magnitude.
  6120. */
  6121. Cartesian4.magnitude = function(cartesian) {
  6122. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  6123. };
  6124. var distanceScratch = new Cartesian4();
  6125. /**
  6126. * Computes the 4-space distance between two points.
  6127. *
  6128. * @param {Cartesian4} left The first point to compute the distance from.
  6129. * @param {Cartesian4} right The second point to compute the distance to.
  6130. * @returns {Number} The distance between two points.
  6131. *
  6132. * @example
  6133. * // Returns 1.0
  6134. * var d = Cesium.Cartesian4.distance(
  6135. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6136. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  6137. */
  6138. Cartesian4.distance = function(left, right) {
  6139. if (!defined(left) || !defined(right)) {
  6140. throw new DeveloperError('left and right are required.');
  6141. }
  6142. Cartesian4.subtract(left, right, distanceScratch);
  6143. return Cartesian4.magnitude(distanceScratch);
  6144. };
  6145. /**
  6146. * Computes the squared distance between two points. Comparing squared distances
  6147. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  6148. *
  6149. * @param {Cartesian4} left The first point to compute the distance from.
  6150. * @param {Cartesian4} right The second point to compute the distance to.
  6151. * @returns {Number} The distance between two points.
  6152. *
  6153. * @example
  6154. * // Returns 4.0, not 2.0
  6155. * var d = Cesium.Cartesian4.distance(
  6156. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6157. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  6158. */
  6159. Cartesian4.distanceSquared = function(left, right) {
  6160. if (!defined(left) || !defined(right)) {
  6161. throw new DeveloperError('left and right are required.');
  6162. }
  6163. Cartesian4.subtract(left, right, distanceScratch);
  6164. return Cartesian4.magnitudeSquared(distanceScratch);
  6165. };
  6166. /**
  6167. * Computes the normalized form of the supplied Cartesian.
  6168. *
  6169. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  6170. * @param {Cartesian4} result The object onto which to store the result.
  6171. * @returns {Cartesian4} The modified result parameter.
  6172. */
  6173. Cartesian4.normalize = function(cartesian, result) {
  6174. if (!defined(cartesian)) {
  6175. throw new DeveloperError('cartesian is required');
  6176. }
  6177. if (!defined(result)) {
  6178. throw new DeveloperError('result is required');
  6179. }
  6180. var magnitude = Cartesian4.magnitude(cartesian);
  6181. result.x = cartesian.x / magnitude;
  6182. result.y = cartesian.y / magnitude;
  6183. result.z = cartesian.z / magnitude;
  6184. result.w = cartesian.w / magnitude;
  6185. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  6186. throw new DeveloperError('normalized result is not a number');
  6187. }
  6188. return result;
  6189. };
  6190. /**
  6191. * Computes the dot (scalar) product of two Cartesians.
  6192. *
  6193. * @param {Cartesian4} left The first Cartesian.
  6194. * @param {Cartesian4} right The second Cartesian.
  6195. * @returns {Number} The dot product.
  6196. */
  6197. Cartesian4.dot = function(left, right) {
  6198. if (!defined(left)) {
  6199. throw new DeveloperError('left is required');
  6200. }
  6201. if (!defined(right)) {
  6202. throw new DeveloperError('right is required');
  6203. }
  6204. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  6205. };
  6206. /**
  6207. * Computes the componentwise product of two Cartesians.
  6208. *
  6209. * @param {Cartesian4} left The first Cartesian.
  6210. * @param {Cartesian4} right The second Cartesian.
  6211. * @param {Cartesian4} result The object onto which to store the result.
  6212. * @returns {Cartesian4} The modified result parameter.
  6213. */
  6214. Cartesian4.multiplyComponents = function(left, right, result) {
  6215. if (!defined(left)) {
  6216. throw new DeveloperError('left is required');
  6217. }
  6218. if (!defined(right)) {
  6219. throw new DeveloperError('right is required');
  6220. }
  6221. if (!defined(result)) {
  6222. throw new DeveloperError('result is required');
  6223. }
  6224. result.x = left.x * right.x;
  6225. result.y = left.y * right.y;
  6226. result.z = left.z * right.z;
  6227. result.w = left.w * right.w;
  6228. return result;
  6229. };
  6230. /**
  6231. * Computes the componentwise quotient of two Cartesians.
  6232. *
  6233. * @param {Cartesian4} left The first Cartesian.
  6234. * @param {Cartesian4} right The second Cartesian.
  6235. * @param {Cartesian4} result The object onto which to store the result.
  6236. * @returns {Cartesian4} The modified result parameter.
  6237. */
  6238. Cartesian4.divideComponents = function(left, right, result) {
  6239. if (!defined(left)) {
  6240. throw new DeveloperError('left is required');
  6241. }
  6242. if (!defined(right)) {
  6243. throw new DeveloperError('right is required');
  6244. }
  6245. if (!defined(result)) {
  6246. throw new DeveloperError('result is required');
  6247. }
  6248. result.x = left.x / right.x;
  6249. result.y = left.y / right.y;
  6250. result.z = left.z / right.z;
  6251. result.w = left.w / right.w;
  6252. return result;
  6253. };
  6254. /**
  6255. * Computes the componentwise sum of two Cartesians.
  6256. *
  6257. * @param {Cartesian4} left The first Cartesian.
  6258. * @param {Cartesian4} right The second Cartesian.
  6259. * @param {Cartesian4} result The object onto which to store the result.
  6260. * @returns {Cartesian4} The modified result parameter.
  6261. */
  6262. Cartesian4.add = function(left, right, result) {
  6263. if (!defined(left)) {
  6264. throw new DeveloperError('left is required');
  6265. }
  6266. if (!defined(right)) {
  6267. throw new DeveloperError('right is required');
  6268. }
  6269. if (!defined(result)) {
  6270. throw new DeveloperError('result is required');
  6271. }
  6272. result.x = left.x + right.x;
  6273. result.y = left.y + right.y;
  6274. result.z = left.z + right.z;
  6275. result.w = left.w + right.w;
  6276. return result;
  6277. };
  6278. /**
  6279. * Computes the componentwise difference of two Cartesians.
  6280. *
  6281. * @param {Cartesian4} left The first Cartesian.
  6282. * @param {Cartesian4} right The second Cartesian.
  6283. * @param {Cartesian4} result The object onto which to store the result.
  6284. * @returns {Cartesian4} The modified result parameter.
  6285. */
  6286. Cartesian4.subtract = function(left, right, result) {
  6287. if (!defined(left)) {
  6288. throw new DeveloperError('left is required');
  6289. }
  6290. if (!defined(right)) {
  6291. throw new DeveloperError('right is required');
  6292. }
  6293. if (!defined(result)) {
  6294. throw new DeveloperError('result is required');
  6295. }
  6296. result.x = left.x - right.x;
  6297. result.y = left.y - right.y;
  6298. result.z = left.z - right.z;
  6299. result.w = left.w - right.w;
  6300. return result;
  6301. };
  6302. /**
  6303. * Multiplies the provided Cartesian componentwise by the provided scalar.
  6304. *
  6305. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  6306. * @param {Number} scalar The scalar to multiply with.
  6307. * @param {Cartesian4} result The object onto which to store the result.
  6308. * @returns {Cartesian4} The modified result parameter.
  6309. */
  6310. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  6311. if (!defined(cartesian)) {
  6312. throw new DeveloperError('cartesian is required');
  6313. }
  6314. if (typeof scalar !== 'number') {
  6315. throw new DeveloperError('scalar is required and must be a number.');
  6316. }
  6317. if (!defined(result)) {
  6318. throw new DeveloperError('result is required');
  6319. }
  6320. result.x = cartesian.x * scalar;
  6321. result.y = cartesian.y * scalar;
  6322. result.z = cartesian.z * scalar;
  6323. result.w = cartesian.w * scalar;
  6324. return result;
  6325. };
  6326. /**
  6327. * Divides the provided Cartesian componentwise by the provided scalar.
  6328. *
  6329. * @param {Cartesian4} cartesian The Cartesian to be divided.
  6330. * @param {Number} scalar The scalar to divide by.
  6331. * @param {Cartesian4} result The object onto which to store the result.
  6332. * @returns {Cartesian4} The modified result parameter.
  6333. */
  6334. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  6335. if (!defined(cartesian)) {
  6336. throw new DeveloperError('cartesian is required');
  6337. }
  6338. if (typeof scalar !== 'number') {
  6339. throw new DeveloperError('scalar is required and must be a number.');
  6340. }
  6341. if (!defined(result)) {
  6342. throw new DeveloperError('result is required');
  6343. }
  6344. result.x = cartesian.x / scalar;
  6345. result.y = cartesian.y / scalar;
  6346. result.z = cartesian.z / scalar;
  6347. result.w = cartesian.w / scalar;
  6348. return result;
  6349. };
  6350. /**
  6351. * Negates the provided Cartesian.
  6352. *
  6353. * @param {Cartesian4} cartesian The Cartesian to be negated.
  6354. * @param {Cartesian4} result The object onto which to store the result.
  6355. * @returns {Cartesian4} The modified result parameter.
  6356. */
  6357. Cartesian4.negate = function(cartesian, result) {
  6358. if (!defined(cartesian)) {
  6359. throw new DeveloperError('cartesian is required');
  6360. }
  6361. if (!defined(result)) {
  6362. throw new DeveloperError('result is required');
  6363. }
  6364. result.x = -cartesian.x;
  6365. result.y = -cartesian.y;
  6366. result.z = -cartesian.z;
  6367. result.w = -cartesian.w;
  6368. return result;
  6369. };
  6370. /**
  6371. * Computes the absolute value of the provided Cartesian.
  6372. *
  6373. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  6374. * @param {Cartesian4} result The object onto which to store the result.
  6375. * @returns {Cartesian4} The modified result parameter.
  6376. */
  6377. Cartesian4.abs = function(cartesian, result) {
  6378. if (!defined(cartesian)) {
  6379. throw new DeveloperError('cartesian is required');
  6380. }
  6381. if (!defined(result)) {
  6382. throw new DeveloperError('result is required');
  6383. }
  6384. result.x = Math.abs(cartesian.x);
  6385. result.y = Math.abs(cartesian.y);
  6386. result.z = Math.abs(cartesian.z);
  6387. result.w = Math.abs(cartesian.w);
  6388. return result;
  6389. };
  6390. var lerpScratch = new Cartesian4();
  6391. /**
  6392. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  6393. *
  6394. * @param {Cartesian4} start The value corresponding to t at 0.0.
  6395. * @param {Cartesian4}end The value corresponding to t at 1.0.
  6396. * @param {Number} t The point along t at which to interpolate.
  6397. * @param {Cartesian4} result The object onto which to store the result.
  6398. * @returns {Cartesian4} The modified result parameter.
  6399. */
  6400. Cartesian4.lerp = function(start, end, t, result) {
  6401. if (!defined(start)) {
  6402. throw new DeveloperError('start is required.');
  6403. }
  6404. if (!defined(end)) {
  6405. throw new DeveloperError('end is required.');
  6406. }
  6407. if (typeof t !== 'number') {
  6408. throw new DeveloperError('t is required and must be a number.');
  6409. }
  6410. if (!defined(result)) {
  6411. throw new DeveloperError('result is required.');
  6412. }
  6413. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  6414. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  6415. return Cartesian4.add(lerpScratch, result, result);
  6416. };
  6417. var mostOrthogonalAxisScratch = new Cartesian4();
  6418. /**
  6419. * Returns the axis that is most orthogonal to the provided Cartesian.
  6420. *
  6421. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  6422. * @param {Cartesian4} result The object onto which to store the result.
  6423. * @returns {Cartesian4} The most orthogonal axis.
  6424. */
  6425. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  6426. if (!defined(cartesian)) {
  6427. throw new DeveloperError('cartesian is required.');
  6428. }
  6429. if (!defined(result)) {
  6430. throw new DeveloperError('result is required.');
  6431. }
  6432. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  6433. Cartesian4.abs(f, f);
  6434. if (f.x <= f.y) {
  6435. if (f.x <= f.z) {
  6436. if (f.x <= f.w) {
  6437. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  6438. } else {
  6439. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  6440. }
  6441. } else if (f.z <= f.w) {
  6442. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  6443. } else {
  6444. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  6445. }
  6446. } else if (f.y <= f.z) {
  6447. if (f.y <= f.w) {
  6448. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  6449. } else {
  6450. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  6451. }
  6452. } else if (f.z <= f.w) {
  6453. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  6454. } else {
  6455. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  6456. }
  6457. return result;
  6458. };
  6459. /**
  6460. * Compares the provided Cartesians componentwise and returns
  6461. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6462. *
  6463. * @param {Cartesian4} [left] The first Cartesian.
  6464. * @param {Cartesian4} [right] The second Cartesian.
  6465. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  6466. */
  6467. Cartesian4.equals = function(left, right) {
  6468. return (left === right) ||
  6469. ((defined(left)) &&
  6470. (defined(right)) &&
  6471. (left.x === right.x) &&
  6472. (left.y === right.y) &&
  6473. (left.z === right.z) &&
  6474. (left.w === right.w));
  6475. };
  6476. /**
  6477. * @private
  6478. */
  6479. Cartesian4.equalsArray = function(cartesian, array, offset) {
  6480. return cartesian.x === array[offset] &&
  6481. cartesian.y === array[offset + 1] &&
  6482. cartesian.z === array[offset + 2] &&
  6483. cartesian.w === array[offset + 3];
  6484. };
  6485. /**
  6486. * Compares the provided Cartesians componentwise and returns
  6487. * <code>true</code> if they pass an absolute or relative tolerance test,
  6488. * <code>false</code> otherwise.
  6489. *
  6490. * @param {Cartesian4} [left] The first Cartesian.
  6491. * @param {Cartesian4} [right] The second Cartesian.
  6492. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  6493. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  6494. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  6495. */
  6496. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  6497. return (left === right) ||
  6498. (defined(left) &&
  6499. defined(right) &&
  6500. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  6501. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  6502. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  6503. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  6504. };
  6505. /**
  6506. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  6507. *
  6508. * @type {Cartesian4}
  6509. * @constant
  6510. */
  6511. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  6512. /**
  6513. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  6514. *
  6515. * @type {Cartesian4}
  6516. * @constant
  6517. */
  6518. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  6519. /**
  6520. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  6521. *
  6522. * @type {Cartesian4}
  6523. * @constant
  6524. */
  6525. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  6526. /**
  6527. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  6528. *
  6529. * @type {Cartesian4}
  6530. * @constant
  6531. */
  6532. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  6533. /**
  6534. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  6535. *
  6536. * @type {Cartesian4}
  6537. * @constant
  6538. */
  6539. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  6540. /**
  6541. * Duplicates this Cartesian4 instance.
  6542. *
  6543. * @param {Cartesian4} [result] The object onto which to store the result.
  6544. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6545. */
  6546. Cartesian4.prototype.clone = function(result) {
  6547. return Cartesian4.clone(this, result);
  6548. };
  6549. /**
  6550. * Compares this Cartesian against the provided Cartesian componentwise and returns
  6551. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6552. *
  6553. * @param {Cartesian4} [right] The right hand side Cartesian.
  6554. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  6555. */
  6556. Cartesian4.prototype.equals = function(right) {
  6557. return Cartesian4.equals(this, right);
  6558. };
  6559. /**
  6560. * Compares this Cartesian against the provided Cartesian componentwise and returns
  6561. * <code>true</code> if they pass an absolute or relative tolerance test,
  6562. * <code>false</code> otherwise.
  6563. *
  6564. * @param {Cartesian4} [right] The right hand side Cartesian.
  6565. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  6566. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  6567. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  6568. */
  6569. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  6570. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  6571. };
  6572. /**
  6573. * Creates a string representing this Cartesian in the format '(x, y)'.
  6574. *
  6575. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  6576. */
  6577. Cartesian4.prototype.toString = function() {
  6578. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  6579. };
  6580. return Cartesian4;
  6581. });
  6582. /*global define*/
  6583. define('Core/RuntimeError',[
  6584. './defined'
  6585. ], function(
  6586. defined) {
  6587. 'use strict';
  6588. /**
  6589. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  6590. * out of memory, could not compile shader, etc. If a function may throw this
  6591. * exception, the calling code should be prepared to catch it.
  6592. * <br /><br />
  6593. * On the other hand, a {@link DeveloperError} indicates an exception due
  6594. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  6595. * calling code.
  6596. *
  6597. * @alias RuntimeError
  6598. * @constructor
  6599. * @extends Error
  6600. *
  6601. * @param {String} [message] The error message for this exception.
  6602. *
  6603. * @see DeveloperError
  6604. */
  6605. function RuntimeError(message) {
  6606. /**
  6607. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  6608. * @type {String}
  6609. * @readonly
  6610. */
  6611. this.name = 'RuntimeError';
  6612. /**
  6613. * The explanation for why this exception was thrown.
  6614. * @type {String}
  6615. * @readonly
  6616. */
  6617. this.message = message;
  6618. //Browsers such as IE don't have a stack property until you actually throw the error.
  6619. var stack;
  6620. try {
  6621. throw new Error();
  6622. } catch (e) {
  6623. stack = e.stack;
  6624. }
  6625. /**
  6626. * The stack trace of this exception, if available.
  6627. * @type {String}
  6628. * @readonly
  6629. */
  6630. this.stack = stack;
  6631. }
  6632. if (defined(Object.create)) {
  6633. RuntimeError.prototype = Object.create(Error.prototype);
  6634. RuntimeError.prototype.constructor = RuntimeError;
  6635. }
  6636. RuntimeError.prototype.toString = function() {
  6637. var str = this.name + ': ' + this.message;
  6638. if (defined(this.stack)) {
  6639. str += '\n' + this.stack.toString();
  6640. }
  6641. return str;
  6642. };
  6643. return RuntimeError;
  6644. });
  6645. /*global define*/
  6646. define('Core/Matrix4',[
  6647. './Cartesian3',
  6648. './Cartesian4',
  6649. './defaultValue',
  6650. './defined',
  6651. './defineProperties',
  6652. './DeveloperError',
  6653. './freezeObject',
  6654. './Math',
  6655. './Matrix3',
  6656. './RuntimeError'
  6657. ], function(
  6658. Cartesian3,
  6659. Cartesian4,
  6660. defaultValue,
  6661. defined,
  6662. defineProperties,
  6663. DeveloperError,
  6664. freezeObject,
  6665. CesiumMath,
  6666. Matrix3,
  6667. RuntimeError) {
  6668. 'use strict';
  6669. /**
  6670. * A 4x4 matrix, indexable as a column-major order array.
  6671. * Constructor parameters are in row-major order for code readability.
  6672. * @alias Matrix4
  6673. * @constructor
  6674. *
  6675. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  6676. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  6677. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  6678. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  6679. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  6680. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  6681. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  6682. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  6683. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  6684. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  6685. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  6686. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  6687. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  6688. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  6689. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  6690. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  6691. *
  6692. * @see Matrix4.fromColumnMajorArray
  6693. * @see Matrix4.fromRowMajorArray
  6694. * @see Matrix4.fromRotationTranslation
  6695. * @see Matrix4.fromTranslationRotationScale
  6696. * @see Matrix4.fromTranslationQuaternionRotationScale
  6697. * @see Matrix4.fromTranslation
  6698. * @see Matrix4.fromScale
  6699. * @see Matrix4.fromUniformScale
  6700. * @see Matrix4.fromCamera
  6701. * @see Matrix4.computePerspectiveFieldOfView
  6702. * @see Matrix4.computeOrthographicOffCenter
  6703. * @see Matrix4.computePerspectiveOffCenter
  6704. * @see Matrix4.computeInfinitePerspectiveOffCenter
  6705. * @see Matrix4.computeViewportTransformation
  6706. * @see Matrix4.computeView
  6707. * @see Matrix2
  6708. * @see Matrix3
  6709. * @see Packable
  6710. */
  6711. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  6712. column0Row1, column1Row1, column2Row1, column3Row1,
  6713. column0Row2, column1Row2, column2Row2, column3Row2,
  6714. column0Row3, column1Row3, column2Row3, column3Row3) {
  6715. this[0] = defaultValue(column0Row0, 0.0);
  6716. this[1] = defaultValue(column0Row1, 0.0);
  6717. this[2] = defaultValue(column0Row2, 0.0);
  6718. this[3] = defaultValue(column0Row3, 0.0);
  6719. this[4] = defaultValue(column1Row0, 0.0);
  6720. this[5] = defaultValue(column1Row1, 0.0);
  6721. this[6] = defaultValue(column1Row2, 0.0);
  6722. this[7] = defaultValue(column1Row3, 0.0);
  6723. this[8] = defaultValue(column2Row0, 0.0);
  6724. this[9] = defaultValue(column2Row1, 0.0);
  6725. this[10] = defaultValue(column2Row2, 0.0);
  6726. this[11] = defaultValue(column2Row3, 0.0);
  6727. this[12] = defaultValue(column3Row0, 0.0);
  6728. this[13] = defaultValue(column3Row1, 0.0);
  6729. this[14] = defaultValue(column3Row2, 0.0);
  6730. this[15] = defaultValue(column3Row3, 0.0);
  6731. }
  6732. /**
  6733. * The number of elements used to pack the object into an array.
  6734. * @type {Number}
  6735. */
  6736. Matrix4.packedLength = 16;
  6737. /**
  6738. * Stores the provided instance into the provided array.
  6739. *
  6740. * @param {Matrix4} value The value to pack.
  6741. * @param {Number[]} array The array to pack into.
  6742. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  6743. *
  6744. * @returns {Number[]} The array that was packed into
  6745. */
  6746. Matrix4.pack = function(value, array, startingIndex) {
  6747. if (!defined(value)) {
  6748. throw new DeveloperError('value is required');
  6749. }
  6750. if (!defined(array)) {
  6751. throw new DeveloperError('array is required');
  6752. }
  6753. startingIndex = defaultValue(startingIndex, 0);
  6754. array[startingIndex++] = value[0];
  6755. array[startingIndex++] = value[1];
  6756. array[startingIndex++] = value[2];
  6757. array[startingIndex++] = value[3];
  6758. array[startingIndex++] = value[4];
  6759. array[startingIndex++] = value[5];
  6760. array[startingIndex++] = value[6];
  6761. array[startingIndex++] = value[7];
  6762. array[startingIndex++] = value[8];
  6763. array[startingIndex++] = value[9];
  6764. array[startingIndex++] = value[10];
  6765. array[startingIndex++] = value[11];
  6766. array[startingIndex++] = value[12];
  6767. array[startingIndex++] = value[13];
  6768. array[startingIndex++] = value[14];
  6769. array[startingIndex] = value[15];
  6770. return array;
  6771. };
  6772. /**
  6773. * Retrieves an instance from a packed array.
  6774. *
  6775. * @param {Number[]} array The packed array.
  6776. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  6777. * @param {Matrix4} [result] The object into which to store the result.
  6778. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  6779. */
  6780. Matrix4.unpack = function(array, startingIndex, result) {
  6781. if (!defined(array)) {
  6782. throw new DeveloperError('array is required');
  6783. }
  6784. startingIndex = defaultValue(startingIndex, 0);
  6785. if (!defined(result)) {
  6786. result = new Matrix4();
  6787. }
  6788. result[0] = array[startingIndex++];
  6789. result[1] = array[startingIndex++];
  6790. result[2] = array[startingIndex++];
  6791. result[3] = array[startingIndex++];
  6792. result[4] = array[startingIndex++];
  6793. result[5] = array[startingIndex++];
  6794. result[6] = array[startingIndex++];
  6795. result[7] = array[startingIndex++];
  6796. result[8] = array[startingIndex++];
  6797. result[9] = array[startingIndex++];
  6798. result[10] = array[startingIndex++];
  6799. result[11] = array[startingIndex++];
  6800. result[12] = array[startingIndex++];
  6801. result[13] = array[startingIndex++];
  6802. result[14] = array[startingIndex++];
  6803. result[15] = array[startingIndex];
  6804. return result;
  6805. };
  6806. /**
  6807. * Duplicates a Matrix4 instance.
  6808. *
  6809. * @param {Matrix4} matrix The matrix to duplicate.
  6810. * @param {Matrix4} [result] The object onto which to store the result.
  6811. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  6812. */
  6813. Matrix4.clone = function(matrix, result) {
  6814. if (!defined(matrix)) {
  6815. return undefined;
  6816. }
  6817. if (!defined(result)) {
  6818. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  6819. matrix[1], matrix[5], matrix[9], matrix[13],
  6820. matrix[2], matrix[6], matrix[10], matrix[14],
  6821. matrix[3], matrix[7], matrix[11], matrix[15]);
  6822. }
  6823. result[0] = matrix[0];
  6824. result[1] = matrix[1];
  6825. result[2] = matrix[2];
  6826. result[3] = matrix[3];
  6827. result[4] = matrix[4];
  6828. result[5] = matrix[5];
  6829. result[6] = matrix[6];
  6830. result[7] = matrix[7];
  6831. result[8] = matrix[8];
  6832. result[9] = matrix[9];
  6833. result[10] = matrix[10];
  6834. result[11] = matrix[11];
  6835. result[12] = matrix[12];
  6836. result[13] = matrix[13];
  6837. result[14] = matrix[14];
  6838. result[15] = matrix[15];
  6839. return result;
  6840. };
  6841. /**
  6842. * Creates a Matrix4 from 16 consecutive elements in an array.
  6843. * @function
  6844. *
  6845. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  6846. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  6847. * @param {Matrix4} [result] The object onto which to store the result.
  6848. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  6849. *
  6850. * @example
  6851. * // Create the Matrix4:
  6852. * // [1.0, 2.0, 3.0, 4.0]
  6853. * // [1.0, 2.0, 3.0, 4.0]
  6854. * // [1.0, 2.0, 3.0, 4.0]
  6855. * // [1.0, 2.0, 3.0, 4.0]
  6856. *
  6857. * 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];
  6858. * var m = Cesium.Matrix4.fromArray(v);
  6859. *
  6860. * // Create same Matrix4 with using an offset into an array
  6861. * 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];
  6862. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  6863. */
  6864. Matrix4.fromArray = Matrix4.unpack;
  6865. /**
  6866. * Computes a Matrix4 instance from a column-major order array.
  6867. *
  6868. * @param {Number[]} values The column-major order array.
  6869. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6870. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6871. */
  6872. Matrix4.fromColumnMajorArray = function(values, result) {
  6873. if (!defined(values)) {
  6874. throw new DeveloperError('values is required');
  6875. }
  6876. return Matrix4.clone(values, result);
  6877. };
  6878. /**
  6879. * Computes a Matrix4 instance from a row-major order array.
  6880. * The resulting matrix will be in column-major order.
  6881. *
  6882. * @param {Number[]} values The row-major order array.
  6883. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6884. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6885. */
  6886. Matrix4.fromRowMajorArray = function(values, result) {
  6887. if (!defined(values)) {
  6888. throw new DeveloperError('values is required.');
  6889. }
  6890. if (!defined(result)) {
  6891. return new Matrix4(values[0], values[1], values[2], values[3],
  6892. values[4], values[5], values[6], values[7],
  6893. values[8], values[9], values[10], values[11],
  6894. values[12], values[13], values[14], values[15]);
  6895. }
  6896. result[0] = values[0];
  6897. result[1] = values[4];
  6898. result[2] = values[8];
  6899. result[3] = values[12];
  6900. result[4] = values[1];
  6901. result[5] = values[5];
  6902. result[6] = values[9];
  6903. result[7] = values[13];
  6904. result[8] = values[2];
  6905. result[9] = values[6];
  6906. result[10] = values[10];
  6907. result[11] = values[14];
  6908. result[12] = values[3];
  6909. result[13] = values[7];
  6910. result[14] = values[11];
  6911. result[15] = values[15];
  6912. return result;
  6913. };
  6914. /**
  6915. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  6916. * and a Cartesian3 representing the translation.
  6917. *
  6918. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  6919. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  6920. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6921. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6922. */
  6923. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  6924. if (!defined(rotation)) {
  6925. throw new DeveloperError('rotation is required.');
  6926. }
  6927. translation = defaultValue(translation, Cartesian3.ZERO);
  6928. if (!defined(result)) {
  6929. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  6930. rotation[1], rotation[4], rotation[7], translation.y,
  6931. rotation[2], rotation[5], rotation[8], translation.z,
  6932. 0.0, 0.0, 0.0, 1.0);
  6933. }
  6934. result[0] = rotation[0];
  6935. result[1] = rotation[1];
  6936. result[2] = rotation[2];
  6937. result[3] = 0.0;
  6938. result[4] = rotation[3];
  6939. result[5] = rotation[4];
  6940. result[6] = rotation[5];
  6941. result[7] = 0.0;
  6942. result[8] = rotation[6];
  6943. result[9] = rotation[7];
  6944. result[10] = rotation[8];
  6945. result[11] = 0.0;
  6946. result[12] = translation.x;
  6947. result[13] = translation.y;
  6948. result[14] = translation.z;
  6949. result[15] = 1.0;
  6950. return result;
  6951. };
  6952. /**
  6953. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  6954. * representation with the rotation represented as a quaternion.
  6955. *
  6956. * @param {Cartesian3} translation The translation transformation.
  6957. * @param {Quaternion} rotation The rotation transformation.
  6958. * @param {Cartesian3} scale The non-uniform scale transformation.
  6959. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6960. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6961. *
  6962. * @example
  6963. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  6964. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  6965. * Cesium.Quaternion.IDENTITY, // rotation
  6966. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  6967. * result);
  6968. */
  6969. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  6970. if (!defined(translation)) {
  6971. throw new DeveloperError('translation is required.');
  6972. }
  6973. if (!defined(rotation)) {
  6974. throw new DeveloperError('rotation is required.');
  6975. }
  6976. if (!defined(scale)) {
  6977. throw new DeveloperError('scale is required.');
  6978. }
  6979. if (!defined(result)) {
  6980. result = new Matrix4();
  6981. }
  6982. var scaleX = scale.x;
  6983. var scaleY = scale.y;
  6984. var scaleZ = scale.z;
  6985. var x2 = rotation.x * rotation.x;
  6986. var xy = rotation.x * rotation.y;
  6987. var xz = rotation.x * rotation.z;
  6988. var xw = rotation.x * rotation.w;
  6989. var y2 = rotation.y * rotation.y;
  6990. var yz = rotation.y * rotation.z;
  6991. var yw = rotation.y * rotation.w;
  6992. var z2 = rotation.z * rotation.z;
  6993. var zw = rotation.z * rotation.w;
  6994. var w2 = rotation.w * rotation.w;
  6995. var m00 = x2 - y2 - z2 + w2;
  6996. var m01 = 2.0 * (xy - zw);
  6997. var m02 = 2.0 * (xz + yw);
  6998. var m10 = 2.0 * (xy + zw);
  6999. var m11 = -x2 + y2 - z2 + w2;
  7000. var m12 = 2.0 * (yz - xw);
  7001. var m20 = 2.0 * (xz - yw);
  7002. var m21 = 2.0 * (yz + xw);
  7003. var m22 = -x2 - y2 + z2 + w2;
  7004. result[0] = m00 * scaleX;
  7005. result[1] = m10 * scaleX;
  7006. result[2] = m20 * scaleX;
  7007. result[3] = 0.0;
  7008. result[4] = m01 * scaleY;
  7009. result[5] = m11 * scaleY;
  7010. result[6] = m21 * scaleY;
  7011. result[7] = 0.0;
  7012. result[8] = m02 * scaleZ;
  7013. result[9] = m12 * scaleZ;
  7014. result[10] = m22 * scaleZ;
  7015. result[11] = 0.0;
  7016. result[12] = translation.x;
  7017. result[13] = translation.y;
  7018. result[14] = translation.z;
  7019. result[15] = 1.0;
  7020. return result;
  7021. };
  7022. /**
  7023. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  7024. *
  7025. * @param {TranslationRotationScale} translationRotationScale The instance.
  7026. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7027. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7028. */
  7029. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  7030. if (!defined(translationRotationScale)) {
  7031. throw new DeveloperError('translationRotationScale is required.');
  7032. }
  7033. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  7034. };
  7035. /**
  7036. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  7037. *
  7038. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  7039. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7040. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7041. *
  7042. * @see Matrix4.multiplyByTranslation
  7043. */
  7044. Matrix4.fromTranslation = function(translation, result) {
  7045. if (!defined(translation)) {
  7046. throw new DeveloperError('translation is required.');
  7047. }
  7048. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  7049. };
  7050. /**
  7051. * Computes a Matrix4 instance representing a non-uniform scale.
  7052. *
  7053. * @param {Cartesian3} scale The x, y, and z scale factors.
  7054. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7055. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7056. *
  7057. * @example
  7058. * // Creates
  7059. * // [7.0, 0.0, 0.0, 0.0]
  7060. * // [0.0, 8.0, 0.0, 0.0]
  7061. * // [0.0, 0.0, 9.0, 0.0]
  7062. * // [0.0, 0.0, 0.0, 1.0]
  7063. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  7064. */
  7065. Matrix4.fromScale = function(scale, result) {
  7066. if (!defined(scale)) {
  7067. throw new DeveloperError('scale is required.');
  7068. }
  7069. if (!defined(result)) {
  7070. return new Matrix4(
  7071. scale.x, 0.0, 0.0, 0.0,
  7072. 0.0, scale.y, 0.0, 0.0,
  7073. 0.0, 0.0, scale.z, 0.0,
  7074. 0.0, 0.0, 0.0, 1.0);
  7075. }
  7076. result[0] = scale.x;
  7077. result[1] = 0.0;
  7078. result[2] = 0.0;
  7079. result[3] = 0.0;
  7080. result[4] = 0.0;
  7081. result[5] = scale.y;
  7082. result[6] = 0.0;
  7083. result[7] = 0.0;
  7084. result[8] = 0.0;
  7085. result[9] = 0.0;
  7086. result[10] = scale.z;
  7087. result[11] = 0.0;
  7088. result[12] = 0.0;
  7089. result[13] = 0.0;
  7090. result[14] = 0.0;
  7091. result[15] = 1.0;
  7092. return result;
  7093. };
  7094. /**
  7095. * Computes a Matrix4 instance representing a uniform scale.
  7096. *
  7097. * @param {Number} scale The uniform scale factor.
  7098. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7099. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7100. *
  7101. * @example
  7102. * // Creates
  7103. * // [2.0, 0.0, 0.0, 0.0]
  7104. * // [0.0, 2.0, 0.0, 0.0]
  7105. * // [0.0, 0.0, 2.0, 0.0]
  7106. * // [0.0, 0.0, 0.0, 1.0]
  7107. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  7108. */
  7109. Matrix4.fromUniformScale = function(scale, result) {
  7110. if (typeof scale !== 'number') {
  7111. throw new DeveloperError('scale is required.');
  7112. }
  7113. if (!defined(result)) {
  7114. return new Matrix4(scale, 0.0, 0.0, 0.0,
  7115. 0.0, scale, 0.0, 0.0,
  7116. 0.0, 0.0, scale, 0.0,
  7117. 0.0, 0.0, 0.0, 1.0);
  7118. }
  7119. result[0] = scale;
  7120. result[1] = 0.0;
  7121. result[2] = 0.0;
  7122. result[3] = 0.0;
  7123. result[4] = 0.0;
  7124. result[5] = scale;
  7125. result[6] = 0.0;
  7126. result[7] = 0.0;
  7127. result[8] = 0.0;
  7128. result[9] = 0.0;
  7129. result[10] = scale;
  7130. result[11] = 0.0;
  7131. result[12] = 0.0;
  7132. result[13] = 0.0;
  7133. result[14] = 0.0;
  7134. result[15] = 1.0;
  7135. return result;
  7136. };
  7137. var fromCameraF = new Cartesian3();
  7138. var fromCameraR = new Cartesian3();
  7139. var fromCameraU = new Cartesian3();
  7140. /**
  7141. * Computes a Matrix4 instance from a Camera.
  7142. *
  7143. * @param {Camera} camera The camera to use.
  7144. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7145. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7146. */
  7147. Matrix4.fromCamera = function(camera, result) {
  7148. if (!defined(camera)) {
  7149. throw new DeveloperError('camera is required.');
  7150. }
  7151. var position = camera.position;
  7152. var direction = camera.direction;
  7153. var up = camera.up;
  7154. if (!defined(position)) {
  7155. throw new DeveloperError('camera.position is required.');
  7156. }
  7157. if (!defined(direction)) {
  7158. throw new DeveloperError('camera.direction is required.');
  7159. }
  7160. if (!defined(up)) {
  7161. throw new DeveloperError('camera.up is required.');
  7162. }
  7163. Cartesian3.normalize(direction, fromCameraF);
  7164. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  7165. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  7166. var sX = fromCameraR.x;
  7167. var sY = fromCameraR.y;
  7168. var sZ = fromCameraR.z;
  7169. var fX = fromCameraF.x;
  7170. var fY = fromCameraF.y;
  7171. var fZ = fromCameraF.z;
  7172. var uX = fromCameraU.x;
  7173. var uY = fromCameraU.y;
  7174. var uZ = fromCameraU.z;
  7175. var positionX = position.x;
  7176. var positionY = position.y;
  7177. var positionZ = position.z;
  7178. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  7179. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  7180. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  7181. // The code below this comment is an optimized
  7182. // version of the commented lines.
  7183. // Rather that create two matrices and then multiply,
  7184. // we just bake in the multiplcation as part of creation.
  7185. // var rotation = new Matrix4(
  7186. // sX, sY, sZ, 0.0,
  7187. // uX, uY, uZ, 0.0,
  7188. // -fX, -fY, -fZ, 0.0,
  7189. // 0.0, 0.0, 0.0, 1.0);
  7190. // var translation = new Matrix4(
  7191. // 1.0, 0.0, 0.0, -position.x,
  7192. // 0.0, 1.0, 0.0, -position.y,
  7193. // 0.0, 0.0, 1.0, -position.z,
  7194. // 0.0, 0.0, 0.0, 1.0);
  7195. // return rotation.multiply(translation);
  7196. if (!defined(result)) {
  7197. return new Matrix4(
  7198. sX, sY, sZ, t0,
  7199. uX, uY, uZ, t1,
  7200. -fX, -fY, -fZ, t2,
  7201. 0.0, 0.0, 0.0, 1.0);
  7202. }
  7203. result[0] = sX;
  7204. result[1] = uX;
  7205. result[2] = -fX;
  7206. result[3] = 0.0;
  7207. result[4] = sY;
  7208. result[5] = uY;
  7209. result[6] = -fY;
  7210. result[7] = 0.0;
  7211. result[8] = sZ;
  7212. result[9] = uZ;
  7213. result[10] = -fZ;
  7214. result[11] = 0.0;
  7215. result[12] = t0;
  7216. result[13] = t1;
  7217. result[14] = t2;
  7218. result[15] = 1.0;
  7219. return result;
  7220. };
  7221. /**
  7222. * Computes a Matrix4 instance representing a perspective transformation matrix.
  7223. *
  7224. * @param {Number} fovY The field of view along the Y axis in radians.
  7225. * @param {Number} aspectRatio The aspect ratio.
  7226. * @param {Number} near The distance to the near plane in meters.
  7227. * @param {Number} far The distance to the far plane in meters.
  7228. * @param {Matrix4} result The object in which the result will be stored.
  7229. * @returns {Matrix4} The modified result parameter.
  7230. *
  7231. * @exception {DeveloperError} fovY must be in (0, PI].
  7232. * @exception {DeveloperError} aspectRatio must be greater than zero.
  7233. * @exception {DeveloperError} near must be greater than zero.
  7234. * @exception {DeveloperError} far must be greater than zero.
  7235. */
  7236. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  7237. if (fovY <= 0.0 || fovY > Math.PI) {
  7238. throw new DeveloperError('fovY must be in (0, PI].');
  7239. }
  7240. if (aspectRatio <= 0.0) {
  7241. throw new DeveloperError('aspectRatio must be greater than zero.');
  7242. }
  7243. if (near <= 0.0) {
  7244. throw new DeveloperError('near must be greater than zero.');
  7245. }
  7246. if (far <= 0.0) {
  7247. throw new DeveloperError('far must be greater than zero.');
  7248. }
  7249. if (!defined(result)) {
  7250. throw new DeveloperError('result is required');
  7251. }
  7252. var bottom = Math.tan(fovY * 0.5);
  7253. var column1Row1 = 1.0 / bottom;
  7254. var column0Row0 = column1Row1 / aspectRatio;
  7255. var column2Row2 = (far + near) / (near - far);
  7256. var column3Row2 = (2.0 * far * near) / (near - far);
  7257. result[0] = column0Row0;
  7258. result[1] = 0.0;
  7259. result[2] = 0.0;
  7260. result[3] = 0.0;
  7261. result[4] = 0.0;
  7262. result[5] = column1Row1;
  7263. result[6] = 0.0;
  7264. result[7] = 0.0;
  7265. result[8] = 0.0;
  7266. result[9] = 0.0;
  7267. result[10] = column2Row2;
  7268. result[11] = -1.0;
  7269. result[12] = 0.0;
  7270. result[13] = 0.0;
  7271. result[14] = column3Row2;
  7272. result[15] = 0.0;
  7273. return result;
  7274. };
  7275. /**
  7276. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  7277. *
  7278. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7279. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7280. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7281. * @param {Number} top The number of meters above of the camera that will be in view.
  7282. * @param {Number} near The distance to the near plane in meters.
  7283. * @param {Number} far The distance to the far plane in meters.
  7284. * @param {Matrix4} result The object in which the result will be stored.
  7285. * @returns {Matrix4} The modified result parameter.
  7286. */
  7287. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  7288. if (!defined(left)) {
  7289. throw new DeveloperError('left is required.');
  7290. }
  7291. if (!defined(right)) {
  7292. throw new DeveloperError('right is required.');
  7293. }
  7294. if (!defined(bottom)) {
  7295. throw new DeveloperError('bottom is required.');
  7296. }
  7297. if (!defined(top)) {
  7298. throw new DeveloperError('top is required.');
  7299. }
  7300. if (!defined(near)) {
  7301. throw new DeveloperError('near is required.');
  7302. }
  7303. if (!defined(far)) {
  7304. throw new DeveloperError('far is required.');
  7305. }
  7306. if (!defined(result)) {
  7307. throw new DeveloperError('result is required');
  7308. }
  7309. var a = 1.0 / (right - left);
  7310. var b = 1.0 / (top - bottom);
  7311. var c = 1.0 / (far - near);
  7312. var tx = -(right + left) * a;
  7313. var ty = -(top + bottom) * b;
  7314. var tz = -(far + near) * c;
  7315. a *= 2.0;
  7316. b *= 2.0;
  7317. c *= -2.0;
  7318. result[0] = a;
  7319. result[1] = 0.0;
  7320. result[2] = 0.0;
  7321. result[3] = 0.0;
  7322. result[4] = 0.0;
  7323. result[5] = b;
  7324. result[6] = 0.0;
  7325. result[7] = 0.0;
  7326. result[8] = 0.0;
  7327. result[9] = 0.0;
  7328. result[10] = c;
  7329. result[11] = 0.0;
  7330. result[12] = tx;
  7331. result[13] = ty;
  7332. result[14] = tz;
  7333. result[15] = 1.0;
  7334. return result;
  7335. };
  7336. /**
  7337. * Computes a Matrix4 instance representing an off center perspective transformation.
  7338. *
  7339. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7340. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7341. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7342. * @param {Number} top The number of meters above of the camera that will be in view.
  7343. * @param {Number} near The distance to the near plane in meters.
  7344. * @param {Number} far The distance to the far plane in meters.
  7345. * @param {Matrix4} result The object in which the result will be stored.
  7346. * @returns {Matrix4} The modified result parameter.
  7347. */
  7348. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  7349. if (!defined(left)) {
  7350. throw new DeveloperError('left is required.');
  7351. }
  7352. if (!defined(right)) {
  7353. throw new DeveloperError('right is required.');
  7354. }
  7355. if (!defined(bottom)) {
  7356. throw new DeveloperError('bottom is required.');
  7357. }
  7358. if (!defined(top)) {
  7359. throw new DeveloperError('top is required.');
  7360. }
  7361. if (!defined(near)) {
  7362. throw new DeveloperError('near is required.');
  7363. }
  7364. if (!defined(far)) {
  7365. throw new DeveloperError('far is required.');
  7366. }
  7367. if (!defined(result)) {
  7368. throw new DeveloperError('result is required');
  7369. }
  7370. var column0Row0 = 2.0 * near / (right - left);
  7371. var column1Row1 = 2.0 * near / (top - bottom);
  7372. var column2Row0 = (right + left) / (right - left);
  7373. var column2Row1 = (top + bottom) / (top - bottom);
  7374. var column2Row2 = -(far + near) / (far - near);
  7375. var column2Row3 = -1.0;
  7376. var column3Row2 = -2.0 * far * near / (far - near);
  7377. result[0] = column0Row0;
  7378. result[1] = 0.0;
  7379. result[2] = 0.0;
  7380. result[3] = 0.0;
  7381. result[4] = 0.0;
  7382. result[5] = column1Row1;
  7383. result[6] = 0.0;
  7384. result[7] = 0.0;
  7385. result[8] = column2Row0;
  7386. result[9] = column2Row1;
  7387. result[10] = column2Row2;
  7388. result[11] = column2Row3;
  7389. result[12] = 0.0;
  7390. result[13] = 0.0;
  7391. result[14] = column3Row2;
  7392. result[15] = 0.0;
  7393. return result;
  7394. };
  7395. /**
  7396. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  7397. *
  7398. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7399. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7400. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7401. * @param {Number} top The number of meters above of the camera that will be in view.
  7402. * @param {Number} near The distance to the near plane in meters.
  7403. * @param {Matrix4} result The object in which the result will be stored.
  7404. * @returns {Matrix4} The modified result parameter.
  7405. */
  7406. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  7407. if (!defined(left)) {
  7408. throw new DeveloperError('left is required.');
  7409. }
  7410. if (!defined(right)) {
  7411. throw new DeveloperError('right is required.');
  7412. }
  7413. if (!defined(bottom)) {
  7414. throw new DeveloperError('bottom is required.');
  7415. }
  7416. if (!defined(top)) {
  7417. throw new DeveloperError('top is required.');
  7418. }
  7419. if (!defined(near)) {
  7420. throw new DeveloperError('near is required.');
  7421. }
  7422. if (!defined(result)) {
  7423. throw new DeveloperError('result is required');
  7424. }
  7425. var column0Row0 = 2.0 * near / (right - left);
  7426. var column1Row1 = 2.0 * near / (top - bottom);
  7427. var column2Row0 = (right + left) / (right - left);
  7428. var column2Row1 = (top + bottom) / (top - bottom);
  7429. var column2Row2 = -1.0;
  7430. var column2Row3 = -1.0;
  7431. var column3Row2 = -2.0 * near;
  7432. result[0] = column0Row0;
  7433. result[1] = 0.0;
  7434. result[2] = 0.0;
  7435. result[3] = 0.0;
  7436. result[4] = 0.0;
  7437. result[5] = column1Row1;
  7438. result[6] = 0.0;
  7439. result[7] = 0.0;
  7440. result[8] = column2Row0;
  7441. result[9] = column2Row1;
  7442. result[10] = column2Row2;
  7443. result[11] = column2Row3;
  7444. result[12] = 0.0;
  7445. result[13] = 0.0;
  7446. result[14] = column3Row2;
  7447. result[15] = 0.0;
  7448. return result;
  7449. };
  7450. /**
  7451. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  7452. *
  7453. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  7454. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  7455. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  7456. * @param {Matrix4} result The object in which the result will be stored.
  7457. * @returns {Matrix4} The modified result parameter.
  7458. *
  7459. * @example
  7460. * // Create viewport transformation using an explicit viewport and depth range.
  7461. * var m = Cesium.Matrix4.computeViewportTransformation({
  7462. * x : 0.0,
  7463. * y : 0.0,
  7464. * width : 1024.0,
  7465. * height : 768.0
  7466. * }, 0.0, 1.0, new Cesium.Matrix4());
  7467. */
  7468. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  7469. if (!defined(result)) {
  7470. throw new DeveloperError('result is required');
  7471. }
  7472. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  7473. var x = defaultValue(viewport.x, 0.0);
  7474. var y = defaultValue(viewport.y, 0.0);
  7475. var width = defaultValue(viewport.width, 0.0);
  7476. var height = defaultValue(viewport.height, 0.0);
  7477. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  7478. farDepthRange = defaultValue(farDepthRange, 1.0);
  7479. var halfWidth = width * 0.5;
  7480. var halfHeight = height * 0.5;
  7481. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  7482. var column0Row0 = halfWidth;
  7483. var column1Row1 = halfHeight;
  7484. var column2Row2 = halfDepth;
  7485. var column3Row0 = x + halfWidth;
  7486. var column3Row1 = y + halfHeight;
  7487. var column3Row2 = nearDepthRange + halfDepth;
  7488. var column3Row3 = 1.0;
  7489. result[0] = column0Row0;
  7490. result[1] = 0.0;
  7491. result[2] = 0.0;
  7492. result[3] = 0.0;
  7493. result[4] = 0.0;
  7494. result[5] = column1Row1;
  7495. result[6] = 0.0;
  7496. result[7] = 0.0;
  7497. result[8] = 0.0;
  7498. result[9] = 0.0;
  7499. result[10] = column2Row2;
  7500. result[11] = 0.0;
  7501. result[12] = column3Row0;
  7502. result[13] = column3Row1;
  7503. result[14] = column3Row2;
  7504. result[15] = column3Row3;
  7505. return result;
  7506. };
  7507. /**
  7508. * Computes a Matrix4 instance that transforms from world space to view space.
  7509. *
  7510. * @param {Cartesian3} position The position of the camera.
  7511. * @param {Cartesian3} direction The forward direction.
  7512. * @param {Cartesian3} up The up direction.
  7513. * @param {Cartesian3} right The right direction.
  7514. * @param {Matrix4} result The object in which the result will be stored.
  7515. * @returns {Matrix4} The modified result parameter.
  7516. */
  7517. Matrix4.computeView = function(position, direction, up, right, result) {
  7518. if (!defined(position)) {
  7519. throw new DeveloperError('position is required');
  7520. }
  7521. if (!defined(direction)) {
  7522. throw new DeveloperError('direction is required');
  7523. }
  7524. if (!defined(up)) {
  7525. throw new DeveloperError('up is required');
  7526. }
  7527. if (!defined(right)) {
  7528. throw new DeveloperError('right is required');
  7529. }
  7530. if (!defined(result)) {
  7531. throw new DeveloperError('result is required');
  7532. }
  7533. result[0] = right.x;
  7534. result[1] = up.x;
  7535. result[2] = -direction.x;
  7536. result[3] = 0.0;
  7537. result[4] = right.y;
  7538. result[5] = up.y;
  7539. result[6] = -direction.y;
  7540. result[7] = 0.0;
  7541. result[8] = right.z;
  7542. result[9] = up.z;
  7543. result[10] = -direction.z;
  7544. result[11] = 0.0;
  7545. result[12] = -Cartesian3.dot(right, position);
  7546. result[13] = -Cartesian3.dot(up, position);
  7547. result[14] = Cartesian3.dot(direction, position);
  7548. result[15] = 1.0;
  7549. return result;
  7550. };
  7551. /**
  7552. * Computes an Array from the provided Matrix4 instance.
  7553. * The array will be in column-major order.
  7554. *
  7555. * @param {Matrix4} matrix The matrix to use..
  7556. * @param {Number[]} [result] The Array onto which to store the result.
  7557. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  7558. *
  7559. * @example
  7560. * //create an array from an instance of Matrix4
  7561. * // m = [10.0, 14.0, 18.0, 22.0]
  7562. * // [11.0, 15.0, 19.0, 23.0]
  7563. * // [12.0, 16.0, 20.0, 24.0]
  7564. * // [13.0, 17.0, 21.0, 25.0]
  7565. * var a = Cesium.Matrix4.toArray(m);
  7566. *
  7567. * // m remains the same
  7568. * //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]
  7569. */
  7570. Matrix4.toArray = function(matrix, result) {
  7571. if (!defined(matrix)) {
  7572. throw new DeveloperError('matrix is required');
  7573. }
  7574. if (!defined(result)) {
  7575. return [matrix[0], matrix[1], matrix[2], matrix[3],
  7576. matrix[4], matrix[5], matrix[6], matrix[7],
  7577. matrix[8], matrix[9], matrix[10], matrix[11],
  7578. matrix[12], matrix[13], matrix[14], matrix[15]];
  7579. }
  7580. result[0] = matrix[0];
  7581. result[1] = matrix[1];
  7582. result[2] = matrix[2];
  7583. result[3] = matrix[3];
  7584. result[4] = matrix[4];
  7585. result[5] = matrix[5];
  7586. result[6] = matrix[6];
  7587. result[7] = matrix[7];
  7588. result[8] = matrix[8];
  7589. result[9] = matrix[9];
  7590. result[10] = matrix[10];
  7591. result[11] = matrix[11];
  7592. result[12] = matrix[12];
  7593. result[13] = matrix[13];
  7594. result[14] = matrix[14];
  7595. result[15] = matrix[15];
  7596. return result;
  7597. };
  7598. /**
  7599. * Computes the array index of the element at the provided row and column.
  7600. *
  7601. * @param {Number} row The zero-based index of the row.
  7602. * @param {Number} column The zero-based index of the column.
  7603. * @returns {Number} The index of the element at the provided row and column.
  7604. *
  7605. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  7606. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  7607. *
  7608. * @example
  7609. * var myMatrix = new Cesium.Matrix4();
  7610. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  7611. * var column1Row0 = myMatrix[column1Row0Index];
  7612. * myMatrix[column1Row0Index] = 10.0;
  7613. */
  7614. Matrix4.getElementIndex = function(column, row) {
  7615. if (typeof row !== 'number' || row < 0 || row > 3) {
  7616. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  7617. }
  7618. if (typeof column !== 'number' || column < 0 || column > 3) {
  7619. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  7620. }
  7621. return column * 4 + row;
  7622. };
  7623. /**
  7624. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  7625. *
  7626. * @param {Matrix4} matrix The matrix to use.
  7627. * @param {Number} index The zero-based index of the column to retrieve.
  7628. * @param {Cartesian4} result The object onto which to store the result.
  7629. * @returns {Cartesian4} The modified result parameter.
  7630. *
  7631. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  7632. *
  7633. * @example
  7634. * //returns a Cartesian4 instance with values from the specified column
  7635. * // m = [10.0, 11.0, 12.0, 13.0]
  7636. * // [14.0, 15.0, 16.0, 17.0]
  7637. * // [18.0, 19.0, 20.0, 21.0]
  7638. * // [22.0, 23.0, 24.0, 25.0]
  7639. *
  7640. * //Example 1: Creates an instance of Cartesian
  7641. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  7642. *
  7643. * @example
  7644. * //Example 2: Sets values for Cartesian instance
  7645. * var a = new Cesium.Cartesian4();
  7646. * Cesium.Matrix4.getColumn(m, 2, a);
  7647. *
  7648. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  7649. */
  7650. Matrix4.getColumn = function(matrix, index, result) {
  7651. if (!defined(matrix)) {
  7652. throw new DeveloperError('matrix is required.');
  7653. }
  7654. if (typeof index !== 'number' || index < 0 || index > 3) {
  7655. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  7656. }
  7657. if (!defined(result)) {
  7658. throw new DeveloperError('result is required');
  7659. }
  7660. var startIndex = index * 4;
  7661. var x = matrix[startIndex];
  7662. var y = matrix[startIndex + 1];
  7663. var z = matrix[startIndex + 2];
  7664. var w = matrix[startIndex + 3];
  7665. result.x = x;
  7666. result.y = y;
  7667. result.z = z;
  7668. result.w = w;
  7669. return result;
  7670. };
  7671. /**
  7672. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  7673. *
  7674. * @param {Matrix4} matrix The matrix to use.
  7675. * @param {Number} index The zero-based index of the column to set.
  7676. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  7677. * @param {Matrix4} result The object onto which to store the result.
  7678. * @returns {Matrix4} The modified result parameter.
  7679. *
  7680. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  7681. *
  7682. * @example
  7683. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  7684. * // m = [10.0, 11.0, 12.0, 13.0]
  7685. * // [14.0, 15.0, 16.0, 17.0]
  7686. * // [18.0, 19.0, 20.0, 21.0]
  7687. * // [22.0, 23.0, 24.0, 25.0]
  7688. *
  7689. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  7690. *
  7691. * // m remains the same
  7692. * // a = [10.0, 11.0, 99.0, 13.0]
  7693. * // [14.0, 15.0, 98.0, 17.0]
  7694. * // [18.0, 19.0, 97.0, 21.0]
  7695. * // [22.0, 23.0, 96.0, 25.0]
  7696. */
  7697. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  7698. if (!defined(matrix)) {
  7699. throw new DeveloperError('matrix is required');
  7700. }
  7701. if (!defined(cartesian)) {
  7702. throw new DeveloperError('cartesian is required');
  7703. }
  7704. if (typeof index !== 'number' || index < 0 || index > 3) {
  7705. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  7706. }
  7707. if (!defined(result)) {
  7708. throw new DeveloperError('result is required');
  7709. }
  7710. result = Matrix4.clone(matrix, result);
  7711. var startIndex = index * 4;
  7712. result[startIndex] = cartesian.x;
  7713. result[startIndex + 1] = cartesian.y;
  7714. result[startIndex + 2] = cartesian.z;
  7715. result[startIndex + 3] = cartesian.w;
  7716. return result;
  7717. };
  7718. /**
  7719. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  7720. * matrix with the provided translation. This assumes the matrix is an affine transformation
  7721. *
  7722. * @param {Matrix4} matrix The matrix to use.
  7723. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  7724. * @param {Cartesian4} result The object onto which to store the result.
  7725. * @returns {Matrix4} The modified result parameter.
  7726. */
  7727. Matrix4.setTranslation = function(matrix, translation, result) {
  7728. if (!defined(matrix)) {
  7729. throw new DeveloperError('matrix is required');
  7730. }
  7731. if (!defined(translation)) {
  7732. throw new DeveloperError('translation is required');
  7733. }
  7734. if (!defined(result)) {
  7735. throw new DeveloperError('result is required');
  7736. }
  7737. result[0] = matrix[0];
  7738. result[1] = matrix[1];
  7739. result[2] = matrix[2];
  7740. result[3] = matrix[3];
  7741. result[4] = matrix[4];
  7742. result[5] = matrix[5];
  7743. result[6] = matrix[6];
  7744. result[7] = matrix[7];
  7745. result[8] = matrix[8];
  7746. result[9] = matrix[9];
  7747. result[10] = matrix[10];
  7748. result[11] = matrix[11];
  7749. result[12] = translation.x;
  7750. result[13] = translation.y;
  7751. result[14] = translation.z;
  7752. result[15] = matrix[15];
  7753. return result;
  7754. };
  7755. /**
  7756. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  7757. *
  7758. * @param {Matrix4} matrix The matrix to use.
  7759. * @param {Number} index The zero-based index of the row to retrieve.
  7760. * @param {Cartesian4} result The object onto which to store the result.
  7761. * @returns {Cartesian4} The modified result parameter.
  7762. *
  7763. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  7764. *
  7765. * @example
  7766. * //returns a Cartesian4 instance with values from the specified column
  7767. * // m = [10.0, 11.0, 12.0, 13.0]
  7768. * // [14.0, 15.0, 16.0, 17.0]
  7769. * // [18.0, 19.0, 20.0, 21.0]
  7770. * // [22.0, 23.0, 24.0, 25.0]
  7771. *
  7772. * //Example 1: Returns an instance of Cartesian
  7773. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  7774. *
  7775. * @example
  7776. * //Example 2: Sets values for a Cartesian instance
  7777. * var a = new Cesium.Cartesian4();
  7778. * Cesium.Matrix4.getRow(m, 2, a);
  7779. *
  7780. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  7781. */
  7782. Matrix4.getRow = function(matrix, index, result) {
  7783. if (!defined(matrix)) {
  7784. throw new DeveloperError('matrix is required.');
  7785. }
  7786. if (typeof index !== 'number' || index < 0 || index > 3) {
  7787. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  7788. }
  7789. if (!defined(result)) {
  7790. throw new DeveloperError('result is required');
  7791. }
  7792. var x = matrix[index];
  7793. var y = matrix[index + 4];
  7794. var z = matrix[index + 8];
  7795. var w = matrix[index + 12];
  7796. result.x = x;
  7797. result.y = y;
  7798. result.z = z;
  7799. result.w = w;
  7800. return result;
  7801. };
  7802. /**
  7803. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  7804. *
  7805. * @param {Matrix4} matrix The matrix to use.
  7806. * @param {Number} index The zero-based index of the row to set.
  7807. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  7808. * @param {Matrix4} result The object onto which to store the result.
  7809. * @returns {Matrix4} The modified result parameter.
  7810. *
  7811. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  7812. *
  7813. * @example
  7814. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  7815. * // m = [10.0, 11.0, 12.0, 13.0]
  7816. * // [14.0, 15.0, 16.0, 17.0]
  7817. * // [18.0, 19.0, 20.0, 21.0]
  7818. * // [22.0, 23.0, 24.0, 25.0]
  7819. *
  7820. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  7821. *
  7822. * // m remains the same
  7823. * // a = [10.0, 11.0, 12.0, 13.0]
  7824. * // [14.0, 15.0, 16.0, 17.0]
  7825. * // [99.0, 98.0, 97.0, 96.0]
  7826. * // [22.0, 23.0, 24.0, 25.0]
  7827. */
  7828. Matrix4.setRow = function(matrix, index, cartesian, result) {
  7829. if (!defined(matrix)) {
  7830. throw new DeveloperError('matrix is required');
  7831. }
  7832. if (!defined(cartesian)) {
  7833. throw new DeveloperError('cartesian is required');
  7834. }
  7835. if (typeof index !== 'number' || index < 0 || index > 3) {
  7836. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  7837. }
  7838. if (!defined(result)) {
  7839. throw new DeveloperError('result is required');
  7840. }
  7841. result = Matrix4.clone(matrix, result);
  7842. result[index] = cartesian.x;
  7843. result[index + 4] = cartesian.y;
  7844. result[index + 8] = cartesian.z;
  7845. result[index + 12] = cartesian.w;
  7846. return result;
  7847. };
  7848. var scratchColumn = new Cartesian3();
  7849. /**
  7850. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  7851. *
  7852. * @param {Matrix4} matrix The matrix.
  7853. * @param {Cartesian3} result The object onto which to store the result.
  7854. * @returns {Cartesian3} The modified result parameter
  7855. */
  7856. Matrix4.getScale = function(matrix, result) {
  7857. if (!defined(matrix)) {
  7858. throw new DeveloperError('matrix is required.');
  7859. }
  7860. if (!defined(result)) {
  7861. throw new DeveloperError('result is required');
  7862. }
  7863. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  7864. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  7865. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  7866. return result;
  7867. };
  7868. var scratchScale = new Cartesian3();
  7869. /**
  7870. * Computes the maximum scale assuming the matrix is an affine transformation.
  7871. * The maximum scale is the maximum length of the column vectors in the upper-left
  7872. * 3x3 matrix.
  7873. *
  7874. * @param {Matrix4} matrix The matrix.
  7875. * @returns {Number} The maximum scale.
  7876. */
  7877. Matrix4.getMaximumScale = function(matrix) {
  7878. Matrix4.getScale(matrix, scratchScale);
  7879. return Cartesian3.maximumComponent(scratchScale);
  7880. };
  7881. /**
  7882. * Computes the product of two matrices.
  7883. *
  7884. * @param {Matrix4} left The first matrix.
  7885. * @param {Matrix4} right The second matrix.
  7886. * @param {Matrix4} result The object onto which to store the result.
  7887. * @returns {Matrix4} The modified result parameter.
  7888. */
  7889. Matrix4.multiply = function(left, right, result) {
  7890. if (!defined(left)) {
  7891. throw new DeveloperError('left is required');
  7892. }
  7893. if (!defined(right)) {
  7894. throw new DeveloperError('right is required');
  7895. }
  7896. if (!defined(result)) {
  7897. throw new DeveloperError('result is required');
  7898. }
  7899. var left0 = left[0];
  7900. var left1 = left[1];
  7901. var left2 = left[2];
  7902. var left3 = left[3];
  7903. var left4 = left[4];
  7904. var left5 = left[5];
  7905. var left6 = left[6];
  7906. var left7 = left[7];
  7907. var left8 = left[8];
  7908. var left9 = left[9];
  7909. var left10 = left[10];
  7910. var left11 = left[11];
  7911. var left12 = left[12];
  7912. var left13 = left[13];
  7913. var left14 = left[14];
  7914. var left15 = left[15];
  7915. var right0 = right[0];
  7916. var right1 = right[1];
  7917. var right2 = right[2];
  7918. var right3 = right[3];
  7919. var right4 = right[4];
  7920. var right5 = right[5];
  7921. var right6 = right[6];
  7922. var right7 = right[7];
  7923. var right8 = right[8];
  7924. var right9 = right[9];
  7925. var right10 = right[10];
  7926. var right11 = right[11];
  7927. var right12 = right[12];
  7928. var right13 = right[13];
  7929. var right14 = right[14];
  7930. var right15 = right[15];
  7931. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  7932. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  7933. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  7934. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  7935. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  7936. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  7937. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  7938. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  7939. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  7940. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  7941. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  7942. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  7943. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  7944. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  7945. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  7946. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  7947. result[0] = column0Row0;
  7948. result[1] = column0Row1;
  7949. result[2] = column0Row2;
  7950. result[3] = column0Row3;
  7951. result[4] = column1Row0;
  7952. result[5] = column1Row1;
  7953. result[6] = column1Row2;
  7954. result[7] = column1Row3;
  7955. result[8] = column2Row0;
  7956. result[9] = column2Row1;
  7957. result[10] = column2Row2;
  7958. result[11] = column2Row3;
  7959. result[12] = column3Row0;
  7960. result[13] = column3Row1;
  7961. result[14] = column3Row2;
  7962. result[15] = column3Row3;
  7963. return result;
  7964. };
  7965. /**
  7966. * Computes the sum of two matrices.
  7967. *
  7968. * @param {Matrix4} left The first matrix.
  7969. * @param {Matrix4} right The second matrix.
  7970. * @param {Matrix4} result The object onto which to store the result.
  7971. * @returns {Matrix4} The modified result parameter.
  7972. */
  7973. Matrix4.add = function(left, right, result) {
  7974. if (!defined(left)) {
  7975. throw new DeveloperError('left is required');
  7976. }
  7977. if (!defined(right)) {
  7978. throw new DeveloperError('right is required');
  7979. }
  7980. if (!defined(result)) {
  7981. throw new DeveloperError('result is required');
  7982. }
  7983. result[0] = left[0] + right[0];
  7984. result[1] = left[1] + right[1];
  7985. result[2] = left[2] + right[2];
  7986. result[3] = left[3] + right[3];
  7987. result[4] = left[4] + right[4];
  7988. result[5] = left[5] + right[5];
  7989. result[6] = left[6] + right[6];
  7990. result[7] = left[7] + right[7];
  7991. result[8] = left[8] + right[8];
  7992. result[9] = left[9] + right[9];
  7993. result[10] = left[10] + right[10];
  7994. result[11] = left[11] + right[11];
  7995. result[12] = left[12] + right[12];
  7996. result[13] = left[13] + right[13];
  7997. result[14] = left[14] + right[14];
  7998. result[15] = left[15] + right[15];
  7999. return result;
  8000. };
  8001. /**
  8002. * Computes the difference of two matrices.
  8003. *
  8004. * @param {Matrix4} left The first matrix.
  8005. * @param {Matrix4} right The second matrix.
  8006. * @param {Matrix4} result The object onto which to store the result.
  8007. * @returns {Matrix4} The modified result parameter.
  8008. */
  8009. Matrix4.subtract = function(left, right, result) {
  8010. if (!defined(left)) {
  8011. throw new DeveloperError('left is required');
  8012. }
  8013. if (!defined(right)) {
  8014. throw new DeveloperError('right is required');
  8015. }
  8016. if (!defined(result)) {
  8017. throw new DeveloperError('result is required');
  8018. }
  8019. result[0] = left[0] - right[0];
  8020. result[1] = left[1] - right[1];
  8021. result[2] = left[2] - right[2];
  8022. result[3] = left[3] - right[3];
  8023. result[4] = left[4] - right[4];
  8024. result[5] = left[5] - right[5];
  8025. result[6] = left[6] - right[6];
  8026. result[7] = left[7] - right[7];
  8027. result[8] = left[8] - right[8];
  8028. result[9] = left[9] - right[9];
  8029. result[10] = left[10] - right[10];
  8030. result[11] = left[11] - right[11];
  8031. result[12] = left[12] - right[12];
  8032. result[13] = left[13] - right[13];
  8033. result[14] = left[14] - right[14];
  8034. result[15] = left[15] - right[15];
  8035. return result;
  8036. };
  8037. /**
  8038. * Computes the product of two matrices assuming the matrices are
  8039. * affine transformation matrices, where the upper left 3x3 elements
  8040. * are a rotation matrix, and the upper three elements in the fourth
  8041. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  8042. * The matrix is not verified to be in the proper form.
  8043. * This method is faster than computing the product for general 4x4
  8044. * matrices using {@link Matrix4.multiply}.
  8045. *
  8046. * @param {Matrix4} left The first matrix.
  8047. * @param {Matrix4} right The second matrix.
  8048. * @param {Matrix4} result The object onto which to store the result.
  8049. * @returns {Matrix4} The modified result parameter.
  8050. *
  8051. * @example
  8052. * 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);
  8053. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  8054. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  8055. */
  8056. Matrix4.multiplyTransformation = function(left, right, result) {
  8057. if (!defined(left)) {
  8058. throw new DeveloperError('left is required');
  8059. }
  8060. if (!defined(right)) {
  8061. throw new DeveloperError('right is required');
  8062. }
  8063. if (!defined(result)) {
  8064. throw new DeveloperError('result is required');
  8065. }
  8066. var left0 = left[0];
  8067. var left1 = left[1];
  8068. var left2 = left[2];
  8069. var left4 = left[4];
  8070. var left5 = left[5];
  8071. var left6 = left[6];
  8072. var left8 = left[8];
  8073. var left9 = left[9];
  8074. var left10 = left[10];
  8075. var left12 = left[12];
  8076. var left13 = left[13];
  8077. var left14 = left[14];
  8078. var right0 = right[0];
  8079. var right1 = right[1];
  8080. var right2 = right[2];
  8081. var right4 = right[4];
  8082. var right5 = right[5];
  8083. var right6 = right[6];
  8084. var right8 = right[8];
  8085. var right9 = right[9];
  8086. var right10 = right[10];
  8087. var right12 = right[12];
  8088. var right13 = right[13];
  8089. var right14 = right[14];
  8090. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8091. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8092. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8093. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8094. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8095. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8096. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8097. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8098. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8099. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  8100. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  8101. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  8102. result[0] = column0Row0;
  8103. result[1] = column0Row1;
  8104. result[2] = column0Row2;
  8105. result[3] = 0.0;
  8106. result[4] = column1Row0;
  8107. result[5] = column1Row1;
  8108. result[6] = column1Row2;
  8109. result[7] = 0.0;
  8110. result[8] = column2Row0;
  8111. result[9] = column2Row1;
  8112. result[10] = column2Row2;
  8113. result[11] = 0.0;
  8114. result[12] = column3Row0;
  8115. result[13] = column3Row1;
  8116. result[14] = column3Row2;
  8117. result[15] = 1.0;
  8118. return result;
  8119. };
  8120. /**
  8121. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8122. * by a 3x3 rotation matrix. This is an optimization
  8123. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  8124. *
  8125. * @param {Matrix4} matrix The matrix on the left-hand side.
  8126. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  8127. * @param {Matrix4} result The object onto which to store the result.
  8128. * @returns {Matrix4} The modified result parameter.
  8129. *
  8130. * @example
  8131. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  8132. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  8133. */
  8134. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  8135. if (!defined(matrix)) {
  8136. throw new DeveloperError('matrix is required');
  8137. }
  8138. if (!defined(rotation)) {
  8139. throw new DeveloperError('rotation is required');
  8140. }
  8141. if (!defined(result)) {
  8142. throw new DeveloperError('result is required');
  8143. }
  8144. var left0 = matrix[0];
  8145. var left1 = matrix[1];
  8146. var left2 = matrix[2];
  8147. var left4 = matrix[4];
  8148. var left5 = matrix[5];
  8149. var left6 = matrix[6];
  8150. var left8 = matrix[8];
  8151. var left9 = matrix[9];
  8152. var left10 = matrix[10];
  8153. var right0 = rotation[0];
  8154. var right1 = rotation[1];
  8155. var right2 = rotation[2];
  8156. var right4 = rotation[3];
  8157. var right5 = rotation[4];
  8158. var right6 = rotation[5];
  8159. var right8 = rotation[6];
  8160. var right9 = rotation[7];
  8161. var right10 = rotation[8];
  8162. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8163. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8164. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8165. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8166. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8167. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8168. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8169. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8170. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8171. result[0] = column0Row0;
  8172. result[1] = column0Row1;
  8173. result[2] = column0Row2;
  8174. result[3] = 0.0;
  8175. result[4] = column1Row0;
  8176. result[5] = column1Row1;
  8177. result[6] = column1Row2;
  8178. result[7] = 0.0;
  8179. result[8] = column2Row0;
  8180. result[9] = column2Row1;
  8181. result[10] = column2Row2;
  8182. result[11] = 0.0;
  8183. result[12] = matrix[12];
  8184. result[13] = matrix[13];
  8185. result[14] = matrix[14];
  8186. result[15] = matrix[15];
  8187. return result;
  8188. };
  8189. /**
  8190. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8191. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  8192. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  8193. *
  8194. * @param {Matrix4} matrix The matrix on the left-hand side.
  8195. * @param {Cartesian3} translation The translation on the right-hand side.
  8196. * @param {Matrix4} result The object onto which to store the result.
  8197. * @returns {Matrix4} The modified result parameter.
  8198. *
  8199. * @example
  8200. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  8201. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  8202. */
  8203. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  8204. if (!defined(matrix)) {
  8205. throw new DeveloperError('matrix is required');
  8206. }
  8207. if (!defined(translation)) {
  8208. throw new DeveloperError('translation is required');
  8209. }
  8210. if (!defined(result)) {
  8211. throw new DeveloperError('result is required');
  8212. }
  8213. var x = translation.x;
  8214. var y = translation.y;
  8215. var z = translation.z;
  8216. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  8217. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  8218. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  8219. result[0] = matrix[0];
  8220. result[1] = matrix[1];
  8221. result[2] = matrix[2];
  8222. result[3] = matrix[3];
  8223. result[4] = matrix[4];
  8224. result[5] = matrix[5];
  8225. result[6] = matrix[6];
  8226. result[7] = matrix[7];
  8227. result[8] = matrix[8];
  8228. result[9] = matrix[9];
  8229. result[10] = matrix[10];
  8230. result[11] = matrix[11];
  8231. result[12] = tx;
  8232. result[13] = ty;
  8233. result[14] = tz;
  8234. result[15] = matrix[15];
  8235. return result;
  8236. };
  8237. var uniformScaleScratch = new Cartesian3();
  8238. /**
  8239. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8240. * by an implicit uniform scale matrix. This is an optimization
  8241. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8242. * <code>m</code> must be an affine matrix.
  8243. * This function performs fewer allocations and arithmetic operations.
  8244. *
  8245. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8246. * @param {Number} scale The uniform scale on the right-hand side.
  8247. * @param {Matrix4} result The object onto which to store the result.
  8248. * @returns {Matrix4} The modified result parameter.
  8249. *
  8250. *
  8251. * @example
  8252. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  8253. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  8254. *
  8255. * @see Matrix4.fromUniformScale
  8256. * @see Matrix4.multiplyByScale
  8257. */
  8258. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  8259. if (!defined(matrix)) {
  8260. throw new DeveloperError('matrix is required');
  8261. }
  8262. if (typeof scale !== 'number') {
  8263. throw new DeveloperError('scale is required');
  8264. }
  8265. if (!defined(result)) {
  8266. throw new DeveloperError('result is required');
  8267. }
  8268. uniformScaleScratch.x = scale;
  8269. uniformScaleScratch.y = scale;
  8270. uniformScaleScratch.z = scale;
  8271. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  8272. };
  8273. /**
  8274. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8275. * by an implicit non-uniform scale matrix. This is an optimization
  8276. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8277. * <code>m</code> must be an affine matrix.
  8278. * This function performs fewer allocations and arithmetic operations.
  8279. *
  8280. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8281. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  8282. * @param {Matrix4} result The object onto which to store the result.
  8283. * @returns {Matrix4} The modified result parameter.
  8284. *
  8285. *
  8286. * @example
  8287. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  8288. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  8289. *
  8290. * @see Matrix4.fromScale
  8291. * @see Matrix4.multiplyByUniformScale
  8292. */
  8293. Matrix4.multiplyByScale = function(matrix, scale, result) {
  8294. if (!defined(matrix)) {
  8295. throw new DeveloperError('matrix is required');
  8296. }
  8297. if (!defined(scale)) {
  8298. throw new DeveloperError('scale is required');
  8299. }
  8300. if (!defined(result)) {
  8301. throw new DeveloperError('result is required');
  8302. }
  8303. var scaleX = scale.x;
  8304. var scaleY = scale.y;
  8305. var scaleZ = scale.z;
  8306. // Faster than Cartesian3.equals
  8307. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  8308. return Matrix4.clone(matrix, result);
  8309. }
  8310. result[0] = scaleX * matrix[0];
  8311. result[1] = scaleX * matrix[1];
  8312. result[2] = scaleX * matrix[2];
  8313. result[3] = 0.0;
  8314. result[4] = scaleY * matrix[4];
  8315. result[5] = scaleY * matrix[5];
  8316. result[6] = scaleY * matrix[6];
  8317. result[7] = 0.0;
  8318. result[8] = scaleZ * matrix[8];
  8319. result[9] = scaleZ * matrix[9];
  8320. result[10] = scaleZ * matrix[10];
  8321. result[11] = 0.0;
  8322. result[12] = matrix[12];
  8323. result[13] = matrix[13];
  8324. result[14] = matrix[14];
  8325. result[15] = 1.0;
  8326. return result;
  8327. };
  8328. /**
  8329. * Computes the product of a matrix and a column vector.
  8330. *
  8331. * @param {Matrix4} matrix The matrix.
  8332. * @param {Cartesian4} cartesian The vector.
  8333. * @param {Cartesian4} result The object onto which to store the result.
  8334. * @returns {Cartesian4} The modified result parameter.
  8335. */
  8336. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  8337. if (!defined(matrix)) {
  8338. throw new DeveloperError('matrix is required');
  8339. }
  8340. if (!defined(cartesian)) {
  8341. throw new DeveloperError('cartesian is required');
  8342. }
  8343. if (!defined(result)) {
  8344. throw new DeveloperError('result is required');
  8345. }
  8346. var vX = cartesian.x;
  8347. var vY = cartesian.y;
  8348. var vZ = cartesian.z;
  8349. var vW = cartesian.w;
  8350. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  8351. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  8352. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  8353. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  8354. result.x = x;
  8355. result.y = y;
  8356. result.z = z;
  8357. result.w = w;
  8358. return result;
  8359. };
  8360. /**
  8361. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  8362. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  8363. *
  8364. * @param {Matrix4} matrix The matrix.
  8365. * @param {Cartesian3} cartesian The point.
  8366. * @param {Cartesian3} result The object onto which to store the result.
  8367. * @returns {Cartesian3} The modified result parameter.
  8368. *
  8369. * @example
  8370. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  8371. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  8372. * // A shortcut for
  8373. * // Cartesian3 p = ...
  8374. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  8375. */
  8376. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  8377. if (!defined(matrix)) {
  8378. throw new DeveloperError('matrix is required');
  8379. }
  8380. if (!defined(cartesian)) {
  8381. throw new DeveloperError('cartesian is required');
  8382. }
  8383. if (!defined(result)) {
  8384. throw new DeveloperError('result is required');
  8385. }
  8386. var vX = cartesian.x;
  8387. var vY = cartesian.y;
  8388. var vZ = cartesian.z;
  8389. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  8390. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  8391. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  8392. result.x = x;
  8393. result.y = y;
  8394. result.z = z;
  8395. return result;
  8396. };
  8397. /**
  8398. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  8399. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  8400. *
  8401. * @param {Matrix4} matrix The matrix.
  8402. * @param {Cartesian3} cartesian The point.
  8403. * @param {Cartesian3} result The object onto which to store the result.
  8404. * @returns {Cartesian3} The modified result parameter.
  8405. *
  8406. * @example
  8407. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  8408. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  8409. */
  8410. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  8411. if (!defined(matrix)) {
  8412. throw new DeveloperError('matrix is required');
  8413. }
  8414. if (!defined(cartesian)) {
  8415. throw new DeveloperError('cartesian is required');
  8416. }
  8417. if (!defined(result)) {
  8418. throw new DeveloperError('result is required');
  8419. }
  8420. var vX = cartesian.x;
  8421. var vY = cartesian.y;
  8422. var vZ = cartesian.z;
  8423. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  8424. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  8425. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  8426. result.x = x;
  8427. result.y = y;
  8428. result.z = z;
  8429. return result;
  8430. };
  8431. /**
  8432. * Computes the product of a matrix and a scalar.
  8433. *
  8434. * @param {Matrix4} matrix The matrix.
  8435. * @param {Number} scalar The number to multiply by.
  8436. * @param {Matrix4} result The object onto which to store the result.
  8437. * @returns {Matrix4} The modified result parameter.
  8438. *
  8439. * @example
  8440. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  8441. * // m = [10.0, 11.0, 12.0, 13.0]
  8442. * // [14.0, 15.0, 16.0, 17.0]
  8443. * // [18.0, 19.0, 20.0, 21.0]
  8444. * // [22.0, 23.0, 24.0, 25.0]
  8445. *
  8446. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  8447. *
  8448. * // m remains the same
  8449. * // a = [-20.0, -22.0, -24.0, -26.0]
  8450. * // [-28.0, -30.0, -32.0, -34.0]
  8451. * // [-36.0, -38.0, -40.0, -42.0]
  8452. * // [-44.0, -46.0, -48.0, -50.0]
  8453. */
  8454. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  8455. if (!defined(matrix)) {
  8456. throw new DeveloperError('matrix is required');
  8457. }
  8458. if (typeof scalar !== 'number') {
  8459. throw new DeveloperError('scalar must be a number');
  8460. }
  8461. if (!defined(result)) {
  8462. throw new DeveloperError('result is required');
  8463. }
  8464. result[0] = matrix[0] * scalar;
  8465. result[1] = matrix[1] * scalar;
  8466. result[2] = matrix[2] * scalar;
  8467. result[3] = matrix[3] * scalar;
  8468. result[4] = matrix[4] * scalar;
  8469. result[5] = matrix[5] * scalar;
  8470. result[6] = matrix[6] * scalar;
  8471. result[7] = matrix[7] * scalar;
  8472. result[8] = matrix[8] * scalar;
  8473. result[9] = matrix[9] * scalar;
  8474. result[10] = matrix[10] * scalar;
  8475. result[11] = matrix[11] * scalar;
  8476. result[12] = matrix[12] * scalar;
  8477. result[13] = matrix[13] * scalar;
  8478. result[14] = matrix[14] * scalar;
  8479. result[15] = matrix[15] * scalar;
  8480. return result;
  8481. };
  8482. /**
  8483. * Computes a negated copy of the provided matrix.
  8484. *
  8485. * @param {Matrix4} matrix The matrix to negate.
  8486. * @param {Matrix4} result The object onto which to store the result.
  8487. * @returns {Matrix4} The modified result parameter.
  8488. *
  8489. * @example
  8490. * //create a new Matrix4 instance which is a negation of a Matrix4
  8491. * // m = [10.0, 11.0, 12.0, 13.0]
  8492. * // [14.0, 15.0, 16.0, 17.0]
  8493. * // [18.0, 19.0, 20.0, 21.0]
  8494. * // [22.0, 23.0, 24.0, 25.0]
  8495. *
  8496. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  8497. *
  8498. * // m remains the same
  8499. * // a = [-10.0, -11.0, -12.0, -13.0]
  8500. * // [-14.0, -15.0, -16.0, -17.0]
  8501. * // [-18.0, -19.0, -20.0, -21.0]
  8502. * // [-22.0, -23.0, -24.0, -25.0]
  8503. */
  8504. Matrix4.negate = function(matrix, result) {
  8505. if (!defined(matrix)) {
  8506. throw new DeveloperError('matrix is required');
  8507. }
  8508. if (!defined(result)) {
  8509. throw new DeveloperError('result is required');
  8510. }
  8511. result[0] = -matrix[0];
  8512. result[1] = -matrix[1];
  8513. result[2] = -matrix[2];
  8514. result[3] = -matrix[3];
  8515. result[4] = -matrix[4];
  8516. result[5] = -matrix[5];
  8517. result[6] = -matrix[6];
  8518. result[7] = -matrix[7];
  8519. result[8] = -matrix[8];
  8520. result[9] = -matrix[9];
  8521. result[10] = -matrix[10];
  8522. result[11] = -matrix[11];
  8523. result[12] = -matrix[12];
  8524. result[13] = -matrix[13];
  8525. result[14] = -matrix[14];
  8526. result[15] = -matrix[15];
  8527. return result;
  8528. };
  8529. /**
  8530. * Computes the transpose of the provided matrix.
  8531. *
  8532. * @param {Matrix4} matrix The matrix to transpose.
  8533. * @param {Matrix4} result The object onto which to store the result.
  8534. * @returns {Matrix4} The modified result parameter.
  8535. *
  8536. * @example
  8537. * //returns transpose of a Matrix4
  8538. * // m = [10.0, 11.0, 12.0, 13.0]
  8539. * // [14.0, 15.0, 16.0, 17.0]
  8540. * // [18.0, 19.0, 20.0, 21.0]
  8541. * // [22.0, 23.0, 24.0, 25.0]
  8542. *
  8543. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  8544. *
  8545. * // m remains the same
  8546. * // a = [10.0, 14.0, 18.0, 22.0]
  8547. * // [11.0, 15.0, 19.0, 23.0]
  8548. * // [12.0, 16.0, 20.0, 24.0]
  8549. * // [13.0, 17.0, 21.0, 25.0]
  8550. */
  8551. Matrix4.transpose = function(matrix, result) {
  8552. if (!defined(matrix)) {
  8553. throw new DeveloperError('matrix is required');
  8554. }
  8555. if (!defined(result)) {
  8556. throw new DeveloperError('result is required');
  8557. }
  8558. var matrix1 = matrix[1];
  8559. var matrix2 = matrix[2];
  8560. var matrix3 = matrix[3];
  8561. var matrix6 = matrix[6];
  8562. var matrix7 = matrix[7];
  8563. var matrix11 = matrix[11];
  8564. result[0] = matrix[0];
  8565. result[1] = matrix[4];
  8566. result[2] = matrix[8];
  8567. result[3] = matrix[12];
  8568. result[4] = matrix1;
  8569. result[5] = matrix[5];
  8570. result[6] = matrix[9];
  8571. result[7] = matrix[13];
  8572. result[8] = matrix2;
  8573. result[9] = matrix6;
  8574. result[10] = matrix[10];
  8575. result[11] = matrix[14];
  8576. result[12] = matrix3;
  8577. result[13] = matrix7;
  8578. result[14] = matrix11;
  8579. result[15] = matrix[15];
  8580. return result;
  8581. };
  8582. /**
  8583. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  8584. *
  8585. * @param {Matrix4} matrix The matrix with signed elements.
  8586. * @param {Matrix4} result The object onto which to store the result.
  8587. * @returns {Matrix4} The modified result parameter.
  8588. */
  8589. Matrix4.abs = function(matrix, result) {
  8590. if (!defined(matrix)) {
  8591. throw new DeveloperError('matrix is required');
  8592. }
  8593. if (!defined(result)) {
  8594. throw new DeveloperError('result is required');
  8595. }
  8596. result[0] = Math.abs(matrix[0]);
  8597. result[1] = Math.abs(matrix[1]);
  8598. result[2] = Math.abs(matrix[2]);
  8599. result[3] = Math.abs(matrix[3]);
  8600. result[4] = Math.abs(matrix[4]);
  8601. result[5] = Math.abs(matrix[5]);
  8602. result[6] = Math.abs(matrix[6]);
  8603. result[7] = Math.abs(matrix[7]);
  8604. result[8] = Math.abs(matrix[8]);
  8605. result[9] = Math.abs(matrix[9]);
  8606. result[10] = Math.abs(matrix[10]);
  8607. result[11] = Math.abs(matrix[11]);
  8608. result[12] = Math.abs(matrix[12]);
  8609. result[13] = Math.abs(matrix[13]);
  8610. result[14] = Math.abs(matrix[14]);
  8611. result[15] = Math.abs(matrix[15]);
  8612. return result;
  8613. };
  8614. /**
  8615. * Compares the provided matrices componentwise and returns
  8616. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8617. *
  8618. * @param {Matrix4} [left] The first matrix.
  8619. * @param {Matrix4} [right] The second matrix.
  8620. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  8621. *
  8622. * @example
  8623. * //compares two Matrix4 instances
  8624. *
  8625. * // a = [10.0, 14.0, 18.0, 22.0]
  8626. * // [11.0, 15.0, 19.0, 23.0]
  8627. * // [12.0, 16.0, 20.0, 24.0]
  8628. * // [13.0, 17.0, 21.0, 25.0]
  8629. *
  8630. * // b = [10.0, 14.0, 18.0, 22.0]
  8631. * // [11.0, 15.0, 19.0, 23.0]
  8632. * // [12.0, 16.0, 20.0, 24.0]
  8633. * // [13.0, 17.0, 21.0, 25.0]
  8634. *
  8635. * if(Cesium.Matrix4.equals(a,b)) {
  8636. * console.log("Both matrices are equal");
  8637. * } else {
  8638. * console.log("They are not equal");
  8639. * }
  8640. *
  8641. * //Prints "Both matrices are equal" on the console
  8642. */
  8643. Matrix4.equals = function(left, right) {
  8644. // Given that most matrices will be transformation matrices, the elements
  8645. // are tested in order such that the test is likely to fail as early
  8646. // as possible. I _think_ this is just as friendly to the L1 cache
  8647. // as testing in index order. It is certainty faster in practice.
  8648. return (left === right) ||
  8649. (defined(left) &&
  8650. defined(right) &&
  8651. // Translation
  8652. left[12] === right[12] &&
  8653. left[13] === right[13] &&
  8654. left[14] === right[14] &&
  8655. // Rotation/scale
  8656. left[0] === right[0] &&
  8657. left[1] === right[1] &&
  8658. left[2] === right[2] &&
  8659. left[4] === right[4] &&
  8660. left[5] === right[5] &&
  8661. left[6] === right[6] &&
  8662. left[8] === right[8] &&
  8663. left[9] === right[9] &&
  8664. left[10] === right[10] &&
  8665. // Bottom row
  8666. left[3] === right[3] &&
  8667. left[7] === right[7] &&
  8668. left[11] === right[11] &&
  8669. left[15] === right[15]);
  8670. };
  8671. /**
  8672. * Compares the provided matrices componentwise and returns
  8673. * <code>true</code> if they are within the provided epsilon,
  8674. * <code>false</code> otherwise.
  8675. *
  8676. * @param {Matrix4} [left] The first matrix.
  8677. * @param {Matrix4} [right] The second matrix.
  8678. * @param {Number} epsilon The epsilon to use for equality testing.
  8679. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  8680. *
  8681. * @example
  8682. * //compares two Matrix4 instances
  8683. *
  8684. * // a = [10.5, 14.5, 18.5, 22.5]
  8685. * // [11.5, 15.5, 19.5, 23.5]
  8686. * // [12.5, 16.5, 20.5, 24.5]
  8687. * // [13.5, 17.5, 21.5, 25.5]
  8688. *
  8689. * // b = [10.0, 14.0, 18.0, 22.0]
  8690. * // [11.0, 15.0, 19.0, 23.0]
  8691. * // [12.0, 16.0, 20.0, 24.0]
  8692. * // [13.0, 17.0, 21.0, 25.0]
  8693. *
  8694. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  8695. * console.log("Difference between both the matrices is less than 0.1");
  8696. * } else {
  8697. * console.log("Difference between both the matrices is not less than 0.1");
  8698. * }
  8699. *
  8700. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  8701. */
  8702. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  8703. if (typeof epsilon !== 'number') {
  8704. throw new DeveloperError('epsilon must be a number');
  8705. }
  8706. return (left === right) ||
  8707. (defined(left) &&
  8708. defined(right) &&
  8709. Math.abs(left[0] - right[0]) <= epsilon &&
  8710. Math.abs(left[1] - right[1]) <= epsilon &&
  8711. Math.abs(left[2] - right[2]) <= epsilon &&
  8712. Math.abs(left[3] - right[3]) <= epsilon &&
  8713. Math.abs(left[4] - right[4]) <= epsilon &&
  8714. Math.abs(left[5] - right[5]) <= epsilon &&
  8715. Math.abs(left[6] - right[6]) <= epsilon &&
  8716. Math.abs(left[7] - right[7]) <= epsilon &&
  8717. Math.abs(left[8] - right[8]) <= epsilon &&
  8718. Math.abs(left[9] - right[9]) <= epsilon &&
  8719. Math.abs(left[10] - right[10]) <= epsilon &&
  8720. Math.abs(left[11] - right[11]) <= epsilon &&
  8721. Math.abs(left[12] - right[12]) <= epsilon &&
  8722. Math.abs(left[13] - right[13]) <= epsilon &&
  8723. Math.abs(left[14] - right[14]) <= epsilon &&
  8724. Math.abs(left[15] - right[15]) <= epsilon);
  8725. };
  8726. /**
  8727. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  8728. *
  8729. * @param {Matrix4} matrix The matrix to use.
  8730. * @param {Cartesian3} result The object onto which to store the result.
  8731. * @returns {Cartesian3} The modified result parameter.
  8732. */
  8733. Matrix4.getTranslation = function(matrix, result) {
  8734. if (!defined(matrix)) {
  8735. throw new DeveloperError('matrix is required');
  8736. }
  8737. if (!defined(result)) {
  8738. throw new DeveloperError('result is required');
  8739. }
  8740. result.x = matrix[12];
  8741. result.y = matrix[13];
  8742. result.z = matrix[14];
  8743. return result;
  8744. };
  8745. /**
  8746. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  8747. *
  8748. * @param {Matrix4} matrix The matrix to use.
  8749. * @param {Matrix3} result The object onto which to store the result.
  8750. * @returns {Matrix3} The modified result parameter.
  8751. *
  8752. * @example
  8753. * // returns a Matrix3 instance from a Matrix4 instance
  8754. *
  8755. * // m = [10.0, 14.0, 18.0, 22.0]
  8756. * // [11.0, 15.0, 19.0, 23.0]
  8757. * // [12.0, 16.0, 20.0, 24.0]
  8758. * // [13.0, 17.0, 21.0, 25.0]
  8759. *
  8760. * var b = new Cesium.Matrix3();
  8761. * Cesium.Matrix4.getRotation(m,b);
  8762. *
  8763. * // b = [10.0, 14.0, 18.0]
  8764. * // [11.0, 15.0, 19.0]
  8765. * // [12.0, 16.0, 20.0]
  8766. */
  8767. Matrix4.getRotation = function(matrix, result) {
  8768. if (!defined(matrix)) {
  8769. throw new DeveloperError('matrix is required');
  8770. }
  8771. if (!defined(result)) {
  8772. throw new DeveloperError('result is required');
  8773. }
  8774. result[0] = matrix[0];
  8775. result[1] = matrix[1];
  8776. result[2] = matrix[2];
  8777. result[3] = matrix[4];
  8778. result[4] = matrix[5];
  8779. result[5] = matrix[6];
  8780. result[6] = matrix[8];
  8781. result[7] = matrix[9];
  8782. result[8] = matrix[10];
  8783. return result;
  8784. };
  8785. var scratchInverseRotation = new Matrix3();
  8786. var scratchMatrix3Zero = new Matrix3();
  8787. var scratchBottomRow = new Cartesian4();
  8788. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  8789. /**
  8790. * Computes the inverse of the provided matrix using Cramers Rule.
  8791. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  8792. * If the matrix is an affine transformation matrix, it is more efficient
  8793. * to invert it with {@link Matrix4.inverseTransformation}.
  8794. *
  8795. * @param {Matrix4} matrix The matrix to invert.
  8796. * @param {Matrix4} result The object onto which to store the result.
  8797. * @returns {Matrix4} The modified result parameter.
  8798. *
  8799. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  8800. */
  8801. Matrix4.inverse = function(matrix, result) {
  8802. if (!defined(matrix)) {
  8803. throw new DeveloperError('matrix is required');
  8804. }
  8805. if (!defined(result)) {
  8806. throw new DeveloperError('result is required');
  8807. }
  8808. // Special case for a zero scale matrix that can occur, for example,
  8809. // when a model's node has a [0, 0, 0] scale.
  8810. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  8811. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  8812. result[0] = 0.0;
  8813. result[1] = 0.0;
  8814. result[2] = 0.0;
  8815. result[3] = 0.0;
  8816. result[4] = 0.0;
  8817. result[5] = 0.0;
  8818. result[6] = 0.0;
  8819. result[7] = 0.0;
  8820. result[8] = 0.0;
  8821. result[9] = 0.0;
  8822. result[10] = 0.0;
  8823. result[11] = 0.0;
  8824. result[12] = -matrix[12];
  8825. result[13] = -matrix[13];
  8826. result[14] = -matrix[14];
  8827. result[15] = 1.0;
  8828. return result;
  8829. }
  8830. //
  8831. // Ported from:
  8832. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  8833. //
  8834. var src0 = matrix[0];
  8835. var src1 = matrix[4];
  8836. var src2 = matrix[8];
  8837. var src3 = matrix[12];
  8838. var src4 = matrix[1];
  8839. var src5 = matrix[5];
  8840. var src6 = matrix[9];
  8841. var src7 = matrix[13];
  8842. var src8 = matrix[2];
  8843. var src9 = matrix[6];
  8844. var src10 = matrix[10];
  8845. var src11 = matrix[14];
  8846. var src12 = matrix[3];
  8847. var src13 = matrix[7];
  8848. var src14 = matrix[11];
  8849. var src15 = matrix[15];
  8850. // calculate pairs for first 8 elements (cofactors)
  8851. var tmp0 = src10 * src15;
  8852. var tmp1 = src11 * src14;
  8853. var tmp2 = src9 * src15;
  8854. var tmp3 = src11 * src13;
  8855. var tmp4 = src9 * src14;
  8856. var tmp5 = src10 * src13;
  8857. var tmp6 = src8 * src15;
  8858. var tmp7 = src11 * src12;
  8859. var tmp8 = src8 * src14;
  8860. var tmp9 = src10 * src12;
  8861. var tmp10 = src8 * src13;
  8862. var tmp11 = src9 * src12;
  8863. // calculate first 8 elements (cofactors)
  8864. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  8865. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  8866. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  8867. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  8868. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  8869. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  8870. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  8871. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  8872. // calculate pairs for second 8 elements (cofactors)
  8873. tmp0 = src2 * src7;
  8874. tmp1 = src3 * src6;
  8875. tmp2 = src1 * src7;
  8876. tmp3 = src3 * src5;
  8877. tmp4 = src1 * src6;
  8878. tmp5 = src2 * src5;
  8879. tmp6 = src0 * src7;
  8880. tmp7 = src3 * src4;
  8881. tmp8 = src0 * src6;
  8882. tmp9 = src2 * src4;
  8883. tmp10 = src0 * src5;
  8884. tmp11 = src1 * src4;
  8885. // calculate second 8 elements (cofactors)
  8886. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  8887. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  8888. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  8889. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  8890. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  8891. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  8892. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  8893. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  8894. // calculate determinant
  8895. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  8896. if (Math.abs(det) < CesiumMath.EPSILON20) {
  8897. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  8898. }
  8899. // calculate matrix inverse
  8900. det = 1.0 / det;
  8901. result[0] = dst0 * det;
  8902. result[1] = dst1 * det;
  8903. result[2] = dst2 * det;
  8904. result[3] = dst3 * det;
  8905. result[4] = dst4 * det;
  8906. result[5] = dst5 * det;
  8907. result[6] = dst6 * det;
  8908. result[7] = dst7 * det;
  8909. result[8] = dst8 * det;
  8910. result[9] = dst9 * det;
  8911. result[10] = dst10 * det;
  8912. result[11] = dst11 * det;
  8913. result[12] = dst12 * det;
  8914. result[13] = dst13 * det;
  8915. result[14] = dst14 * det;
  8916. result[15] = dst15 * det;
  8917. return result;
  8918. };
  8919. /**
  8920. * Computes the inverse of the provided matrix assuming it is
  8921. * an affine transformation matrix, where the upper left 3x3 elements
  8922. * are a rotation matrix, and the upper three elements in the fourth
  8923. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  8924. * The matrix is not verified to be in the proper form.
  8925. * This method is faster than computing the inverse for a general 4x4
  8926. * matrix using {@link Matrix4.inverse}.
  8927. *
  8928. * @param {Matrix4} matrix The matrix to invert.
  8929. * @param {Matrix4} result The object onto which to store the result.
  8930. * @returns {Matrix4} The modified result parameter.
  8931. */
  8932. Matrix4.inverseTransformation = function(matrix, result) {
  8933. if (!defined(matrix)) {
  8934. throw new DeveloperError('matrix is required');
  8935. }
  8936. if (!defined(result)) {
  8937. throw new DeveloperError('result is required');
  8938. }
  8939. //This function is an optimized version of the below 4 lines.
  8940. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  8941. //var rTN = Matrix3.negate(rT);
  8942. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  8943. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  8944. var matrix0 = matrix[0];
  8945. var matrix1 = matrix[1];
  8946. var matrix2 = matrix[2];
  8947. var matrix4 = matrix[4];
  8948. var matrix5 = matrix[5];
  8949. var matrix6 = matrix[6];
  8950. var matrix8 = matrix[8];
  8951. var matrix9 = matrix[9];
  8952. var matrix10 = matrix[10];
  8953. var vX = matrix[12];
  8954. var vY = matrix[13];
  8955. var vZ = matrix[14];
  8956. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  8957. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  8958. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  8959. result[0] = matrix0;
  8960. result[1] = matrix4;
  8961. result[2] = matrix8;
  8962. result[3] = 0.0;
  8963. result[4] = matrix1;
  8964. result[5] = matrix5;
  8965. result[6] = matrix9;
  8966. result[7] = 0.0;
  8967. result[8] = matrix2;
  8968. result[9] = matrix6;
  8969. result[10] = matrix10;
  8970. result[11] = 0.0;
  8971. result[12] = x;
  8972. result[13] = y;
  8973. result[14] = z;
  8974. result[15] = 1.0;
  8975. return result;
  8976. };
  8977. /**
  8978. * An immutable Matrix4 instance initialized to the identity matrix.
  8979. *
  8980. * @type {Matrix4}
  8981. * @constant
  8982. */
  8983. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  8984. 0.0, 1.0, 0.0, 0.0,
  8985. 0.0, 0.0, 1.0, 0.0,
  8986. 0.0, 0.0, 0.0, 1.0));
  8987. /**
  8988. * An immutable Matrix4 instance initialized to the zero matrix.
  8989. *
  8990. * @type {Matrix4}
  8991. * @constant
  8992. */
  8993. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  8994. 0.0, 0.0, 0.0, 0.0,
  8995. 0.0, 0.0, 0.0, 0.0,
  8996. 0.0, 0.0, 0.0, 0.0));
  8997. /**
  8998. * The index into Matrix4 for column 0, row 0.
  8999. *
  9000. * @type {Number}
  9001. * @constant
  9002. */
  9003. Matrix4.COLUMN0ROW0 = 0;
  9004. /**
  9005. * The index into Matrix4 for column 0, row 1.
  9006. *
  9007. * @type {Number}
  9008. * @constant
  9009. */
  9010. Matrix4.COLUMN0ROW1 = 1;
  9011. /**
  9012. * The index into Matrix4 for column 0, row 2.
  9013. *
  9014. * @type {Number}
  9015. * @constant
  9016. */
  9017. Matrix4.COLUMN0ROW2 = 2;
  9018. /**
  9019. * The index into Matrix4 for column 0, row 3.
  9020. *
  9021. * @type {Number}
  9022. * @constant
  9023. */
  9024. Matrix4.COLUMN0ROW3 = 3;
  9025. /**
  9026. * The index into Matrix4 for column 1, row 0.
  9027. *
  9028. * @type {Number}
  9029. * @constant
  9030. */
  9031. Matrix4.COLUMN1ROW0 = 4;
  9032. /**
  9033. * The index into Matrix4 for column 1, row 1.
  9034. *
  9035. * @type {Number}
  9036. * @constant
  9037. */
  9038. Matrix4.COLUMN1ROW1 = 5;
  9039. /**
  9040. * The index into Matrix4 for column 1, row 2.
  9041. *
  9042. * @type {Number}
  9043. * @constant
  9044. */
  9045. Matrix4.COLUMN1ROW2 = 6;
  9046. /**
  9047. * The index into Matrix4 for column 1, row 3.
  9048. *
  9049. * @type {Number}
  9050. * @constant
  9051. */
  9052. Matrix4.COLUMN1ROW3 = 7;
  9053. /**
  9054. * The index into Matrix4 for column 2, row 0.
  9055. *
  9056. * @type {Number}
  9057. * @constant
  9058. */
  9059. Matrix4.COLUMN2ROW0 = 8;
  9060. /**
  9061. * The index into Matrix4 for column 2, row 1.
  9062. *
  9063. * @type {Number}
  9064. * @constant
  9065. */
  9066. Matrix4.COLUMN2ROW1 = 9;
  9067. /**
  9068. * The index into Matrix4 for column 2, row 2.
  9069. *
  9070. * @type {Number}
  9071. * @constant
  9072. */
  9073. Matrix4.COLUMN2ROW2 = 10;
  9074. /**
  9075. * The index into Matrix4 for column 2, row 3.
  9076. *
  9077. * @type {Number}
  9078. * @constant
  9079. */
  9080. Matrix4.COLUMN2ROW3 = 11;
  9081. /**
  9082. * The index into Matrix4 for column 3, row 0.
  9083. *
  9084. * @type {Number}
  9085. * @constant
  9086. */
  9087. Matrix4.COLUMN3ROW0 = 12;
  9088. /**
  9089. * The index into Matrix4 for column 3, row 1.
  9090. *
  9091. * @type {Number}
  9092. * @constant
  9093. */
  9094. Matrix4.COLUMN3ROW1 = 13;
  9095. /**
  9096. * The index into Matrix4 for column 3, row 2.
  9097. *
  9098. * @type {Number}
  9099. * @constant
  9100. */
  9101. Matrix4.COLUMN3ROW2 = 14;
  9102. /**
  9103. * The index into Matrix4 for column 3, row 3.
  9104. *
  9105. * @type {Number}
  9106. * @constant
  9107. */
  9108. Matrix4.COLUMN3ROW3 = 15;
  9109. defineProperties(Matrix4.prototype, {
  9110. /**
  9111. * Gets the number of items in the collection.
  9112. * @memberof Matrix4.prototype
  9113. *
  9114. * @type {Number}
  9115. */
  9116. length : {
  9117. get : function() {
  9118. return Matrix4.packedLength;
  9119. }
  9120. }
  9121. });
  9122. /**
  9123. * Duplicates the provided Matrix4 instance.
  9124. *
  9125. * @param {Matrix4} [result] The object onto which to store the result.
  9126. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  9127. */
  9128. Matrix4.prototype.clone = function(result) {
  9129. return Matrix4.clone(this, result);
  9130. };
  9131. /**
  9132. * Compares this matrix to the provided matrix componentwise and returns
  9133. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9134. *
  9135. * @param {Matrix4} [right] The right hand side matrix.
  9136. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9137. */
  9138. Matrix4.prototype.equals = function(right) {
  9139. return Matrix4.equals(this, right);
  9140. };
  9141. /**
  9142. * @private
  9143. */
  9144. Matrix4.equalsArray = function(matrix, array, offset) {
  9145. return matrix[0] === array[offset] &&
  9146. matrix[1] === array[offset + 1] &&
  9147. matrix[2] === array[offset + 2] &&
  9148. matrix[3] === array[offset + 3] &&
  9149. matrix[4] === array[offset + 4] &&
  9150. matrix[5] === array[offset + 5] &&
  9151. matrix[6] === array[offset + 6] &&
  9152. matrix[7] === array[offset + 7] &&
  9153. matrix[8] === array[offset + 8] &&
  9154. matrix[9] === array[offset + 9] &&
  9155. matrix[10] === array[offset + 10] &&
  9156. matrix[11] === array[offset + 11] &&
  9157. matrix[12] === array[offset + 12] &&
  9158. matrix[13] === array[offset + 13] &&
  9159. matrix[14] === array[offset + 14] &&
  9160. matrix[15] === array[offset + 15];
  9161. };
  9162. /**
  9163. * Compares this matrix to the provided matrix componentwise and returns
  9164. * <code>true</code> if they are within the provided epsilon,
  9165. * <code>false</code> otherwise.
  9166. *
  9167. * @param {Matrix4} [right] The right hand side matrix.
  9168. * @param {Number} epsilon The epsilon to use for equality testing.
  9169. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  9170. */
  9171. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  9172. return Matrix4.equalsEpsilon(this, right, epsilon);
  9173. };
  9174. /**
  9175. * Computes a string representing this Matrix with each row being
  9176. * on a separate line and in the format '(column0, column1, column2, column3)'.
  9177. *
  9178. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  9179. */
  9180. Matrix4.prototype.toString = function() {
  9181. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  9182. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  9183. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  9184. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  9185. };
  9186. return Matrix4;
  9187. });
  9188. /*global define*/
  9189. define('Core/Rectangle',[
  9190. './Cartographic',
  9191. './defaultValue',
  9192. './defined',
  9193. './defineProperties',
  9194. './DeveloperError',
  9195. './Ellipsoid',
  9196. './freezeObject',
  9197. './Math'
  9198. ], function(
  9199. Cartographic,
  9200. defaultValue,
  9201. defined,
  9202. defineProperties,
  9203. DeveloperError,
  9204. Ellipsoid,
  9205. freezeObject,
  9206. CesiumMath) {
  9207. 'use strict';
  9208. /**
  9209. * A two dimensional region specified as longitude and latitude coordinates.
  9210. *
  9211. * @alias Rectangle
  9212. * @constructor
  9213. *
  9214. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  9215. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  9216. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  9217. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  9218. *
  9219. * @see Packable
  9220. */
  9221. function Rectangle(west, south, east, north) {
  9222. /**
  9223. * The westernmost longitude in radians in the range [-Pi, Pi].
  9224. *
  9225. * @type {Number}
  9226. * @default 0.0
  9227. */
  9228. this.west = defaultValue(west, 0.0);
  9229. /**
  9230. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  9231. *
  9232. * @type {Number}
  9233. * @default 0.0
  9234. */
  9235. this.south = defaultValue(south, 0.0);
  9236. /**
  9237. * The easternmost longitude in radians in the range [-Pi, Pi].
  9238. *
  9239. * @type {Number}
  9240. * @default 0.0
  9241. */
  9242. this.east = defaultValue(east, 0.0);
  9243. /**
  9244. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  9245. *
  9246. * @type {Number}
  9247. * @default 0.0
  9248. */
  9249. this.north = defaultValue(north, 0.0);
  9250. }
  9251. defineProperties(Rectangle.prototype, {
  9252. /**
  9253. * Gets the width of the rectangle in radians.
  9254. * @memberof Rectangle.prototype
  9255. * @type {Number}
  9256. */
  9257. width : {
  9258. get : function() {
  9259. return Rectangle.computeWidth(this);
  9260. }
  9261. },
  9262. /**
  9263. * Gets the height of the rectangle in radians.
  9264. * @memberof Rectangle.prototype
  9265. * @type {Number}
  9266. */
  9267. height : {
  9268. get : function() {
  9269. return Rectangle.computeHeight(this);
  9270. }
  9271. }
  9272. });
  9273. /**
  9274. * The number of elements used to pack the object into an array.
  9275. * @type {Number}
  9276. */
  9277. Rectangle.packedLength = 4;
  9278. /**
  9279. * Stores the provided instance into the provided array.
  9280. *
  9281. * @param {Rectangle} value The value to pack.
  9282. * @param {Number[]} array The array to pack into.
  9283. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  9284. *
  9285. * @returns {Number[]} The array that was packed into
  9286. */
  9287. Rectangle.pack = function(value, array, startingIndex) {
  9288. if (!defined(value)) {
  9289. throw new DeveloperError('value is required');
  9290. }
  9291. if (!defined(array)) {
  9292. throw new DeveloperError('array is required');
  9293. }
  9294. startingIndex = defaultValue(startingIndex, 0);
  9295. array[startingIndex++] = value.west;
  9296. array[startingIndex++] = value.south;
  9297. array[startingIndex++] = value.east;
  9298. array[startingIndex] = value.north;
  9299. return array;
  9300. };
  9301. /**
  9302. * Retrieves an instance from a packed array.
  9303. *
  9304. * @param {Number[]} array The packed array.
  9305. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  9306. * @param {Rectangle} [result] The object into which to store the result.
  9307. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  9308. */
  9309. Rectangle.unpack = function(array, startingIndex, result) {
  9310. if (!defined(array)) {
  9311. throw new DeveloperError('array is required');
  9312. }
  9313. startingIndex = defaultValue(startingIndex, 0);
  9314. if (!defined(result)) {
  9315. result = new Rectangle();
  9316. }
  9317. result.west = array[startingIndex++];
  9318. result.south = array[startingIndex++];
  9319. result.east = array[startingIndex++];
  9320. result.north = array[startingIndex];
  9321. return result;
  9322. };
  9323. /**
  9324. * Computes the width of a rectangle in radians.
  9325. * @param {Rectangle} rectangle The rectangle to compute the width of.
  9326. * @returns {Number} The width.
  9327. */
  9328. Rectangle.computeWidth = function(rectangle) {
  9329. if (!defined(rectangle)) {
  9330. throw new DeveloperError('rectangle is required.');
  9331. }
  9332. var east = rectangle.east;
  9333. var west = rectangle.west;
  9334. if (east < west) {
  9335. east += CesiumMath.TWO_PI;
  9336. }
  9337. return east - west;
  9338. };
  9339. /**
  9340. * Computes the height of a rectangle in radians.
  9341. * @param {Rectangle} rectangle The rectangle to compute the height of.
  9342. * @returns {Number} The height.
  9343. */
  9344. Rectangle.computeHeight = function(rectangle) {
  9345. if (!defined(rectangle)) {
  9346. throw new DeveloperError('rectangle is required.');
  9347. }
  9348. return rectangle.north - rectangle.south;
  9349. };
  9350. /**
  9351. * Creates an rectangle given the boundary longitude and latitude in degrees.
  9352. *
  9353. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  9354. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  9355. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  9356. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  9357. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  9358. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  9359. *
  9360. * @example
  9361. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  9362. */
  9363. Rectangle.fromDegrees = function(west, south, east, north, result) {
  9364. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  9365. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  9366. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  9367. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  9368. if (!defined(result)) {
  9369. return new Rectangle(west, south, east, north);
  9370. }
  9371. result.west = west;
  9372. result.south = south;
  9373. result.east = east;
  9374. result.north = north;
  9375. return result;
  9376. };
  9377. /**
  9378. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  9379. *
  9380. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  9381. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  9382. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  9383. */
  9384. Rectangle.fromCartographicArray = function(cartographics, result) {
  9385. if (!defined(cartographics)) {
  9386. throw new DeveloperError('cartographics is required.');
  9387. }
  9388. var west = Number.MAX_VALUE;
  9389. var east = -Number.MAX_VALUE;
  9390. var westOverIDL = Number.MAX_VALUE;
  9391. var eastOverIDL = -Number.MAX_VALUE;
  9392. var south = Number.MAX_VALUE;
  9393. var north = -Number.MAX_VALUE;
  9394. for ( var i = 0, len = cartographics.length; i < len; i++) {
  9395. var position = cartographics[i];
  9396. west = Math.min(west, position.longitude);
  9397. east = Math.max(east, position.longitude);
  9398. south = Math.min(south, position.latitude);
  9399. north = Math.max(north, position.latitude);
  9400. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  9401. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  9402. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  9403. }
  9404. if(east - west > eastOverIDL - westOverIDL) {
  9405. west = westOverIDL;
  9406. east = eastOverIDL;
  9407. if (east > CesiumMath.PI) {
  9408. east = east - CesiumMath.TWO_PI;
  9409. }
  9410. if (west > CesiumMath.PI) {
  9411. west = west - CesiumMath.TWO_PI;
  9412. }
  9413. }
  9414. if (!defined(result)) {
  9415. return new Rectangle(west, south, east, north);
  9416. }
  9417. result.west = west;
  9418. result.south = south;
  9419. result.east = east;
  9420. result.north = north;
  9421. return result;
  9422. };
  9423. /**
  9424. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  9425. *
  9426. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  9427. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  9428. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  9429. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  9430. */
  9431. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  9432. if (!defined(cartesians)) {
  9433. throw new DeveloperError('cartesians is required.');
  9434. }
  9435. var west = Number.MAX_VALUE;
  9436. var east = -Number.MAX_VALUE;
  9437. var westOverIDL = Number.MAX_VALUE;
  9438. var eastOverIDL = -Number.MAX_VALUE;
  9439. var south = Number.MAX_VALUE;
  9440. var north = -Number.MAX_VALUE;
  9441. for ( var i = 0, len = cartesians.length; i < len; i++) {
  9442. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  9443. west = Math.min(west, position.longitude);
  9444. east = Math.max(east, position.longitude);
  9445. south = Math.min(south, position.latitude);
  9446. north = Math.max(north, position.latitude);
  9447. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  9448. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  9449. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  9450. }
  9451. if(east - west > eastOverIDL - westOverIDL) {
  9452. west = westOverIDL;
  9453. east = eastOverIDL;
  9454. if (east > CesiumMath.PI) {
  9455. east = east - CesiumMath.TWO_PI;
  9456. }
  9457. if (west > CesiumMath.PI) {
  9458. west = west - CesiumMath.TWO_PI;
  9459. }
  9460. }
  9461. if (!defined(result)) {
  9462. return new Rectangle(west, south, east, north);
  9463. }
  9464. result.west = west;
  9465. result.south = south;
  9466. result.east = east;
  9467. result.north = north;
  9468. return result;
  9469. };
  9470. /**
  9471. * Duplicates an Rectangle.
  9472. *
  9473. * @param {Rectangle} rectangle The rectangle to clone.
  9474. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  9475. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  9476. */
  9477. Rectangle.clone = function(rectangle, result) {
  9478. if (!defined(rectangle)) {
  9479. return undefined;
  9480. }
  9481. if (!defined(result)) {
  9482. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  9483. }
  9484. result.west = rectangle.west;
  9485. result.south = rectangle.south;
  9486. result.east = rectangle.east;
  9487. result.north = rectangle.north;
  9488. return result;
  9489. };
  9490. /**
  9491. * Duplicates this Rectangle.
  9492. *
  9493. * @param {Rectangle} [result] The object onto which to store the result.
  9494. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  9495. */
  9496. Rectangle.prototype.clone = function(result) {
  9497. return Rectangle.clone(this, result);
  9498. };
  9499. /**
  9500. * Compares the provided Rectangle with this Rectangle componentwise and returns
  9501. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9502. *
  9503. * @param {Rectangle} [other] The Rectangle to compare.
  9504. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  9505. */
  9506. Rectangle.prototype.equals = function(other) {
  9507. return Rectangle.equals(this, other);
  9508. };
  9509. /**
  9510. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  9511. * <code>false</code> otherwise.
  9512. *
  9513. * @param {Rectangle} [left] The first Rectangle.
  9514. * @param {Rectangle} [right] The second Rectangle.
  9515. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  9516. */
  9517. Rectangle.equals = function(left, right) {
  9518. return (left === right) ||
  9519. ((defined(left)) &&
  9520. (defined(right)) &&
  9521. (left.west === right.west) &&
  9522. (left.south === right.south) &&
  9523. (left.east === right.east) &&
  9524. (left.north === right.north));
  9525. };
  9526. /**
  9527. * Compares the provided Rectangle with this Rectangle componentwise and returns
  9528. * <code>true</code> if they are within the provided epsilon,
  9529. * <code>false</code> otherwise.
  9530. *
  9531. * @param {Rectangle} [other] The Rectangle to compare.
  9532. * @param {Number} epsilon The epsilon to use for equality testing.
  9533. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  9534. */
  9535. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  9536. if (typeof epsilon !== 'number') {
  9537. throw new DeveloperError('epsilon is required and must be a number.');
  9538. }
  9539. return defined(other) &&
  9540. (Math.abs(this.west - other.west) <= epsilon) &&
  9541. (Math.abs(this.south - other.south) <= epsilon) &&
  9542. (Math.abs(this.east - other.east) <= epsilon) &&
  9543. (Math.abs(this.north - other.north) <= epsilon);
  9544. };
  9545. /**
  9546. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  9547. *
  9548. * @param {Rectangle} rectangle The rectangle to validate
  9549. *
  9550. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  9551. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  9552. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  9553. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  9554. */
  9555. Rectangle.validate = function(rectangle) {
  9556. if (!defined(rectangle)) {
  9557. throw new DeveloperError('rectangle is required');
  9558. }
  9559. var north = rectangle.north;
  9560. if (typeof north !== 'number') {
  9561. throw new DeveloperError('north is required to be a number.');
  9562. }
  9563. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  9564. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  9565. }
  9566. var south = rectangle.south;
  9567. if (typeof south !== 'number') {
  9568. throw new DeveloperError('south is required to be a number.');
  9569. }
  9570. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  9571. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  9572. }
  9573. var west = rectangle.west;
  9574. if (typeof west !== 'number') {
  9575. throw new DeveloperError('west is required to be a number.');
  9576. }
  9577. if (west < -Math.PI || west > Math.PI) {
  9578. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  9579. }
  9580. var east = rectangle.east;
  9581. if (typeof east !== 'number') {
  9582. throw new DeveloperError('east is required to be a number.');
  9583. }
  9584. if (east < -Math.PI || east > Math.PI) {
  9585. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  9586. }
  9587. };
  9588. /**
  9589. * Computes the southwest corner of an rectangle.
  9590. *
  9591. * @param {Rectangle} rectangle The rectangle for which to find the corner
  9592. * @param {Cartographic} [result] The object onto which to store the result.
  9593. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  9594. */
  9595. Rectangle.southwest = function(rectangle, result) {
  9596. if (!defined(rectangle)) {
  9597. throw new DeveloperError('rectangle is required');
  9598. }
  9599. if (!defined(result)) {
  9600. return new Cartographic(rectangle.west, rectangle.south);
  9601. }
  9602. result.longitude = rectangle.west;
  9603. result.latitude = rectangle.south;
  9604. result.height = 0.0;
  9605. return result;
  9606. };
  9607. /**
  9608. * Computes the northwest corner of an rectangle.
  9609. *
  9610. * @param {Rectangle} rectangle The rectangle for which to find the corner
  9611. * @param {Cartographic} [result] The object onto which to store the result.
  9612. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  9613. */
  9614. Rectangle.northwest = function(rectangle, result) {
  9615. if (!defined(rectangle)) {
  9616. throw new DeveloperError('rectangle is required');
  9617. }
  9618. if (!defined(result)) {
  9619. return new Cartographic(rectangle.west, rectangle.north);
  9620. }
  9621. result.longitude = rectangle.west;
  9622. result.latitude = rectangle.north;
  9623. result.height = 0.0;
  9624. return result;
  9625. };
  9626. /**
  9627. * Computes the northeast corner of an rectangle.
  9628. *
  9629. * @param {Rectangle} rectangle The rectangle for which to find the corner
  9630. * @param {Cartographic} [result] The object onto which to store the result.
  9631. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  9632. */
  9633. Rectangle.northeast = function(rectangle, result) {
  9634. if (!defined(rectangle)) {
  9635. throw new DeveloperError('rectangle is required');
  9636. }
  9637. if (!defined(result)) {
  9638. return new Cartographic(rectangle.east, rectangle.north);
  9639. }
  9640. result.longitude = rectangle.east;
  9641. result.latitude = rectangle.north;
  9642. result.height = 0.0;
  9643. return result;
  9644. };
  9645. /**
  9646. * Computes the southeast corner of an rectangle.
  9647. *
  9648. * @param {Rectangle} rectangle The rectangle for which to find the corner
  9649. * @param {Cartographic} [result] The object onto which to store the result.
  9650. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  9651. */
  9652. Rectangle.southeast = function(rectangle, result) {
  9653. if (!defined(rectangle)) {
  9654. throw new DeveloperError('rectangle is required');
  9655. }
  9656. if (!defined(result)) {
  9657. return new Cartographic(rectangle.east, rectangle.south);
  9658. }
  9659. result.longitude = rectangle.east;
  9660. result.latitude = rectangle.south;
  9661. result.height = 0.0;
  9662. return result;
  9663. };
  9664. /**
  9665. * Computes the center of an rectangle.
  9666. *
  9667. * @param {Rectangle} rectangle The rectangle for which to find the center
  9668. * @param {Cartographic} [result] The object onto which to store the result.
  9669. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  9670. */
  9671. Rectangle.center = function(rectangle, result) {
  9672. if (!defined(rectangle)) {
  9673. throw new DeveloperError('rectangle is required');
  9674. }
  9675. var east = rectangle.east;
  9676. var west = rectangle.west;
  9677. if (east < west) {
  9678. east += CesiumMath.TWO_PI;
  9679. }
  9680. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  9681. var latitude = (rectangle.south + rectangle.north) * 0.5;
  9682. if (!defined(result)) {
  9683. return new Cartographic(longitude, latitude);
  9684. }
  9685. result.longitude = longitude;
  9686. result.latitude = latitude;
  9687. result.height = 0.0;
  9688. return result;
  9689. };
  9690. /**
  9691. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  9692. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  9693. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  9694. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  9695. * coordinates, see {@link Rectangle.simpleIntersection}.
  9696. *
  9697. * @param {Rectangle} rectangle On rectangle to find an intersection
  9698. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  9699. * @param {Rectangle} [result] The object onto which to store the result.
  9700. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  9701. */
  9702. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  9703. if (!defined(rectangle)) {
  9704. throw new DeveloperError('rectangle is required');
  9705. }
  9706. if (!defined(otherRectangle)) {
  9707. throw new DeveloperError('otherRectangle is required.');
  9708. }
  9709. var rectangleEast = rectangle.east;
  9710. var rectangleWest = rectangle.west;
  9711. var otherRectangleEast = otherRectangle.east;
  9712. var otherRectangleWest = otherRectangle.west;
  9713. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  9714. rectangleEast += CesiumMath.TWO_PI;
  9715. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  9716. otherRectangleEast += CesiumMath.TWO_PI;
  9717. }
  9718. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  9719. otherRectangleWest += CesiumMath.TWO_PI;
  9720. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  9721. rectangleWest += CesiumMath.TWO_PI;
  9722. }
  9723. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  9724. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  9725. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  9726. return undefined;
  9727. }
  9728. var south = Math.max(rectangle.south, otherRectangle.south);
  9729. var north = Math.min(rectangle.north, otherRectangle.north);
  9730. if (south >= north) {
  9731. return undefined;
  9732. }
  9733. if (!defined(result)) {
  9734. return new Rectangle(west, south, east, north);
  9735. }
  9736. result.west = west;
  9737. result.south = south;
  9738. result.east = east;
  9739. result.north = north;
  9740. return result;
  9741. };
  9742. /**
  9743. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  9744. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  9745. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  9746. * and longitude (i.e. projected coordinates).
  9747. *
  9748. * @param {Rectangle} rectangle On rectangle to find an intersection
  9749. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  9750. * @param {Rectangle} [result] The object onto which to store the result.
  9751. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  9752. */
  9753. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  9754. if (!defined(rectangle)) {
  9755. throw new DeveloperError('rectangle is required');
  9756. }
  9757. if (!defined(otherRectangle)) {
  9758. throw new DeveloperError('otherRectangle is required.');
  9759. }
  9760. var west = Math.max(rectangle.west, otherRectangle.west);
  9761. var south = Math.max(rectangle.south, otherRectangle.south);
  9762. var east = Math.min(rectangle.east, otherRectangle.east);
  9763. var north = Math.min(rectangle.north, otherRectangle.north);
  9764. if (south >= north || west >= east) {
  9765. return undefined;
  9766. }
  9767. if (!defined(result)) {
  9768. return new Rectangle(west, south, east, north);
  9769. }
  9770. result.west = west;
  9771. result.south = south;
  9772. result.east = east;
  9773. result.north = north;
  9774. return result;
  9775. };
  9776. /**
  9777. * Computes a rectangle that is the union of two rectangles.
  9778. *
  9779. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  9780. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  9781. * @param {Rectangle} [result] The object onto which to store the result.
  9782. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  9783. */
  9784. Rectangle.union = function(rectangle, otherRectangle, result) {
  9785. if (!defined(rectangle)) {
  9786. throw new DeveloperError('rectangle is required');
  9787. }
  9788. if (!defined(otherRectangle)) {
  9789. throw new DeveloperError('otherRectangle is required.');
  9790. }
  9791. if (!defined(result)) {
  9792. result = new Rectangle();
  9793. }
  9794. var rectangleEast = rectangle.east;
  9795. var rectangleWest = rectangle.west;
  9796. var otherRectangleEast = otherRectangle.east;
  9797. var otherRectangleWest = otherRectangle.west;
  9798. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  9799. rectangleEast += CesiumMath.TWO_PI;
  9800. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  9801. otherRectangleEast += CesiumMath.TWO_PI;
  9802. }
  9803. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  9804. otherRectangleWest += CesiumMath.TWO_PI;
  9805. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  9806. rectangleWest += CesiumMath.TWO_PI;
  9807. }
  9808. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  9809. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  9810. result.west = west;
  9811. result.south = Math.min(rectangle.south, otherRectangle.south);
  9812. result.east = east;
  9813. result.north = Math.max(rectangle.north, otherRectangle.north);
  9814. return result;
  9815. };
  9816. /**
  9817. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  9818. *
  9819. * @param {Rectangle} rectangle A rectangle to expand.
  9820. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  9821. * @param {Rectangle} [result] The object onto which to store the result.
  9822. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  9823. */
  9824. Rectangle.expand = function(rectangle, cartographic, result) {
  9825. if (!defined(rectangle)) {
  9826. throw new DeveloperError('rectangle is required.');
  9827. }
  9828. if (!defined(cartographic)) {
  9829. throw new DeveloperError('cartographic is required.');
  9830. }
  9831. if (!defined(result)) {
  9832. result = new Rectangle();
  9833. }
  9834. result.west = Math.min(rectangle.west, cartographic.longitude);
  9835. result.south = Math.min(rectangle.south, cartographic.latitude);
  9836. result.east = Math.max(rectangle.east, cartographic.longitude);
  9837. result.north = Math.max(rectangle.north, cartographic.latitude);
  9838. return result;
  9839. };
  9840. /**
  9841. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  9842. *
  9843. * @param {Rectangle} rectangle The rectangle
  9844. * @param {Cartographic} cartographic The cartographic to test.
  9845. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  9846. */
  9847. Rectangle.contains = function(rectangle, cartographic) {
  9848. if (!defined(rectangle)) {
  9849. throw new DeveloperError('rectangle is required');
  9850. }
  9851. if (!defined(cartographic)) {
  9852. throw new DeveloperError('cartographic is required.');
  9853. }
  9854. var longitude = cartographic.longitude;
  9855. var latitude = cartographic.latitude;
  9856. var west = rectangle.west;
  9857. var east = rectangle.east;
  9858. if (east < west) {
  9859. east += CesiumMath.TWO_PI;
  9860. if (longitude < 0.0) {
  9861. longitude += CesiumMath.TWO_PI;
  9862. }
  9863. }
  9864. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  9865. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  9866. latitude >= rectangle.south &&
  9867. latitude <= rectangle.north;
  9868. };
  9869. var subsampleLlaScratch = new Cartographic();
  9870. /**
  9871. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  9872. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  9873. * for rectangles that cover the poles or cross the equator.
  9874. *
  9875. * @param {Rectangle} rectangle The rectangle to subsample.
  9876. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  9877. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  9878. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  9879. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  9880. */
  9881. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  9882. if (!defined(rectangle)) {
  9883. throw new DeveloperError('rectangle is required');
  9884. }
  9885. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  9886. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  9887. if (!defined(result)) {
  9888. result = [];
  9889. }
  9890. var length = 0;
  9891. var north = rectangle.north;
  9892. var south = rectangle.south;
  9893. var east = rectangle.east;
  9894. var west = rectangle.west;
  9895. var lla = subsampleLlaScratch;
  9896. lla.height = surfaceHeight;
  9897. lla.longitude = west;
  9898. lla.latitude = north;
  9899. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9900. length++;
  9901. lla.longitude = east;
  9902. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9903. length++;
  9904. lla.latitude = south;
  9905. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9906. length++;
  9907. lla.longitude = west;
  9908. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9909. length++;
  9910. if (north < 0.0) {
  9911. lla.latitude = north;
  9912. } else if (south > 0.0) {
  9913. lla.latitude = south;
  9914. } else {
  9915. lla.latitude = 0.0;
  9916. }
  9917. for ( var i = 1; i < 8; ++i) {
  9918. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  9919. if (Rectangle.contains(rectangle, lla)) {
  9920. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9921. length++;
  9922. }
  9923. }
  9924. if (lla.latitude === 0.0) {
  9925. lla.longitude = west;
  9926. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9927. length++;
  9928. lla.longitude = east;
  9929. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  9930. length++;
  9931. }
  9932. result.length = length;
  9933. return result;
  9934. };
  9935. /**
  9936. * The largest possible rectangle.
  9937. *
  9938. * @type {Rectangle}
  9939. * @constant
  9940. */
  9941. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  9942. return Rectangle;
  9943. });
  9944. /*global define*/
  9945. define('Core/BoundingSphere',[
  9946. './Cartesian3',
  9947. './Cartographic',
  9948. './defaultValue',
  9949. './defined',
  9950. './DeveloperError',
  9951. './Ellipsoid',
  9952. './GeographicProjection',
  9953. './Intersect',
  9954. './Interval',
  9955. './Matrix3',
  9956. './Matrix4',
  9957. './Rectangle'
  9958. ], function(
  9959. Cartesian3,
  9960. Cartographic,
  9961. defaultValue,
  9962. defined,
  9963. DeveloperError,
  9964. Ellipsoid,
  9965. GeographicProjection,
  9966. Intersect,
  9967. Interval,
  9968. Matrix3,
  9969. Matrix4,
  9970. Rectangle) {
  9971. 'use strict';
  9972. /**
  9973. * A bounding sphere with a center and a radius.
  9974. * @alias BoundingSphere
  9975. * @constructor
  9976. *
  9977. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  9978. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  9979. *
  9980. * @see AxisAlignedBoundingBox
  9981. * @see BoundingRectangle
  9982. * @see Packable
  9983. */
  9984. function BoundingSphere(center, radius) {
  9985. /**
  9986. * The center point of the sphere.
  9987. * @type {Cartesian3}
  9988. * @default {@link Cartesian3.ZERO}
  9989. */
  9990. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  9991. /**
  9992. * The radius of the sphere.
  9993. * @type {Number}
  9994. * @default 0.0
  9995. */
  9996. this.radius = defaultValue(radius, 0.0);
  9997. }
  9998. var fromPointsXMin = new Cartesian3();
  9999. var fromPointsYMin = new Cartesian3();
  10000. var fromPointsZMin = new Cartesian3();
  10001. var fromPointsXMax = new Cartesian3();
  10002. var fromPointsYMax = new Cartesian3();
  10003. var fromPointsZMax = new Cartesian3();
  10004. var fromPointsCurrentPos = new Cartesian3();
  10005. var fromPointsScratch = new Cartesian3();
  10006. var fromPointsRitterCenter = new Cartesian3();
  10007. var fromPointsMinBoxPt = new Cartesian3();
  10008. var fromPointsMaxBoxPt = new Cartesian3();
  10009. var fromPointsNaiveCenterScratch = new Cartesian3();
  10010. /**
  10011. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  10012. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  10013. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  10014. *
  10015. * @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.
  10016. * @param {BoundingSphere} [result] The object onto which to store the result.
  10017. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10018. *
  10019. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10020. */
  10021. BoundingSphere.fromPoints = function(positions, result) {
  10022. if (!defined(result)) {
  10023. result = new BoundingSphere();
  10024. }
  10025. if (!defined(positions) || positions.length === 0) {
  10026. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10027. result.radius = 0.0;
  10028. return result;
  10029. }
  10030. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  10031. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10032. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10033. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10034. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10035. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10036. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10037. var numPositions = positions.length;
  10038. for (var i = 1; i < numPositions; i++) {
  10039. Cartesian3.clone(positions[i], currentPos);
  10040. var x = currentPos.x;
  10041. var y = currentPos.y;
  10042. var z = currentPos.z;
  10043. // Store points containing the the smallest and largest components
  10044. if (x < xMin.x) {
  10045. Cartesian3.clone(currentPos, xMin);
  10046. }
  10047. if (x > xMax.x) {
  10048. Cartesian3.clone(currentPos, xMax);
  10049. }
  10050. if (y < yMin.y) {
  10051. Cartesian3.clone(currentPos, yMin);
  10052. }
  10053. if (y > yMax.y) {
  10054. Cartesian3.clone(currentPos, yMax);
  10055. }
  10056. if (z < zMin.z) {
  10057. Cartesian3.clone(currentPos, zMin);
  10058. }
  10059. if (z > zMax.z) {
  10060. Cartesian3.clone(currentPos, zMax);
  10061. }
  10062. }
  10063. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10064. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10065. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10066. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10067. // Set the diameter endpoints to the largest span.
  10068. var diameter1 = xMin;
  10069. var diameter2 = xMax;
  10070. var maxSpan = xSpan;
  10071. if (ySpan > maxSpan) {
  10072. maxSpan = ySpan;
  10073. diameter1 = yMin;
  10074. diameter2 = yMax;
  10075. }
  10076. if (zSpan > maxSpan) {
  10077. maxSpan = zSpan;
  10078. diameter1 = zMin;
  10079. diameter2 = zMax;
  10080. }
  10081. // Calculate the center of the initial sphere found by Ritter's algorithm
  10082. var ritterCenter = fromPointsRitterCenter;
  10083. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10084. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10085. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10086. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10087. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10088. var ritterRadius = Math.sqrt(radiusSquared);
  10089. // Find the center of the sphere found using the Naive method.
  10090. var minBoxPt = fromPointsMinBoxPt;
  10091. minBoxPt.x = xMin.x;
  10092. minBoxPt.y = yMin.y;
  10093. minBoxPt.z = zMin.z;
  10094. var maxBoxPt = fromPointsMaxBoxPt;
  10095. maxBoxPt.x = xMax.x;
  10096. maxBoxPt.y = yMax.y;
  10097. maxBoxPt.z = zMax.z;
  10098. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10099. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10100. var naiveRadius = 0;
  10101. for (i = 0; i < numPositions; i++) {
  10102. Cartesian3.clone(positions[i], currentPos);
  10103. // Find the furthest point from the naive center to calculate the naive radius.
  10104. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10105. if (r > naiveRadius) {
  10106. naiveRadius = r;
  10107. }
  10108. // Make adjustments to the Ritter Sphere to include all points.
  10109. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10110. if (oldCenterToPointSquared > radiusSquared) {
  10111. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10112. // Calculate new radius to include the point that lies outside
  10113. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10114. radiusSquared = ritterRadius * ritterRadius;
  10115. // Calculate center of new Ritter sphere
  10116. var oldToNew = oldCenterToPoint - ritterRadius;
  10117. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10118. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10119. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10120. }
  10121. }
  10122. if (ritterRadius < naiveRadius) {
  10123. Cartesian3.clone(ritterCenter, result.center);
  10124. result.radius = ritterRadius;
  10125. } else {
  10126. Cartesian3.clone(naiveCenter, result.center);
  10127. result.radius = naiveRadius;
  10128. }
  10129. return result;
  10130. };
  10131. var defaultProjection = new GeographicProjection();
  10132. var fromRectangle2DLowerLeft = new Cartesian3();
  10133. var fromRectangle2DUpperRight = new Cartesian3();
  10134. var fromRectangle2DSouthwest = new Cartographic();
  10135. var fromRectangle2DNortheast = new Cartographic();
  10136. /**
  10137. * Computes a bounding sphere from an rectangle projected in 2D.
  10138. *
  10139. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10140. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10141. * @param {BoundingSphere} [result] The object onto which to store the result.
  10142. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10143. */
  10144. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  10145. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  10146. };
  10147. /**
  10148. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  10149. * object's minimum and maximum heights over the rectangle.
  10150. *
  10151. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10152. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10153. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  10154. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  10155. * @param {BoundingSphere} [result] The object onto which to store the result.
  10156. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10157. */
  10158. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  10159. if (!defined(result)) {
  10160. result = new BoundingSphere();
  10161. }
  10162. if (!defined(rectangle)) {
  10163. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10164. result.radius = 0.0;
  10165. return result;
  10166. }
  10167. projection = defaultValue(projection, defaultProjection);
  10168. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  10169. fromRectangle2DSouthwest.height = minimumHeight;
  10170. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  10171. fromRectangle2DNortheast.height = maximumHeight;
  10172. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  10173. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  10174. var width = upperRight.x - lowerLeft.x;
  10175. var height = upperRight.y - lowerLeft.y;
  10176. var elevation = upperRight.z - lowerLeft.z;
  10177. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  10178. var center = result.center;
  10179. center.x = lowerLeft.x + width * 0.5;
  10180. center.y = lowerLeft.y + height * 0.5;
  10181. center.z = lowerLeft.z + elevation * 0.5;
  10182. return result;
  10183. };
  10184. var fromRectangle3DScratch = [];
  10185. /**
  10186. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  10187. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  10188. *
  10189. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  10190. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  10191. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  10192. * @param {BoundingSphere} [result] The object onto which to store the result.
  10193. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10194. */
  10195. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  10196. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  10197. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  10198. var positions;
  10199. if (defined(rectangle)) {
  10200. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  10201. }
  10202. return BoundingSphere.fromPoints(positions, result);
  10203. };
  10204. /**
  10205. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  10206. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  10207. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10208. * ensure a tight fit.
  10209. *
  10210. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  10211. * is formed from three elements in the array in the order X, Y, Z.
  10212. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  10213. * origin of the coordinate system. This is useful when the positions are to be used for
  10214. * relative-to-center (RTC) rendering.
  10215. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  10216. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  10217. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  10218. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  10219. * the stride is 5, however, two array elements are skipped and the next position begins at array
  10220. * index 5.
  10221. * @param {BoundingSphere} [result] The object onto which to store the result.
  10222. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10223. *
  10224. * @example
  10225. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  10226. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  10227. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  10228. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  10229. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  10230. * 4.0, 5.0, 6.0, 0.1, 0.2,
  10231. * 7.0, 8.0, 9.0, 0.1, 0.2];
  10232. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  10233. *
  10234. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10235. */
  10236. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  10237. if (!defined(result)) {
  10238. result = new BoundingSphere();
  10239. }
  10240. if (!defined(positions) || positions.length === 0) {
  10241. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10242. result.radius = 0.0;
  10243. return result;
  10244. }
  10245. center = defaultValue(center, Cartesian3.ZERO);
  10246. stride = defaultValue(stride, 3);
  10247. if (stride < 3) {
  10248. throw new DeveloperError('stride must be 3 or greater.');
  10249. }
  10250. var currentPos = fromPointsCurrentPos;
  10251. currentPos.x = positions[0] + center.x;
  10252. currentPos.y = positions[1] + center.y;
  10253. currentPos.z = positions[2] + center.z;
  10254. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10255. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10256. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10257. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10258. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10259. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10260. var numElements = positions.length;
  10261. for (var i = 0; i < numElements; i += stride) {
  10262. var x = positions[i] + center.x;
  10263. var y = positions[i + 1] + center.y;
  10264. var z = positions[i + 2] + center.z;
  10265. currentPos.x = x;
  10266. currentPos.y = y;
  10267. currentPos.z = z;
  10268. // Store points containing the the smallest and largest components
  10269. if (x < xMin.x) {
  10270. Cartesian3.clone(currentPos, xMin);
  10271. }
  10272. if (x > xMax.x) {
  10273. Cartesian3.clone(currentPos, xMax);
  10274. }
  10275. if (y < yMin.y) {
  10276. Cartesian3.clone(currentPos, yMin);
  10277. }
  10278. if (y > yMax.y) {
  10279. Cartesian3.clone(currentPos, yMax);
  10280. }
  10281. if (z < zMin.z) {
  10282. Cartesian3.clone(currentPos, zMin);
  10283. }
  10284. if (z > zMax.z) {
  10285. Cartesian3.clone(currentPos, zMax);
  10286. }
  10287. }
  10288. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10289. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10290. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10291. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10292. // Set the diameter endpoints to the largest span.
  10293. var diameter1 = xMin;
  10294. var diameter2 = xMax;
  10295. var maxSpan = xSpan;
  10296. if (ySpan > maxSpan) {
  10297. maxSpan = ySpan;
  10298. diameter1 = yMin;
  10299. diameter2 = yMax;
  10300. }
  10301. if (zSpan > maxSpan) {
  10302. maxSpan = zSpan;
  10303. diameter1 = zMin;
  10304. diameter2 = zMax;
  10305. }
  10306. // Calculate the center of the initial sphere found by Ritter's algorithm
  10307. var ritterCenter = fromPointsRitterCenter;
  10308. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10309. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10310. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10311. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10312. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10313. var ritterRadius = Math.sqrt(radiusSquared);
  10314. // Find the center of the sphere found using the Naive method.
  10315. var minBoxPt = fromPointsMinBoxPt;
  10316. minBoxPt.x = xMin.x;
  10317. minBoxPt.y = yMin.y;
  10318. minBoxPt.z = zMin.z;
  10319. var maxBoxPt = fromPointsMaxBoxPt;
  10320. maxBoxPt.x = xMax.x;
  10321. maxBoxPt.y = yMax.y;
  10322. maxBoxPt.z = zMax.z;
  10323. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10324. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10325. var naiveRadius = 0;
  10326. for (i = 0; i < numElements; i += stride) {
  10327. currentPos.x = positions[i] + center.x;
  10328. currentPos.y = positions[i + 1] + center.y;
  10329. currentPos.z = positions[i + 2] + center.z;
  10330. // Find the furthest point from the naive center to calculate the naive radius.
  10331. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10332. if (r > naiveRadius) {
  10333. naiveRadius = r;
  10334. }
  10335. // Make adjustments to the Ritter Sphere to include all points.
  10336. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10337. if (oldCenterToPointSquared > radiusSquared) {
  10338. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10339. // Calculate new radius to include the point that lies outside
  10340. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10341. radiusSquared = ritterRadius * ritterRadius;
  10342. // Calculate center of new Ritter sphere
  10343. var oldToNew = oldCenterToPoint - ritterRadius;
  10344. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10345. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10346. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10347. }
  10348. }
  10349. if (ritterRadius < naiveRadius) {
  10350. Cartesian3.clone(ritterCenter, result.center);
  10351. result.radius = ritterRadius;
  10352. } else {
  10353. Cartesian3.clone(naiveCenter, result.center);
  10354. result.radius = naiveRadius;
  10355. }
  10356. return result;
  10357. };
  10358. /**
  10359. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  10360. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  10361. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10362. * ensure a tight fit.
  10363. *
  10364. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10365. * is formed from three elements in the array in the order X, Y, Z.
  10366. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10367. * is formed from three elements in the array in the order X, Y, Z.
  10368. * @param {BoundingSphere} [result] The object onto which to store the result.
  10369. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10370. *
  10371. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10372. */
  10373. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  10374. if (!defined(result)) {
  10375. result = new BoundingSphere();
  10376. }
  10377. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  10378. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10379. result.radius = 0.0;
  10380. return result;
  10381. }
  10382. var currentPos = fromPointsCurrentPos;
  10383. currentPos.x = positionsHigh[0] + positionsLow[0];
  10384. currentPos.y = positionsHigh[1] + positionsLow[1];
  10385. currentPos.z = positionsHigh[2] + positionsLow[2];
  10386. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10387. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10388. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10389. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10390. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10391. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10392. var numElements = positionsHigh.length;
  10393. for (var i = 0; i < numElements; i += 3) {
  10394. var x = positionsHigh[i] + positionsLow[i];
  10395. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  10396. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  10397. currentPos.x = x;
  10398. currentPos.y = y;
  10399. currentPos.z = z;
  10400. // Store points containing the the smallest and largest components
  10401. if (x < xMin.x) {
  10402. Cartesian3.clone(currentPos, xMin);
  10403. }
  10404. if (x > xMax.x) {
  10405. Cartesian3.clone(currentPos, xMax);
  10406. }
  10407. if (y < yMin.y) {
  10408. Cartesian3.clone(currentPos, yMin);
  10409. }
  10410. if (y > yMax.y) {
  10411. Cartesian3.clone(currentPos, yMax);
  10412. }
  10413. if (z < zMin.z) {
  10414. Cartesian3.clone(currentPos, zMin);
  10415. }
  10416. if (z > zMax.z) {
  10417. Cartesian3.clone(currentPos, zMax);
  10418. }
  10419. }
  10420. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10421. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10422. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10423. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10424. // Set the diameter endpoints to the largest span.
  10425. var diameter1 = xMin;
  10426. var diameter2 = xMax;
  10427. var maxSpan = xSpan;
  10428. if (ySpan > maxSpan) {
  10429. maxSpan = ySpan;
  10430. diameter1 = yMin;
  10431. diameter2 = yMax;
  10432. }
  10433. if (zSpan > maxSpan) {
  10434. maxSpan = zSpan;
  10435. diameter1 = zMin;
  10436. diameter2 = zMax;
  10437. }
  10438. // Calculate the center of the initial sphere found by Ritter's algorithm
  10439. var ritterCenter = fromPointsRitterCenter;
  10440. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10441. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10442. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10443. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10444. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10445. var ritterRadius = Math.sqrt(radiusSquared);
  10446. // Find the center of the sphere found using the Naive method.
  10447. var minBoxPt = fromPointsMinBoxPt;
  10448. minBoxPt.x = xMin.x;
  10449. minBoxPt.y = yMin.y;
  10450. minBoxPt.z = zMin.z;
  10451. var maxBoxPt = fromPointsMaxBoxPt;
  10452. maxBoxPt.x = xMax.x;
  10453. maxBoxPt.y = yMax.y;
  10454. maxBoxPt.z = zMax.z;
  10455. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10456. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10457. var naiveRadius = 0;
  10458. for (i = 0; i < numElements; i += 3) {
  10459. currentPos.x = positionsHigh[i] + positionsLow[i];
  10460. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  10461. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  10462. // Find the furthest point from the naive center to calculate the naive radius.
  10463. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10464. if (r > naiveRadius) {
  10465. naiveRadius = r;
  10466. }
  10467. // Make adjustments to the Ritter Sphere to include all points.
  10468. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10469. if (oldCenterToPointSquared > radiusSquared) {
  10470. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10471. // Calculate new radius to include the point that lies outside
  10472. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10473. radiusSquared = ritterRadius * ritterRadius;
  10474. // Calculate center of new Ritter sphere
  10475. var oldToNew = oldCenterToPoint - ritterRadius;
  10476. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10477. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10478. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10479. }
  10480. }
  10481. if (ritterRadius < naiveRadius) {
  10482. Cartesian3.clone(ritterCenter, result.center);
  10483. result.radius = ritterRadius;
  10484. } else {
  10485. Cartesian3.clone(naiveCenter, result.center);
  10486. result.radius = naiveRadius;
  10487. }
  10488. return result;
  10489. };
  10490. /**
  10491. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  10492. * tighly and fully encompases the box.
  10493. *
  10494. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  10495. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  10496. * @param {BoundingSphere} [result] The object onto which to store the result.
  10497. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10498. *
  10499. * @example
  10500. * // Create a bounding sphere around the unit cube
  10501. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  10502. */
  10503. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  10504. if (!defined(corner) || !defined(oppositeCorner)) {
  10505. throw new DeveloperError('corner and oppositeCorner are required.');
  10506. }
  10507. if (!defined(result)) {
  10508. result = new BoundingSphere();
  10509. }
  10510. var center = result.center;
  10511. Cartesian3.add(corner, oppositeCorner, center);
  10512. Cartesian3.multiplyByScalar(center, 0.5, center);
  10513. result.radius = Cartesian3.distance(center, oppositeCorner);
  10514. return result;
  10515. };
  10516. /**
  10517. * Creates a bounding sphere encompassing an ellipsoid.
  10518. *
  10519. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  10520. * @param {BoundingSphere} [result] The object onto which to store the result.
  10521. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10522. *
  10523. * @example
  10524. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  10525. */
  10526. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  10527. if (!defined(ellipsoid)) {
  10528. throw new DeveloperError('ellipsoid is required.');
  10529. }
  10530. if (!defined(result)) {
  10531. result = new BoundingSphere();
  10532. }
  10533. Cartesian3.clone(Cartesian3.ZERO, result.center);
  10534. result.radius = ellipsoid.maximumRadius;
  10535. return result;
  10536. };
  10537. var fromBoundingSpheresScratch = new Cartesian3();
  10538. /**
  10539. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  10540. *
  10541. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  10542. * @param {BoundingSphere} [result] The object onto which to store the result.
  10543. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10544. */
  10545. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  10546. if (!defined(result)) {
  10547. result = new BoundingSphere();
  10548. }
  10549. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  10550. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10551. result.radius = 0.0;
  10552. return result;
  10553. }
  10554. var length = boundingSpheres.length;
  10555. if (length === 1) {
  10556. return BoundingSphere.clone(boundingSpheres[0], result);
  10557. }
  10558. if (length === 2) {
  10559. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  10560. }
  10561. var positions = [];
  10562. for (var i = 0; i < length; i++) {
  10563. positions.push(boundingSpheres[i].center);
  10564. }
  10565. result = BoundingSphere.fromPoints(positions, result);
  10566. var center = result.center;
  10567. var radius = result.radius;
  10568. for (i = 0; i < length; i++) {
  10569. var tmp = boundingSpheres[i];
  10570. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  10571. }
  10572. result.radius = radius;
  10573. return result;
  10574. };
  10575. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  10576. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  10577. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  10578. /**
  10579. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  10580. *
  10581. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  10582. * @param {BoundingSphere} [result] The object onto which to store the result.
  10583. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10584. */
  10585. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  10586. if (!defined(result)) {
  10587. result = new BoundingSphere();
  10588. }
  10589. var halfAxes = orientedBoundingBox.halfAxes;
  10590. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  10591. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  10592. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  10593. var uHalf = Cartesian3.magnitude(u);
  10594. var vHalf = Cartesian3.magnitude(v);
  10595. var wHalf = Cartesian3.magnitude(w);
  10596. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  10597. result.radius = Math.max(uHalf, vHalf, wHalf);
  10598. return result;
  10599. };
  10600. /**
  10601. * Duplicates a BoundingSphere instance.
  10602. *
  10603. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  10604. * @param {BoundingSphere} [result] The object onto which to store the result.
  10605. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  10606. */
  10607. BoundingSphere.clone = function(sphere, result) {
  10608. if (!defined(sphere)) {
  10609. return undefined;
  10610. }
  10611. if (!defined(result)) {
  10612. return new BoundingSphere(sphere.center, sphere.radius);
  10613. }
  10614. result.center = Cartesian3.clone(sphere.center, result.center);
  10615. result.radius = sphere.radius;
  10616. return result;
  10617. };
  10618. /**
  10619. * The number of elements used to pack the object into an array.
  10620. * @type {Number}
  10621. */
  10622. BoundingSphere.packedLength = 4;
  10623. /**
  10624. * Stores the provided instance into the provided array.
  10625. *
  10626. * @param {BoundingSphere} value The value to pack.
  10627. * @param {Number[]} array The array to pack into.
  10628. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  10629. *
  10630. * @returns {Number[]} The array that was packed into
  10631. */
  10632. BoundingSphere.pack = function(value, array, startingIndex) {
  10633. if (!defined(value)) {
  10634. throw new DeveloperError('value is required');
  10635. }
  10636. if (!defined(array)) {
  10637. throw new DeveloperError('array is required');
  10638. }
  10639. startingIndex = defaultValue(startingIndex, 0);
  10640. var center = value.center;
  10641. array[startingIndex++] = center.x;
  10642. array[startingIndex++] = center.y;
  10643. array[startingIndex++] = center.z;
  10644. array[startingIndex] = value.radius;
  10645. return array;
  10646. };
  10647. /**
  10648. * Retrieves an instance from a packed array.
  10649. *
  10650. * @param {Number[]} array The packed array.
  10651. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10652. * @param {BoundingSphere} [result] The object into which to store the result.
  10653. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10654. */
  10655. BoundingSphere.unpack = function(array, startingIndex, result) {
  10656. if (!defined(array)) {
  10657. throw new DeveloperError('array is required');
  10658. }
  10659. startingIndex = defaultValue(startingIndex, 0);
  10660. if (!defined(result)) {
  10661. result = new BoundingSphere();
  10662. }
  10663. var center = result.center;
  10664. center.x = array[startingIndex++];
  10665. center.y = array[startingIndex++];
  10666. center.z = array[startingIndex++];
  10667. result.radius = array[startingIndex];
  10668. return result;
  10669. };
  10670. var unionScratch = new Cartesian3();
  10671. var unionScratchCenter = new Cartesian3();
  10672. /**
  10673. * Computes a bounding sphere that contains both the left and right bounding spheres.
  10674. *
  10675. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  10676. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  10677. * @param {BoundingSphere} [result] The object onto which to store the result.
  10678. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10679. */
  10680. BoundingSphere.union = function(left, right, result) {
  10681. if (!defined(left)) {
  10682. throw new DeveloperError('left is required.');
  10683. }
  10684. if (!defined(right)) {
  10685. throw new DeveloperError('right is required.');
  10686. }
  10687. if (!defined(result)) {
  10688. result = new BoundingSphere();
  10689. }
  10690. var leftCenter = left.center;
  10691. var leftRadius = left.radius;
  10692. var rightCenter = right.center;
  10693. var rightRadius = right.radius;
  10694. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  10695. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  10696. if (leftRadius >= (centerSeparation + rightRadius)) {
  10697. // Left sphere wins.
  10698. left.clone(result);
  10699. return result;
  10700. }
  10701. if (rightRadius >= (centerSeparation + leftRadius)) {
  10702. // Right sphere wins.
  10703. right.clone(result);
  10704. return result;
  10705. }
  10706. // There are two tangent points, one on far side of each sphere.
  10707. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  10708. // Compute the center point halfway between the two tangent points.
  10709. var center = Cartesian3.multiplyByScalar(toRightCenter,
  10710. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  10711. Cartesian3.add(center, leftCenter, center);
  10712. Cartesian3.clone(center, result.center);
  10713. result.radius = halfDistanceBetweenTangentPoints;
  10714. return result;
  10715. };
  10716. var expandScratch = new Cartesian3();
  10717. /**
  10718. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  10719. *
  10720. * @param {BoundingSphere} sphere A sphere to expand.
  10721. * @param {Cartesian3} point A point to enclose in a 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.expand = function(sphere, point, result) {
  10726. if (!defined(sphere)) {
  10727. throw new DeveloperError('sphere is required.');
  10728. }
  10729. if (!defined(point)) {
  10730. throw new DeveloperError('point is required.');
  10731. }
  10732. result = BoundingSphere.clone(sphere, result);
  10733. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  10734. if (radius > result.radius) {
  10735. result.radius = radius;
  10736. }
  10737. return result;
  10738. };
  10739. /**
  10740. * Determines which side of a plane a sphere is located.
  10741. *
  10742. * @param {BoundingSphere} sphere The bounding sphere to test.
  10743. * @param {Plane} plane The plane to test against.
  10744. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10745. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10746. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10747. * intersects the plane.
  10748. */
  10749. BoundingSphere.intersectPlane = function(sphere, plane) {
  10750. if (!defined(sphere)) {
  10751. throw new DeveloperError('sphere is required.');
  10752. }
  10753. if (!defined(plane)) {
  10754. throw new DeveloperError('plane is required.');
  10755. }
  10756. var center = sphere.center;
  10757. var radius = sphere.radius;
  10758. var normal = plane.normal;
  10759. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  10760. if (distanceToPlane < -radius) {
  10761. // The center point is negative side of the plane normal
  10762. return Intersect.OUTSIDE;
  10763. } else if (distanceToPlane < radius) {
  10764. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  10765. return Intersect.INTERSECTING;
  10766. }
  10767. return Intersect.INSIDE;
  10768. };
  10769. /**
  10770. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  10771. *
  10772. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10773. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10774. * @param {BoundingSphere} [result] The object onto which to store the result.
  10775. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10776. */
  10777. BoundingSphere.transform = function(sphere, transform, result) {
  10778. if (!defined(sphere)) {
  10779. throw new DeveloperError('sphere is required.');
  10780. }
  10781. if (!defined(transform)) {
  10782. throw new DeveloperError('transform is required.');
  10783. }
  10784. if (!defined(result)) {
  10785. result = new BoundingSphere();
  10786. }
  10787. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10788. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  10789. return result;
  10790. };
  10791. var distanceSquaredToScratch = new Cartesian3();
  10792. /**
  10793. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10794. *
  10795. * @param {BoundingSphere} sphere The sphere.
  10796. * @param {Cartesian3} cartesian The point
  10797. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10798. *
  10799. * @example
  10800. * // Sort bounding spheres from back to front
  10801. * spheres.sort(function(a, b) {
  10802. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  10803. * });
  10804. */
  10805. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  10806. if (!defined(sphere)) {
  10807. throw new DeveloperError('sphere is required.');
  10808. }
  10809. if (!defined(cartesian)) {
  10810. throw new DeveloperError('cartesian is required.');
  10811. }
  10812. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  10813. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  10814. };
  10815. /**
  10816. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  10817. * The transformation matrix is not verified to have a uniform scale of 1.
  10818. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  10819. *
  10820. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10821. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10822. * @param {BoundingSphere} [result] The object onto which to store the result.
  10823. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10824. *
  10825. * @example
  10826. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  10827. * var boundingSphere = new Cesium.BoundingSphere();
  10828. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  10829. */
  10830. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  10831. if (!defined(sphere)) {
  10832. throw new DeveloperError('sphere is required.');
  10833. }
  10834. if (!defined(transform)) {
  10835. throw new DeveloperError('transform is required.');
  10836. }
  10837. if (!defined(result)) {
  10838. result = new BoundingSphere();
  10839. }
  10840. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10841. result.radius = sphere.radius;
  10842. return result;
  10843. };
  10844. var scratchCartesian3 = new Cartesian3();
  10845. /**
  10846. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10847. * plus/minus the radius of the bounding sphere.
  10848. * <br>
  10849. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10850. * closest and farthest planes from position that intersect the bounding sphere.
  10851. *
  10852. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  10853. * @param {Cartesian3} position The position to calculate the distance from.
  10854. * @param {Cartesian3} direction The direction from position.
  10855. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10856. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10857. */
  10858. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  10859. if (!defined(sphere)) {
  10860. throw new DeveloperError('sphere is required.');
  10861. }
  10862. if (!defined(position)) {
  10863. throw new DeveloperError('position is required.');
  10864. }
  10865. if (!defined(direction)) {
  10866. throw new DeveloperError('direction is required.');
  10867. }
  10868. if (!defined(result)) {
  10869. result = new Interval();
  10870. }
  10871. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  10872. var mag = Cartesian3.dot(direction, toCenter);
  10873. result.start = mag - sphere.radius;
  10874. result.stop = mag + sphere.radius;
  10875. return result;
  10876. };
  10877. var projectTo2DNormalScratch = new Cartesian3();
  10878. var projectTo2DEastScratch = new Cartesian3();
  10879. var projectTo2DNorthScratch = new Cartesian3();
  10880. var projectTo2DWestScratch = new Cartesian3();
  10881. var projectTo2DSouthScratch = new Cartesian3();
  10882. var projectTo2DCartographicScratch = new Cartographic();
  10883. var projectTo2DPositionsScratch = new Array(8);
  10884. for (var n = 0; n < 8; ++n) {
  10885. projectTo2DPositionsScratch[n] = new Cartesian3();
  10886. }
  10887. var projectTo2DProjection = new GeographicProjection();
  10888. /**
  10889. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  10890. *
  10891. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  10892. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  10893. * @param {BoundingSphere} [result] The object onto which to store the result.
  10894. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10895. */
  10896. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  10897. if (!defined(sphere)) {
  10898. throw new DeveloperError('sphere is required.');
  10899. }
  10900. projection = defaultValue(projection, projectTo2DProjection);
  10901. var ellipsoid = projection.ellipsoid;
  10902. var center = sphere.center;
  10903. var radius = sphere.radius;
  10904. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  10905. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  10906. Cartesian3.normalize(east, east);
  10907. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  10908. Cartesian3.normalize(north, north);
  10909. Cartesian3.multiplyByScalar(normal, radius, normal);
  10910. Cartesian3.multiplyByScalar(north, radius, north);
  10911. Cartesian3.multiplyByScalar(east, radius, east);
  10912. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  10913. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  10914. var positions = projectTo2DPositionsScratch;
  10915. // top NE corner
  10916. var corner = positions[0];
  10917. Cartesian3.add(normal, north, corner);
  10918. Cartesian3.add(corner, east, corner);
  10919. // top NW corner
  10920. corner = positions[1];
  10921. Cartesian3.add(normal, north, corner);
  10922. Cartesian3.add(corner, west, corner);
  10923. // top SW corner
  10924. corner = positions[2];
  10925. Cartesian3.add(normal, south, corner);
  10926. Cartesian3.add(corner, west, corner);
  10927. // top SE corner
  10928. corner = positions[3];
  10929. Cartesian3.add(normal, south, corner);
  10930. Cartesian3.add(corner, east, corner);
  10931. Cartesian3.negate(normal, normal);
  10932. // bottom NE corner
  10933. corner = positions[4];
  10934. Cartesian3.add(normal, north, corner);
  10935. Cartesian3.add(corner, east, corner);
  10936. // bottom NW corner
  10937. corner = positions[5];
  10938. Cartesian3.add(normal, north, corner);
  10939. Cartesian3.add(corner, west, corner);
  10940. // bottom SW corner
  10941. corner = positions[6];
  10942. Cartesian3.add(normal, south, corner);
  10943. Cartesian3.add(corner, west, corner);
  10944. // bottom SE corner
  10945. corner = positions[7];
  10946. Cartesian3.add(normal, south, corner);
  10947. Cartesian3.add(corner, east, corner);
  10948. var length = positions.length;
  10949. for (var i = 0; i < length; ++i) {
  10950. var position = positions[i];
  10951. Cartesian3.add(center, position, position);
  10952. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  10953. projection.project(cartographic, position);
  10954. }
  10955. result = BoundingSphere.fromPoints(positions, result);
  10956. // swizzle center components
  10957. center = result.center;
  10958. var x = center.x;
  10959. var y = center.y;
  10960. var z = center.z;
  10961. center.x = z;
  10962. center.y = x;
  10963. center.z = y;
  10964. return result;
  10965. };
  10966. /**
  10967. * Determines whether or not a sphere is hidden from view by the occluder.
  10968. *
  10969. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  10970. * @param {Occluder} occluder The occluder.
  10971. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10972. */
  10973. BoundingSphere.isOccluded = function(sphere, occluder) {
  10974. if (!defined(sphere)) {
  10975. throw new DeveloperError('sphere is required.');
  10976. }
  10977. if (!defined(occluder)) {
  10978. throw new DeveloperError('occluder is required.');
  10979. }
  10980. return !occluder.isBoundingSphereVisible(sphere);
  10981. };
  10982. /**
  10983. * Compares the provided BoundingSphere componentwise and returns
  10984. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10985. *
  10986. * @param {BoundingSphere} [left] The first BoundingSphere.
  10987. * @param {BoundingSphere} [right] The second BoundingSphere.
  10988. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10989. */
  10990. BoundingSphere.equals = function(left, right) {
  10991. return (left === right) ||
  10992. ((defined(left)) &&
  10993. (defined(right)) &&
  10994. Cartesian3.equals(left.center, right.center) &&
  10995. left.radius === right.radius);
  10996. };
  10997. /**
  10998. * Determines which side of a plane the sphere is located.
  10999. *
  11000. * @param {Plane} plane The plane to test against.
  11001. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  11002. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  11003. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  11004. * intersects the plane.
  11005. */
  11006. BoundingSphere.prototype.intersectPlane = function(plane) {
  11007. return BoundingSphere.intersectPlane(this, plane);
  11008. };
  11009. /**
  11010. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  11011. *
  11012. * @param {Cartesian3} cartesian The point
  11013. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  11014. *
  11015. * @example
  11016. * // Sort bounding spheres from back to front
  11017. * spheres.sort(function(a, b) {
  11018. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  11019. * });
  11020. */
  11021. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  11022. return BoundingSphere.distanceSquaredTo(this, cartesian);
  11023. };
  11024. /**
  11025. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  11026. * plus/minus the radius of the bounding sphere.
  11027. * <br>
  11028. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  11029. * closest and farthest planes from position that intersect the bounding sphere.
  11030. *
  11031. * @param {Cartesian3} position The position to calculate the distance from.
  11032. * @param {Cartesian3} direction The direction from position.
  11033. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  11034. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  11035. */
  11036. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  11037. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  11038. };
  11039. /**
  11040. * Determines whether or not a sphere is hidden from view by the occluder.
  11041. *
  11042. * @param {Occluder} occluder The occluder.
  11043. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  11044. */
  11045. BoundingSphere.prototype.isOccluded = function(occluder) {
  11046. return BoundingSphere.isOccluded(this, occluder);
  11047. };
  11048. /**
  11049. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  11050. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11051. *
  11052. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  11053. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11054. */
  11055. BoundingSphere.prototype.equals = function(right) {
  11056. return BoundingSphere.equals(this, right);
  11057. };
  11058. /**
  11059. * Duplicates this BoundingSphere instance.
  11060. *
  11061. * @param {BoundingSphere} [result] The object onto which to store the result.
  11062. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  11063. */
  11064. BoundingSphere.prototype.clone = function(result) {
  11065. return BoundingSphere.clone(this, result);
  11066. };
  11067. return BoundingSphere;
  11068. });
  11069. /*global define*/
  11070. define('Core/WebGLConstants',[
  11071. './freezeObject'
  11072. ], function(
  11073. freezeObject) {
  11074. 'use strict';
  11075. /**
  11076. * Enum containing WebGL Constant values by name.
  11077. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  11078. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  11079. *
  11080. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  11081. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  11082. * specifications.
  11083. *
  11084. * @exports WebGLConstants
  11085. */
  11086. var WebGLConstants = {
  11087. DEPTH_BUFFER_BIT : 0x00000100,
  11088. STENCIL_BUFFER_BIT : 0x00000400,
  11089. COLOR_BUFFER_BIT : 0x00004000,
  11090. POINTS : 0x0000,
  11091. LINES : 0x0001,
  11092. LINE_LOOP : 0x0002,
  11093. LINE_STRIP : 0x0003,
  11094. TRIANGLES : 0x0004,
  11095. TRIANGLE_STRIP : 0x0005,
  11096. TRIANGLE_FAN : 0x0006,
  11097. ZERO : 0,
  11098. ONE : 1,
  11099. SRC_COLOR : 0x0300,
  11100. ONE_MINUS_SRC_COLOR : 0x0301,
  11101. SRC_ALPHA : 0x0302,
  11102. ONE_MINUS_SRC_ALPHA : 0x0303,
  11103. DST_ALPHA : 0x0304,
  11104. ONE_MINUS_DST_ALPHA : 0x0305,
  11105. DST_COLOR : 0x0306,
  11106. ONE_MINUS_DST_COLOR : 0x0307,
  11107. SRC_ALPHA_SATURATE : 0x0308,
  11108. FUNC_ADD : 0x8006,
  11109. BLEND_EQUATION : 0x8009,
  11110. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  11111. BLEND_EQUATION_ALPHA : 0x883D,
  11112. FUNC_SUBTRACT : 0x800A,
  11113. FUNC_REVERSE_SUBTRACT : 0x800B,
  11114. BLEND_DST_RGB : 0x80C8,
  11115. BLEND_SRC_RGB : 0x80C9,
  11116. BLEND_DST_ALPHA : 0x80CA,
  11117. BLEND_SRC_ALPHA : 0x80CB,
  11118. CONSTANT_COLOR : 0x8001,
  11119. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  11120. CONSTANT_ALPHA : 0x8003,
  11121. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  11122. BLEND_COLOR : 0x8005,
  11123. ARRAY_BUFFER : 0x8892,
  11124. ELEMENT_ARRAY_BUFFER : 0x8893,
  11125. ARRAY_BUFFER_BINDING : 0x8894,
  11126. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  11127. STREAM_DRAW : 0x88E0,
  11128. STATIC_DRAW : 0x88E4,
  11129. DYNAMIC_DRAW : 0x88E8,
  11130. BUFFER_SIZE : 0x8764,
  11131. BUFFER_USAGE : 0x8765,
  11132. CURRENT_VERTEX_ATTRIB : 0x8626,
  11133. FRONT : 0x0404,
  11134. BACK : 0x0405,
  11135. FRONT_AND_BACK : 0x0408,
  11136. CULL_FACE : 0x0B44,
  11137. BLEND : 0x0BE2,
  11138. DITHER : 0x0BD0,
  11139. STENCIL_TEST : 0x0B90,
  11140. DEPTH_TEST : 0x0B71,
  11141. SCISSOR_TEST : 0x0C11,
  11142. POLYGON_OFFSET_FILL : 0x8037,
  11143. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  11144. SAMPLE_COVERAGE : 0x80A0,
  11145. NO_ERROR : 0,
  11146. INVALID_ENUM : 0x0500,
  11147. INVALID_VALUE : 0x0501,
  11148. INVALID_OPERATION : 0x0502,
  11149. OUT_OF_MEMORY : 0x0505,
  11150. CW : 0x0900,
  11151. CCW : 0x0901,
  11152. LINE_WIDTH : 0x0B21,
  11153. ALIASED_POINT_SIZE_RANGE : 0x846D,
  11154. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  11155. CULL_FACE_MODE : 0x0B45,
  11156. FRONT_FACE : 0x0B46,
  11157. DEPTH_RANGE : 0x0B70,
  11158. DEPTH_WRITEMASK : 0x0B72,
  11159. DEPTH_CLEAR_VALUE : 0x0B73,
  11160. DEPTH_FUNC : 0x0B74,
  11161. STENCIL_CLEAR_VALUE : 0x0B91,
  11162. STENCIL_FUNC : 0x0B92,
  11163. STENCIL_FAIL : 0x0B94,
  11164. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  11165. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  11166. STENCIL_REF : 0x0B97,
  11167. STENCIL_VALUE_MASK : 0x0B93,
  11168. STENCIL_WRITEMASK : 0x0B98,
  11169. STENCIL_BACK_FUNC : 0x8800,
  11170. STENCIL_BACK_FAIL : 0x8801,
  11171. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  11172. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  11173. STENCIL_BACK_REF : 0x8CA3,
  11174. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  11175. STENCIL_BACK_WRITEMASK : 0x8CA5,
  11176. VIEWPORT : 0x0BA2,
  11177. SCISSOR_BOX : 0x0C10,
  11178. COLOR_CLEAR_VALUE : 0x0C22,
  11179. COLOR_WRITEMASK : 0x0C23,
  11180. UNPACK_ALIGNMENT : 0x0CF5,
  11181. PACK_ALIGNMENT : 0x0D05,
  11182. MAX_TEXTURE_SIZE : 0x0D33,
  11183. MAX_VIEWPORT_DIMS : 0x0D3A,
  11184. SUBPIXEL_BITS : 0x0D50,
  11185. RED_BITS : 0x0D52,
  11186. GREEN_BITS : 0x0D53,
  11187. BLUE_BITS : 0x0D54,
  11188. ALPHA_BITS : 0x0D55,
  11189. DEPTH_BITS : 0x0D56,
  11190. STENCIL_BITS : 0x0D57,
  11191. POLYGON_OFFSET_UNITS : 0x2A00,
  11192. POLYGON_OFFSET_FACTOR : 0x8038,
  11193. TEXTURE_BINDING_2D : 0x8069,
  11194. SAMPLE_BUFFERS : 0x80A8,
  11195. SAMPLES : 0x80A9,
  11196. SAMPLE_COVERAGE_VALUE : 0x80AA,
  11197. SAMPLE_COVERAGE_INVERT : 0x80AB,
  11198. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  11199. DONT_CARE : 0x1100,
  11200. FASTEST : 0x1101,
  11201. NICEST : 0x1102,
  11202. GENERATE_MIPMAP_HINT : 0x8192,
  11203. BYTE : 0x1400,
  11204. UNSIGNED_BYTE : 0x1401,
  11205. SHORT : 0x1402,
  11206. UNSIGNED_SHORT : 0x1403,
  11207. INT : 0x1404,
  11208. UNSIGNED_INT : 0x1405,
  11209. FLOAT : 0x1406,
  11210. DEPTH_COMPONENT : 0x1902,
  11211. ALPHA : 0x1906,
  11212. RGB : 0x1907,
  11213. RGBA : 0x1908,
  11214. LUMINANCE : 0x1909,
  11215. LUMINANCE_ALPHA : 0x190A,
  11216. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  11217. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  11218. UNSIGNED_SHORT_5_6_5 : 0x8363,
  11219. FRAGMENT_SHADER : 0x8B30,
  11220. VERTEX_SHADER : 0x8B31,
  11221. MAX_VERTEX_ATTRIBS : 0x8869,
  11222. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  11223. MAX_VARYING_VECTORS : 0x8DFC,
  11224. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  11225. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  11226. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  11227. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  11228. SHADER_TYPE : 0x8B4F,
  11229. DELETE_STATUS : 0x8B80,
  11230. LINK_STATUS : 0x8B82,
  11231. VALIDATE_STATUS : 0x8B83,
  11232. ATTACHED_SHADERS : 0x8B85,
  11233. ACTIVE_UNIFORMS : 0x8B86,
  11234. ACTIVE_ATTRIBUTES : 0x8B89,
  11235. SHADING_LANGUAGE_VERSION : 0x8B8C,
  11236. CURRENT_PROGRAM : 0x8B8D,
  11237. NEVER : 0x0200,
  11238. LESS : 0x0201,
  11239. EQUAL : 0x0202,
  11240. LEQUAL : 0x0203,
  11241. GREATER : 0x0204,
  11242. NOTEQUAL : 0x0205,
  11243. GEQUAL : 0x0206,
  11244. ALWAYS : 0x0207,
  11245. KEEP : 0x1E00,
  11246. REPLACE : 0x1E01,
  11247. INCR : 0x1E02,
  11248. DECR : 0x1E03,
  11249. INVERT : 0x150A,
  11250. INCR_WRAP : 0x8507,
  11251. DECR_WRAP : 0x8508,
  11252. VENDOR : 0x1F00,
  11253. RENDERER : 0x1F01,
  11254. VERSION : 0x1F02,
  11255. NEAREST : 0x2600,
  11256. LINEAR : 0x2601,
  11257. NEAREST_MIPMAP_NEAREST : 0x2700,
  11258. LINEAR_MIPMAP_NEAREST : 0x2701,
  11259. NEAREST_MIPMAP_LINEAR : 0x2702,
  11260. LINEAR_MIPMAP_LINEAR : 0x2703,
  11261. TEXTURE_MAG_FILTER : 0x2800,
  11262. TEXTURE_MIN_FILTER : 0x2801,
  11263. TEXTURE_WRAP_S : 0x2802,
  11264. TEXTURE_WRAP_T : 0x2803,
  11265. TEXTURE_2D : 0x0DE1,
  11266. TEXTURE : 0x1702,
  11267. TEXTURE_CUBE_MAP : 0x8513,
  11268. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  11269. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  11270. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  11271. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  11272. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  11273. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  11274. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  11275. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  11276. TEXTURE0 : 0x84C0,
  11277. TEXTURE1 : 0x84C1,
  11278. TEXTURE2 : 0x84C2,
  11279. TEXTURE3 : 0x84C3,
  11280. TEXTURE4 : 0x84C4,
  11281. TEXTURE5 : 0x84C5,
  11282. TEXTURE6 : 0x84C6,
  11283. TEXTURE7 : 0x84C7,
  11284. TEXTURE8 : 0x84C8,
  11285. TEXTURE9 : 0x84C9,
  11286. TEXTURE10 : 0x84CA,
  11287. TEXTURE11 : 0x84CB,
  11288. TEXTURE12 : 0x84CC,
  11289. TEXTURE13 : 0x84CD,
  11290. TEXTURE14 : 0x84CE,
  11291. TEXTURE15 : 0x84CF,
  11292. TEXTURE16 : 0x84D0,
  11293. TEXTURE17 : 0x84D1,
  11294. TEXTURE18 : 0x84D2,
  11295. TEXTURE19 : 0x84D3,
  11296. TEXTURE20 : 0x84D4,
  11297. TEXTURE21 : 0x84D5,
  11298. TEXTURE22 : 0x84D6,
  11299. TEXTURE23 : 0x84D7,
  11300. TEXTURE24 : 0x84D8,
  11301. TEXTURE25 : 0x84D9,
  11302. TEXTURE26 : 0x84DA,
  11303. TEXTURE27 : 0x84DB,
  11304. TEXTURE28 : 0x84DC,
  11305. TEXTURE29 : 0x84DD,
  11306. TEXTURE30 : 0x84DE,
  11307. TEXTURE31 : 0x84DF,
  11308. ACTIVE_TEXTURE : 0x84E0,
  11309. REPEAT : 0x2901,
  11310. CLAMP_TO_EDGE : 0x812F,
  11311. MIRRORED_REPEAT : 0x8370,
  11312. FLOAT_VEC2 : 0x8B50,
  11313. FLOAT_VEC3 : 0x8B51,
  11314. FLOAT_VEC4 : 0x8B52,
  11315. INT_VEC2 : 0x8B53,
  11316. INT_VEC3 : 0x8B54,
  11317. INT_VEC4 : 0x8B55,
  11318. BOOL : 0x8B56,
  11319. BOOL_VEC2 : 0x8B57,
  11320. BOOL_VEC3 : 0x8B58,
  11321. BOOL_VEC4 : 0x8B59,
  11322. FLOAT_MAT2 : 0x8B5A,
  11323. FLOAT_MAT3 : 0x8B5B,
  11324. FLOAT_MAT4 : 0x8B5C,
  11325. SAMPLER_2D : 0x8B5E,
  11326. SAMPLER_CUBE : 0x8B60,
  11327. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  11328. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  11329. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  11330. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  11331. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  11332. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  11333. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  11334. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  11335. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  11336. COMPILE_STATUS : 0x8B81,
  11337. LOW_FLOAT : 0x8DF0,
  11338. MEDIUM_FLOAT : 0x8DF1,
  11339. HIGH_FLOAT : 0x8DF2,
  11340. LOW_INT : 0x8DF3,
  11341. MEDIUM_INT : 0x8DF4,
  11342. HIGH_INT : 0x8DF5,
  11343. FRAMEBUFFER : 0x8D40,
  11344. RENDERBUFFER : 0x8D41,
  11345. RGBA4 : 0x8056,
  11346. RGB5_A1 : 0x8057,
  11347. RGB565 : 0x8D62,
  11348. DEPTH_COMPONENT16 : 0x81A5,
  11349. STENCIL_INDEX : 0x1901,
  11350. STENCIL_INDEX8 : 0x8D48,
  11351. DEPTH_STENCIL : 0x84F9,
  11352. RENDERBUFFER_WIDTH : 0x8D42,
  11353. RENDERBUFFER_HEIGHT : 0x8D43,
  11354. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  11355. RENDERBUFFER_RED_SIZE : 0x8D50,
  11356. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  11357. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  11358. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  11359. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  11360. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  11361. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  11362. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  11363. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  11364. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  11365. COLOR_ATTACHMENT0 : 0x8CE0,
  11366. DEPTH_ATTACHMENT : 0x8D00,
  11367. STENCIL_ATTACHMENT : 0x8D20,
  11368. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  11369. NONE : 0,
  11370. FRAMEBUFFER_COMPLETE : 0x8CD5,
  11371. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  11372. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  11373. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  11374. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  11375. FRAMEBUFFER_BINDING : 0x8CA6,
  11376. RENDERBUFFER_BINDING : 0x8CA7,
  11377. MAX_RENDERBUFFER_SIZE : 0x84E8,
  11378. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  11379. UNPACK_FLIP_Y_WEBGL : 0x9240,
  11380. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  11381. CONTEXT_LOST_WEBGL : 0x9242,
  11382. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  11383. BROWSER_DEFAULT_WEBGL : 0x9244,
  11384. // Desktop OpenGL
  11385. DOUBLE : 0x140A,
  11386. // WebGL 2
  11387. READ_BUFFER : 0x0C02,
  11388. UNPACK_ROW_LENGTH : 0x0CF2,
  11389. UNPACK_SKIP_ROWS : 0x0CF3,
  11390. UNPACK_SKIP_PIXELS : 0x0CF4,
  11391. PACK_ROW_LENGTH : 0x0D02,
  11392. PACK_SKIP_ROWS : 0x0D03,
  11393. PACK_SKIP_PIXELS : 0x0D04,
  11394. COLOR : 0x1800,
  11395. DEPTH : 0x1801,
  11396. STENCIL : 0x1802,
  11397. RED : 0x1903,
  11398. RGB8 : 0x8051,
  11399. RGBA8 : 0x8058,
  11400. RGB10_A2 : 0x8059,
  11401. TEXTURE_BINDING_3D : 0x806A,
  11402. UNPACK_SKIP_IMAGES : 0x806D,
  11403. UNPACK_IMAGE_HEIGHT : 0x806E,
  11404. TEXTURE_3D : 0x806F,
  11405. TEXTURE_WRAP_R : 0x8072,
  11406. MAX_3D_TEXTURE_SIZE : 0x8073,
  11407. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  11408. MAX_ELEMENTS_VERTICES : 0x80E8,
  11409. MAX_ELEMENTS_INDICES : 0x80E9,
  11410. TEXTURE_MIN_LOD : 0x813A,
  11411. TEXTURE_MAX_LOD : 0x813B,
  11412. TEXTURE_BASE_LEVEL : 0x813C,
  11413. TEXTURE_MAX_LEVEL : 0x813D,
  11414. MIN : 0x8007,
  11415. MAX : 0x8008,
  11416. DEPTH_COMPONENT24 : 0x81A6,
  11417. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  11418. TEXTURE_COMPARE_MODE : 0x884C,
  11419. TEXTURE_COMPARE_FUNC : 0x884D,
  11420. CURRENT_QUERY : 0x8865,
  11421. QUERY_RESULT : 0x8866,
  11422. QUERY_RESULT_AVAILABLE : 0x8867,
  11423. STREAM_READ : 0x88E1,
  11424. STREAM_COPY : 0x88E2,
  11425. STATIC_READ : 0x88E5,
  11426. STATIC_COPY : 0x88E6,
  11427. DYNAMIC_READ : 0x88E9,
  11428. DYNAMIC_COPY : 0x88EA,
  11429. MAX_DRAW_BUFFERS : 0x8824,
  11430. DRAW_BUFFER0 : 0x8825,
  11431. DRAW_BUFFER1 : 0x8826,
  11432. DRAW_BUFFER2 : 0x8827,
  11433. DRAW_BUFFER3 : 0x8828,
  11434. DRAW_BUFFER4 : 0x8829,
  11435. DRAW_BUFFER5 : 0x882A,
  11436. DRAW_BUFFER6 : 0x882B,
  11437. DRAW_BUFFER7 : 0x882C,
  11438. DRAW_BUFFER8 : 0x882D,
  11439. DRAW_BUFFER9 : 0x882E,
  11440. DRAW_BUFFER10 : 0x882F,
  11441. DRAW_BUFFER11 : 0x8830,
  11442. DRAW_BUFFER12 : 0x8831,
  11443. DRAW_BUFFER13 : 0x8832,
  11444. DRAW_BUFFER14 : 0x8833,
  11445. DRAW_BUFFER15 : 0x8834,
  11446. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  11447. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  11448. SAMPLER_3D : 0x8B5F,
  11449. SAMPLER_2D_SHADOW : 0x8B62,
  11450. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  11451. PIXEL_PACK_BUFFER : 0x88EB,
  11452. PIXEL_UNPACK_BUFFER : 0x88EC,
  11453. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  11454. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  11455. FLOAT_MAT2x3 : 0x8B65,
  11456. FLOAT_MAT2x4 : 0x8B66,
  11457. FLOAT_MAT3x2 : 0x8B67,
  11458. FLOAT_MAT3x4 : 0x8B68,
  11459. FLOAT_MAT4x2 : 0x8B69,
  11460. FLOAT_MAT4x3 : 0x8B6A,
  11461. SRGB : 0x8C40,
  11462. SRGB8 : 0x8C41,
  11463. SRGB8_ALPHA8 : 0x8C43,
  11464. COMPARE_REF_TO_TEXTURE : 0x884E,
  11465. RGBA32F : 0x8814,
  11466. RGB32F : 0x8815,
  11467. RGBA16F : 0x881A,
  11468. RGB16F : 0x881B,
  11469. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  11470. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  11471. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  11472. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  11473. MAX_VARYING_COMPONENTS : 0x8B4B,
  11474. TEXTURE_2D_ARRAY : 0x8C1A,
  11475. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  11476. R11F_G11F_B10F : 0x8C3A,
  11477. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  11478. RGB9_E5 : 0x8C3D,
  11479. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  11480. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  11481. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  11482. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  11483. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  11484. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  11485. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  11486. RASTERIZER_DISCARD : 0x8C89,
  11487. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  11488. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  11489. INTERLEAVED_ATTRIBS : 0x8C8C,
  11490. SEPARATE_ATTRIBS : 0x8C8D,
  11491. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  11492. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  11493. RGBA32UI : 0x8D70,
  11494. RGB32UI : 0x8D71,
  11495. RGBA16UI : 0x8D76,
  11496. RGB16UI : 0x8D77,
  11497. RGBA8UI : 0x8D7C,
  11498. RGB8UI : 0x8D7D,
  11499. RGBA32I : 0x8D82,
  11500. RGB32I : 0x8D83,
  11501. RGBA16I : 0x8D88,
  11502. RGB16I : 0x8D89,
  11503. RGBA8I : 0x8D8E,
  11504. RGB8I : 0x8D8F,
  11505. RED_INTEGER : 0x8D94,
  11506. RGB_INTEGER : 0x8D98,
  11507. RGBA_INTEGER : 0x8D99,
  11508. SAMPLER_2D_ARRAY : 0x8DC1,
  11509. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  11510. SAMPLER_CUBE_SHADOW : 0x8DC5,
  11511. UNSIGNED_INT_VEC2 : 0x8DC6,
  11512. UNSIGNED_INT_VEC3 : 0x8DC7,
  11513. UNSIGNED_INT_VEC4 : 0x8DC8,
  11514. INT_SAMPLER_2D : 0x8DCA,
  11515. INT_SAMPLER_3D : 0x8DCB,
  11516. INT_SAMPLER_CUBE : 0x8DCC,
  11517. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  11518. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  11519. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  11520. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  11521. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  11522. DEPTH_COMPONENT32F : 0x8CAC,
  11523. DEPTH32F_STENCIL8 : 0x8CAD,
  11524. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  11525. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  11526. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  11527. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  11528. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  11529. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  11530. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  11531. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  11532. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  11533. FRAMEBUFFER_DEFAULT : 0x8218,
  11534. UNSIGNED_INT_24_8 : 0x84FA,
  11535. DEPTH24_STENCIL8 : 0x88F0,
  11536. UNSIGNED_NORMALIZED : 0x8C17,
  11537. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  11538. READ_FRAMEBUFFER : 0x8CA8,
  11539. DRAW_FRAMEBUFFER : 0x8CA9,
  11540. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  11541. RENDERBUFFER_SAMPLES : 0x8CAB,
  11542. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  11543. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  11544. COLOR_ATTACHMENT1 : 0x8CE1,
  11545. COLOR_ATTACHMENT2 : 0x8CE2,
  11546. COLOR_ATTACHMENT3 : 0x8CE3,
  11547. COLOR_ATTACHMENT4 : 0x8CE4,
  11548. COLOR_ATTACHMENT5 : 0x8CE5,
  11549. COLOR_ATTACHMENT6 : 0x8CE6,
  11550. COLOR_ATTACHMENT7 : 0x8CE7,
  11551. COLOR_ATTACHMENT8 : 0x8CE8,
  11552. COLOR_ATTACHMENT9 : 0x8CE9,
  11553. COLOR_ATTACHMENT10 : 0x8CEA,
  11554. COLOR_ATTACHMENT11 : 0x8CEB,
  11555. COLOR_ATTACHMENT12 : 0x8CEC,
  11556. COLOR_ATTACHMENT13 : 0x8CED,
  11557. COLOR_ATTACHMENT14 : 0x8CEE,
  11558. COLOR_ATTACHMENT15 : 0x8CEF,
  11559. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  11560. MAX_SAMPLES : 0x8D57,
  11561. HALF_FLOAT : 0x140B,
  11562. RG : 0x8227,
  11563. RG_INTEGER : 0x8228,
  11564. R8 : 0x8229,
  11565. RG8 : 0x822B,
  11566. R16F : 0x822D,
  11567. R32F : 0x822E,
  11568. RG16F : 0x822F,
  11569. RG32F : 0x8230,
  11570. R8I : 0x8231,
  11571. R8UI : 0x8232,
  11572. R16I : 0x8233,
  11573. R16UI : 0x8234,
  11574. R32I : 0x8235,
  11575. R32UI : 0x8236,
  11576. RG8I : 0x8237,
  11577. RG8UI : 0x8238,
  11578. RG16I : 0x8239,
  11579. RG16UI : 0x823A,
  11580. RG32I : 0x823B,
  11581. RG32UI : 0x823C,
  11582. VERTEX_ARRAY_BINDING : 0x85B5,
  11583. R8_SNORM : 0x8F94,
  11584. RG8_SNORM : 0x8F95,
  11585. RGB8_SNORM : 0x8F96,
  11586. RGBA8_SNORM : 0x8F97,
  11587. SIGNED_NORMALIZED : 0x8F9C,
  11588. COPY_READ_BUFFER : 0x8F36,
  11589. COPY_WRITE_BUFFER : 0x8F37,
  11590. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  11591. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  11592. UNIFORM_BUFFER : 0x8A11,
  11593. UNIFORM_BUFFER_BINDING : 0x8A28,
  11594. UNIFORM_BUFFER_START : 0x8A29,
  11595. UNIFORM_BUFFER_SIZE : 0x8A2A,
  11596. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  11597. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  11598. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  11599. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  11600. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  11601. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  11602. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  11603. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  11604. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  11605. UNIFORM_TYPE : 0x8A37,
  11606. UNIFORM_SIZE : 0x8A38,
  11607. UNIFORM_BLOCK_INDEX : 0x8A3A,
  11608. UNIFORM_OFFSET : 0x8A3B,
  11609. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  11610. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  11611. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  11612. UNIFORM_BLOCK_BINDING : 0x8A3F,
  11613. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  11614. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  11615. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  11616. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  11617. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  11618. INVALID_INDEX : 0xFFFFFFFF,
  11619. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  11620. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  11621. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  11622. OBJECT_TYPE : 0x9112,
  11623. SYNC_CONDITION : 0x9113,
  11624. SYNC_STATUS : 0x9114,
  11625. SYNC_FLAGS : 0x9115,
  11626. SYNC_FENCE : 0x9116,
  11627. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  11628. UNSIGNALED : 0x9118,
  11629. SIGNALED : 0x9119,
  11630. ALREADY_SIGNALED : 0x911A,
  11631. TIMEOUT_EXPIRED : 0x911B,
  11632. CONDITION_SATISFIED : 0x911C,
  11633. WAIT_FAILED : 0x911D,
  11634. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  11635. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  11636. ANY_SAMPLES_PASSED : 0x8C2F,
  11637. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  11638. SAMPLER_BINDING : 0x8919,
  11639. RGB10_A2UI : 0x906F,
  11640. INT_2_10_10_10_REV : 0x8D9F,
  11641. TRANSFORM_FEEDBACK : 0x8E22,
  11642. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  11643. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  11644. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  11645. COMPRESSED_R11_EAC : 0x9270,
  11646. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  11647. COMPRESSED_RG11_EAC : 0x9272,
  11648. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  11649. COMPRESSED_RGB8_ETC2 : 0x9274,
  11650. COMPRESSED_SRGB8_ETC2 : 0x9275,
  11651. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  11652. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  11653. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  11654. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  11655. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  11656. MAX_ELEMENT_INDEX : 0x8D6B,
  11657. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  11658. };
  11659. return freezeObject(WebGLConstants);
  11660. });
  11661. /*global define*/
  11662. define('Core/IndexDatatype',[
  11663. './defined',
  11664. './DeveloperError',
  11665. './freezeObject',
  11666. './Math',
  11667. './WebGLConstants'
  11668. ], function(
  11669. defined,
  11670. DeveloperError,
  11671. freezeObject,
  11672. CesiumMath,
  11673. WebGLConstants) {
  11674. 'use strict';
  11675. /**
  11676. * Constants for WebGL index datatypes. These corresponds to the
  11677. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  11678. *
  11679. * @exports IndexDatatype
  11680. */
  11681. var IndexDatatype = {
  11682. /**
  11683. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  11684. * of an element in <code>Uint8Array</code>.
  11685. *
  11686. * @type {Number}
  11687. * @constant
  11688. */
  11689. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  11690. /**
  11691. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  11692. * of an element in <code>Uint16Array</code>.
  11693. *
  11694. * @type {Number}
  11695. * @constant
  11696. */
  11697. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  11698. /**
  11699. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  11700. * of an element in <code>Uint32Array</code>.
  11701. *
  11702. * @type {Number}
  11703. * @constant
  11704. */
  11705. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  11706. };
  11707. /**
  11708. * Returns the size, in bytes, of the corresponding datatype.
  11709. *
  11710. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  11711. * @returns {Number} The size in bytes.
  11712. *
  11713. * @example
  11714. * // Returns 2
  11715. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  11716. */
  11717. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  11718. switch(indexDatatype) {
  11719. case IndexDatatype.UNSIGNED_BYTE:
  11720. return Uint8Array.BYTES_PER_ELEMENT;
  11721. case IndexDatatype.UNSIGNED_SHORT:
  11722. return Uint16Array.BYTES_PER_ELEMENT;
  11723. case IndexDatatype.UNSIGNED_INT:
  11724. return Uint32Array.BYTES_PER_ELEMENT;
  11725. }
  11726. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  11727. };
  11728. /**
  11729. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  11730. *
  11731. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  11732. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  11733. *
  11734. * @example
  11735. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  11736. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  11737. * }
  11738. */
  11739. IndexDatatype.validate = function(indexDatatype) {
  11740. return defined(indexDatatype) &&
  11741. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  11742. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  11743. indexDatatype === IndexDatatype.UNSIGNED_INT);
  11744. };
  11745. /**
  11746. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  11747. * or <code>Uint32Array</code> depending on the number of vertices.
  11748. *
  11749. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  11750. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  11751. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  11752. *
  11753. * @example
  11754. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  11755. */
  11756. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  11757. if (!defined(numberOfVertices)) {
  11758. throw new DeveloperError('numberOfVertices is required.');
  11759. }
  11760. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  11761. return new Uint32Array(indicesLengthOrArray);
  11762. }
  11763. return new Uint16Array(indicesLengthOrArray);
  11764. };
  11765. /**
  11766. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  11767. * or <code>Uint32Array</code> depending on the number of vertices.
  11768. *
  11769. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  11770. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  11771. * @param {Number} byteOffset Passed through to the typed array constructor.
  11772. * @param {Number} length Passed through to the typed array constructor.
  11773. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  11774. *
  11775. */
  11776. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  11777. if (!defined(numberOfVertices)) {
  11778. throw new DeveloperError('numberOfVertices is required.');
  11779. }
  11780. if (!defined(sourceArray)) {
  11781. throw new DeveloperError('sourceArray is required.');
  11782. }
  11783. if (!defined(byteOffset)) {
  11784. throw new DeveloperError('byteOffset is required.');
  11785. }
  11786. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  11787. return new Uint32Array(sourceArray, byteOffset, length);
  11788. }
  11789. return new Uint16Array(sourceArray, byteOffset, length);
  11790. };
  11791. return freezeObject(IndexDatatype);
  11792. });
  11793. /*global define*/
  11794. define('Core/QuadraticRealPolynomial',[
  11795. './DeveloperError',
  11796. './Math'
  11797. ], function(
  11798. DeveloperError,
  11799. CesiumMath) {
  11800. 'use strict';
  11801. /**
  11802. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  11803. *
  11804. * @exports QuadraticRealPolynomial
  11805. */
  11806. var QuadraticRealPolynomial = {};
  11807. /**
  11808. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  11809. *
  11810. * @param {Number} a The coefficient of the 2nd order monomial.
  11811. * @param {Number} b The coefficient of the 1st order monomial.
  11812. * @param {Number} c The coefficient of the 0th order monomial.
  11813. * @returns {Number} The value of the discriminant.
  11814. */
  11815. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  11816. if (typeof a !== 'number') {
  11817. throw new DeveloperError('a is a required number.');
  11818. }
  11819. if (typeof b !== 'number') {
  11820. throw new DeveloperError('b is a required number.');
  11821. }
  11822. if (typeof c !== 'number') {
  11823. throw new DeveloperError('c is a required number.');
  11824. }
  11825. var discriminant = b * b - 4.0 * a * c;
  11826. return discriminant;
  11827. };
  11828. function addWithCancellationCheck(left, right, tolerance) {
  11829. var difference = left + right;
  11830. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  11831. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  11832. return 0.0;
  11833. }
  11834. return difference;
  11835. }
  11836. /**
  11837. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  11838. *
  11839. * @param {Number} a The coefficient of the 2nd order monomial.
  11840. * @param {Number} b The coefficient of the 1st order monomial.
  11841. * @param {Number} c The coefficient of the 0th order monomial.
  11842. * @returns {Number[]} The real valued roots.
  11843. */
  11844. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  11845. if (typeof a !== 'number') {
  11846. throw new DeveloperError('a is a required number.');
  11847. }
  11848. if (typeof b !== 'number') {
  11849. throw new DeveloperError('b is a required number.');
  11850. }
  11851. if (typeof c !== 'number') {
  11852. throw new DeveloperError('c is a required number.');
  11853. }
  11854. var ratio;
  11855. if (a === 0.0) {
  11856. if (b === 0.0) {
  11857. // Constant function: c = 0.
  11858. return [];
  11859. }
  11860. // Linear function: b * x + c = 0.
  11861. return [-c / b];
  11862. } else if (b === 0.0) {
  11863. if (c === 0.0) {
  11864. // 2nd order monomial: a * x^2 = 0.
  11865. return [0.0, 0.0];
  11866. }
  11867. var cMagnitude = Math.abs(c);
  11868. var aMagnitude = Math.abs(a);
  11869. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  11870. // 2nd order monomial: a * x^2 = 0.
  11871. return [0.0, 0.0];
  11872. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  11873. // Constant function: c = 0.
  11874. return [];
  11875. }
  11876. // a * x^2 + c = 0
  11877. ratio = -c / a;
  11878. if (ratio < 0.0) {
  11879. // Both roots are complex.
  11880. return [];
  11881. }
  11882. // Both roots are real.
  11883. var root = Math.sqrt(ratio);
  11884. return [-root, root];
  11885. } else if (c === 0.0) {
  11886. // a * x^2 + b * x = 0
  11887. ratio = -b / a;
  11888. if (ratio < 0.0) {
  11889. return [ratio, 0.0];
  11890. }
  11891. return [0.0, ratio];
  11892. }
  11893. // a * x^2 + b * x + c = 0
  11894. var b2 = b * b;
  11895. var four_ac = 4.0 * a * c;
  11896. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  11897. if (radicand < 0.0) {
  11898. // Both roots are complex.
  11899. return [];
  11900. }
  11901. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  11902. if (b > 0.0) {
  11903. return [q / a, c / q];
  11904. }
  11905. return [c / q, q / a];
  11906. };
  11907. return QuadraticRealPolynomial;
  11908. });
  11909. /*global define*/
  11910. define('Core/CubicRealPolynomial',[
  11911. './DeveloperError',
  11912. './QuadraticRealPolynomial'
  11913. ], function(
  11914. DeveloperError,
  11915. QuadraticRealPolynomial) {
  11916. 'use strict';
  11917. /**
  11918. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  11919. *
  11920. * @exports CubicRealPolynomial
  11921. */
  11922. var CubicRealPolynomial = {};
  11923. /**
  11924. * Provides the discriminant of the cubic equation from the supplied coefficients.
  11925. *
  11926. * @param {Number} a The coefficient of the 3rd order monomial.
  11927. * @param {Number} b The coefficient of the 2nd order monomial.
  11928. * @param {Number} c The coefficient of the 1st order monomial.
  11929. * @param {Number} d The coefficient of the 0th order monomial.
  11930. * @returns {Number} The value of the discriminant.
  11931. */
  11932. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  11933. if (typeof a !== 'number') {
  11934. throw new DeveloperError('a is a required number.');
  11935. }
  11936. if (typeof b !== 'number') {
  11937. throw new DeveloperError('b is a required number.');
  11938. }
  11939. if (typeof c !== 'number') {
  11940. throw new DeveloperError('c is a required number.');
  11941. }
  11942. if (typeof d !== 'number') {
  11943. throw new DeveloperError('d is a required number.');
  11944. }
  11945. var a2 = a * a;
  11946. var b2 = b * b;
  11947. var c2 = c * c;
  11948. var d2 = d * d;
  11949. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  11950. return discriminant;
  11951. };
  11952. function computeRealRoots(a, b, c, d) {
  11953. var A = a;
  11954. var B = b / 3.0;
  11955. var C = c / 3.0;
  11956. var D = d;
  11957. var AC = A * C;
  11958. var BD = B * D;
  11959. var B2 = B * B;
  11960. var C2 = C * C;
  11961. var delta1 = A * C - B2;
  11962. var delta2 = A * D - B * C;
  11963. var delta3 = B * D - C2;
  11964. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  11965. var temp;
  11966. var temp1;
  11967. if (discriminant < 0.0) {
  11968. var ABar;
  11969. var CBar;
  11970. var DBar;
  11971. if (B2 * BD >= AC * C2) {
  11972. ABar = A;
  11973. CBar = delta1;
  11974. DBar = -2.0 * B * delta1 + A * delta2;
  11975. } else {
  11976. ABar = D;
  11977. CBar = delta3;
  11978. DBar = -D * delta2 + 2.0 * C * delta3;
  11979. }
  11980. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  11981. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  11982. temp1 = -DBar + temp0;
  11983. var x = temp1 / 2.0;
  11984. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  11985. var q = (temp1 === temp0) ? -p : -CBar / p;
  11986. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  11987. if (B2 * BD >= AC * C2) {
  11988. return [(temp - B) / A];
  11989. }
  11990. return [-D / (temp + C)];
  11991. }
  11992. var CBarA = delta1;
  11993. var DBarA = -2.0 * B * delta1 + A * delta2;
  11994. var CBarD = delta3;
  11995. var DBarD = -D * delta2 + 2.0 * C * delta3;
  11996. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  11997. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  11998. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  11999. temp = 2.0 * Math.sqrt(-CBarA);
  12000. var cosine = Math.cos(theta);
  12001. temp1 = temp * cosine;
  12002. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12003. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  12004. var denominatorLarge = A;
  12005. var root1 = numeratorLarge / denominatorLarge;
  12006. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  12007. temp = 2.0 * Math.sqrt(-CBarD);
  12008. cosine = Math.cos(theta);
  12009. temp1 = temp * cosine;
  12010. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12011. var numeratorSmall = -D;
  12012. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  12013. var root3 = numeratorSmall / denominatorSmall;
  12014. var E = denominatorLarge * denominatorSmall;
  12015. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  12016. var G = numeratorLarge * numeratorSmall;
  12017. var root2 = (C * F - B * G) / (-B * F + C * E);
  12018. if (root1 <= root2) {
  12019. if (root1 <= root3) {
  12020. if (root2 <= root3) {
  12021. return [root1, root2, root3];
  12022. }
  12023. return [root1, root3, root2];
  12024. }
  12025. return [root3, root1, root2];
  12026. }
  12027. if (root1 <= root3) {
  12028. return [root2, root1, root3];
  12029. }
  12030. if (root2 <= root3) {
  12031. return [root2, root3, root1];
  12032. }
  12033. return [root3, root2, root1];
  12034. }
  12035. /**
  12036. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  12037. *
  12038. * @param {Number} a The coefficient of the 3rd order monomial.
  12039. * @param {Number} b The coefficient of the 2nd order monomial.
  12040. * @param {Number} c The coefficient of the 1st order monomial.
  12041. * @param {Number} d The coefficient of the 0th order monomial.
  12042. * @returns {Number[]} The real valued roots.
  12043. */
  12044. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  12045. if (typeof a !== 'number') {
  12046. throw new DeveloperError('a is a required number.');
  12047. }
  12048. if (typeof b !== 'number') {
  12049. throw new DeveloperError('b is a required number.');
  12050. }
  12051. if (typeof c !== 'number') {
  12052. throw new DeveloperError('c is a required number.');
  12053. }
  12054. if (typeof d !== 'number') {
  12055. throw new DeveloperError('d is a required number.');
  12056. }
  12057. var roots;
  12058. var ratio;
  12059. if (a === 0.0) {
  12060. // Quadratic function: b * x^2 + c * x + d = 0.
  12061. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  12062. } else if (b === 0.0) {
  12063. if (c === 0.0) {
  12064. if (d === 0.0) {
  12065. // 3rd order monomial: a * x^3 = 0.
  12066. return [0.0, 0.0, 0.0];
  12067. }
  12068. // a * x^3 + d = 0
  12069. ratio = -d / a;
  12070. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  12071. return [root, root, root];
  12072. } else if (d === 0.0) {
  12073. // x * (a * x^2 + c) = 0.
  12074. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  12075. // Return the roots in ascending order.
  12076. if (roots.Length === 0) {
  12077. return [0.0];
  12078. }
  12079. return [roots[0], 0.0, roots[1]];
  12080. }
  12081. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  12082. return computeRealRoots(a, 0, c, d);
  12083. } else if (c === 0.0) {
  12084. if (d === 0.0) {
  12085. // x^2 * (a * x + b) = 0.
  12086. ratio = -b / a;
  12087. if (ratio < 0.0) {
  12088. return [ratio, 0.0, 0.0];
  12089. }
  12090. return [0.0, 0.0, ratio];
  12091. }
  12092. // a * x^3 + b * x^2 + d = 0.
  12093. return computeRealRoots(a, b, 0, d);
  12094. } else if (d === 0.0) {
  12095. // x * (a * x^2 + b * x + c) = 0
  12096. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  12097. // Return the roots in ascending order.
  12098. if (roots.length === 0) {
  12099. return [0.0];
  12100. } else if (roots[1] <= 0.0) {
  12101. return [roots[0], roots[1], 0.0];
  12102. } else if (roots[0] >= 0.0) {
  12103. return [0.0, roots[0], roots[1]];
  12104. }
  12105. return [roots[0], 0.0, roots[1]];
  12106. }
  12107. return computeRealRoots(a, b, c, d);
  12108. };
  12109. return CubicRealPolynomial;
  12110. });
  12111. /*global define*/
  12112. define('Core/QuarticRealPolynomial',[
  12113. './CubicRealPolynomial',
  12114. './DeveloperError',
  12115. './Math',
  12116. './QuadraticRealPolynomial'
  12117. ], function(
  12118. CubicRealPolynomial,
  12119. DeveloperError,
  12120. CesiumMath,
  12121. QuadraticRealPolynomial) {
  12122. 'use strict';
  12123. /**
  12124. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  12125. *
  12126. * @exports QuarticRealPolynomial
  12127. */
  12128. var QuarticRealPolynomial = {};
  12129. /**
  12130. * Provides the discriminant of the quartic equation from the supplied coefficients.
  12131. *
  12132. * @param {Number} a The coefficient of the 4th order monomial.
  12133. * @param {Number} b The coefficient of the 3rd order monomial.
  12134. * @param {Number} c The coefficient of the 2nd order monomial.
  12135. * @param {Number} d The coefficient of the 1st order monomial.
  12136. * @param {Number} e The coefficient of the 0th order monomial.
  12137. * @returns {Number} The value of the discriminant.
  12138. */
  12139. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  12140. if (typeof a !== 'number') {
  12141. throw new DeveloperError('a is a required number.');
  12142. }
  12143. if (typeof b !== 'number') {
  12144. throw new DeveloperError('b is a required number.');
  12145. }
  12146. if (typeof c !== 'number') {
  12147. throw new DeveloperError('c is a required number.');
  12148. }
  12149. if (typeof d !== 'number') {
  12150. throw new DeveloperError('d is a required number.');
  12151. }
  12152. if (typeof e !== 'number') {
  12153. throw new DeveloperError('e is a required number.');
  12154. }
  12155. var a2 = a * a;
  12156. var a3 = a2 * a;
  12157. var b2 = b * b;
  12158. var b3 = b2 * b;
  12159. var c2 = c * c;
  12160. var c3 = c2 * c;
  12161. var d2 = d * d;
  12162. var d3 = d2 * d;
  12163. var e2 = e * e;
  12164. var e3 = e2 * e;
  12165. 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) +
  12166. 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) +
  12167. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  12168. return discriminant;
  12169. };
  12170. function original(a3, a2, a1, a0) {
  12171. var a3Squared = a3 * a3;
  12172. var p = a2 - 3.0 * a3Squared / 8.0;
  12173. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  12174. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  12175. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  12176. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  12177. if (cubicRoots.length > 0) {
  12178. var temp = -a3 / 4.0;
  12179. // Use the largest positive root.
  12180. var hSquared = cubicRoots[cubicRoots.length - 1];
  12181. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  12182. // y^4 + p y^2 + r = 0.
  12183. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  12184. if (roots.length === 2) {
  12185. var root0 = roots[0];
  12186. var root1 = roots[1];
  12187. var y;
  12188. if (root0 >= 0.0 && root1 >= 0.0) {
  12189. var y0 = Math.sqrt(root0);
  12190. var y1 = Math.sqrt(root1);
  12191. return [temp - y1, temp - y0, temp + y0, temp + y1];
  12192. } else if (root0 >= 0.0 && root1 < 0.0) {
  12193. y = Math.sqrt(root0);
  12194. return [temp - y, temp + y];
  12195. } else if (root0 < 0.0 && root1 >= 0.0) {
  12196. y = Math.sqrt(root1);
  12197. return [temp - y, temp + y];
  12198. }
  12199. }
  12200. return [];
  12201. } else if (hSquared > 0.0) {
  12202. var h = Math.sqrt(hSquared);
  12203. var m = (p + hSquared - q / h) / 2.0;
  12204. var n = (p + hSquared + q / h) / 2.0;
  12205. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  12206. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  12207. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  12208. if (roots1.length !== 0) {
  12209. roots1[0] += temp;
  12210. roots1[1] += temp;
  12211. if (roots2.length !== 0) {
  12212. roots2[0] += temp;
  12213. roots2[1] += temp;
  12214. if (roots1[1] <= roots2[0]) {
  12215. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12216. } else if (roots2[1] <= roots1[0]) {
  12217. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  12218. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  12219. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  12220. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  12221. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  12222. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  12223. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  12224. }
  12225. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  12226. }
  12227. return roots1;
  12228. }
  12229. if (roots2.length !== 0) {
  12230. roots2[0] += temp;
  12231. roots2[1] += temp;
  12232. return roots2;
  12233. }
  12234. return [];
  12235. }
  12236. }
  12237. return [];
  12238. }
  12239. function neumark(a3, a2, a1, a0) {
  12240. var a1Squared = a1 * a1;
  12241. var a2Squared = a2 * a2;
  12242. var a3Squared = a3 * a3;
  12243. var p = -2.0 * a2;
  12244. var q = a1 * a3 + a2Squared - 4.0 * a0;
  12245. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  12246. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  12247. if (cubicRoots.length > 0) {
  12248. // Use the most positive root
  12249. var y = cubicRoots[0];
  12250. var temp = (a2 - y);
  12251. var tempSquared = temp * temp;
  12252. var g1 = a3 / 2.0;
  12253. var h1 = temp / 2.0;
  12254. var m = tempSquared - 4.0 * a0;
  12255. var mError = tempSquared + 4.0 * Math.abs(a0);
  12256. var n = a3Squared - 4.0 * y;
  12257. var nError = a3Squared + 4.0 * Math.abs(y);
  12258. var g2;
  12259. var h2;
  12260. if (y < 0.0 || (m * nError < n * mError)) {
  12261. var squareRootOfN = Math.sqrt(n);
  12262. g2 = squareRootOfN / 2.0;
  12263. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  12264. } else {
  12265. var squareRootOfM = Math.sqrt(m);
  12266. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  12267. h2 = squareRootOfM / 2.0;
  12268. }
  12269. var G;
  12270. var g;
  12271. if (g1 === 0.0 && g2 === 0.0) {
  12272. G = 0.0;
  12273. g = 0.0;
  12274. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  12275. G = g1 + g2;
  12276. g = y / G;
  12277. } else {
  12278. g = g1 - g2;
  12279. G = y / g;
  12280. }
  12281. var H;
  12282. var h;
  12283. if (h1 === 0.0 && h2 === 0.0) {
  12284. H = 0.0;
  12285. h = 0.0;
  12286. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  12287. H = h1 + h2;
  12288. h = a0 / H;
  12289. } else {
  12290. h = h1 - h2;
  12291. H = a0 / h;
  12292. }
  12293. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  12294. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  12295. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  12296. if (roots1.length !== 0) {
  12297. if (roots2.length !== 0) {
  12298. if (roots1[1] <= roots2[0]) {
  12299. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12300. } else if (roots2[1] <= roots1[0]) {
  12301. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  12302. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  12303. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  12304. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  12305. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  12306. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  12307. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  12308. } else {
  12309. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  12310. }
  12311. }
  12312. return roots1;
  12313. }
  12314. if (roots2.length !== 0) {
  12315. return roots2;
  12316. }
  12317. }
  12318. return [];
  12319. }
  12320. /**
  12321. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  12322. *
  12323. * @param {Number} a The coefficient of the 4th order monomial.
  12324. * @param {Number} b The coefficient of the 3rd order monomial.
  12325. * @param {Number} c The coefficient of the 2nd order monomial.
  12326. * @param {Number} d The coefficient of the 1st order monomial.
  12327. * @param {Number} e The coefficient of the 0th order monomial.
  12328. * @returns {Number[]} The real valued roots.
  12329. */
  12330. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  12331. if (typeof a !== 'number') {
  12332. throw new DeveloperError('a is a required number.');
  12333. }
  12334. if (typeof b !== 'number') {
  12335. throw new DeveloperError('b is a required number.');
  12336. }
  12337. if (typeof c !== 'number') {
  12338. throw new DeveloperError('c is a required number.');
  12339. }
  12340. if (typeof d !== 'number') {
  12341. throw new DeveloperError('d is a required number.');
  12342. }
  12343. if (typeof e !== 'number') {
  12344. throw new DeveloperError('e is a required number.');
  12345. }
  12346. if (Math.abs(a) < CesiumMath.EPSILON15) {
  12347. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  12348. }
  12349. var a3 = b / a;
  12350. var a2 = c / a;
  12351. var a1 = d / a;
  12352. var a0 = e / a;
  12353. var k = (a3 < 0.0) ? 1 : 0;
  12354. k += (a2 < 0.0) ? k + 1 : k;
  12355. k += (a1 < 0.0) ? k + 1 : k;
  12356. k += (a0 < 0.0) ? k + 1 : k;
  12357. switch (k) {
  12358. case 0:
  12359. return original(a3, a2, a1, a0);
  12360. case 1:
  12361. return neumark(a3, a2, a1, a0);
  12362. case 2:
  12363. return neumark(a3, a2, a1, a0);
  12364. case 3:
  12365. return original(a3, a2, a1, a0);
  12366. case 4:
  12367. return original(a3, a2, a1, a0);
  12368. case 5:
  12369. return neumark(a3, a2, a1, a0);
  12370. case 6:
  12371. return original(a3, a2, a1, a0);
  12372. case 7:
  12373. return original(a3, a2, a1, a0);
  12374. case 8:
  12375. return neumark(a3, a2, a1, a0);
  12376. case 9:
  12377. return original(a3, a2, a1, a0);
  12378. case 10:
  12379. return original(a3, a2, a1, a0);
  12380. case 11:
  12381. return neumark(a3, a2, a1, a0);
  12382. case 12:
  12383. return original(a3, a2, a1, a0);
  12384. case 13:
  12385. return original(a3, a2, a1, a0);
  12386. case 14:
  12387. return original(a3, a2, a1, a0);
  12388. case 15:
  12389. return original(a3, a2, a1, a0);
  12390. default:
  12391. return undefined;
  12392. }
  12393. };
  12394. return QuarticRealPolynomial;
  12395. });
  12396. /*global define*/
  12397. define('Core/Ray',[
  12398. './Cartesian3',
  12399. './defaultValue',
  12400. './defined',
  12401. './DeveloperError'
  12402. ], function(
  12403. Cartesian3,
  12404. defaultValue,
  12405. defined,
  12406. DeveloperError) {
  12407. 'use strict';
  12408. /**
  12409. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  12410. * @alias Ray
  12411. * @constructor
  12412. *
  12413. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  12414. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  12415. */
  12416. function Ray(origin, direction) {
  12417. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  12418. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  12419. Cartesian3.normalize(direction, direction);
  12420. }
  12421. /**
  12422. * The origin of the ray.
  12423. * @type {Cartesian3}
  12424. * @default {@link Cartesian3.ZERO}
  12425. */
  12426. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  12427. /**
  12428. * The direction of the ray.
  12429. * @type {Cartesian3}
  12430. */
  12431. this.direction = direction;
  12432. }
  12433. /**
  12434. * Computes the point along the ray given by r(t) = o + t*d,
  12435. * where o is the origin of the ray and d is the direction.
  12436. *
  12437. * @param {Ray} ray The ray.
  12438. * @param {Number} t A scalar value.
  12439. * @param {Cartesian3} [result] The object in which the result will be stored.
  12440. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  12441. *
  12442. * @example
  12443. * //Get the first intersection point of a ray and an ellipsoid.
  12444. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  12445. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  12446. */
  12447. Ray.getPoint = function(ray, t, result) {
  12448. if (!defined(ray)){
  12449. throw new DeveloperError('ray is requred');
  12450. }
  12451. if (typeof t !== 'number') {
  12452. throw new DeveloperError('t is a required number');
  12453. }
  12454. if (!defined(result)) {
  12455. result = new Cartesian3();
  12456. }
  12457. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  12458. return Cartesian3.add(ray.origin, result, result);
  12459. };
  12460. return Ray;
  12461. });
  12462. /*global define*/
  12463. define('Core/IntersectionTests',[
  12464. './Cartesian3',
  12465. './Cartographic',
  12466. './defaultValue',
  12467. './defined',
  12468. './DeveloperError',
  12469. './Math',
  12470. './Matrix3',
  12471. './QuadraticRealPolynomial',
  12472. './QuarticRealPolynomial',
  12473. './Ray'
  12474. ], function(
  12475. Cartesian3,
  12476. Cartographic,
  12477. defaultValue,
  12478. defined,
  12479. DeveloperError,
  12480. CesiumMath,
  12481. Matrix3,
  12482. QuadraticRealPolynomial,
  12483. QuarticRealPolynomial,
  12484. Ray) {
  12485. 'use strict';
  12486. /**
  12487. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  12488. *
  12489. * @exports IntersectionTests
  12490. */
  12491. var IntersectionTests = {};
  12492. /**
  12493. * Computes the intersection of a ray and a plane.
  12494. *
  12495. * @param {Ray} ray The ray.
  12496. * @param {Plane} plane The plane.
  12497. * @param {Cartesian3} [result] The object onto which to store the result.
  12498. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  12499. */
  12500. IntersectionTests.rayPlane = function(ray, plane, result) {
  12501. if (!defined(ray)) {
  12502. throw new DeveloperError('ray is required.');
  12503. }
  12504. if (!defined(plane)) {
  12505. throw new DeveloperError('plane is required.');
  12506. }
  12507. if (!defined(result)) {
  12508. result = new Cartesian3();
  12509. }
  12510. var origin = ray.origin;
  12511. var direction = ray.direction;
  12512. var normal = plane.normal;
  12513. var denominator = Cartesian3.dot(normal, direction);
  12514. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  12515. // Ray is parallel to plane. The ray may be in the polygon's plane.
  12516. return undefined;
  12517. }
  12518. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  12519. if (t < 0) {
  12520. return undefined;
  12521. }
  12522. result = Cartesian3.multiplyByScalar(direction, t, result);
  12523. return Cartesian3.add(origin, result, result);
  12524. };
  12525. var scratchEdge0 = new Cartesian3();
  12526. var scratchEdge1 = new Cartesian3();
  12527. var scratchPVec = new Cartesian3();
  12528. var scratchTVec = new Cartesian3();
  12529. var scratchQVec = new Cartesian3();
  12530. /**
  12531. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  12532. *
  12533. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  12534. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  12535. *
  12536. * @memberof IntersectionTests
  12537. *
  12538. * @param {Ray} ray The ray.
  12539. * @param {Cartesian3} p0 The first vertex of the triangle.
  12540. * @param {Cartesian3} p1 The second vertex of the triangle.
  12541. * @param {Cartesian3} p2 The third vertex of the triangle.
  12542. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  12543. * and return undefined for intersections with the back face.
  12544. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  12545. */
  12546. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  12547. if (!defined(ray)) {
  12548. throw new DeveloperError('ray is required.');
  12549. }
  12550. if (!defined(p0)) {
  12551. throw new DeveloperError('p0 is required.');
  12552. }
  12553. if (!defined(p1)) {
  12554. throw new DeveloperError('p1 is required.');
  12555. }
  12556. if (!defined(p2)) {
  12557. throw new DeveloperError('p2 is required.');
  12558. }
  12559. cullBackFaces = defaultValue(cullBackFaces, false);
  12560. var origin = ray.origin;
  12561. var direction = ray.direction;
  12562. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  12563. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  12564. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  12565. var det = Cartesian3.dot(edge0, p);
  12566. var tvec;
  12567. var q;
  12568. var u;
  12569. var v;
  12570. var t;
  12571. if (cullBackFaces) {
  12572. if (det < CesiumMath.EPSILON6) {
  12573. return undefined;
  12574. }
  12575. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  12576. u = Cartesian3.dot(tvec, p);
  12577. if (u < 0.0 || u > det) {
  12578. return undefined;
  12579. }
  12580. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  12581. v = Cartesian3.dot(direction, q);
  12582. if (v < 0.0 || u + v > det) {
  12583. return undefined;
  12584. }
  12585. t = Cartesian3.dot(edge1, q) / det;
  12586. } else {
  12587. if (Math.abs(det) < CesiumMath.EPSILON6) {
  12588. return undefined;
  12589. }
  12590. var invDet = 1.0 / det;
  12591. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  12592. u = Cartesian3.dot(tvec, p) * invDet;
  12593. if (u < 0.0 || u > 1.0) {
  12594. return undefined;
  12595. }
  12596. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  12597. v = Cartesian3.dot(direction, q) * invDet;
  12598. if (v < 0.0 || u + v > 1.0) {
  12599. return undefined;
  12600. }
  12601. t = Cartesian3.dot(edge1, q) * invDet;
  12602. }
  12603. return t;
  12604. };
  12605. /**
  12606. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  12607. *
  12608. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  12609. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  12610. *
  12611. * @memberof IntersectionTests
  12612. *
  12613. * @param {Ray} ray The ray.
  12614. * @param {Cartesian3} p0 The first vertex of the triangle.
  12615. * @param {Cartesian3} p1 The second vertex of the triangle.
  12616. * @param {Cartesian3} p2 The third vertex of the triangle.
  12617. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  12618. * and return undefined for intersections with the back face.
  12619. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  12620. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  12621. */
  12622. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  12623. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  12624. if (!defined(t) || t < 0.0) {
  12625. return undefined;
  12626. }
  12627. if (!defined(result)) {
  12628. result = new Cartesian3();
  12629. }
  12630. Cartesian3.multiplyByScalar(ray.direction, t, result);
  12631. return Cartesian3.add(ray.origin, result, result);
  12632. };
  12633. var scratchLineSegmentTriangleRay = new Ray();
  12634. /**
  12635. * Computes the intersection of a line segment and a triangle.
  12636. * @memberof IntersectionTests
  12637. *
  12638. * @param {Cartesian3} v0 The an end point of the line segment.
  12639. * @param {Cartesian3} v1 The other end point of the line segment.
  12640. * @param {Cartesian3} p0 The first vertex of the triangle.
  12641. * @param {Cartesian3} p1 The second vertex of the triangle.
  12642. * @param {Cartesian3} p2 The third vertex of the triangle.
  12643. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  12644. * and return undefined for intersections with the back face.
  12645. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  12646. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  12647. */
  12648. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  12649. if (!defined(v0)) {
  12650. throw new DeveloperError('v0 is required.');
  12651. }
  12652. if (!defined(v1)) {
  12653. throw new DeveloperError('v1 is required.');
  12654. }
  12655. if (!defined(p0)) {
  12656. throw new DeveloperError('p0 is required.');
  12657. }
  12658. if (!defined(p1)) {
  12659. throw new DeveloperError('p1 is required.');
  12660. }
  12661. if (!defined(p2)) {
  12662. throw new DeveloperError('p2 is required.');
  12663. }
  12664. var ray = scratchLineSegmentTriangleRay;
  12665. Cartesian3.clone(v0, ray.origin);
  12666. Cartesian3.subtract(v1, v0, ray.direction);
  12667. Cartesian3.normalize(ray.direction, ray.direction);
  12668. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  12669. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  12670. return undefined;
  12671. }
  12672. if (!defined(result)) {
  12673. result = new Cartesian3();
  12674. }
  12675. Cartesian3.multiplyByScalar(ray.direction, t, result);
  12676. return Cartesian3.add(ray.origin, result, result);
  12677. };
  12678. function solveQuadratic(a, b, c, result) {
  12679. var det = b * b - 4.0 * a * c;
  12680. if (det < 0.0) {
  12681. return undefined;
  12682. } else if (det > 0.0) {
  12683. var denom = 1.0 / (2.0 * a);
  12684. var disc = Math.sqrt(det);
  12685. var root0 = (-b + disc) * denom;
  12686. var root1 = (-b - disc) * denom;
  12687. if (root0 < root1) {
  12688. result.root0 = root0;
  12689. result.root1 = root1;
  12690. } else {
  12691. result.root0 = root1;
  12692. result.root1 = root0;
  12693. }
  12694. return result;
  12695. }
  12696. var root = -b / (2.0 * a);
  12697. if (root === 0.0) {
  12698. return undefined;
  12699. }
  12700. result.root0 = result.root1 = root;
  12701. return result;
  12702. }
  12703. var raySphereRoots = {
  12704. root0 : 0.0,
  12705. root1 : 0.0
  12706. };
  12707. function raySphere(ray, sphere, result) {
  12708. if (!defined(result)) {
  12709. result = {};
  12710. }
  12711. var origin = ray.origin;
  12712. var direction = ray.direction;
  12713. var center = sphere.center;
  12714. var radiusSquared = sphere.radius * sphere.radius;
  12715. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  12716. var a = Cartesian3.dot(direction, direction);
  12717. var b = 2.0 * Cartesian3.dot(direction, diff);
  12718. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  12719. var roots = solveQuadratic(a, b, c, raySphereRoots);
  12720. if (!defined(roots)) {
  12721. return undefined;
  12722. }
  12723. result.start = roots.root0;
  12724. result.stop = roots.root1;
  12725. return result;
  12726. }
  12727. /**
  12728. * Computes the intersection points of a ray with a sphere.
  12729. * @memberof IntersectionTests
  12730. *
  12731. * @param {Ray} ray The ray.
  12732. * @param {BoundingSphere} sphere The sphere.
  12733. * @param {Object} [result] The result onto which to store the result.
  12734. * @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.
  12735. */
  12736. IntersectionTests.raySphere = function(ray, sphere, result) {
  12737. if (!defined(ray)) {
  12738. throw new DeveloperError('ray is required.');
  12739. }
  12740. if (!defined(sphere)) {
  12741. throw new DeveloperError('sphere is required.');
  12742. }
  12743. result = raySphere(ray, sphere, result);
  12744. if (!defined(result) || result.stop < 0.0) {
  12745. return undefined;
  12746. }
  12747. result.start = Math.max(result.start, 0.0);
  12748. return result;
  12749. };
  12750. var scratchLineSegmentRay = new Ray();
  12751. /**
  12752. * Computes the intersection points of a line segment with a sphere.
  12753. * @memberof IntersectionTests
  12754. *
  12755. * @param {Cartesian3} p0 An end point of the line segment.
  12756. * @param {Cartesian3} p1 The other end point of the line segment.
  12757. * @param {BoundingSphere} sphere The sphere.
  12758. * @param {Object} [result] The result onto which to store the result.
  12759. * @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.
  12760. */
  12761. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  12762. if (!defined(p0)) {
  12763. throw new DeveloperError('p0 is required.');
  12764. }
  12765. if (!defined(p1)) {
  12766. throw new DeveloperError('p1 is required.');
  12767. }
  12768. if (!defined(sphere)) {
  12769. throw new DeveloperError('sphere is required.');
  12770. }
  12771. var ray = scratchLineSegmentRay;
  12772. Cartesian3.clone(p0, ray.origin);
  12773. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  12774. var maxT = Cartesian3.magnitude(direction);
  12775. Cartesian3.normalize(direction, direction);
  12776. result = raySphere(ray, sphere, result);
  12777. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  12778. return undefined;
  12779. }
  12780. result.start = Math.max(result.start, 0.0);
  12781. result.stop = Math.min(result.stop, maxT);
  12782. return result;
  12783. };
  12784. var scratchQ = new Cartesian3();
  12785. var scratchW = new Cartesian3();
  12786. /**
  12787. * Computes the intersection points of a ray with an ellipsoid.
  12788. *
  12789. * @param {Ray} ray The ray.
  12790. * @param {Ellipsoid} ellipsoid The ellipsoid.
  12791. * @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.
  12792. */
  12793. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  12794. if (!defined(ray)) {
  12795. throw new DeveloperError('ray is required.');
  12796. }
  12797. if (!defined(ellipsoid)) {
  12798. throw new DeveloperError('ellipsoid is required.');
  12799. }
  12800. var inverseRadii = ellipsoid.oneOverRadii;
  12801. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  12802. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  12803. var q2 = Cartesian3.magnitudeSquared(q);
  12804. var qw = Cartesian3.dot(q, w);
  12805. var difference, w2, product, discriminant, temp;
  12806. if (q2 > 1.0) {
  12807. // Outside ellipsoid.
  12808. if (qw >= 0.0) {
  12809. // Looking outward or tangent (0 intersections).
  12810. return undefined;
  12811. }
  12812. // qw < 0.0.
  12813. var qw2 = qw * qw;
  12814. difference = q2 - 1.0; // Positively valued.
  12815. w2 = Cartesian3.magnitudeSquared(w);
  12816. product = w2 * difference;
  12817. if (qw2 < product) {
  12818. // Imaginary roots (0 intersections).
  12819. return undefined;
  12820. } else if (qw2 > product) {
  12821. // Distinct roots (2 intersections).
  12822. discriminant = qw * qw - product;
  12823. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  12824. var root0 = temp / w2;
  12825. var root1 = difference / temp;
  12826. if (root0 < root1) {
  12827. return {
  12828. start : root0,
  12829. stop : root1
  12830. };
  12831. }
  12832. return {
  12833. start : root1,
  12834. stop : root0
  12835. };
  12836. } else {
  12837. // qw2 == product. Repeated roots (2 intersections).
  12838. var root = Math.sqrt(difference / w2);
  12839. return {
  12840. start : root,
  12841. stop : root
  12842. };
  12843. }
  12844. } else if (q2 < 1.0) {
  12845. // Inside ellipsoid (2 intersections).
  12846. difference = q2 - 1.0; // Negatively valued.
  12847. w2 = Cartesian3.magnitudeSquared(w);
  12848. product = w2 * difference; // Negatively valued.
  12849. discriminant = qw * qw - product;
  12850. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  12851. return {
  12852. start : 0.0,
  12853. stop : temp / w2
  12854. };
  12855. } else {
  12856. // q2 == 1.0. On ellipsoid.
  12857. if (qw < 0.0) {
  12858. // Looking inward.
  12859. w2 = Cartesian3.magnitudeSquared(w);
  12860. return {
  12861. start : 0.0,
  12862. stop : -qw / w2
  12863. };
  12864. }
  12865. // qw >= 0.0. Looking outward or tangent.
  12866. return undefined;
  12867. }
  12868. };
  12869. function addWithCancellationCheck(left, right, tolerance) {
  12870. var difference = left + right;
  12871. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  12872. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  12873. return 0.0;
  12874. }
  12875. return difference;
  12876. }
  12877. function quadraticVectorExpression(A, b, c, x, w) {
  12878. var xSquared = x * x;
  12879. var wSquared = w * w;
  12880. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  12881. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  12882. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  12883. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  12884. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  12885. var cosines;
  12886. var solutions = [];
  12887. if (r0 === 0.0 && r1 === 0.0) {
  12888. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  12889. if (cosines.length === 0) {
  12890. return solutions;
  12891. }
  12892. var cosine0 = cosines[0];
  12893. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  12894. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  12895. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  12896. if (cosines.length === 2) {
  12897. var cosine1 = cosines[1];
  12898. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  12899. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  12900. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  12901. }
  12902. return solutions;
  12903. }
  12904. var r0Squared = r0 * r0;
  12905. var r1Squared = r1 * r1;
  12906. var l2Squared = l2 * l2;
  12907. var r0r1 = r0 * r1;
  12908. var c4 = l2Squared + r1Squared;
  12909. var c3 = 2.0 * (l1 * l2 + r0r1);
  12910. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  12911. var c1 = 2.0 * (l0 * l1 - r0r1);
  12912. var c0 = l0 * l0 - r0Squared;
  12913. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  12914. return solutions;
  12915. }
  12916. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  12917. var length = cosines.length;
  12918. if (length === 0) {
  12919. return solutions;
  12920. }
  12921. for ( var i = 0; i < length; ++i) {
  12922. var cosine = cosines[i];
  12923. var cosineSquared = cosine * cosine;
  12924. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  12925. var sine = Math.sqrt(sineSquared);
  12926. //var left = l2 * cosineSquared + l1 * cosine + l0;
  12927. var left;
  12928. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  12929. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  12930. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  12931. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  12932. } else {
  12933. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  12934. }
  12935. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  12936. var product = left * right;
  12937. if (product < 0.0) {
  12938. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12939. } else if (product > 0.0) {
  12940. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  12941. } else if (sine !== 0.0) {
  12942. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  12943. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12944. ++i;
  12945. } else {
  12946. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12947. }
  12948. }
  12949. return solutions;
  12950. }
  12951. var firstAxisScratch = new Cartesian3();
  12952. var secondAxisScratch = new Cartesian3();
  12953. var thirdAxisScratch = new Cartesian3();
  12954. var referenceScratch = new Cartesian3();
  12955. var bCart = new Cartesian3();
  12956. var bScratch = new Matrix3();
  12957. var btScratch = new Matrix3();
  12958. var diScratch = new Matrix3();
  12959. var dScratch = new Matrix3();
  12960. var cScratch = new Matrix3();
  12961. var tempMatrix = new Matrix3();
  12962. var aScratch = new Matrix3();
  12963. var sScratch = new Cartesian3();
  12964. var closestScratch = new Cartesian3();
  12965. var surfPointScratch = new Cartographic();
  12966. /**
  12967. * Provides the point along the ray which is nearest to the ellipsoid.
  12968. *
  12969. * @param {Ray} ray The ray.
  12970. * @param {Ellipsoid} ellipsoid The ellipsoid.
  12971. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  12972. */
  12973. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  12974. if (!defined(ray)) {
  12975. throw new DeveloperError('ray is required.');
  12976. }
  12977. if (!defined(ellipsoid)) {
  12978. throw new DeveloperError('ellipsoid is required.');
  12979. }
  12980. var position = ray.origin;
  12981. var direction = ray.direction;
  12982. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  12983. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  12984. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  12985. return position;
  12986. }
  12987. }
  12988. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  12989. // Compute the scaled direction vector.
  12990. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  12991. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  12992. var firstAxis = Cartesian3.normalize(f, f);
  12993. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  12994. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  12995. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  12996. var B = bScratch;
  12997. B[0] = firstAxis.x;
  12998. B[1] = firstAxis.y;
  12999. B[2] = firstAxis.z;
  13000. B[3] = secondAxis.x;
  13001. B[4] = secondAxis.y;
  13002. B[5] = secondAxis.z;
  13003. B[6] = thirdAxis.x;
  13004. B[7] = thirdAxis.y;
  13005. B[8] = thirdAxis.z;
  13006. var B_T = Matrix3.transpose(B, btScratch);
  13007. // Get the scaling matrix and its inverse.
  13008. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  13009. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  13010. var C = cScratch;
  13011. C[0] = 0.0;
  13012. C[1] = -direction.z;
  13013. C[2] = direction.y;
  13014. C[3] = direction.z;
  13015. C[4] = 0.0;
  13016. C[5] = -direction.x;
  13017. C[6] = -direction.y;
  13018. C[7] = direction.x;
  13019. C[8] = 0.0;
  13020. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  13021. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  13022. var b = Matrix3.multiplyByVector(temp, position, bCart);
  13023. // Solve for the solutions to the expression in standard form:
  13024. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  13025. var s;
  13026. var altitude;
  13027. var length = solutions.length;
  13028. if (length > 0) {
  13029. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  13030. var maximumValue = Number.NEGATIVE_INFINITY;
  13031. for ( var i = 0; i < length; ++i) {
  13032. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  13033. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  13034. var dotProduct = Cartesian3.dot(v, direction);
  13035. if (dotProduct > maximumValue) {
  13036. maximumValue = dotProduct;
  13037. closest = Cartesian3.clone(s, closest);
  13038. }
  13039. }
  13040. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  13041. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  13042. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  13043. altitude = intersects ? -altitude : altitude;
  13044. surfacePoint.height = altitude;
  13045. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  13046. }
  13047. return undefined;
  13048. };
  13049. var lineSegmentPlaneDifference = new Cartesian3();
  13050. /**
  13051. * Computes the intersection of a line segment and a plane.
  13052. *
  13053. * @param {Cartesian3} endPoint0 An end point of the line segment.
  13054. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  13055. * @param {Plane} plane The plane.
  13056. * @param {Cartesian3} [result] The object onto which to store the result.
  13057. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  13058. *
  13059. * @example
  13060. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13061. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13062. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13063. *
  13064. * var p0 = new Cesium.Cartesian3(...);
  13065. * var p1 = new Cesium.Cartesian3(...);
  13066. *
  13067. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  13068. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  13069. */
  13070. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  13071. if (!defined(endPoint0)) {
  13072. throw new DeveloperError('endPoint0 is required.');
  13073. }
  13074. if (!defined(endPoint1)) {
  13075. throw new DeveloperError('endPoint1 is required.');
  13076. }
  13077. if (!defined(plane)) {
  13078. throw new DeveloperError('plane is required.');
  13079. }
  13080. if (!defined(result)) {
  13081. result = new Cartesian3();
  13082. }
  13083. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  13084. var normal = plane.normal;
  13085. var nDotDiff = Cartesian3.dot(normal, difference);
  13086. // check if the segment and plane are parallel
  13087. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  13088. return undefined;
  13089. }
  13090. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  13091. var t = -(plane.distance + nDotP0) / nDotDiff;
  13092. // intersection only if t is in [0, 1]
  13093. if (t < 0.0 || t > 1.0) {
  13094. return undefined;
  13095. }
  13096. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  13097. Cartesian3.multiplyByScalar(difference, t, result);
  13098. Cartesian3.add(endPoint0, result, result);
  13099. return result;
  13100. };
  13101. /**
  13102. * Computes the intersection of a triangle and a plane
  13103. *
  13104. * @param {Cartesian3} p0 First point of the triangle
  13105. * @param {Cartesian3} p1 Second point of the triangle
  13106. * @param {Cartesian3} p2 Third point of the triangle
  13107. * @param {Plane} plane Intersection plane
  13108. * @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)
  13109. *
  13110. * @example
  13111. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13112. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13113. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13114. *
  13115. * var p0 = new Cesium.Cartesian3(...);
  13116. * var p1 = new Cesium.Cartesian3(...);
  13117. * var p2 = new Cesium.Cartesian3(...);
  13118. *
  13119. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  13120. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  13121. */
  13122. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  13123. if ((!defined(p0)) ||
  13124. (!defined(p1)) ||
  13125. (!defined(p2)) ||
  13126. (!defined(plane))) {
  13127. throw new DeveloperError('p0, p1, p2, and plane are required.');
  13128. }
  13129. var planeNormal = plane.normal;
  13130. var planeD = plane.distance;
  13131. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  13132. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  13133. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  13134. // Given these dots products, the calls to lineSegmentPlaneIntersection
  13135. // always have defined results.
  13136. var numBehind = 0;
  13137. numBehind += p0Behind ? 1 : 0;
  13138. numBehind += p1Behind ? 1 : 0;
  13139. numBehind += p2Behind ? 1 : 0;
  13140. var u1, u2;
  13141. if (numBehind === 1 || numBehind === 2) {
  13142. u1 = new Cartesian3();
  13143. u2 = new Cartesian3();
  13144. }
  13145. if (numBehind === 1) {
  13146. if (p0Behind) {
  13147. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  13148. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  13149. return {
  13150. positions : [p0, p1, p2, u1, u2 ],
  13151. indices : [
  13152. // Behind
  13153. 0, 3, 4,
  13154. // In front
  13155. 1, 2, 4,
  13156. 1, 4, 3
  13157. ]
  13158. };
  13159. } else if (p1Behind) {
  13160. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  13161. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  13162. return {
  13163. positions : [p0, p1, p2, u1, u2 ],
  13164. indices : [
  13165. // Behind
  13166. 1, 3, 4,
  13167. // In front
  13168. 2, 0, 4,
  13169. 2, 4, 3
  13170. ]
  13171. };
  13172. } else if (p2Behind) {
  13173. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  13174. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  13175. return {
  13176. positions : [p0, p1, p2, u1, u2 ],
  13177. indices : [
  13178. // Behind
  13179. 2, 3, 4,
  13180. // In front
  13181. 0, 1, 4,
  13182. 0, 4, 3
  13183. ]
  13184. };
  13185. }
  13186. } else if (numBehind === 2) {
  13187. if (!p0Behind) {
  13188. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  13189. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  13190. return {
  13191. positions : [p0, p1, p2, u1, u2 ],
  13192. indices : [
  13193. // Behind
  13194. 1, 2, 4,
  13195. 1, 4, 3,
  13196. // In front
  13197. 0, 3, 4
  13198. ]
  13199. };
  13200. } else if (!p1Behind) {
  13201. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  13202. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  13203. return {
  13204. positions : [p0, p1, p2, u1, u2 ],
  13205. indices : [
  13206. // Behind
  13207. 2, 0, 4,
  13208. 2, 4, 3,
  13209. // In front
  13210. 1, 3, 4
  13211. ]
  13212. };
  13213. } else if (!p2Behind) {
  13214. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  13215. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  13216. return {
  13217. positions : [p0, p1, p2, u1, u2 ],
  13218. indices : [
  13219. // Behind
  13220. 0, 1, 4,
  13221. 0, 4, 3,
  13222. // In front
  13223. 2, 3, 4
  13224. ]
  13225. };
  13226. }
  13227. }
  13228. // if numBehind is 3, the triangle is completely behind the plane;
  13229. // otherwise, it is completely in front (numBehind is 0).
  13230. return undefined;
  13231. };
  13232. return IntersectionTests;
  13233. });
  13234. /*global define*/
  13235. define('Core/Plane',[
  13236. './Cartesian3',
  13237. './defined',
  13238. './DeveloperError',
  13239. './freezeObject'
  13240. ], function(
  13241. Cartesian3,
  13242. defined,
  13243. DeveloperError,
  13244. freezeObject) {
  13245. 'use strict';
  13246. /**
  13247. * A plane in Hessian Normal Form defined by
  13248. * <pre>
  13249. * ax + by + cz + d = 0
  13250. * </pre>
  13251. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  13252. * <code>distance</code> to the plane, and (x, y, z) is any point on
  13253. * the plane.
  13254. *
  13255. * @alias Plane
  13256. * @constructor
  13257. *
  13258. * @param {Cartesian3} normal The plane's normal (normalized).
  13259. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  13260. * <code>distance</code> determines which side of the plane the origin
  13261. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13262. * in the direction of the normal; if negative, the origin is in the half-space
  13263. * opposite to the normal; if zero, the plane passes through the origin.
  13264. *
  13265. * @example
  13266. * // The plane x=0
  13267. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  13268. */
  13269. function Plane(normal, distance) {
  13270. if (!defined(normal)) {
  13271. throw new DeveloperError('normal is required.');
  13272. }
  13273. if (!defined(distance)) {
  13274. throw new DeveloperError('distance is required.');
  13275. }
  13276. /**
  13277. * The plane's normal.
  13278. *
  13279. * @type {Cartesian3}
  13280. */
  13281. this.normal = Cartesian3.clone(normal);
  13282. /**
  13283. * The shortest distance from the origin to the plane. The sign of
  13284. * <code>distance</code> determines which side of the plane the origin
  13285. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13286. * in the direction of the normal; if negative, the origin is in the half-space
  13287. * opposite to the normal; if zero, the plane passes through the origin.
  13288. *
  13289. * @type {Number}
  13290. */
  13291. this.distance = distance;
  13292. }
  13293. /**
  13294. * Creates a plane from a normal and a point on the plane.
  13295. *
  13296. * @param {Cartesian3} point The point on the plane.
  13297. * @param {Cartesian3} normal The plane's normal (normalized).
  13298. * @param {Plane} [result] The object onto which to store the result.
  13299. * @returns {Plane} A new plane instance or the modified result parameter.
  13300. *
  13301. * @example
  13302. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  13303. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  13304. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  13305. */
  13306. Plane.fromPointNormal = function(point, normal, result) {
  13307. if (!defined(point)) {
  13308. throw new DeveloperError('point is required.');
  13309. }
  13310. if (!defined(normal)) {
  13311. throw new DeveloperError('normal is required.');
  13312. }
  13313. var distance = -Cartesian3.dot(normal, point);
  13314. if (!defined(result)) {
  13315. return new Plane(normal, distance);
  13316. }
  13317. Cartesian3.clone(normal, result.normal);
  13318. result.distance = distance;
  13319. return result;
  13320. };
  13321. var scratchNormal = new Cartesian3();
  13322. /**
  13323. * Creates a plane from the general equation
  13324. *
  13325. * @param {Cartesian4} coefficients The plane's normal (normalized).
  13326. * @param {Plane} [result] The object onto which to store the result.
  13327. * @returns {Plane} A new plane instance or the modified result parameter.
  13328. */
  13329. Plane.fromCartesian4 = function(coefficients, result) {
  13330. if (!defined(coefficients)) {
  13331. throw new DeveloperError('coefficients is required.');
  13332. }
  13333. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  13334. var distance = coefficients.w;
  13335. if (!defined(result)) {
  13336. return new Plane(normal, distance);
  13337. } else {
  13338. Cartesian3.clone(normal, result.normal);
  13339. result.distance = distance;
  13340. return result;
  13341. }
  13342. };
  13343. /**
  13344. * Computes the signed shortest distance of a point to a plane.
  13345. * The sign of the distance determines which side of the plane the point
  13346. * is on. If the distance is positive, the point is in the half-space
  13347. * in the direction of the normal; if negative, the point is in the half-space
  13348. * opposite to the normal; if zero, the plane passes through the point.
  13349. *
  13350. * @param {Plane} plane The plane.
  13351. * @param {Cartesian3} point The point.
  13352. * @returns {Number} The signed shortest distance of the point to the plane.
  13353. */
  13354. Plane.getPointDistance = function(plane, point) {
  13355. if (!defined(plane)) {
  13356. throw new DeveloperError('plane is required.');
  13357. }
  13358. if (!defined(point)) {
  13359. throw new DeveloperError('point is required.');
  13360. }
  13361. return Cartesian3.dot(plane.normal, point) + plane.distance;
  13362. };
  13363. /**
  13364. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  13365. *
  13366. * @type {Plane}
  13367. * @constant
  13368. */
  13369. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  13370. /**
  13371. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  13372. *
  13373. * @type {Plane}
  13374. * @constant
  13375. */
  13376. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  13377. /**
  13378. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  13379. *
  13380. * @type {Plane}
  13381. * @constant
  13382. */
  13383. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  13384. return Plane;
  13385. });
  13386. /**
  13387. @license
  13388. when.js - https://github.com/cujojs/when
  13389. MIT License (c) copyright B Cavalier & J Hann
  13390. * A lightweight CommonJS Promises/A and when() implementation
  13391. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  13392. *
  13393. * Licensed under the MIT License at:
  13394. * http://www.opensource.org/licenses/mit-license.php
  13395. *
  13396. * @version 1.7.1
  13397. */
  13398. (function(define) { 'use strict';
  13399. define('ThirdParty/when',[],function () {
  13400. var reduceArray, slice, undef;
  13401. //
  13402. // Public API
  13403. //
  13404. when.defer = defer; // Create a deferred
  13405. when.resolve = resolve; // Create a resolved promise
  13406. when.reject = reject; // Create a rejected promise
  13407. when.join = join; // Join 2 or more promises
  13408. when.all = all; // Resolve a list of promises
  13409. when.map = map; // Array.map() for promises
  13410. when.reduce = reduce; // Array.reduce() for promises
  13411. when.any = any; // One-winner race
  13412. when.some = some; // Multi-winner race
  13413. when.chain = chain; // Make a promise trigger another resolver
  13414. when.isPromise = isPromise; // Determine if a thing is a promise
  13415. /**
  13416. * Register an observer for a promise or immediate value.
  13417. *
  13418. * @param {*} promiseOrValue
  13419. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  13420. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  13421. * will be invoked immediately.
  13422. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  13423. * rejected.
  13424. * @param {function?} [onProgress] callback to be called when progress updates
  13425. * are issued for promiseOrValue.
  13426. * @returns {Promise} a new {@link Promise} that will complete with the return
  13427. * value of callback or errback or the completion value of promiseOrValue if
  13428. * callback and/or errback is not supplied.
  13429. */
  13430. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  13431. // Get a trusted promise for the input promiseOrValue, and then
  13432. // register promise handlers
  13433. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  13434. }
  13435. /**
  13436. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  13437. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  13438. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  13439. *
  13440. * @param {*} promiseOrValue
  13441. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  13442. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  13443. * whose resolution value is:
  13444. * * the resolution value of promiseOrValue if it's a foreign promise, or
  13445. * * promiseOrValue if it's a value
  13446. */
  13447. function resolve(promiseOrValue) {
  13448. var promise, deferred;
  13449. if(promiseOrValue instanceof Promise) {
  13450. // It's a when.js promise, so we trust it
  13451. promise = promiseOrValue;
  13452. } else {
  13453. // It's not a when.js promise. See if it's a foreign promise or a value.
  13454. if(isPromise(promiseOrValue)) {
  13455. // It's a thenable, but we don't know where it came from, so don't trust
  13456. // its implementation entirely. Introduce a trusted middleman when.js promise
  13457. deferred = defer();
  13458. // IMPORTANT: This is the only place when.js should ever call .then() on an
  13459. // untrusted promise. Don't expose the return value to the untrusted promise
  13460. promiseOrValue.then(
  13461. function(value) { deferred.resolve(value); },
  13462. function(reason) { deferred.reject(reason); },
  13463. function(update) { deferred.progress(update); }
  13464. );
  13465. promise = deferred.promise;
  13466. } else {
  13467. // It's a value, not a promise. Create a resolved promise for it.
  13468. promise = fulfilled(promiseOrValue);
  13469. }
  13470. }
  13471. return promise;
  13472. }
  13473. /**
  13474. * Returns a rejected promise for the supplied promiseOrValue. The returned
  13475. * promise will be rejected with:
  13476. * - promiseOrValue, if it is a value, or
  13477. * - if promiseOrValue is a promise
  13478. * - promiseOrValue's value after it is fulfilled
  13479. * - promiseOrValue's reason after it is rejected
  13480. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  13481. * @returns {Promise} rejected {@link Promise}
  13482. */
  13483. function reject(promiseOrValue) {
  13484. return when(promiseOrValue, rejected);
  13485. }
  13486. /**
  13487. * Trusted Promise constructor. A Promise created from this constructor is
  13488. * a trusted when.js promise. Any other duck-typed promise is considered
  13489. * untrusted.
  13490. * @constructor
  13491. * @name Promise
  13492. */
  13493. function Promise(then) {
  13494. this.then = then;
  13495. }
  13496. Promise.prototype = {
  13497. /**
  13498. * Register a callback that will be called when a promise is
  13499. * fulfilled or rejected. Optionally also register a progress handler.
  13500. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  13501. * @param {function?} [onFulfilledOrRejected]
  13502. * @param {function?} [onProgress]
  13503. * @returns {Promise}
  13504. */
  13505. always: function(onFulfilledOrRejected, onProgress) {
  13506. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  13507. },
  13508. /**
  13509. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  13510. * @param {function?} onRejected
  13511. * @returns {Promise}
  13512. */
  13513. otherwise: function(onRejected) {
  13514. return this.then(undef, onRejected);
  13515. },
  13516. /**
  13517. * Shortcut for .then(function() { return value; })
  13518. * @param {*} value
  13519. * @returns {Promise} a promise that:
  13520. * - is fulfilled if value is not a promise, or
  13521. * - if value is a promise, will fulfill with its value, or reject
  13522. * with its reason.
  13523. */
  13524. yield: function(value) {
  13525. return this.then(function() {
  13526. return value;
  13527. });
  13528. },
  13529. /**
  13530. * Assumes that this promise will fulfill with an array, and arranges
  13531. * for the onFulfilled to be called with the array as its argument list
  13532. * i.e. onFulfilled.spread(undefined, array).
  13533. * @param {function} onFulfilled function to receive spread arguments
  13534. * @returns {Promise}
  13535. */
  13536. spread: function(onFulfilled) {
  13537. return this.then(function(array) {
  13538. // array may contain promises, so resolve its contents.
  13539. return all(array, function(array) {
  13540. return onFulfilled.apply(undef, array);
  13541. });
  13542. });
  13543. }
  13544. };
  13545. /**
  13546. * Create an already-resolved promise for the supplied value
  13547. * @private
  13548. *
  13549. * @param {*} value
  13550. * @returns {Promise} fulfilled promise
  13551. */
  13552. function fulfilled(value) {
  13553. var p = new Promise(function(onFulfilled) {
  13554. // TODO: Promises/A+ check typeof onFulfilled
  13555. try {
  13556. return resolve(onFulfilled ? onFulfilled(value) : value);
  13557. } catch(e) {
  13558. return rejected(e);
  13559. }
  13560. });
  13561. return p;
  13562. }
  13563. /**
  13564. * Create an already-rejected {@link Promise} with the supplied
  13565. * rejection reason.
  13566. * @private
  13567. *
  13568. * @param {*} reason
  13569. * @returns {Promise} rejected promise
  13570. */
  13571. function rejected(reason) {
  13572. var p = new Promise(function(_, onRejected) {
  13573. // TODO: Promises/A+ check typeof onRejected
  13574. try {
  13575. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  13576. } catch(e) {
  13577. return rejected(e);
  13578. }
  13579. });
  13580. return p;
  13581. }
  13582. /**
  13583. * Creates a new, Deferred with fully isolated resolver and promise parts,
  13584. * either or both of which may be given out safely to consumers.
  13585. * The Deferred itself has the full API: resolve, reject, progress, and
  13586. * then. The resolver has resolve, reject, and progress. The promise
  13587. * only has then.
  13588. *
  13589. * @returns {Deferred}
  13590. */
  13591. function defer() {
  13592. var deferred, promise, handlers, progressHandlers,
  13593. _then, _progress, _resolve;
  13594. /**
  13595. * The promise for the new deferred
  13596. * @type {Promise}
  13597. */
  13598. promise = new Promise(then);
  13599. /**
  13600. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  13601. * @class Deferred
  13602. * @name Deferred
  13603. */
  13604. deferred = {
  13605. then: then, // DEPRECATED: use deferred.promise.then
  13606. resolve: promiseResolve,
  13607. reject: promiseReject,
  13608. // TODO: Consider renaming progress() to notify()
  13609. progress: promiseProgress,
  13610. promise: promise,
  13611. resolver: {
  13612. resolve: promiseResolve,
  13613. reject: promiseReject,
  13614. progress: promiseProgress
  13615. }
  13616. };
  13617. handlers = [];
  13618. progressHandlers = [];
  13619. /**
  13620. * Pre-resolution then() that adds the supplied callback, errback, and progback
  13621. * functions to the registered listeners
  13622. * @private
  13623. *
  13624. * @param {function?} [onFulfilled] resolution handler
  13625. * @param {function?} [onRejected] rejection handler
  13626. * @param {function?} [onProgress] progress handler
  13627. */
  13628. _then = function(onFulfilled, onRejected, onProgress) {
  13629. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  13630. var deferred, progressHandler;
  13631. deferred = defer();
  13632. progressHandler = typeof onProgress === 'function'
  13633. ? function(update) {
  13634. try {
  13635. // Allow progress handler to transform progress event
  13636. deferred.progress(onProgress(update));
  13637. } catch(e) {
  13638. // Use caught value as progress
  13639. deferred.progress(e);
  13640. }
  13641. }
  13642. : function(update) { deferred.progress(update); };
  13643. handlers.push(function(promise) {
  13644. promise.then(onFulfilled, onRejected)
  13645. .then(deferred.resolve, deferred.reject, progressHandler);
  13646. });
  13647. progressHandlers.push(progressHandler);
  13648. return deferred.promise;
  13649. };
  13650. /**
  13651. * Issue a progress event, notifying all progress listeners
  13652. * @private
  13653. * @param {*} update progress event payload to pass to all listeners
  13654. */
  13655. _progress = function(update) {
  13656. processQueue(progressHandlers, update);
  13657. return update;
  13658. };
  13659. /**
  13660. * Transition from pre-resolution state to post-resolution state, notifying
  13661. * all listeners of the resolution or rejection
  13662. * @private
  13663. * @param {*} value the value of this deferred
  13664. */
  13665. _resolve = function(value) {
  13666. value = resolve(value);
  13667. // Replace _then with one that directly notifies with the result.
  13668. _then = value.then;
  13669. // Replace _resolve so that this Deferred can only be resolved once
  13670. _resolve = resolve;
  13671. // Make _progress a noop, to disallow progress for the resolved promise.
  13672. _progress = noop;
  13673. // Notify handlers
  13674. processQueue(handlers, value);
  13675. // Free progressHandlers array since we'll never issue progress events
  13676. progressHandlers = handlers = undef;
  13677. return value;
  13678. };
  13679. return deferred;
  13680. /**
  13681. * Wrapper to allow _then to be replaced safely
  13682. * @param {function?} [onFulfilled] resolution handler
  13683. * @param {function?} [onRejected] rejection handler
  13684. * @param {function?} [onProgress] progress handler
  13685. * @returns {Promise} new promise
  13686. */
  13687. function then(onFulfilled, onRejected, onProgress) {
  13688. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  13689. return _then(onFulfilled, onRejected, onProgress);
  13690. }
  13691. /**
  13692. * Wrapper to allow _resolve to be replaced
  13693. */
  13694. function promiseResolve(val) {
  13695. return _resolve(val);
  13696. }
  13697. /**
  13698. * Wrapper to allow _reject to be replaced
  13699. */
  13700. function promiseReject(err) {
  13701. return _resolve(rejected(err));
  13702. }
  13703. /**
  13704. * Wrapper to allow _progress to be replaced
  13705. */
  13706. function promiseProgress(update) {
  13707. return _progress(update);
  13708. }
  13709. }
  13710. /**
  13711. * Determines if promiseOrValue is a promise or not. Uses the feature
  13712. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  13713. * promiseOrValue is a promise.
  13714. *
  13715. * @param {*} promiseOrValue anything
  13716. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  13717. */
  13718. function isPromise(promiseOrValue) {
  13719. return promiseOrValue && typeof promiseOrValue.then === 'function';
  13720. }
  13721. /**
  13722. * Initiates a competitive race, returning a promise that will resolve when
  13723. * howMany of the supplied promisesOrValues have resolved, or will reject when
  13724. * it becomes impossible for howMany to resolve, for example, when
  13725. * (promisesOrValues.length - howMany) + 1 input promises reject.
  13726. *
  13727. * @param {Array} promisesOrValues array of anything, may contain a mix
  13728. * of promises and values
  13729. * @param howMany {number} number of promisesOrValues to resolve
  13730. * @param {function?} [onFulfilled] resolution handler
  13731. * @param {function?} [onRejected] rejection handler
  13732. * @param {function?} [onProgress] progress handler
  13733. * @returns {Promise} promise that will resolve to an array of howMany values that
  13734. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  13735. * rejection reasons.
  13736. */
  13737. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  13738. checkCallbacks(2, arguments);
  13739. return when(promisesOrValues, function(promisesOrValues) {
  13740. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  13741. len = promisesOrValues.length >>> 0;
  13742. toResolve = Math.max(0, Math.min(howMany, len));
  13743. values = [];
  13744. toReject = (len - toResolve) + 1;
  13745. reasons = [];
  13746. deferred = defer();
  13747. // No items in the input, resolve immediately
  13748. if (!toResolve) {
  13749. deferred.resolve(values);
  13750. } else {
  13751. progress = deferred.progress;
  13752. rejectOne = function(reason) {
  13753. reasons.push(reason);
  13754. if(!--toReject) {
  13755. fulfillOne = rejectOne = noop;
  13756. deferred.reject(reasons);
  13757. }
  13758. };
  13759. fulfillOne = function(val) {
  13760. // This orders the values based on promise resolution order
  13761. // Another strategy would be to use the original position of
  13762. // the corresponding promise.
  13763. values.push(val);
  13764. if (!--toResolve) {
  13765. fulfillOne = rejectOne = noop;
  13766. deferred.resolve(values);
  13767. }
  13768. };
  13769. for(i = 0; i < len; ++i) {
  13770. if(i in promisesOrValues) {
  13771. when(promisesOrValues[i], fulfiller, rejecter, progress);
  13772. }
  13773. }
  13774. }
  13775. return deferred.then(onFulfilled, onRejected, onProgress);
  13776. function rejecter(reason) {
  13777. rejectOne(reason);
  13778. }
  13779. function fulfiller(val) {
  13780. fulfillOne(val);
  13781. }
  13782. });
  13783. }
  13784. /**
  13785. * Initiates a competitive race, returning a promise that will resolve when
  13786. * any one of the supplied promisesOrValues has resolved or will reject when
  13787. * *all* promisesOrValues have rejected.
  13788. *
  13789. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  13790. * of {@link Promise}s and values
  13791. * @param {function?} [onFulfilled] resolution handler
  13792. * @param {function?} [onRejected] rejection handler
  13793. * @param {function?} [onProgress] progress handler
  13794. * @returns {Promise} promise that will resolve to the value that resolved first, or
  13795. * will reject with an array of all rejected inputs.
  13796. */
  13797. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  13798. function unwrapSingleResult(val) {
  13799. return onFulfilled ? onFulfilled(val[0]) : val[0];
  13800. }
  13801. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  13802. }
  13803. /**
  13804. * Return a promise that will resolve only once all the supplied promisesOrValues
  13805. * have resolved. The resolution value of the returned promise will be an array
  13806. * containing the resolution values of each of the promisesOrValues.
  13807. * @memberOf when
  13808. *
  13809. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  13810. * of {@link Promise}s and values
  13811. * @param {function?} [onFulfilled] resolution handler
  13812. * @param {function?} [onRejected] rejection handler
  13813. * @param {function?} [onProgress] progress handler
  13814. * @returns {Promise}
  13815. */
  13816. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  13817. checkCallbacks(1, arguments);
  13818. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  13819. }
  13820. /**
  13821. * Joins multiple promises into a single returned promise.
  13822. * @returns {Promise} a promise that will fulfill when *all* the input promises
  13823. * have fulfilled, or will reject when *any one* of the input promises rejects.
  13824. */
  13825. function join(/* ...promises */) {
  13826. return map(arguments, identity);
  13827. }
  13828. /**
  13829. * Traditional map function, similar to `Array.prototype.map()`, but allows
  13830. * input to contain {@link Promise}s and/or values, and mapFunc may return
  13831. * either a value or a {@link Promise}
  13832. *
  13833. * @param {Array|Promise} promise array of anything, may contain a mix
  13834. * of {@link Promise}s and values
  13835. * @param {function} mapFunc mapping function mapFunc(value) which may return
  13836. * either a {@link Promise} or value
  13837. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  13838. * the mapped output values.
  13839. */
  13840. function map(promise, mapFunc) {
  13841. return when(promise, function(array) {
  13842. var results, len, toResolve, resolve, i, d;
  13843. // Since we know the resulting length, we can preallocate the results
  13844. // array to avoid array expansions.
  13845. toResolve = len = array.length >>> 0;
  13846. results = [];
  13847. d = defer();
  13848. if(!toResolve) {
  13849. d.resolve(results);
  13850. } else {
  13851. resolve = function resolveOne(item, i) {
  13852. when(item, mapFunc).then(function(mapped) {
  13853. results[i] = mapped;
  13854. if(!--toResolve) {
  13855. d.resolve(results);
  13856. }
  13857. }, d.reject);
  13858. };
  13859. // Since mapFunc may be async, get all invocations of it into flight
  13860. for(i = 0; i < len; i++) {
  13861. if(i in array) {
  13862. resolve(array[i], i);
  13863. } else {
  13864. --toResolve;
  13865. }
  13866. }
  13867. }
  13868. return d.promise;
  13869. });
  13870. }
  13871. /**
  13872. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  13873. * input may contain promises and/or values, and reduceFunc
  13874. * may return either a value or a promise, *and* initialValue may
  13875. * be a promise for the starting value.
  13876. *
  13877. * @param {Array|Promise} promise array or promise for an array of anything,
  13878. * may contain a mix of promises and values.
  13879. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  13880. * where total is the total number of items being reduced, and will be the same
  13881. * in each call to reduceFunc.
  13882. * @returns {Promise} that will resolve to the final reduced value
  13883. */
  13884. function reduce(promise, reduceFunc /*, initialValue */) {
  13885. var args = slice.call(arguments, 1);
  13886. return when(promise, function(array) {
  13887. var total;
  13888. total = array.length;
  13889. // Wrap the supplied reduceFunc with one that handles promises and then
  13890. // delegates to the supplied.
  13891. args[0] = function (current, val, i) {
  13892. return when(current, function (c) {
  13893. return when(val, function (value) {
  13894. return reduceFunc(c, value, i, total);
  13895. });
  13896. });
  13897. };
  13898. return reduceArray.apply(array, args);
  13899. });
  13900. }
  13901. /**
  13902. * Ensure that resolution of promiseOrValue will trigger resolver with the
  13903. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  13904. *
  13905. * @param promiseOrValue
  13906. * @param {Object} resolver
  13907. * @param {function} resolver.resolve
  13908. * @param {function} resolver.reject
  13909. * @param {*} [resolveValue]
  13910. * @returns {Promise}
  13911. */
  13912. function chain(promiseOrValue, resolver, resolveValue) {
  13913. var useResolveValue = arguments.length > 2;
  13914. return when(promiseOrValue,
  13915. function(val) {
  13916. val = useResolveValue ? resolveValue : val;
  13917. resolver.resolve(val);
  13918. return val;
  13919. },
  13920. function(reason) {
  13921. resolver.reject(reason);
  13922. return rejected(reason);
  13923. },
  13924. resolver.progress
  13925. );
  13926. }
  13927. //
  13928. // Utility functions
  13929. //
  13930. /**
  13931. * Apply all functions in queue to value
  13932. * @param {Array} queue array of functions to execute
  13933. * @param {*} value argument passed to each function
  13934. */
  13935. function processQueue(queue, value) {
  13936. var handler, i = 0;
  13937. while (handler = queue[i++]) {
  13938. handler(value);
  13939. }
  13940. }
  13941. /**
  13942. * Helper that checks arrayOfCallbacks to ensure that each element is either
  13943. * a function, or null or undefined.
  13944. * @private
  13945. * @param {number} start index at which to start checking items in arrayOfCallbacks
  13946. * @param {Array} arrayOfCallbacks array to check
  13947. * @throws {Error} if any element of arrayOfCallbacks is something other than
  13948. * a functions, null, or undefined.
  13949. */
  13950. function checkCallbacks(start, arrayOfCallbacks) {
  13951. // TODO: Promises/A+ update type checking and docs
  13952. var arg, i = arrayOfCallbacks.length;
  13953. while(i > start) {
  13954. arg = arrayOfCallbacks[--i];
  13955. if (arg != null && typeof arg != 'function') {
  13956. throw new Error('arg '+i+' must be a function');
  13957. }
  13958. }
  13959. }
  13960. /**
  13961. * No-Op function used in method replacement
  13962. * @private
  13963. */
  13964. function noop() {}
  13965. slice = [].slice;
  13966. // ES5 reduce implementation if native not available
  13967. // See: http://es5.github.com/#x15.4.4.21 as there are many
  13968. // specifics and edge cases.
  13969. reduceArray = [].reduce ||
  13970. function(reduceFunc /*, initialValue */) {
  13971. /*jshint maxcomplexity: 7*/
  13972. // ES5 dictates that reduce.length === 1
  13973. // This implementation deviates from ES5 spec in the following ways:
  13974. // 1. It does not check if reduceFunc is a Callable
  13975. var arr, args, reduced, len, i;
  13976. i = 0;
  13977. // This generates a jshint warning, despite being valid
  13978. // "Missing 'new' prefix when invoking a constructor."
  13979. // See https://github.com/jshint/jshint/issues/392
  13980. arr = Object(this);
  13981. len = arr.length >>> 0;
  13982. args = arguments;
  13983. // If no initialValue, use first item of array (we know length !== 0 here)
  13984. // and adjust i to start at second item
  13985. if(args.length <= 1) {
  13986. // Skip to the first real element in the array
  13987. for(;;) {
  13988. if(i in arr) {
  13989. reduced = arr[i++];
  13990. break;
  13991. }
  13992. // If we reached the end of the array without finding any real
  13993. // elements, it's a TypeError
  13994. if(++i >= len) {
  13995. throw new TypeError();
  13996. }
  13997. }
  13998. } else {
  13999. // If initialValue provided, use it
  14000. reduced = args[1];
  14001. }
  14002. // Do the actual reduce
  14003. for(;i < len; ++i) {
  14004. // Skip holes
  14005. if(i in arr) {
  14006. reduced = reduceFunc(reduced, arr[i], i, arr);
  14007. }
  14008. }
  14009. return reduced;
  14010. };
  14011. function identity(x) {
  14012. return x;
  14013. }
  14014. return when;
  14015. });
  14016. })(typeof define == 'function' && define.amd
  14017. ? define
  14018. : function (factory) { typeof exports === 'object'
  14019. ? (module.exports = factory())
  14020. : (this.when = factory());
  14021. }
  14022. // Boilerplate for AMD, Node, and browser global
  14023. );
  14024. /*global define*/
  14025. define('Core/oneTimeWarning',[
  14026. './defaultValue',
  14027. './defined',
  14028. './DeveloperError'
  14029. ], function(
  14030. defaultValue,
  14031. defined,
  14032. DeveloperError) {
  14033. "use strict";
  14034. var warnings = {};
  14035. /**
  14036. * Logs a one time message to the console. Use this function instead of
  14037. * <code>console.log</code> directly since this does not log duplicate messages
  14038. * unless it is called from multiple workers.
  14039. *
  14040. * @exports oneTimeWarning
  14041. *
  14042. * @param {String} identifier The unique identifier for this warning.
  14043. * @param {String} [message=identifier] The message to log to the console.
  14044. *
  14045. * @example
  14046. * for(var i=0;i<foo.length;++i) {
  14047. * if (!defined(foo[i].bar)) {
  14048. * // Something that can be recovered from but may happen a lot
  14049. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  14050. * foo[i].bar = 0;
  14051. * // ...
  14052. * }
  14053. * }
  14054. *
  14055. * @private
  14056. */
  14057. function oneTimeWarning(identifier, message) {
  14058. if (!defined(identifier)) {
  14059. throw new DeveloperError('identifier is required.');
  14060. }
  14061. if (!defined(warnings[identifier])) {
  14062. warnings[identifier] = true;
  14063. console.log(defaultValue(message, identifier));
  14064. }
  14065. }
  14066. 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.';
  14067. return oneTimeWarning;
  14068. });
  14069. /*global define*/
  14070. define('Core/deprecationWarning',[
  14071. './defined',
  14072. './DeveloperError',
  14073. './oneTimeWarning'
  14074. ], function(
  14075. defined,
  14076. DeveloperError,
  14077. oneTimeWarning) {
  14078. 'use strict';
  14079. /**
  14080. * Logs a deprecation message to the console. Use this function instead of
  14081. * <code>console.log</code> directly since this does not log duplicate messages
  14082. * unless it is called from multiple workers.
  14083. *
  14084. * @exports deprecationWarning
  14085. *
  14086. * @param {String} identifier The unique identifier for this deprecated API.
  14087. * @param {String} message The message to log to the console.
  14088. *
  14089. * @example
  14090. * // Deprecated function or class
  14091. * function Foo() {
  14092. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  14093. * // ...
  14094. * }
  14095. *
  14096. * // Deprecated function
  14097. * Bar.prototype.func = function() {
  14098. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  14099. * // ...
  14100. * };
  14101. *
  14102. * // Deprecated property
  14103. * defineProperties(Bar.prototype, {
  14104. * prop : {
  14105. * get : function() {
  14106. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14107. * // ...
  14108. * },
  14109. * set : function(value) {
  14110. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14111. * // ...
  14112. * }
  14113. * }
  14114. * });
  14115. *
  14116. * @private
  14117. */
  14118. function deprecationWarning(identifier, message) {
  14119. if (!defined(identifier) || !defined(message)) {
  14120. throw new DeveloperError('identifier and message are required.');
  14121. }
  14122. oneTimeWarning(identifier, message);
  14123. }
  14124. return deprecationWarning;
  14125. });
  14126. /*global define*/
  14127. define('Core/binarySearch',[
  14128. './defined',
  14129. './DeveloperError'
  14130. ], function(
  14131. defined,
  14132. DeveloperError) {
  14133. 'use strict';
  14134. /**
  14135. * Finds an item in a sorted array.
  14136. *
  14137. * @exports binarySearch
  14138. *
  14139. * @param {Array} array The sorted array to search.
  14140. * @param {Object} itemToFind The item to find in the array.
  14141. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  14142. * elements in the array.
  14143. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  14144. * does not exist, the return value is a negative number which is the bitwise complement (~)
  14145. * of the index before which the itemToFind should be inserted in order to maintain the
  14146. * sorted order of the array.
  14147. *
  14148. * @example
  14149. * // Create a comparator function to search through an array of numbers.
  14150. * function comparator(a, b) {
  14151. * return a - b;
  14152. * };
  14153. * var numbers = [0, 2, 4, 6, 8];
  14154. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  14155. */
  14156. function binarySearch(array, itemToFind, comparator) {
  14157. if (!defined(array)) {
  14158. throw new DeveloperError('array is required.');
  14159. }
  14160. if (!defined(itemToFind)) {
  14161. throw new DeveloperError('itemToFind is required.');
  14162. }
  14163. if (!defined(comparator)) {
  14164. throw new DeveloperError('comparator is required.');
  14165. }
  14166. var low = 0;
  14167. var high = array.length - 1;
  14168. var i;
  14169. var comparison;
  14170. while (low <= high) {
  14171. i = ~~((low + high) / 2);
  14172. comparison = comparator(array[i], itemToFind);
  14173. if (comparison < 0) {
  14174. low = i + 1;
  14175. continue;
  14176. }
  14177. if (comparison > 0) {
  14178. high = i - 1;
  14179. continue;
  14180. }
  14181. return i;
  14182. }
  14183. return ~(high + 1);
  14184. }
  14185. /**
  14186. * A function used to compare two items while performing a binary search.
  14187. * @callback binarySearch~Comparator
  14188. *
  14189. * @param {Object} a An item in the array.
  14190. * @param {Object} b The item being searched for.
  14191. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  14192. * a positive value if <code>a</code> is greater than <code>b</code>, or
  14193. * 0 if <code>a</code> is equal to <code>b</code>.
  14194. *
  14195. * @example
  14196. * function compareNumbers(a, b) {
  14197. * return a - b;
  14198. * }
  14199. */
  14200. return binarySearch;
  14201. });
  14202. /*global define*/
  14203. define('Core/EarthOrientationParametersSample',[],function() {
  14204. 'use strict';
  14205. /**
  14206. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  14207. *
  14208. * @alias EarthOrientationParametersSample
  14209. * @constructor
  14210. *
  14211. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  14212. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  14213. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14214. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14215. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  14216. *
  14217. * @private
  14218. */
  14219. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  14220. /**
  14221. * The pole wander about the X axis, in radians.
  14222. * @type {Number}
  14223. */
  14224. this.xPoleWander = xPoleWander;
  14225. /**
  14226. * The pole wander about the Y axis, in radians.
  14227. * @type {Number}
  14228. */
  14229. this.yPoleWander = yPoleWander;
  14230. /**
  14231. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14232. * @type {Number}
  14233. */
  14234. this.xPoleOffset = xPoleOffset;
  14235. /**
  14236. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14237. * @type {Number}
  14238. */
  14239. this.yPoleOffset = yPoleOffset;
  14240. /**
  14241. * The difference in time standards, UT1 - UTC, in seconds.
  14242. * @type {Number}
  14243. */
  14244. this.ut1MinusUtc = ut1MinusUtc;
  14245. }
  14246. return EarthOrientationParametersSample;
  14247. });
  14248. /**
  14249. @license
  14250. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  14251. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  14252. php.js is copyright 2012 Kevin van Zonneveld.
  14253. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  14254. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  14255. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  14256. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  14257. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  14258. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  14259. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  14260. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  14261. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  14262. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  14263. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  14264. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  14265. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  14266. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  14267. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  14268. (http://geekfg.blogspot.com), Andrea Giammarchi
  14269. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  14270. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  14271. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  14272. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  14273. Marc Palau, Martin
  14274. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  14275. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  14276. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  14277. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  14278. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  14279. Ariede (http://caioariede.com), Robin, Kankrelune
  14280. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  14281. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  14282. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  14283. David, Aman Gupta, Michael White, Public Domain
  14284. (http://www.json.org/json2.js), Steven Levithan
  14285. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  14286. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  14287. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  14288. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  14289. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  14290. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  14291. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  14292. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  14293. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  14294. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  14295. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  14296. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  14297. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  14298. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  14299. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  14300. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  14301. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  14302. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  14303. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  14304. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  14305. (http://yass.meetcweb.com), Peter-Paul Koch
  14306. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  14307. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  14308. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  14309. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  14310. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  14311. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  14312. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  14313. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  14314. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  14315. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  14316. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  14317. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  14318. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  14319. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  14320. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  14321. (http://www.premasolutions.com/), Philippe Jausions
  14322. (http://pear.php.net/user/jausions), Aidan Lister
  14323. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  14324. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  14325. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  14326. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  14327. (http://www.pedrotainha.com), James, Arnout Kazemier
  14328. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  14329. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  14330. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  14331. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  14332. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  14333. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  14334. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  14335. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  14336. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  14337. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  14338. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  14339. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  14340. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  14341. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  14342. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  14343. (http://benblume.co.uk/), DtTvB
  14344. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  14345. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  14346. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  14347. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  14348. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  14349. Bryan
  14350. Licensed under the MIT (MIT-LICENSE.txt) license.
  14351. Permission is hereby granted, free of charge, to any person obtaining a
  14352. copy of this software and associated documentation files (the
  14353. "Software"), to deal in the Software without restriction, including
  14354. without limitation the rights to use, copy, modify, merge, publish,
  14355. distribute, sublicense, and/or sell copies of the Software, and to
  14356. permit persons to whom the Software is furnished to do so, subject to
  14357. the following conditions:
  14358. The above copyright notice and this permission notice shall be included
  14359. in all copies or substantial portions of the Software.
  14360. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14361. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14362. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  14363. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  14364. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  14365. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  14366. OTHER DEALINGS IN THE SOFTWARE.
  14367. */
  14368. /*global define*/
  14369. define('ThirdParty/sprintf',[],function() {
  14370. function sprintf () {
  14371. // http://kevin.vanzonneveld.net
  14372. // + original by: Ash Searle (http://hexmen.com/blog/)
  14373. // + namespaced by: Michael White (http://getsprink.com)
  14374. // + tweaked by: Jack
  14375. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14376. // + input by: Paulo Freitas
  14377. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14378. // + input by: Brett Zamir (http://brett-zamir.me)
  14379. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14380. // + improved by: Dj
  14381. // + improved by: Allidylls
  14382. // * example 1: sprintf("%01.2f", 123.1);
  14383. // * returns 1: 123.10
  14384. // * example 2: sprintf("[%10s]", 'monkey');
  14385. // * returns 2: '[ monkey]'
  14386. // * example 3: sprintf("[%'#10s]", 'monkey');
  14387. // * returns 3: '[####monkey]'
  14388. // * example 4: sprintf("%d", 123456789012345);
  14389. // * returns 4: '123456789012345'
  14390. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  14391. var a = arguments,
  14392. i = 0,
  14393. format = a[i++];
  14394. // pad()
  14395. var pad = function (str, len, chr, leftJustify) {
  14396. if (!chr) {
  14397. chr = ' ';
  14398. }
  14399. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  14400. return leftJustify ? str + padding : padding + str;
  14401. };
  14402. // justify()
  14403. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  14404. var diff = minWidth - value.length;
  14405. if (diff > 0) {
  14406. if (leftJustify || !zeroPad) {
  14407. value = pad(value, minWidth, customPadChar, leftJustify);
  14408. } else {
  14409. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  14410. }
  14411. }
  14412. return value;
  14413. };
  14414. // formatBaseX()
  14415. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  14416. // Note: casts negative numbers to positive ones
  14417. var number = value >>> 0;
  14418. prefix = prefix && number && {
  14419. '2': '0b',
  14420. '8': '0',
  14421. '16': '0x'
  14422. }[base] || '';
  14423. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  14424. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  14425. };
  14426. // formatString()
  14427. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  14428. if (precision != null) {
  14429. value = value.slice(0, precision);
  14430. }
  14431. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  14432. };
  14433. // doFormat()
  14434. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  14435. var number;
  14436. var prefix;
  14437. var method;
  14438. var textTransform;
  14439. var value;
  14440. if (substring == '%%') {
  14441. return '%';
  14442. }
  14443. // parse flags
  14444. var leftJustify = false,
  14445. positivePrefix = '',
  14446. zeroPad = false,
  14447. prefixBaseX = false,
  14448. customPadChar = ' ';
  14449. var flagsl = flags.length;
  14450. for (var j = 0; flags && j < flagsl; j++) {
  14451. switch (flags.charAt(j)) {
  14452. case ' ':
  14453. positivePrefix = ' ';
  14454. break;
  14455. case '+':
  14456. positivePrefix = '+';
  14457. break;
  14458. case '-':
  14459. leftJustify = true;
  14460. break;
  14461. case "'":
  14462. customPadChar = flags.charAt(j + 1);
  14463. break;
  14464. case '0':
  14465. zeroPad = true;
  14466. break;
  14467. case '#':
  14468. prefixBaseX = true;
  14469. break;
  14470. }
  14471. }
  14472. // parameters may be null, undefined, empty-string or real valued
  14473. // we want to ignore null, undefined and empty-string values
  14474. if (!minWidth) {
  14475. minWidth = 0;
  14476. } else if (minWidth == '*') {
  14477. minWidth = +a[i++];
  14478. } else if (minWidth.charAt(0) == '*') {
  14479. minWidth = +a[minWidth.slice(1, -1)];
  14480. } else {
  14481. minWidth = +minWidth;
  14482. }
  14483. // Note: undocumented perl feature:
  14484. if (minWidth < 0) {
  14485. minWidth = -minWidth;
  14486. leftJustify = true;
  14487. }
  14488. if (!isFinite(minWidth)) {
  14489. throw new Error('sprintf: (minimum-)width must be finite');
  14490. }
  14491. if (!precision) {
  14492. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  14493. } else if (precision == '*') {
  14494. precision = +a[i++];
  14495. } else if (precision.charAt(0) == '*') {
  14496. precision = +a[precision.slice(1, -1)];
  14497. } else {
  14498. precision = +precision;
  14499. }
  14500. // grab value using valueIndex if required?
  14501. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  14502. switch (type) {
  14503. case 's':
  14504. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  14505. case 'c':
  14506. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  14507. case 'b':
  14508. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14509. case 'o':
  14510. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14511. case 'x':
  14512. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14513. case 'X':
  14514. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  14515. case 'u':
  14516. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14517. case 'i':
  14518. case 'd':
  14519. number = +value || 0;
  14520. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  14521. prefix = number < 0 ? '-' : positivePrefix;
  14522. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  14523. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  14524. case 'e':
  14525. case 'E':
  14526. case 'f': // Should handle locales (as per setlocale)
  14527. case 'F':
  14528. case 'g':
  14529. case 'G':
  14530. number = +value;
  14531. prefix = number < 0 ? '-' : positivePrefix;
  14532. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  14533. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  14534. value = prefix + Math.abs(number)[method](precision);
  14535. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  14536. default:
  14537. return substring;
  14538. }
  14539. };
  14540. return format.replace(regex, doFormat);
  14541. }
  14542. return sprintf;
  14543. });
  14544. /*global define*/
  14545. define('Core/GregorianDate',[],function() {
  14546. 'use strict';
  14547. /**
  14548. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  14549. * In addition to submillisecond precision, this object can also represent leap seconds.
  14550. * @alias GregorianDate
  14551. * @constructor
  14552. *
  14553. * @see JulianDate#toGregorianDate
  14554. */
  14555. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  14556. /**
  14557. * Gets or sets the year as a whole number.
  14558. * @type {Number}
  14559. */
  14560. this.year = year;
  14561. /**
  14562. * Gets or sets the month as a whole number with range [1, 12].
  14563. * @type {Number}
  14564. */
  14565. this.month = month;
  14566. /**
  14567. * Gets or sets the day of the month as a whole number starting at 1.
  14568. * @type {Number}
  14569. */
  14570. this.day = day;
  14571. /**
  14572. * Gets or sets the hour as a whole number with range [0, 23].
  14573. * @type {Number}
  14574. */
  14575. this.hour = hour;
  14576. /**
  14577. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  14578. * @type {Number}
  14579. */
  14580. this.minute = minute;
  14581. /**
  14582. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  14583. * @type {Number}
  14584. */
  14585. this.second = second;
  14586. /**
  14587. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  14588. * @type {Number}
  14589. */
  14590. this.millisecond = millisecond;
  14591. /**
  14592. * Gets or sets whether this time is during a leap second.
  14593. * @type {Boolean}
  14594. */
  14595. this.isLeapSecond = isLeapSecond;
  14596. }
  14597. return GregorianDate;
  14598. });
  14599. /*global define*/
  14600. define('Core/isLeapYear',[
  14601. './DeveloperError'
  14602. ], function(
  14603. DeveloperError) {
  14604. 'use strict';
  14605. /**
  14606. * Determines if a given date is a leap year.
  14607. *
  14608. * @exports isLeapYear
  14609. *
  14610. * @param {Number} year The year to be tested.
  14611. * @returns {Boolean} True if <code>year</code> is a leap year.
  14612. *
  14613. * @example
  14614. * var leapYear = Cesium.isLeapYear(2000); // true
  14615. */
  14616. function isLeapYear(year) {
  14617. if (year === null || isNaN(year)) {
  14618. throw new DeveloperError('year is required and must be a number.');
  14619. }
  14620. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  14621. }
  14622. return isLeapYear;
  14623. });
  14624. /*global define*/
  14625. define('Core/LeapSecond',[],function() {
  14626. 'use strict';
  14627. /**
  14628. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  14629. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  14630. * @alias LeapSecond
  14631. * @constructor
  14632. *
  14633. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  14634. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  14635. */
  14636. function LeapSecond(date, offset) {
  14637. /**
  14638. * Gets or sets the date at which this leap second occurs.
  14639. * @type {JulianDate}
  14640. */
  14641. this.julianDate = date;
  14642. /**
  14643. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  14644. * of this leap second.
  14645. * @type {Number}
  14646. */
  14647. this.offset = offset;
  14648. }
  14649. return LeapSecond;
  14650. });
  14651. /*global define*/
  14652. define('Core/TimeConstants',[
  14653. './freezeObject'
  14654. ], function(
  14655. freezeObject) {
  14656. 'use strict';
  14657. /**
  14658. * Constants for time conversions like those done by {@link JulianDate}.
  14659. *
  14660. * @exports TimeConstants
  14661. *
  14662. * @see JulianDate
  14663. *
  14664. * @private
  14665. */
  14666. var TimeConstants = {
  14667. /**
  14668. * The number of seconds in one millisecond: <code>0.001</code>
  14669. * @type {Number}
  14670. * @constant
  14671. */
  14672. SECONDS_PER_MILLISECOND : 0.001,
  14673. /**
  14674. * The number of seconds in one minute: <code>60</code>.
  14675. * @type {Number}
  14676. * @constant
  14677. */
  14678. SECONDS_PER_MINUTE : 60.0,
  14679. /**
  14680. * The number of minutes in one hour: <code>60</code>.
  14681. * @type {Number}
  14682. * @constant
  14683. */
  14684. MINUTES_PER_HOUR : 60.0,
  14685. /**
  14686. * The number of hours in one day: <code>24</code>.
  14687. * @type {Number}
  14688. * @constant
  14689. */
  14690. HOURS_PER_DAY : 24.0,
  14691. /**
  14692. * The number of seconds in one hour: <code>3600</code>.
  14693. * @type {Number}
  14694. * @constant
  14695. */
  14696. SECONDS_PER_HOUR : 3600.0,
  14697. /**
  14698. * The number of minutes in one day: <code>1440</code>.
  14699. * @type {Number}
  14700. * @constant
  14701. */
  14702. MINUTES_PER_DAY : 1440.0,
  14703. /**
  14704. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  14705. * @type {Number}
  14706. * @constant
  14707. */
  14708. SECONDS_PER_DAY : 86400.0,
  14709. /**
  14710. * The number of days in one Julian century: <code>36525</code>.
  14711. * @type {Number}
  14712. * @constant
  14713. */
  14714. DAYS_PER_JULIAN_CENTURY : 36525.0,
  14715. /**
  14716. * One trillionth of a second.
  14717. * @type {Number}
  14718. * @constant
  14719. */
  14720. PICOSECOND : 0.000000001,
  14721. /**
  14722. * The number of days to subtract from a Julian date to determine the
  14723. * modified Julian date, which gives the number of days since midnight
  14724. * on November 17, 1858.
  14725. * @type {Number}
  14726. * @constant
  14727. */
  14728. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  14729. };
  14730. return freezeObject(TimeConstants);
  14731. });
  14732. /*global define*/
  14733. define('Core/TimeStandard',[
  14734. './freezeObject'
  14735. ], function(
  14736. freezeObject) {
  14737. 'use strict';
  14738. /**
  14739. * Provides the type of time standards which JulianDate can take as input.
  14740. *
  14741. * @exports TimeStandard
  14742. *
  14743. * @see JulianDate
  14744. */
  14745. var TimeStandard = {
  14746. /**
  14747. * Represents the coordinated Universal Time (UTC) time standard.
  14748. *
  14749. * UTC is related to TAI according to the relationship
  14750. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  14751. * seconds which have been introduced as of the time in TAI.
  14752. *
  14753. */
  14754. UTC : 0,
  14755. /**
  14756. * Represents the International Atomic Time (TAI) time standard.
  14757. * TAI is the principal time standard to which the other time standards are related.
  14758. */
  14759. TAI : 1
  14760. };
  14761. return freezeObject(TimeStandard);
  14762. });
  14763. /*global define*/
  14764. define('Core/JulianDate',[
  14765. '../ThirdParty/sprintf',
  14766. './binarySearch',
  14767. './defaultValue',
  14768. './defined',
  14769. './DeveloperError',
  14770. './GregorianDate',
  14771. './isLeapYear',
  14772. './LeapSecond',
  14773. './TimeConstants',
  14774. './TimeStandard'
  14775. ], function(
  14776. sprintf,
  14777. binarySearch,
  14778. defaultValue,
  14779. defined,
  14780. DeveloperError,
  14781. GregorianDate,
  14782. isLeapYear,
  14783. LeapSecond,
  14784. TimeConstants,
  14785. TimeStandard) {
  14786. 'use strict';
  14787. var gregorianDateScratch = new GregorianDate();
  14788. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  14789. var daysInLeapFeburary = 29;
  14790. function compareLeapSecondDates(leapSecond, dateToFind) {
  14791. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  14792. }
  14793. // we don't really need a leap second instance, anything with a julianDate property will do
  14794. var binarySearchScratchLeapSecond = new LeapSecond();
  14795. function convertUtcToTai(julianDate) {
  14796. //Even though julianDate is in UTC, we'll treat it as TAI and
  14797. //search the leap second table for it.
  14798. binarySearchScratchLeapSecond.julianDate = julianDate;
  14799. var leapSeconds = JulianDate.leapSeconds;
  14800. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  14801. if (index < 0) {
  14802. index = ~index;
  14803. }
  14804. if (index >= leapSeconds.length) {
  14805. index = leapSeconds.length - 1;
  14806. }
  14807. var offset = leapSeconds[index].offset;
  14808. if (index > 0) {
  14809. //Now we have the index of the closest leap second that comes on or after our UTC time.
  14810. //However, if the difference between the UTC date being converted and the TAI
  14811. //defined leap second is greater than the offset, we are off by one and need to use
  14812. //the previous leap second.
  14813. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  14814. if (difference > offset) {
  14815. index--;
  14816. offset = leapSeconds[index].offset;
  14817. }
  14818. }
  14819. JulianDate.addSeconds(julianDate, offset, julianDate);
  14820. }
  14821. function convertTaiToUtc(julianDate, result) {
  14822. binarySearchScratchLeapSecond.julianDate = julianDate;
  14823. var leapSeconds = JulianDate.leapSeconds;
  14824. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  14825. if (index < 0) {
  14826. index = ~index;
  14827. }
  14828. //All times before our first leap second get the first offset.
  14829. if (index === 0) {
  14830. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  14831. }
  14832. //All times after our leap second get the last offset.
  14833. if (index >= leapSeconds.length) {
  14834. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  14835. }
  14836. //Compute the difference between the found leap second and the time we are converting.
  14837. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  14838. if (difference === 0) {
  14839. //The date is in our leap second table.
  14840. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  14841. }
  14842. if (difference <= 1.0) {
  14843. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  14844. return undefined;
  14845. }
  14846. //The time is in between two leap seconds, index is the leap second after the date
  14847. //we're converting, so we subtract one to get the correct LeapSecond instance.
  14848. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  14849. }
  14850. function setComponents(wholeDays, secondsOfDay, julianDate) {
  14851. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  14852. wholeDays += extraDays;
  14853. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  14854. if (secondsOfDay < 0) {
  14855. wholeDays--;
  14856. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  14857. }
  14858. julianDate.dayNumber = wholeDays;
  14859. julianDate.secondsOfDay = secondsOfDay;
  14860. return julianDate;
  14861. }
  14862. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  14863. // Algorithm from page 604 of the Explanatory Supplement to the
  14864. // Astronomical Almanac (Seidelmann 1992).
  14865. var a = ((month - 14) / 12) | 0;
  14866. var b = year + 4800 + a;
  14867. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  14868. // JulianDates are noon-based
  14869. hour = hour - 12;
  14870. if (hour < 0) {
  14871. hour += 24;
  14872. }
  14873. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  14874. if (secondsOfDay >= 43200.0) {
  14875. dayNumber -= 1;
  14876. }
  14877. return [dayNumber, secondsOfDay];
  14878. }
  14879. //Regular expressions used for ISO8601 date parsing.
  14880. //YYYY
  14881. var matchCalendarYear = /^(\d{4})$/;
  14882. //YYYY-MM (YYYYMM is invalid)
  14883. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  14884. //YYYY-DDD or YYYYDDD
  14885. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  14886. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  14887. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  14888. //YYYY-MM-DD or YYYYMMDD
  14889. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  14890. // Match utc offset
  14891. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  14892. // Match hours HH or HH.xxxxx
  14893. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  14894. // Match hours/minutes HH:MM HHMM.xxxxx
  14895. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  14896. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  14897. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  14898. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  14899. /**
  14900. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  14901. * For increased precision, this class stores the whole number part of the date and the seconds
  14902. * part of the date in separate components. In order to be safe for arithmetic and represent
  14903. * leap seconds, the date is always stored in the International Atomic Time standard
  14904. * {@link TimeStandard.TAI}.
  14905. * @alias JulianDate
  14906. * @constructor
  14907. *
  14908. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  14909. * @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.
  14910. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  14911. */
  14912. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  14913. /**
  14914. * Gets or sets the number of whole days.
  14915. * @type {Number}
  14916. */
  14917. this.dayNumber = undefined;
  14918. /**
  14919. * Gets or sets the number of seconds into the current day.
  14920. * @type {Number}
  14921. */
  14922. this.secondsOfDay = undefined;
  14923. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  14924. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  14925. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  14926. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  14927. var wholeDays = julianDayNumber | 0;
  14928. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  14929. setComponents(wholeDays, secondsOfDay, this);
  14930. if (timeStandard === TimeStandard.UTC) {
  14931. convertUtcToTai(this);
  14932. }
  14933. }
  14934. /**
  14935. * Creates a new instance from a JavaScript Date.
  14936. *
  14937. * @param {Date} date A JavaScript Date.
  14938. * @param {JulianDate} [result] An existing instance to use for the result.
  14939. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14940. *
  14941. * @exception {DeveloperError} date must be a valid JavaScript Date.
  14942. */
  14943. JulianDate.fromDate = function(date, result) {
  14944. if (!(date instanceof Date) || isNaN(date.getTime())) {
  14945. throw new DeveloperError('date must be a valid JavaScript Date.');
  14946. }
  14947. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  14948. if (!defined(result)) {
  14949. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  14950. }
  14951. setComponents(components[0], components[1], result);
  14952. convertUtcToTai(result);
  14953. return result;
  14954. };
  14955. /**
  14956. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  14957. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  14958. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  14959. *
  14960. * @param {String} iso8601String An ISO 8601 date.
  14961. * @param {JulianDate} [result] An existing instance to use for the result.
  14962. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14963. *
  14964. * @exception {DeveloperError} Invalid ISO 8601 date.
  14965. */
  14966. JulianDate.fromIso8601 = function(iso8601String, result) {
  14967. if (typeof iso8601String !== 'string') {
  14968. throw new DeveloperError(iso8601ErrorMessage);
  14969. }
  14970. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  14971. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  14972. iso8601String = iso8601String.replace(',', '.');
  14973. //Split the string into its date and time components, denoted by a mandatory T
  14974. var tokens = iso8601String.split('T');
  14975. var year;
  14976. var month = 1;
  14977. var day = 1;
  14978. var hour = 0;
  14979. var minute = 0;
  14980. var second = 0;
  14981. var millisecond = 0;
  14982. //Lacking a time is okay, but a missing date is illegal.
  14983. var date = tokens[0];
  14984. var time = tokens[1];
  14985. var tmp;
  14986. var inLeapYear;
  14987. if (!defined(date)) {
  14988. throw new DeveloperError(iso8601ErrorMessage);
  14989. }
  14990. var dashCount;
  14991. //First match the date against possible regular expressions.
  14992. tokens = date.match(matchCalendarDate);
  14993. if (tokens !== null) {
  14994. dashCount = date.split('-').length - 1;
  14995. if (dashCount > 0 && dashCount !== 2) {
  14996. throw new DeveloperError(iso8601ErrorMessage);
  14997. }
  14998. year = +tokens[1];
  14999. month = +tokens[2];
  15000. day = +tokens[3];
  15001. } else {
  15002. tokens = date.match(matchCalendarMonth);
  15003. if (tokens !== null) {
  15004. year = +tokens[1];
  15005. month = +tokens[2];
  15006. } else {
  15007. tokens = date.match(matchCalendarYear);
  15008. if (tokens !== null) {
  15009. year = +tokens[1];
  15010. } else {
  15011. //Not a year/month/day so it must be an ordinal date.
  15012. var dayOfYear;
  15013. tokens = date.match(matchOrdinalDate);
  15014. if (tokens !== null) {
  15015. year = +tokens[1];
  15016. dayOfYear = +tokens[2];
  15017. inLeapYear = isLeapYear(year);
  15018. //This validation is only applicable for this format.
  15019. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  15020. throw new DeveloperError(iso8601ErrorMessage);
  15021. }
  15022. } else {
  15023. tokens = date.match(matchWeekDate);
  15024. if (tokens !== null) {
  15025. //ISO week date to ordinal date from
  15026. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  15027. year = +tokens[1];
  15028. var weekNumber = +tokens[2];
  15029. var dayOfWeek = +tokens[3] || 0;
  15030. dashCount = date.split('-').length - 1;
  15031. if (dashCount > 0 &&
  15032. ((!defined(tokens[3]) && dashCount !== 1) ||
  15033. (defined(tokens[3]) && dashCount !== 2))) {
  15034. throw new DeveloperError(iso8601ErrorMessage);
  15035. }
  15036. var january4 = new Date(Date.UTC(year, 0, 4));
  15037. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  15038. } else {
  15039. //None of our regular expressions succeeded in parsing the date properly.
  15040. throw new DeveloperError(iso8601ErrorMessage);
  15041. }
  15042. }
  15043. //Split an ordinal date into month/day.
  15044. tmp = new Date(Date.UTC(year, 0, 1));
  15045. tmp.setUTCDate(dayOfYear);
  15046. month = tmp.getUTCMonth() + 1;
  15047. day = tmp.getUTCDate();
  15048. }
  15049. }
  15050. }
  15051. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  15052. inLeapYear = isLeapYear(year);
  15053. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  15054. throw new DeveloperError(iso8601ErrorMessage);
  15055. }
  15056. //Not move onto the time string, which is much simpler.
  15057. var offsetIndex;
  15058. if (defined(time)) {
  15059. tokens = time.match(matchHoursMinutesSeconds);
  15060. if (tokens !== null) {
  15061. dashCount = time.split(':').length - 1;
  15062. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  15063. throw new DeveloperError(iso8601ErrorMessage);
  15064. }
  15065. hour = +tokens[1];
  15066. minute = +tokens[2];
  15067. second = +tokens[3];
  15068. millisecond = +(tokens[4] || 0) * 1000.0;
  15069. offsetIndex = 5;
  15070. } else {
  15071. tokens = time.match(matchHoursMinutes);
  15072. if (tokens !== null) {
  15073. dashCount = time.split(':').length - 1;
  15074. if (dashCount > 2) {
  15075. throw new DeveloperError(iso8601ErrorMessage);
  15076. }
  15077. hour = +tokens[1];
  15078. minute = +tokens[2];
  15079. second = +(tokens[3] || 0) * 60.0;
  15080. offsetIndex = 4;
  15081. } else {
  15082. tokens = time.match(matchHours);
  15083. if (tokens !== null) {
  15084. hour = +tokens[1];
  15085. minute = +(tokens[2] || 0) * 60.0;
  15086. offsetIndex = 3;
  15087. } else {
  15088. throw new DeveloperError(iso8601ErrorMessage);
  15089. }
  15090. }
  15091. }
  15092. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  15093. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  15094. throw new DeveloperError(iso8601ErrorMessage);
  15095. }
  15096. //Check the UTC offset value, if no value exists, use local time
  15097. //a Z indicates UTC, + or - are offsets.
  15098. var offset = tokens[offsetIndex];
  15099. var offsetHours = +(tokens[offsetIndex + 1]);
  15100. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  15101. switch (offset) {
  15102. case '+':
  15103. hour = hour - offsetHours;
  15104. minute = minute - offsetMinutes;
  15105. break;
  15106. case '-':
  15107. hour = hour + offsetHours;
  15108. minute = minute + offsetMinutes;
  15109. break;
  15110. case 'Z':
  15111. break;
  15112. default:
  15113. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  15114. break;
  15115. }
  15116. } else {
  15117. //If no time is specified, it is considered the beginning of the day, local time.
  15118. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  15119. }
  15120. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  15121. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  15122. //Then we add it back in after converting to TAI.
  15123. var isLeapSecond = second === 60;
  15124. if (isLeapSecond) {
  15125. second--;
  15126. }
  15127. //Even if we successfully parsed the string into its components, after applying UTC offset or
  15128. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  15129. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  15130. while (minute >= 60) {
  15131. minute -= 60;
  15132. hour++;
  15133. }
  15134. while (hour >= 24) {
  15135. hour -= 24;
  15136. day++;
  15137. }
  15138. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15139. while (day > tmp) {
  15140. day -= tmp;
  15141. month++;
  15142. if (month > 12) {
  15143. month -= 12;
  15144. year++;
  15145. }
  15146. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15147. }
  15148. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  15149. while (minute < 0) {
  15150. minute += 60;
  15151. hour--;
  15152. }
  15153. while (hour < 0) {
  15154. hour += 24;
  15155. day--;
  15156. }
  15157. while (day < 1) {
  15158. month--;
  15159. if (month < 1) {
  15160. month += 12;
  15161. year--;
  15162. }
  15163. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15164. day += tmp;
  15165. }
  15166. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  15167. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  15168. if (!defined(result)) {
  15169. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  15170. } else {
  15171. setComponents(components[0], components[1], result);
  15172. convertUtcToTai(result);
  15173. }
  15174. //If we were on a leap second, add it back.
  15175. if (isLeapSecond) {
  15176. JulianDate.addSeconds(result, 1, result);
  15177. }
  15178. return result;
  15179. };
  15180. /**
  15181. * Creates a new instance that represents the current system time.
  15182. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  15183. *
  15184. * @param {JulianDate} [result] An existing instance to use for the result.
  15185. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15186. */
  15187. JulianDate.now = function(result) {
  15188. return JulianDate.fromDate(new Date(), result);
  15189. };
  15190. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  15191. /**
  15192. * Creates a {@link GregorianDate} from the provided instance.
  15193. *
  15194. * @param {JulianDate} julianDate The date to be converted.
  15195. * @param {GregorianDate} [result] An existing instance to use for the result.
  15196. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  15197. */
  15198. JulianDate.toGregorianDate = function(julianDate, result) {
  15199. if (!defined(julianDate)) {
  15200. throw new DeveloperError('julianDate is required.');
  15201. }
  15202. var isLeapSecond = false;
  15203. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  15204. if (!defined(thisUtc)) {
  15205. //Conversion to UTC will fail if we are during a leap second.
  15206. //If that's the case, subtract a second and convert again.
  15207. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  15208. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  15209. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  15210. isLeapSecond = true;
  15211. }
  15212. var julianDayNumber = thisUtc.dayNumber;
  15213. var secondsOfDay = thisUtc.secondsOfDay;
  15214. if (secondsOfDay >= 43200.0) {
  15215. julianDayNumber += 1;
  15216. }
  15217. // Algorithm from page 604 of the Explanatory Supplement to the
  15218. // Astronomical Almanac (Seidelmann 1992).
  15219. var L = (julianDayNumber + 68569) | 0;
  15220. var N = (4 * L / 146097) | 0;
  15221. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  15222. var I = ((4000 * (L + 1)) / 1461001) | 0;
  15223. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  15224. var J = ((80 * L) / 2447) | 0;
  15225. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  15226. L = (J / 11) | 0;
  15227. var month = (J + 2 - 12 * L) | 0;
  15228. var year = (100 * (N - 49) + I + L) | 0;
  15229. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  15230. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  15231. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  15232. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  15233. var second = remainingSeconds | 0;
  15234. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  15235. // JulianDates are noon-based
  15236. hour += 12;
  15237. if (hour > 23) {
  15238. hour -= 24;
  15239. }
  15240. //If we were on a leap second, add it back.
  15241. if (isLeapSecond) {
  15242. second += 1;
  15243. }
  15244. if (!defined(result)) {
  15245. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  15246. }
  15247. result.year = year;
  15248. result.month = month;
  15249. result.day = day;
  15250. result.hour = hour;
  15251. result.minute = minute;
  15252. result.second = second;
  15253. result.millisecond = millisecond;
  15254. result.isLeapSecond = isLeapSecond;
  15255. return result;
  15256. };
  15257. /**
  15258. * Creates a JavaScript Date from the provided instance.
  15259. * Since JavaScript dates are only accurate to the nearest millisecond and
  15260. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  15261. * If the provided JulianDate is during a leap second, the previous second is used.
  15262. *
  15263. * @param {JulianDate} julianDate The date to be converted.
  15264. * @returns {Date} A new instance representing the provided date.
  15265. */
  15266. JulianDate.toDate = function(julianDate) {
  15267. if (!defined(julianDate)) {
  15268. throw new DeveloperError('julianDate is required.');
  15269. }
  15270. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  15271. var second = gDate.second;
  15272. if (gDate.isLeapSecond) {
  15273. second -= 1;
  15274. }
  15275. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  15276. };
  15277. /**
  15278. * Creates an ISO8601 representation of the provided date.
  15279. *
  15280. * @param {JulianDate} julianDate The date to be converted.
  15281. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  15282. * @returns {String} The ISO8601 representation of the provided date.
  15283. */
  15284. JulianDate.toIso8601 = function(julianDate, precision) {
  15285. if (!defined(julianDate)) {
  15286. throw new DeveloperError('julianDate is required.');
  15287. }
  15288. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  15289. var millisecondStr;
  15290. if (!defined(precision) && gDate.millisecond !== 0) {
  15291. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  15292. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  15293. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  15294. }
  15295. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  15296. if (!defined(precision) || precision === 0) {
  15297. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  15298. }
  15299. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  15300. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  15301. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  15302. };
  15303. /**
  15304. * Duplicates a JulianDate instance.
  15305. *
  15306. * @param {JulianDate} julianDate The date to duplicate.
  15307. * @param {JulianDate} [result] An existing instance to use for the result.
  15308. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  15309. */
  15310. JulianDate.clone = function(julianDate, result) {
  15311. if (!defined(julianDate)) {
  15312. return undefined;
  15313. }
  15314. if (!defined(result)) {
  15315. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  15316. }
  15317. result.dayNumber = julianDate.dayNumber;
  15318. result.secondsOfDay = julianDate.secondsOfDay;
  15319. return result;
  15320. };
  15321. /**
  15322. * Compares two instances.
  15323. *
  15324. * @param {JulianDate} left The first instance.
  15325. * @param {JulianDate} right The second instance.
  15326. * @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.
  15327. */
  15328. JulianDate.compare = function(left, right) {
  15329. if (!defined(left)) {
  15330. throw new DeveloperError('left is required.');
  15331. }
  15332. if (!defined(right)) {
  15333. throw new DeveloperError('right is required.');
  15334. }
  15335. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  15336. if (julianDayNumberDifference !== 0) {
  15337. return julianDayNumberDifference;
  15338. }
  15339. return left.secondsOfDay - right.secondsOfDay;
  15340. };
  15341. /**
  15342. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  15343. *
  15344. * @param {JulianDate} [left] The first instance.
  15345. * @param {JulianDate} [right] The second instance.
  15346. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  15347. */
  15348. JulianDate.equals = function(left, right) {
  15349. return (left === right) ||
  15350. (defined(left) &&
  15351. defined(right) &&
  15352. left.dayNumber === right.dayNumber &&
  15353. left.secondsOfDay === right.secondsOfDay);
  15354. };
  15355. /**
  15356. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  15357. * each other. That is, in order for the dates to be considered equal (and for
  15358. * this function to return <code>true</code>), the absolute value of the difference between them, in
  15359. * seconds, must be less than <code>epsilon</code>.
  15360. *
  15361. * @param {JulianDate} [left] The first instance.
  15362. * @param {JulianDate} [right] The second instance.
  15363. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  15364. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  15365. */
  15366. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  15367. if (!defined(epsilon)) {
  15368. throw new DeveloperError('epsilon is required.');
  15369. }
  15370. return (left === right) ||
  15371. (defined(left) &&
  15372. defined(right) &&
  15373. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  15374. };
  15375. /**
  15376. * Computes the total number of whole and fractional days represented by the provided instance.
  15377. *
  15378. * @param {JulianDate} julianDate The date.
  15379. * @returns {Number} The Julian date as single floating point number.
  15380. */
  15381. JulianDate.totalDays = function(julianDate) {
  15382. if (!defined(julianDate)) {
  15383. throw new DeveloperError('julianDate is required.');
  15384. }
  15385. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  15386. };
  15387. /**
  15388. * Computes the difference in seconds between the provided instance.
  15389. *
  15390. * @param {JulianDate} left The first instance.
  15391. * @param {JulianDate} right The second instance.
  15392. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  15393. */
  15394. JulianDate.secondsDifference = function(left, right) {
  15395. if (!defined(left)) {
  15396. throw new DeveloperError('left is required.');
  15397. }
  15398. if (!defined(right)) {
  15399. throw new DeveloperError('right is required.');
  15400. }
  15401. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  15402. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  15403. };
  15404. /**
  15405. * Computes the difference in days between the provided instance.
  15406. *
  15407. * @param {JulianDate} left The first instance.
  15408. * @param {JulianDate} right The second instance.
  15409. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  15410. */
  15411. JulianDate.daysDifference = function(left, right) {
  15412. if (!defined(left)) {
  15413. throw new DeveloperError('left is required.');
  15414. }
  15415. if (!defined(right)) {
  15416. throw new DeveloperError('right is required.');
  15417. }
  15418. var dayDifference = (left.dayNumber - right.dayNumber);
  15419. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  15420. return dayDifference + secondDifference;
  15421. };
  15422. /**
  15423. * Computes the number of seconds the provided instance is ahead of UTC.
  15424. *
  15425. * @param {JulianDate} julianDate The date.
  15426. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  15427. */
  15428. JulianDate.computeTaiMinusUtc = function(julianDate) {
  15429. binarySearchScratchLeapSecond.julianDate = julianDate;
  15430. var leapSeconds = JulianDate.leapSeconds;
  15431. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15432. if (index < 0) {
  15433. index = ~index;
  15434. --index;
  15435. if (index < 0) {
  15436. index = 0;
  15437. }
  15438. }
  15439. return leapSeconds[index].offset;
  15440. };
  15441. /**
  15442. * Adds the provided number of seconds to the provided date instance.
  15443. *
  15444. * @param {JulianDate} julianDate The date.
  15445. * @param {Number} seconds The number of seconds to add or subtract.
  15446. * @param {JulianDate} result An existing instance to use for the result.
  15447. * @returns {JulianDate} The modified result parameter.
  15448. */
  15449. JulianDate.addSeconds = function(julianDate, seconds, result) {
  15450. if (!defined(julianDate)) {
  15451. throw new DeveloperError('julianDate is required.');
  15452. }
  15453. if (!defined(seconds)) {
  15454. throw new DeveloperError('seconds is required.');
  15455. }
  15456. if (!defined(result)) {
  15457. throw new DeveloperError('result is required.');
  15458. }
  15459. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  15460. };
  15461. /**
  15462. * Adds the provided number of minutes to the provided date instance.
  15463. *
  15464. * @param {JulianDate} julianDate The date.
  15465. * @param {Number} minutes The number of minutes to add or subtract.
  15466. * @param {JulianDate} result An existing instance to use for the result.
  15467. * @returns {JulianDate} The modified result parameter.
  15468. */
  15469. JulianDate.addMinutes = function(julianDate, minutes, result) {
  15470. if (!defined(julianDate)) {
  15471. throw new DeveloperError('julianDate is required.');
  15472. }
  15473. if (!defined(minutes)) {
  15474. throw new DeveloperError('minutes is required.');
  15475. }
  15476. if (!defined(result)) {
  15477. throw new DeveloperError('result is required.');
  15478. }
  15479. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  15480. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  15481. };
  15482. /**
  15483. * Adds the provided number of hours to the provided date instance.
  15484. *
  15485. * @param {JulianDate} julianDate The date.
  15486. * @param {Number} hours The number of hours to add or subtract.
  15487. * @param {JulianDate} result An existing instance to use for the result.
  15488. * @returns {JulianDate} The modified result parameter.
  15489. */
  15490. JulianDate.addHours = function(julianDate, hours, result) {
  15491. if (!defined(julianDate)) {
  15492. throw new DeveloperError('julianDate is required.');
  15493. }
  15494. if (!defined(hours)) {
  15495. throw new DeveloperError('hours is required.');
  15496. }
  15497. if (!defined(result)) {
  15498. throw new DeveloperError('result is required.');
  15499. }
  15500. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  15501. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  15502. };
  15503. /**
  15504. * Adds the provided number of days to the provided date instance.
  15505. *
  15506. * @param {JulianDate} julianDate The date.
  15507. * @param {Number} days The number of days to add or subtract.
  15508. * @param {JulianDate} result An existing instance to use for the result.
  15509. * @returns {JulianDate} The modified result parameter.
  15510. */
  15511. JulianDate.addDays = function(julianDate, days, result) {
  15512. if (!defined(julianDate)) {
  15513. throw new DeveloperError('julianDate is required.');
  15514. }
  15515. if (!defined(days)) {
  15516. throw new DeveloperError('days is required.');
  15517. }
  15518. if (!defined(result)) {
  15519. throw new DeveloperError('result is required.');
  15520. }
  15521. var newJulianDayNumber = julianDate.dayNumber + days;
  15522. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  15523. };
  15524. /**
  15525. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  15526. *
  15527. * @param {JulianDate} left The first instance.
  15528. * @param {JulianDate} right The second instance.
  15529. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  15530. */
  15531. JulianDate.lessThan = function(left, right) {
  15532. return JulianDate.compare(left, right) < 0;
  15533. };
  15534. /**
  15535. * 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.
  15536. *
  15537. * @param {JulianDate} left The first instance.
  15538. * @param {JulianDate} right The second instance.
  15539. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  15540. */
  15541. JulianDate.lessThanOrEquals = function(left, right) {
  15542. return JulianDate.compare(left, right) <= 0;
  15543. };
  15544. /**
  15545. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  15546. *
  15547. * @param {JulianDate} left The first instance.
  15548. * @param {JulianDate} right The second instance.
  15549. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  15550. */
  15551. JulianDate.greaterThan = function(left, right) {
  15552. return JulianDate.compare(left, right) > 0;
  15553. };
  15554. /**
  15555. * 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.
  15556. *
  15557. * @param {JulianDate} left The first instance.
  15558. * @param {JulianDate} right The second instance.
  15559. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  15560. */
  15561. JulianDate.greaterThanOrEquals = function(left, right) {
  15562. return JulianDate.compare(left, right) >= 0;
  15563. };
  15564. /**
  15565. * Duplicates this instance.
  15566. *
  15567. * @param {JulianDate} [result] An existing instance to use for the result.
  15568. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15569. */
  15570. JulianDate.prototype.clone = function(result) {
  15571. return JulianDate.clone(this, result);
  15572. };
  15573. /**
  15574. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  15575. *
  15576. * @param {JulianDate} [right] The second instance.
  15577. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  15578. */
  15579. JulianDate.prototype.equals = function(right) {
  15580. return JulianDate.equals(this, right);
  15581. };
  15582. /**
  15583. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  15584. * each other. That is, in order for the dates to be considered equal (and for
  15585. * this function to return <code>true</code>), the absolute value of the difference between them, in
  15586. * seconds, must be less than <code>epsilon</code>.
  15587. *
  15588. * @param {JulianDate} [right] The second instance.
  15589. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  15590. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  15591. */
  15592. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  15593. return JulianDate.equalsEpsilon(this, right, epsilon);
  15594. };
  15595. /**
  15596. * Creates a string representing this date in ISO8601 format.
  15597. *
  15598. * @returns {String} A string representing this date in ISO8601 format.
  15599. */
  15600. JulianDate.prototype.toString = function() {
  15601. return JulianDate.toIso8601(this);
  15602. };
  15603. /**
  15604. * Gets or sets the list of leap seconds used throughout Cesium.
  15605. * @memberof JulianDate
  15606. * @type {LeapSecond[]}
  15607. */
  15608. JulianDate.leapSeconds = [
  15609. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  15610. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  15611. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  15612. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  15613. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  15614. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  15615. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  15616. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  15617. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  15618. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  15619. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  15620. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  15621. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  15622. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  15623. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  15624. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  15625. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  15626. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  15627. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  15628. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  15629. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  15630. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  15631. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  15632. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  15633. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  15634. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  15635. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  15636. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  15637. ];
  15638. return JulianDate;
  15639. });
  15640. /*global define*/
  15641. define('Core/clone',[
  15642. './defaultValue'
  15643. ], function(
  15644. defaultValue) {
  15645. 'use strict';
  15646. /**
  15647. * Clones an object, returning a new object containing the same properties.
  15648. *
  15649. * @exports clone
  15650. *
  15651. * @param {Object} object The object to clone.
  15652. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  15653. * @returns {Object} The cloned object.
  15654. */
  15655. function clone(object, deep) {
  15656. if (object === null || typeof object !== 'object') {
  15657. return object;
  15658. }
  15659. deep = defaultValue(deep, false);
  15660. var result = new object.constructor();
  15661. for ( var propertyName in object) {
  15662. if (object.hasOwnProperty(propertyName)) {
  15663. var value = object[propertyName];
  15664. if (deep) {
  15665. value = clone(value, deep);
  15666. }
  15667. result[propertyName] = value;
  15668. }
  15669. }
  15670. return result;
  15671. }
  15672. return clone;
  15673. });
  15674. /*global define*/
  15675. define('Core/parseResponseHeaders',[], function() {
  15676. 'use strict';
  15677. /**
  15678. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  15679. * a dictionary.
  15680. *
  15681. * @exports parseResponseHeaders
  15682. *
  15683. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  15684. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  15685. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  15686. * is that header's value.
  15687. *
  15688. * @private
  15689. */
  15690. function parseResponseHeaders(headerString) {
  15691. var headers = {};
  15692. if (!headerString) {
  15693. return headers;
  15694. }
  15695. var headerPairs = headerString.split('\u000d\u000a');
  15696. for (var i = 0; i < headerPairs.length; ++i) {
  15697. var headerPair = headerPairs[i];
  15698. // Can't use split() here because it does the wrong thing
  15699. // if the header value has the string ": " in it.
  15700. var index = headerPair.indexOf('\u003a\u0020');
  15701. if (index > 0) {
  15702. var key = headerPair.substring(0, index);
  15703. var val = headerPair.substring(index + 2);
  15704. headers[key] = val;
  15705. }
  15706. }
  15707. return headers;
  15708. }
  15709. return parseResponseHeaders;
  15710. });
  15711. /*global define*/
  15712. define('Core/RequestErrorEvent',[
  15713. './defined',
  15714. './parseResponseHeaders'
  15715. ], function(
  15716. defined,
  15717. parseResponseHeaders) {
  15718. 'use strict';
  15719. /**
  15720. * An event that is raised when a request encounters an error.
  15721. *
  15722. * @constructor
  15723. * @alias RequestErrorEvent
  15724. *
  15725. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  15726. * @param {Object} [response] The response included along with the error.
  15727. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  15728. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  15729. */
  15730. function RequestErrorEvent(statusCode, response, responseHeaders) {
  15731. /**
  15732. * The HTTP error status code, such as 404. If the error does not have a particular
  15733. * HTTP code, this property will be undefined.
  15734. *
  15735. * @type {Number}
  15736. */
  15737. this.statusCode = statusCode;
  15738. /**
  15739. * The response included along with the error. If the error does not include a response,
  15740. * this property will be undefined.
  15741. *
  15742. * @type {Object}
  15743. */
  15744. this.response = response;
  15745. /**
  15746. * The headers included in the response, represented as an object literal of key/value pairs.
  15747. * If the error does not include any headers, this property will be undefined.
  15748. *
  15749. * @type {Object}
  15750. */
  15751. this.responseHeaders = responseHeaders;
  15752. if (typeof this.responseHeaders === 'string') {
  15753. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  15754. }
  15755. }
  15756. /**
  15757. * Creates a string representing this RequestErrorEvent.
  15758. * @memberof RequestErrorEvent
  15759. *
  15760. * @returns {String} A string representing the provided RequestErrorEvent.
  15761. */
  15762. RequestErrorEvent.prototype.toString = function() {
  15763. var str = 'Request has failed.';
  15764. if (defined(this.statusCode)) {
  15765. str += ' Status Code: ' + this.statusCode;
  15766. }
  15767. return str;
  15768. };
  15769. return RequestErrorEvent;
  15770. });
  15771. /**
  15772. * @license
  15773. *
  15774. * Grauw URI utilities
  15775. *
  15776. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  15777. *
  15778. * @author Laurens Holst (http://www.grauw.nl/)
  15779. *
  15780. * Copyright 2012 Laurens Holst
  15781. *
  15782. * Licensed under the Apache License, Version 2.0 (the "License");
  15783. * you may not use this file except in compliance with the License.
  15784. * You may obtain a copy of the License at
  15785. *
  15786. * http://www.apache.org/licenses/LICENSE-2.0
  15787. *
  15788. * Unless required by applicable law or agreed to in writing, software
  15789. * distributed under the License is distributed on an "AS IS" BASIS,
  15790. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15791. * See the License for the specific language governing permissions and
  15792. * limitations under the License.
  15793. *
  15794. */
  15795. /*global define*/
  15796. define('ThirdParty/Uri',[],function() {
  15797. /**
  15798. * Constructs a URI object.
  15799. * @constructor
  15800. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  15801. * @param {string|URI} uri A string or URI object to create the object from.
  15802. */
  15803. function URI(uri) {
  15804. if (uri instanceof URI) { // copy constructor
  15805. this.scheme = uri.scheme;
  15806. this.authority = uri.authority;
  15807. this.path = uri.path;
  15808. this.query = uri.query;
  15809. this.fragment = uri.fragment;
  15810. } else if (uri) { // uri is URI string or cast to string
  15811. var c = parseRegex.exec(uri);
  15812. this.scheme = c[1];
  15813. this.authority = c[2];
  15814. this.path = c[3];
  15815. this.query = c[4];
  15816. this.fragment = c[5];
  15817. }
  15818. }
  15819. // Initial values on the prototype
  15820. URI.prototype.scheme = null;
  15821. URI.prototype.authority = null;
  15822. URI.prototype.path = '';
  15823. URI.prototype.query = null;
  15824. URI.prototype.fragment = null;
  15825. // Regular expression from RFC 3986 appendix B
  15826. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  15827. /**
  15828. * Returns the scheme part of the URI.
  15829. * In "http://example.com:80/a/b?x#y" this is "http".
  15830. */
  15831. URI.prototype.getScheme = function() {
  15832. return this.scheme;
  15833. };
  15834. /**
  15835. * Returns the authority part of the URI.
  15836. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  15837. */
  15838. URI.prototype.getAuthority = function() {
  15839. return this.authority;
  15840. };
  15841. /**
  15842. * Returns the path part of the URI.
  15843. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  15844. * In "mailto:mike@example.com" this is "mike@example.com".
  15845. */
  15846. URI.prototype.getPath = function() {
  15847. return this.path;
  15848. };
  15849. /**
  15850. * Returns the query part of the URI.
  15851. * In "http://example.com:80/a/b?x#y" this is "x".
  15852. */
  15853. URI.prototype.getQuery = function() {
  15854. return this.query;
  15855. };
  15856. /**
  15857. * Returns the fragment part of the URI.
  15858. * In "http://example.com:80/a/b?x#y" this is "y".
  15859. */
  15860. URI.prototype.getFragment = function() {
  15861. return this.fragment;
  15862. };
  15863. /**
  15864. * Tests whether the URI is an absolute URI.
  15865. * See RFC 3986 section 4.3.
  15866. */
  15867. URI.prototype.isAbsolute = function() {
  15868. return !!this.scheme && !this.fragment;
  15869. };
  15870. ///**
  15871. //* Extensive validation of the URI against the ABNF in RFC 3986
  15872. //*/
  15873. //URI.prototype.validate
  15874. /**
  15875. * Tests whether the URI is a same-document reference.
  15876. * See RFC 3986 section 4.4.
  15877. *
  15878. * To perform more thorough comparison, you can normalise the URI objects.
  15879. */
  15880. URI.prototype.isSameDocumentAs = function(uri) {
  15881. return uri.scheme == this.scheme &&
  15882. uri.authority == this.authority &&
  15883. uri.path == this.path &&
  15884. uri.query == this.query;
  15885. };
  15886. /**
  15887. * Simple String Comparison of two URIs.
  15888. * See RFC 3986 section 6.2.1.
  15889. *
  15890. * To perform more thorough comparison, you can normalise the URI objects.
  15891. */
  15892. URI.prototype.equals = function(uri) {
  15893. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  15894. };
  15895. /**
  15896. * Normalizes the URI using syntax-based normalization.
  15897. * This includes case normalization, percent-encoding normalization and path segment normalization.
  15898. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  15899. * (Although that would not be a valid URI in the first place. See validate().)
  15900. * See RFC 3986 section 6.2.2.
  15901. */
  15902. URI.prototype.normalize = function() {
  15903. this.removeDotSegments();
  15904. if (this.scheme)
  15905. this.scheme = this.scheme.toLowerCase();
  15906. if (this.authority)
  15907. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  15908. replace(caseRegex, replaceCase);
  15909. if (this.path)
  15910. this.path = this.path.replace(caseRegex, replaceCase);
  15911. if (this.query)
  15912. this.query = this.query.replace(caseRegex, replaceCase);
  15913. if (this.fragment)
  15914. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  15915. };
  15916. var caseRegex = /%[0-9a-z]{2}/gi;
  15917. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  15918. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  15919. function replaceCase(str) {
  15920. var dec = unescape(str);
  15921. return percentRegex.test(dec) ? dec : str.toUpperCase();
  15922. }
  15923. function replaceAuthority(str, p1, p2, p3) {
  15924. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  15925. }
  15926. /**
  15927. * Resolve a relative URI (this) against a base URI.
  15928. * The base URI must be an absolute URI.
  15929. * See RFC 3986 section 5.2
  15930. */
  15931. URI.prototype.resolve = function(baseURI) {
  15932. var uri = new URI();
  15933. if (this.scheme) {
  15934. uri.scheme = this.scheme;
  15935. uri.authority = this.authority;
  15936. uri.path = this.path;
  15937. uri.query = this.query;
  15938. } else {
  15939. uri.scheme = baseURI.scheme;
  15940. if (this.authority) {
  15941. uri.authority = this.authority;
  15942. uri.path = this.path;
  15943. uri.query = this.query;
  15944. } else {
  15945. uri.authority = baseURI.authority;
  15946. if (this.path == '') {
  15947. uri.path = baseURI.path;
  15948. uri.query = this.query || baseURI.query;
  15949. } else {
  15950. if (this.path.charAt(0) == '/') {
  15951. uri.path = this.path;
  15952. uri.removeDotSegments();
  15953. } else {
  15954. if (baseURI.authority && baseURI.path == '') {
  15955. uri.path = '/' + this.path;
  15956. } else {
  15957. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  15958. }
  15959. uri.removeDotSegments();
  15960. }
  15961. uri.query = this.query;
  15962. }
  15963. }
  15964. }
  15965. uri.fragment = this.fragment;
  15966. return uri;
  15967. };
  15968. /**
  15969. * Remove dot segments from path.
  15970. * See RFC 3986 section 5.2.4
  15971. * @private
  15972. */
  15973. URI.prototype.removeDotSegments = function() {
  15974. var input = this.path.split('/'),
  15975. output = [],
  15976. segment,
  15977. absPath = input[0] == '';
  15978. if (absPath)
  15979. input.shift();
  15980. var sFirst = input[0] == '' ? input.shift() : null;
  15981. while (input.length) {
  15982. segment = input.shift();
  15983. if (segment == '..') {
  15984. output.pop();
  15985. } else if (segment != '.') {
  15986. output.push(segment);
  15987. }
  15988. }
  15989. if (segment == '.' || segment == '..')
  15990. output.push('');
  15991. if (absPath)
  15992. output.unshift('');
  15993. this.path = output.join('/');
  15994. };
  15995. // We don't like this function because it builds up a cache that is never cleared.
  15996. // /**
  15997. // * Resolves a relative URI against an absolute base URI.
  15998. // * Convenience method.
  15999. // * @param {String} uri the relative URI to resolve
  16000. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  16001. // */
  16002. // URI.resolve = function(sURI, sBaseURI) {
  16003. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  16004. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  16005. // return uri.resolve(baseURI).toString();
  16006. // };
  16007. // var cache = {};
  16008. /**
  16009. * Serialises the URI to a string.
  16010. */
  16011. URI.prototype.toString = function() {
  16012. var result = '';
  16013. if (this.scheme)
  16014. result += this.scheme + ':';
  16015. if (this.authority)
  16016. result += '//' + this.authority;
  16017. result += this.path;
  16018. if (this.query)
  16019. result += '?' + this.query;
  16020. if (this.fragment)
  16021. result += '#' + this.fragment;
  16022. return result;
  16023. };
  16024. return URI;
  16025. });
  16026. /*global define*/
  16027. define('Core/TrustedServers',[
  16028. '../ThirdParty/Uri',
  16029. './defined',
  16030. './DeveloperError'
  16031. ], function(
  16032. Uri,
  16033. defined,
  16034. DeveloperError) {
  16035. 'use strict';
  16036. /**
  16037. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  16038. * any requests to these servers.
  16039. *
  16040. * @exports TrustedServers
  16041. *
  16042. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16043. */
  16044. var TrustedServers = {};
  16045. var _servers = {};
  16046. /**
  16047. * Adds a trusted server to the registry
  16048. *
  16049. * @param {String} host The host to be added.
  16050. * @param {Number} port The port used to access the host.
  16051. *
  16052. * @example
  16053. * // Add a trusted server
  16054. * TrustedServers.add('my.server.com', 80);
  16055. */
  16056. TrustedServers.add = function(host, port) {
  16057. if (!defined(host)) {
  16058. throw new DeveloperError('host is required.');
  16059. }
  16060. if (!defined(port) || port <= 0) {
  16061. throw new DeveloperError('port is required to be greater than 0.');
  16062. }
  16063. var authority = host.toLowerCase() + ':' + port;
  16064. if (!defined(_servers[authority])) {
  16065. _servers[authority] = true;
  16066. }
  16067. };
  16068. /**
  16069. * Removes a trusted server from the registry
  16070. *
  16071. * @param {String} host The host to be removed.
  16072. * @param {Number} port The port used to access the host.
  16073. *
  16074. * @example
  16075. * // Remove a trusted server
  16076. * TrustedServers.remove('my.server.com', 80);
  16077. */
  16078. TrustedServers.remove = function(host, port) {
  16079. if (!defined(host)) {
  16080. throw new DeveloperError('host is required.');
  16081. }
  16082. if (!defined(port) || port <= 0) {
  16083. throw new DeveloperError('port is required to be greater than 0.');
  16084. }
  16085. var authority = host.toLowerCase() + ':' + port;
  16086. if (defined(_servers[authority])) {
  16087. delete _servers[authority];
  16088. }
  16089. };
  16090. function getAuthority(url) {
  16091. var uri = new Uri(url);
  16092. uri.normalize();
  16093. // Removes username:password@ so we just have host[:port]
  16094. var authority = uri.getAuthority();
  16095. if (!defined(authority)) {
  16096. return undefined; // Relative URL
  16097. }
  16098. if (authority.indexOf('@') !== -1) {
  16099. var parts = authority.split('@');
  16100. authority = parts[1];
  16101. }
  16102. // If the port is missing add one based on the scheme
  16103. if (authority.indexOf(':') === -1) {
  16104. var scheme = uri.getScheme();
  16105. if (!defined(scheme)) {
  16106. scheme = window.location.protocol;
  16107. scheme = scheme.substring(0, scheme.length-1);
  16108. }
  16109. if (scheme === 'http') {
  16110. authority += ':80';
  16111. } else if (scheme === 'https') {
  16112. authority += ':443';
  16113. } else {
  16114. return undefined;
  16115. }
  16116. }
  16117. return authority;
  16118. }
  16119. /**
  16120. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  16121. *
  16122. * @param {String} url The url to be tested against the trusted list
  16123. *
  16124. * @returns {boolean} Returns true if url is trusted, false otherwise.
  16125. *
  16126. * @example
  16127. * // Add server
  16128. * TrustedServers.add('my.server.com', 81);
  16129. *
  16130. * // Check if server is trusted
  16131. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  16132. * // my.server.com:81 is trusted
  16133. * }
  16134. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  16135. * // my.server.com isn't trusted
  16136. * }
  16137. */
  16138. TrustedServers.contains = function(url) {
  16139. if (!defined(url)) {
  16140. throw new DeveloperError('url is required.');
  16141. }
  16142. var authority = getAuthority(url);
  16143. if (defined(authority) && defined(_servers[authority])) {
  16144. return true;
  16145. }
  16146. return false;
  16147. };
  16148. /**
  16149. * Clears the registry
  16150. *
  16151. * @example
  16152. * // Remove a trusted server
  16153. * TrustedServers.clear();
  16154. */
  16155. TrustedServers.clear = function() {
  16156. _servers = {};
  16157. };
  16158. return TrustedServers;
  16159. });
  16160. /*global define*/
  16161. define('Core/loadWithXhr',[
  16162. '../ThirdParty/when',
  16163. './defaultValue',
  16164. './defined',
  16165. './DeveloperError',
  16166. './RequestErrorEvent',
  16167. './RuntimeError',
  16168. './TrustedServers'
  16169. ], function(
  16170. when,
  16171. defaultValue,
  16172. defined,
  16173. DeveloperError,
  16174. RequestErrorEvent,
  16175. RuntimeError,
  16176. TrustedServers) {
  16177. 'use strict';
  16178. /**
  16179. * Asynchronously loads the given URL. Returns a promise that will resolve to
  16180. * the result once loaded, or reject if the URL failed to load. The data is loaded
  16181. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16182. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  16183. *
  16184. * @exports loadWithXhr
  16185. *
  16186. * @param {Object} options Object with the following properties:
  16187. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  16188. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  16189. * @param {String} [options.method='GET'] The HTTP method to use.
  16190. * @param {String} [options.data] The data to send with the request, if any.
  16191. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  16192. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  16193. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  16194. *
  16195. *
  16196. * @example
  16197. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  16198. * Cesium.loadWithXhr({
  16199. * url : 'some/url',
  16200. * responseType : 'blob'
  16201. * }).then(function(blob) {
  16202. * // use the data
  16203. * }).otherwise(function(error) {
  16204. * // an error occurred
  16205. * });
  16206. *
  16207. * @see loadArrayBuffer
  16208. * @see loadBlob
  16209. * @see loadJson
  16210. * @see loadText
  16211. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16212. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16213. */
  16214. function loadWithXhr(options) {
  16215. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16216. if (!defined(options.url)) {
  16217. throw new DeveloperError('options.url is required.');
  16218. }
  16219. var responseType = options.responseType;
  16220. var method = defaultValue(options.method, 'GET');
  16221. var data = options.data;
  16222. var headers = options.headers;
  16223. var overrideMimeType = options.overrideMimeType;
  16224. return when(options.url, function(url) {
  16225. var deferred = when.defer();
  16226. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  16227. return deferred.promise;
  16228. });
  16229. }
  16230. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  16231. function decodeDataUriText(isBase64, data) {
  16232. var result = decodeURIComponent(data);
  16233. if (isBase64) {
  16234. return atob(result);
  16235. }
  16236. return result;
  16237. }
  16238. function decodeDataUriArrayBuffer(isBase64, data) {
  16239. var byteString = decodeDataUriText(isBase64, data);
  16240. var buffer = new ArrayBuffer(byteString.length);
  16241. var view = new Uint8Array(buffer);
  16242. for (var i = 0; i < byteString.length; i++) {
  16243. view[i] = byteString.charCodeAt(i);
  16244. }
  16245. return buffer;
  16246. }
  16247. function decodeDataUri(dataUriRegexResult, responseType) {
  16248. responseType = defaultValue(responseType, '');
  16249. var mimeType = dataUriRegexResult[1];
  16250. var isBase64 = !!dataUriRegexResult[2];
  16251. var data = dataUriRegexResult[3];
  16252. switch (responseType) {
  16253. case '':
  16254. case 'text':
  16255. return decodeDataUriText(isBase64, data);
  16256. case 'arraybuffer':
  16257. return decodeDataUriArrayBuffer(isBase64, data);
  16258. case 'blob':
  16259. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  16260. return new Blob([buffer], {
  16261. type : mimeType
  16262. });
  16263. case 'document':
  16264. var parser = new DOMParser();
  16265. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  16266. case 'json':
  16267. return JSON.parse(decodeDataUriText(isBase64, data));
  16268. default:
  16269. throw new DeveloperError('Unhandled responseType: ' + responseType);
  16270. }
  16271. }
  16272. // This is broken out into a separate function so that it can be mocked for testing purposes.
  16273. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  16274. var dataUriRegexResult = dataUriRegex.exec(url);
  16275. if (dataUriRegexResult !== null) {
  16276. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  16277. return;
  16278. }
  16279. var xhr = new XMLHttpRequest();
  16280. if (TrustedServers.contains(url)) {
  16281. xhr.withCredentials = true;
  16282. }
  16283. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  16284. xhr.overrideMimeType(overrideMimeType);
  16285. }
  16286. xhr.open(method, url, true);
  16287. if (defined(headers)) {
  16288. for (var key in headers) {
  16289. if (headers.hasOwnProperty(key)) {
  16290. xhr.setRequestHeader(key, headers[key]);
  16291. }
  16292. }
  16293. }
  16294. if (defined(responseType)) {
  16295. xhr.responseType = responseType;
  16296. }
  16297. xhr.onload = function() {
  16298. if (xhr.status < 200 || xhr.status >= 300) {
  16299. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  16300. return;
  16301. }
  16302. var response = xhr.response;
  16303. var browserResponseType = xhr.responseType;
  16304. //All modern browsers will go into either the first if block or last else block.
  16305. //Other code paths support older browsers that either do not support the supplied responseType
  16306. //or do not support the xhr.response property.
  16307. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  16308. deferred.resolve(response);
  16309. } else if ((responseType === 'json') && typeof response === 'string') {
  16310. try {
  16311. deferred.resolve(JSON.parse(response));
  16312. } catch (e) {
  16313. deferred.reject(e);
  16314. }
  16315. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  16316. deferred.resolve(xhr.responseXML);
  16317. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  16318. deferred.resolve(xhr.responseText);
  16319. } else {
  16320. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  16321. }
  16322. };
  16323. xhr.onerror = function(e) {
  16324. deferred.reject(new RequestErrorEvent());
  16325. };
  16326. xhr.send(data);
  16327. };
  16328. loadWithXhr.defaultLoad = loadWithXhr.load;
  16329. return loadWithXhr;
  16330. });
  16331. /*global define*/
  16332. define('Core/loadText',[
  16333. './loadWithXhr'
  16334. ], function(
  16335. loadWithXhr) {
  16336. 'use strict';
  16337. /**
  16338. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  16339. * a String once loaded, or reject if the URL failed to load. The data is loaded
  16340. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16341. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  16342. *
  16343. * @exports loadText
  16344. *
  16345. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  16346. * @param {Object} [headers] HTTP headers to send with the request.
  16347. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  16348. *
  16349. *
  16350. * @example
  16351. * // load text from a URL, setting a custom header
  16352. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  16353. * 'X-Custom-Header' : 'some value'
  16354. * }).then(function(text) {
  16355. * // Do something with the text
  16356. * }).otherwise(function(error) {
  16357. * // an error occurred
  16358. * });
  16359. *
  16360. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  16361. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16362. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16363. */
  16364. function loadText(url, headers) {
  16365. return loadWithXhr({
  16366. url : url,
  16367. headers : headers
  16368. });
  16369. }
  16370. return loadText;
  16371. });
  16372. /*global define*/
  16373. define('Core/loadJson',[
  16374. './clone',
  16375. './defined',
  16376. './DeveloperError',
  16377. './loadText'
  16378. ], function(
  16379. clone,
  16380. defined,
  16381. DeveloperError,
  16382. loadText) {
  16383. 'use strict';
  16384. var defaultHeaders = {
  16385. Accept : 'application/json,*/*;q=0.01'
  16386. };
  16387. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  16388. /**
  16389. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  16390. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  16391. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16392. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  16393. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  16394. * already specified.
  16395. *
  16396. * @exports loadJson
  16397. *
  16398. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  16399. * @param {Object} [headers] HTTP headers to send with the request.
  16400. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  16401. * if not specified.
  16402. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  16403. *
  16404. *
  16405. * @example
  16406. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  16407. * // Do something with the JSON object
  16408. * }).otherwise(function(error) {
  16409. * // an error occurred
  16410. * });
  16411. *
  16412. * @see loadText
  16413. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16414. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16415. */
  16416. function loadJson(url, headers) {
  16417. if (!defined(url)) {
  16418. throw new DeveloperError('url is required.');
  16419. }
  16420. if (!defined(headers)) {
  16421. headers = defaultHeaders;
  16422. } else if (!defined(headers.Accept)) {
  16423. // clone before adding the Accept header
  16424. headers = clone(headers);
  16425. headers.Accept = defaultHeaders.Accept;
  16426. }
  16427. return loadText(url, headers).then(function(value) {
  16428. return JSON.parse(value);
  16429. });
  16430. }
  16431. return loadJson;
  16432. });
  16433. /*global define*/
  16434. define('Core/EarthOrientationParameters',[
  16435. '../ThirdParty/when',
  16436. './binarySearch',
  16437. './defaultValue',
  16438. './defined',
  16439. './EarthOrientationParametersSample',
  16440. './freezeObject',
  16441. './JulianDate',
  16442. './LeapSecond',
  16443. './loadJson',
  16444. './RuntimeError',
  16445. './TimeConstants',
  16446. './TimeStandard'
  16447. ], function(
  16448. when,
  16449. binarySearch,
  16450. defaultValue,
  16451. defined,
  16452. EarthOrientationParametersSample,
  16453. freezeObject,
  16454. JulianDate,
  16455. LeapSecond,
  16456. loadJson,
  16457. RuntimeError,
  16458. TimeConstants,
  16459. TimeStandard) {
  16460. 'use strict';
  16461. /**
  16462. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  16463. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  16464. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  16465. * Reference Frame (ITRF).
  16466. *
  16467. * @alias EarthOrientationParameters
  16468. * @constructor
  16469. *
  16470. * @param {Object} [options] Object with the following properties:
  16471. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  16472. * parameter nor options.data is specified, all EOP values are assumed
  16473. * to be 0.0. If options.data is specified, this parameter is
  16474. * ignored.
  16475. * @param {Object} [options.data] The actual EOP data. If neither this
  16476. * parameter nor options.data is specified, all EOP values are assumed
  16477. * to be 0.0.
  16478. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  16479. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  16480. * should be added to {@link JulianDate.leapSeconds}. False if
  16481. * new leap seconds should be handled correctly in the context
  16482. * of the EOP data but otherwise ignored.
  16483. *
  16484. * @example
  16485. * // An example EOP data file, EOP.json:
  16486. * {
  16487. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  16488. * "samples" : [
  16489. * "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,
  16490. * "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,
  16491. * "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
  16492. * ]
  16493. * }
  16494. *
  16495. * @example
  16496. * // Loading the EOP data
  16497. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  16498. * Cesium.Transforms.earthOrientationParameters = eop;
  16499. *
  16500. * @private
  16501. */
  16502. function EarthOrientationParameters(options) {
  16503. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16504. this._dates = undefined;
  16505. this._samples = undefined;
  16506. this._dateColumn = -1;
  16507. this._xPoleWanderRadiansColumn = -1;
  16508. this._yPoleWanderRadiansColumn = -1;
  16509. this._ut1MinusUtcSecondsColumn = -1;
  16510. this._xCelestialPoleOffsetRadiansColumn = -1;
  16511. this._yCelestialPoleOffsetRadiansColumn = -1;
  16512. this._taiMinusUtcSecondsColumn = -1;
  16513. this._columnCount = 0;
  16514. this._lastIndex = -1;
  16515. this._downloadPromise = undefined;
  16516. this._dataError = undefined;
  16517. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  16518. if (defined(options.data)) {
  16519. // Use supplied EOP data.
  16520. onDataReady(this, options.data);
  16521. } else if (defined(options.url)) {
  16522. // Download EOP data.
  16523. var that = this;
  16524. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  16525. onDataReady(that, eopData);
  16526. }, function() {
  16527. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  16528. });
  16529. } else {
  16530. // Use all zeros for EOP data.
  16531. onDataReady(this, {
  16532. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  16533. 'samples' : []
  16534. });
  16535. }
  16536. }
  16537. /**
  16538. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  16539. */
  16540. EarthOrientationParameters.NONE = freezeObject({
  16541. getPromiseToLoad : function() {
  16542. return when();
  16543. },
  16544. compute : function(date, result) {
  16545. if (!defined(result)) {
  16546. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  16547. } else {
  16548. result.xPoleWander = 0.0;
  16549. result.yPoleWander = 0.0;
  16550. result.xPoleOffset = 0.0;
  16551. result.yPoleOffset = 0.0;
  16552. result.ut1MinusUtc = 0.0;
  16553. }
  16554. return result;
  16555. }
  16556. });
  16557. /**
  16558. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  16559. * ready to use.
  16560. *
  16561. * @returns {Promise.<undefined>} The promise.
  16562. *
  16563. * @see when
  16564. */
  16565. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  16566. return when(this._downloadPromise);
  16567. };
  16568. /**
  16569. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  16570. * If the EOP data has not yet been download, this method returns undefined.
  16571. *
  16572. * @param {JulianDate} date The date for each to evaluate the EOP.
  16573. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  16574. * If this parameter is undefined, a new instance is created and returned.
  16575. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  16576. * undefined if the data necessary to evaluate EOP at the date has not yet been
  16577. * downloaded.
  16578. *
  16579. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  16580. *
  16581. * @see EarthOrientationParameters#getPromiseToLoad
  16582. */
  16583. EarthOrientationParameters.prototype.compute = function(date, result) {
  16584. // We cannot compute until the samples are available.
  16585. if (!defined(this._samples)) {
  16586. if (defined(this._dataError)) {
  16587. throw new RuntimeError(this._dataError);
  16588. }
  16589. return undefined;
  16590. }
  16591. if (!defined(result)) {
  16592. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  16593. }
  16594. if (this._samples.length === 0) {
  16595. result.xPoleWander = 0.0;
  16596. result.yPoleWander = 0.0;
  16597. result.xPoleOffset = 0.0;
  16598. result.yPoleOffset = 0.0;
  16599. result.ut1MinusUtc = 0.0;
  16600. return result;
  16601. }
  16602. var dates = this._dates;
  16603. var lastIndex = this._lastIndex;
  16604. var before = 0;
  16605. var after = 0;
  16606. if (defined(lastIndex)) {
  16607. var previousIndexDate = dates[lastIndex];
  16608. var nextIndexDate = dates[lastIndex + 1];
  16609. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  16610. var isAfterLastSample = !defined(nextIndexDate);
  16611. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  16612. if (isAfterPrevious && isBeforeNext) {
  16613. before = lastIndex;
  16614. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  16615. ++before;
  16616. }
  16617. after = before + 1;
  16618. interpolate(this, dates, this._samples, date, before, after, result);
  16619. return result;
  16620. }
  16621. }
  16622. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  16623. if (index >= 0) {
  16624. // If the next entry is the same date, use the later entry. This way, if two entries
  16625. // describe the same moment, one before a leap second and the other after, then we will use
  16626. // the post-leap second data.
  16627. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  16628. ++index;
  16629. }
  16630. before = index;
  16631. after = index;
  16632. } else {
  16633. after = ~index;
  16634. before = after - 1;
  16635. // Use the first entry if the date requested is before the beginning of the data.
  16636. if (before < 0) {
  16637. before = 0;
  16638. }
  16639. }
  16640. this._lastIndex = before;
  16641. interpolate(this, dates, this._samples, date, before, after, result);
  16642. return result;
  16643. };
  16644. function compareLeapSecondDates(leapSecond, dateToFind) {
  16645. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  16646. }
  16647. function onDataReady(eop, eopData) {
  16648. if (!defined(eopData.columnNames)) {
  16649. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  16650. return;
  16651. }
  16652. if (!defined(eopData.samples)) {
  16653. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  16654. return;
  16655. }
  16656. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  16657. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  16658. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  16659. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  16660. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  16661. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  16662. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  16663. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  16664. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  16665. return;
  16666. }
  16667. var samples = eop._samples = eopData.samples;
  16668. var dates = eop._dates = [];
  16669. eop._dateColumn = dateColumn;
  16670. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  16671. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  16672. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  16673. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  16674. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  16675. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  16676. eop._columnCount = eopData.columnNames.length;
  16677. eop._lastIndex = undefined;
  16678. var lastTaiMinusUtc;
  16679. var addNewLeapSeconds = eop._addNewLeapSeconds;
  16680. // Convert the ISO8601 dates to JulianDates.
  16681. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  16682. var mjd = samples[i + dateColumn];
  16683. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  16684. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  16685. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  16686. dates.push(date);
  16687. if (addNewLeapSeconds) {
  16688. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  16689. // We crossed a leap second boundary, so add the leap second
  16690. // if it does not already exist.
  16691. var leapSeconds = JulianDate.leapSeconds;
  16692. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  16693. if (leapSecondIndex < 0) {
  16694. var leapSecond = new LeapSecond(date, taiMinusUtc);
  16695. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  16696. }
  16697. }
  16698. lastTaiMinusUtc = taiMinusUtc;
  16699. }
  16700. }
  16701. }
  16702. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  16703. var start = index * columnCount;
  16704. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  16705. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  16706. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  16707. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  16708. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  16709. }
  16710. function linearInterp(dx, y1, y2) {
  16711. return y1 + dx * (y2 - y1);
  16712. }
  16713. function interpolate(eop, dates, samples, date, before, after, result) {
  16714. var columnCount = eop._columnCount;
  16715. // First check the bounds on the EOP data
  16716. // If we are after the bounds of the data, return zeros.
  16717. // The 'before' index should never be less than zero.
  16718. if (after > dates.length - 1) {
  16719. result.xPoleWander = 0;
  16720. result.yPoleWander = 0;
  16721. result.xPoleOffset = 0;
  16722. result.yPoleOffset = 0;
  16723. result.ut1MinusUtc = 0;
  16724. return result;
  16725. }
  16726. var beforeDate = dates[before];
  16727. var afterDate = dates[after];
  16728. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  16729. fillResultFromIndex(eop, samples, before, columnCount, result);
  16730. return result;
  16731. } else if (date.equals(afterDate)) {
  16732. fillResultFromIndex(eop, samples, after, columnCount, result);
  16733. return result;
  16734. }
  16735. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  16736. var startBefore = before * columnCount;
  16737. var startAfter = after * columnCount;
  16738. // Handle UT1 leap second edge case
  16739. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  16740. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  16741. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  16742. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  16743. // The absolute difference between the values is more than 0.5, so we may have
  16744. // crossed a leap second. Check if this is the case and, if so, adjust the
  16745. // afterValue to account for the leap second. This way, our interpolation will
  16746. // produce reasonable results.
  16747. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  16748. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  16749. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  16750. if (afterDate.equals(date)) {
  16751. // If we are at the end of the leap second interval, take the second value
  16752. // Otherwise, the interpolation below will yield the wrong side of the
  16753. // discontinuity
  16754. // At the end of the leap second, we need to start accounting for the jump
  16755. beforeUt1MinusUtc = afterUt1MinusUtc;
  16756. } else {
  16757. // Otherwise, remove the leap second so that the interpolation is correct
  16758. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  16759. }
  16760. }
  16761. }
  16762. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  16763. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  16764. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  16765. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  16766. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  16767. return result;
  16768. }
  16769. return EarthOrientationParameters;
  16770. });
  16771. /*global define*/
  16772. define('Core/HeadingPitchRoll',[
  16773. './defaultValue',
  16774. './defined',
  16775. './DeveloperError',
  16776. './Math'
  16777. ], function(
  16778. defaultValue,
  16779. defined,
  16780. DeveloperError,
  16781. CesiumMath) {
  16782. "use strict";
  16783. /**
  16784. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  16785. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  16786. * the positive x axis.
  16787. * @alias HeadingPitchRoll
  16788. * @constructor
  16789. *
  16790. * @param {Number} [heading=0.0] The heading component in radians.
  16791. * @param {Number} [pitch=0.0] The pitch component in radians.
  16792. * @param {Number} [roll=0.0] The roll component in radians.
  16793. */
  16794. function HeadingPitchRoll(heading, pitch, roll) {
  16795. this.heading = defaultValue(heading, 0.0);
  16796. this.pitch = defaultValue(pitch, 0.0);
  16797. this.roll = defaultValue(roll, 0.0);
  16798. }
  16799. /**
  16800. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  16801. *
  16802. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  16803. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  16804. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  16805. */
  16806. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  16807. if (!defined(quaternion)) {
  16808. throw new DeveloperError('quaternion is required');
  16809. }
  16810. if (!defined(result)) {
  16811. result = new HeadingPitchRoll();
  16812. }
  16813. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  16814. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  16815. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  16816. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  16817. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  16818. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  16819. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  16820. result.pitch = -Math.asin(test);
  16821. return result;
  16822. };
  16823. /**
  16824. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  16825. *
  16826. * @param {Number} heading the heading in degrees
  16827. * @param {Number} pitch the pitch in degrees
  16828. * @param {Number} roll the heading in degrees
  16829. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  16830. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  16831. */
  16832. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  16833. if (!defined(heading)) {
  16834. throw new DeveloperError('heading is required');
  16835. }
  16836. if (!defined(pitch)) {
  16837. throw new DeveloperError('pitch is required');
  16838. }
  16839. if (!defined(roll)) {
  16840. throw new DeveloperError('roll is required');
  16841. }
  16842. if (!defined(result)) {
  16843. result = new HeadingPitchRoll();
  16844. }
  16845. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  16846. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  16847. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  16848. return result;
  16849. };
  16850. /**
  16851. * Duplicates a HeadingPitchRoll instance.
  16852. *
  16853. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  16854. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  16855. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  16856. */
  16857. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  16858. if (!defined(headingPitchRoll)) {
  16859. return undefined;
  16860. }
  16861. if (!defined(result)) {
  16862. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  16863. }
  16864. result.heading = headingPitchRoll.heading;
  16865. result.pitch = headingPitchRoll.pitch;
  16866. result.roll = headingPitchRoll.roll;
  16867. return result;
  16868. };
  16869. /**
  16870. * Compares the provided HeadingPitchRolls componentwise and returns
  16871. * <code>true</code> if they are equal, <code>false</code> otherwise.
  16872. *
  16873. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  16874. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  16875. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  16876. */
  16877. HeadingPitchRoll.equals = function(left, right) {
  16878. return (left === right) ||
  16879. ((defined(left)) &&
  16880. (defined(right)) &&
  16881. (left.heading === right.heading) &&
  16882. (left.pitch === right.pitch) &&
  16883. (left.roll === right.roll));
  16884. };
  16885. /**
  16886. * Compares the provided HeadingPitchRolls componentwise and returns
  16887. * <code>true</code> if they pass an absolute or relative tolerance test,
  16888. * <code>false</code> otherwise.
  16889. *
  16890. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  16891. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  16892. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  16893. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  16894. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  16895. */
  16896. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  16897. return (left === right) ||
  16898. (defined(left) &&
  16899. defined(right) &&
  16900. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  16901. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  16902. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  16903. };
  16904. /**
  16905. * Duplicates this HeadingPitchRoll instance.
  16906. *
  16907. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  16908. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  16909. */
  16910. HeadingPitchRoll.prototype.clone = function(result) {
  16911. return HeadingPitchRoll.clone(this, result);
  16912. };
  16913. /**
  16914. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  16915. * <code>true</code> if they are equal, <code>false</code> otherwise.
  16916. *
  16917. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  16918. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  16919. */
  16920. HeadingPitchRoll.prototype.equals = function(right) {
  16921. return HeadingPitchRoll.equals(this, right);
  16922. };
  16923. /**
  16924. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  16925. * <code>true</code> if they pass an absolute or relative tolerance test,
  16926. * <code>false</code> otherwise.
  16927. *
  16928. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  16929. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  16930. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  16931. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  16932. */
  16933. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  16934. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  16935. };
  16936. /**
  16937. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  16938. *
  16939. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  16940. */
  16941. HeadingPitchRoll.prototype.toString = function() {
  16942. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  16943. };
  16944. return HeadingPitchRoll;
  16945. });
  16946. /*global define*/
  16947. define('Core/getAbsoluteUri',[
  16948. '../ThirdParty/Uri',
  16949. './defaultValue',
  16950. './defined',
  16951. './DeveloperError'
  16952. ], function(
  16953. Uri,
  16954. defaultValue,
  16955. defined,
  16956. DeveloperError) {
  16957. 'use strict';
  16958. /**
  16959. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  16960. * @exports getAbsoluteUri
  16961. *
  16962. * @param {String} relative The relative Uri.
  16963. * @param {String} [base] The base Uri.
  16964. * @returns {String} The absolute Uri of the given relative Uri.
  16965. *
  16966. * @example
  16967. * //absolute Uri will be "https://test.com/awesome.png";
  16968. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  16969. */
  16970. function getAbsoluteUri(relative, base) {
  16971. if (!defined(relative)) {
  16972. throw new DeveloperError('relative uri is required.');
  16973. }
  16974. base = defaultValue(base, document.location.href);
  16975. var baseUri = new Uri(base);
  16976. var relativeUri = new Uri(relative);
  16977. return relativeUri.resolve(baseUri).toString();
  16978. }
  16979. return getAbsoluteUri;
  16980. });
  16981. /*global define*/
  16982. define('Core/joinUrls',[
  16983. '../ThirdParty/Uri',
  16984. './defaultValue',
  16985. './defined',
  16986. './DeveloperError'
  16987. ], function(
  16988. Uri,
  16989. defaultValue,
  16990. defined,
  16991. DeveloperError) {
  16992. 'use strict';
  16993. /**
  16994. * Function for joining URLs in a manner that is aware of query strings and fragments.
  16995. * This is useful when the base URL has a query string that needs to be maintained
  16996. * (e.g. a presigned base URL).
  16997. * @param {String|Uri} first The base URL.
  16998. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  16999. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  17000. * @private
  17001. */
  17002. function joinUrls(first, second, appendSlash) {
  17003. if (!defined(first)) {
  17004. throw new DeveloperError('first is required');
  17005. }
  17006. if (!defined(second)) {
  17007. throw new DeveloperError('second is required');
  17008. }
  17009. appendSlash = defaultValue(appendSlash, true);
  17010. if (!(first instanceof Uri)) {
  17011. first = new Uri(first);
  17012. }
  17013. if (!(second instanceof Uri)) {
  17014. second = new Uri(second);
  17015. }
  17016. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  17017. // not a scheme, add a scheme matching the page's scheme.
  17018. if (defined(second.authority) && !defined(second.scheme)) {
  17019. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  17020. second.scheme = new Uri(document.location.href).scheme;
  17021. } else {
  17022. // Not in a browser? Use the first URL's scheme instead.
  17023. second.scheme = first.scheme;
  17024. }
  17025. }
  17026. // If the second URL is absolute, use it for the scheme, authority, and path.
  17027. var baseUri = first;
  17028. if (second.isAbsolute()) {
  17029. baseUri = second;
  17030. }
  17031. var url = '';
  17032. if (defined(baseUri.scheme)) {
  17033. url += baseUri.scheme + ':';
  17034. }
  17035. if (defined(baseUri.authority)) {
  17036. url += '//' + baseUri.authority;
  17037. if (baseUri.path !== '' && baseUri.path !== '/') {
  17038. url = url.replace(/\/?$/, '/');
  17039. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  17040. }
  17041. }
  17042. // Combine the paths (only if second is relative).
  17043. if (baseUri === first) {
  17044. if (appendSlash) {
  17045. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  17046. } else {
  17047. url += first.path + second.path;
  17048. }
  17049. } else {
  17050. url += second.path;
  17051. }
  17052. // Combine the queries and fragments.
  17053. var hasFirstQuery = defined(first.query);
  17054. var hasSecondQuery = defined(second.query);
  17055. if (hasFirstQuery && hasSecondQuery) {
  17056. url += '?' + first.query + '&' + second.query;
  17057. } else if (hasFirstQuery && !hasSecondQuery) {
  17058. url += '?' + first.query;
  17059. } else if (!hasFirstQuery && hasSecondQuery) {
  17060. url += '?' + second.query;
  17061. }
  17062. var hasSecondFragment = defined(second.fragment);
  17063. if (defined(first.fragment) && !hasSecondFragment) {
  17064. url += '#' + first.fragment;
  17065. } else if (hasSecondFragment) {
  17066. url += '#' + second.fragment;
  17067. }
  17068. return url;
  17069. }
  17070. return joinUrls;
  17071. });
  17072. /*global define*/
  17073. define('Core/buildModuleUrl',[
  17074. '../ThirdParty/Uri',
  17075. './defined',
  17076. './DeveloperError',
  17077. './getAbsoluteUri',
  17078. './joinUrls',
  17079. 'require'
  17080. ], function(
  17081. Uri,
  17082. defined,
  17083. DeveloperError,
  17084. getAbsoluteUri,
  17085. joinUrls,
  17086. require) {
  17087. 'use strict';
  17088. /*global CESIUM_BASE_URL*/
  17089. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  17090. function getBaseUrlFromCesiumScript() {
  17091. var scripts = document.getElementsByTagName('script');
  17092. for ( var i = 0, len = scripts.length; i < len; ++i) {
  17093. var src = scripts[i].getAttribute('src');
  17094. var result = cesiumScriptRegex.exec(src);
  17095. if (result !== null) {
  17096. return result[1];
  17097. }
  17098. }
  17099. return undefined;
  17100. }
  17101. var baseUrl;
  17102. function getCesiumBaseUrl() {
  17103. if (defined(baseUrl)) {
  17104. return baseUrl;
  17105. }
  17106. var baseUrlString;
  17107. if (typeof CESIUM_BASE_URL !== 'undefined') {
  17108. baseUrlString = CESIUM_BASE_URL;
  17109. } else {
  17110. baseUrlString = getBaseUrlFromCesiumScript();
  17111. }
  17112. if (!defined(baseUrlString)) {
  17113. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  17114. }
  17115. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  17116. return baseUrl;
  17117. }
  17118. function buildModuleUrlFromRequireToUrl(moduleID) {
  17119. //moduleID will be non-relative, so require it relative to this module, in Core.
  17120. return require.toUrl('../' + moduleID);
  17121. }
  17122. function buildModuleUrlFromBaseUrl(moduleID) {
  17123. return joinUrls(getCesiumBaseUrl(), moduleID);
  17124. }
  17125. var implementation;
  17126. var a;
  17127. /**
  17128. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  17129. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  17130. * the base URL of the Cesium.js script.
  17131. *
  17132. * @private
  17133. */
  17134. function buildModuleUrl(moduleID) {
  17135. if (!defined(implementation)) {
  17136. //select implementation
  17137. if (defined(require.toUrl)) {
  17138. implementation = buildModuleUrlFromRequireToUrl;
  17139. } else {
  17140. implementation = buildModuleUrlFromBaseUrl;
  17141. }
  17142. }
  17143. if (!defined(a)) {
  17144. a = document.createElement('a');
  17145. }
  17146. var url = implementation(moduleID);
  17147. a.href = url;
  17148. a.href = a.href; // IE only absolutizes href on get, not set
  17149. return a.href;
  17150. }
  17151. // exposed for testing
  17152. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  17153. /**
  17154. * Sets the base URL for resolving modules.
  17155. * @param {String} value The new base URL.
  17156. */
  17157. buildModuleUrl.setBaseUrl = function(value) {
  17158. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  17159. };
  17160. return buildModuleUrl;
  17161. });
  17162. /*global define*/
  17163. define('Core/Iau2006XysSample',[],function() {
  17164. 'use strict';
  17165. /**
  17166. * An IAU 2006 XYS value sampled at a particular time.
  17167. *
  17168. * @alias Iau2006XysSample
  17169. * @constructor
  17170. *
  17171. * @param {Number} x The X value.
  17172. * @param {Number} y The Y value.
  17173. * @param {Number} s The S value.
  17174. *
  17175. * @private
  17176. */
  17177. function Iau2006XysSample(x, y, s) {
  17178. /**
  17179. * The X value.
  17180. * @type {Number}
  17181. */
  17182. this.x = x;
  17183. /**
  17184. * The Y value.
  17185. * @type {Number}
  17186. */
  17187. this.y = y;
  17188. /**
  17189. * The S value.
  17190. * @type {Number}
  17191. */
  17192. this.s = s;
  17193. }
  17194. return Iau2006XysSample;
  17195. });
  17196. /*global define*/
  17197. define('Core/Iau2006XysData',[
  17198. '../ThirdParty/when',
  17199. './buildModuleUrl',
  17200. './defaultValue',
  17201. './defined',
  17202. './Iau2006XysSample',
  17203. './JulianDate',
  17204. './loadJson',
  17205. './TimeStandard'
  17206. ], function(
  17207. when,
  17208. buildModuleUrl,
  17209. defaultValue,
  17210. defined,
  17211. Iau2006XysSample,
  17212. JulianDate,
  17213. loadJson,
  17214. TimeStandard) {
  17215. 'use strict';
  17216. /**
  17217. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  17218. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  17219. *
  17220. * @alias Iau2006XysData
  17221. * @constructor
  17222. *
  17223. * @param {Object} [options] Object with the following properties:
  17224. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  17225. * `{0}` will be replaced with the file index.
  17226. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  17227. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  17228. * first XYS sample.
  17229. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  17230. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  17231. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  17232. *
  17233. * @private
  17234. */
  17235. function Iau2006XysData(options) {
  17236. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  17237. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  17238. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  17239. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  17240. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  17241. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  17242. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  17243. this._totalSamples = defaultValue(options.totalSamples, 27426);
  17244. this._samples = new Array(this._totalSamples * 3);
  17245. this._chunkDownloadsInProgress = [];
  17246. var order = this._interpolationOrder;
  17247. // Compute denominators and X values for interpolation.
  17248. var denom = this._denominators = new Array(order + 1);
  17249. var xTable = this._xTable = new Array(order + 1);
  17250. var stepN = Math.pow(this._stepSizeDays, order);
  17251. for ( var i = 0; i <= order; ++i) {
  17252. denom[i] = stepN;
  17253. xTable[i] = i * this._stepSizeDays;
  17254. for ( var j = 0; j <= order; ++j) {
  17255. if (j !== i) {
  17256. denom[i] *= (i - j);
  17257. }
  17258. }
  17259. denom[i] = 1.0 / denom[i];
  17260. }
  17261. // Allocate scratch arrays for interpolation.
  17262. this._work = new Array(order + 1);
  17263. this._coef = new Array(order + 1);
  17264. }
  17265. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  17266. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  17267. var dateTT = julianDateScratch;
  17268. dateTT.dayNumber = dayTT;
  17269. dateTT.secondsOfDay = secondTT;
  17270. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  17271. }
  17272. /**
  17273. * Preloads XYS data for a specified date range.
  17274. *
  17275. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  17276. * the Terrestrial Time (TT) time standard.
  17277. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  17278. * the Terrestrial Time (TT) time standard.
  17279. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  17280. * the Terrestrial Time (TT) time standard.
  17281. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  17282. * the Terrestrial Time (TT) time standard.
  17283. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  17284. * preloaded.
  17285. */
  17286. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  17287. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  17288. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  17289. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  17290. if (startIndex < 0) {
  17291. startIndex = 0;
  17292. }
  17293. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  17294. if (stopIndex >= this._totalSamples) {
  17295. stopIndex = this._totalSamples - 1;
  17296. }
  17297. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  17298. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  17299. var promises = [];
  17300. for ( var i = startChunk; i <= stopChunk; ++i) {
  17301. promises.push(requestXysChunk(this, i));
  17302. }
  17303. return when.all(promises);
  17304. };
  17305. /**
  17306. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  17307. * this method will return undefined.
  17308. *
  17309. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  17310. * the Terrestrial Time (TT) time standard.
  17311. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  17312. * the Terrestrial Time (TT) time standard.
  17313. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  17314. * is undefined, a new instance is allocated and returned.
  17315. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  17316. * computation has not yet been downloaded.
  17317. *
  17318. * @see Iau2006XysData#preload
  17319. */
  17320. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  17321. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  17322. if (daysSinceEpoch < 0.0) {
  17323. // Can't evaluate prior to the epoch of the data.
  17324. return undefined;
  17325. }
  17326. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  17327. if (centerIndex >= this._totalSamples) {
  17328. // Can't evaluate after the last sample in the data.
  17329. return undefined;
  17330. }
  17331. var degree = this._interpolationOrder;
  17332. var firstIndex = centerIndex - ((degree / 2) | 0);
  17333. if (firstIndex < 0) {
  17334. firstIndex = 0;
  17335. }
  17336. var lastIndex = firstIndex + degree;
  17337. if (lastIndex >= this._totalSamples) {
  17338. lastIndex = this._totalSamples - 1;
  17339. firstIndex = lastIndex - degree;
  17340. if (firstIndex < 0) {
  17341. firstIndex = 0;
  17342. }
  17343. }
  17344. // Are all the samples we need present?
  17345. // We can assume so if the first and last are present
  17346. var isDataMissing = false;
  17347. var samples = this._samples;
  17348. if (!defined(samples[firstIndex * 3])) {
  17349. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  17350. isDataMissing = true;
  17351. }
  17352. if (!defined(samples[lastIndex * 3])) {
  17353. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  17354. isDataMissing = true;
  17355. }
  17356. if (isDataMissing) {
  17357. return undefined;
  17358. }
  17359. if (!defined(result)) {
  17360. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  17361. } else {
  17362. result.x = 0.0;
  17363. result.y = 0.0;
  17364. result.s = 0.0;
  17365. }
  17366. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  17367. var work = this._work;
  17368. var denom = this._denominators;
  17369. var coef = this._coef;
  17370. var xTable = this._xTable;
  17371. var i, j;
  17372. for (i = 0; i <= degree; ++i) {
  17373. work[i] = x - xTable[i];
  17374. }
  17375. for (i = 0; i <= degree; ++i) {
  17376. coef[i] = 1.0;
  17377. for (j = 0; j <= degree; ++j) {
  17378. if (j !== i) {
  17379. coef[i] *= work[j];
  17380. }
  17381. }
  17382. coef[i] *= denom[i];
  17383. var sampleIndex = (firstIndex + i) * 3;
  17384. result.x += coef[i] * samples[sampleIndex++];
  17385. result.y += coef[i] * samples[sampleIndex++];
  17386. result.s += coef[i] * samples[sampleIndex];
  17387. }
  17388. return result;
  17389. };
  17390. function requestXysChunk(xysData, chunkIndex) {
  17391. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  17392. // Chunk has already been requested.
  17393. return xysData._chunkDownloadsInProgress[chunkIndex];
  17394. }
  17395. var deferred = when.defer();
  17396. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  17397. var chunkUrl;
  17398. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  17399. if (defined(xysFileUrlTemplate)) {
  17400. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  17401. } else {
  17402. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  17403. }
  17404. when(loadJson(chunkUrl), function(chunk) {
  17405. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  17406. var samples = xysData._samples;
  17407. var newSamples = chunk.samples;
  17408. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  17409. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  17410. samples[startIndex + i] = newSamples[i];
  17411. }
  17412. deferred.resolve();
  17413. });
  17414. return deferred.promise;
  17415. }
  17416. return Iau2006XysData;
  17417. });
  17418. /*global define*/
  17419. define('Core/Fullscreen',[
  17420. './defined',
  17421. './defineProperties'
  17422. ], function(
  17423. defined,
  17424. defineProperties) {
  17425. 'use strict';
  17426. var _supportsFullscreen;
  17427. var _names = {
  17428. requestFullscreen : undefined,
  17429. exitFullscreen : undefined,
  17430. fullscreenEnabled : undefined,
  17431. fullscreenElement : undefined,
  17432. fullscreenchange : undefined,
  17433. fullscreenerror : undefined
  17434. };
  17435. /**
  17436. * Browser-independent functions for working with the standard fullscreen API.
  17437. *
  17438. * @exports Fullscreen
  17439. *
  17440. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  17441. */
  17442. var Fullscreen = {};
  17443. defineProperties(Fullscreen, {
  17444. /**
  17445. * The element that is currently fullscreen, if any. To simply check if the
  17446. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  17447. * @memberof Fullscreen
  17448. * @type {Object}
  17449. * @readonly
  17450. */
  17451. element : {
  17452. get : function() {
  17453. if (!Fullscreen.supportsFullscreen()) {
  17454. return undefined;
  17455. }
  17456. return document[_names.fullscreenElement];
  17457. }
  17458. },
  17459. /**
  17460. * The name of the event on the document that is fired when fullscreen is
  17461. * entered or exited. This event name is intended for use with addEventListener.
  17462. * In your event handler, to determine if the browser is in fullscreen mode or not,
  17463. * use {@link Fullscreen#fullscreen}.
  17464. * @memberof Fullscreen
  17465. * @type {String}
  17466. * @readonly
  17467. */
  17468. changeEventName : {
  17469. get : function() {
  17470. if (!Fullscreen.supportsFullscreen()) {
  17471. return undefined;
  17472. }
  17473. return _names.fullscreenchange;
  17474. }
  17475. },
  17476. /**
  17477. * The name of the event that is fired when a fullscreen error
  17478. * occurs. This event name is intended for use with addEventListener.
  17479. * @memberof Fullscreen
  17480. * @type {String}
  17481. * @readonly
  17482. */
  17483. errorEventName : {
  17484. get : function() {
  17485. if (!Fullscreen.supportsFullscreen()) {
  17486. return undefined;
  17487. }
  17488. return _names.fullscreenerror;
  17489. }
  17490. },
  17491. /**
  17492. * Determine whether the browser will allow an element to be made fullscreen, or not.
  17493. * For example, by default, iframes cannot go fullscreen unless the containing page
  17494. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  17495. * @memberof Fullscreen
  17496. * @type {Boolean}
  17497. * @readonly
  17498. */
  17499. enabled : {
  17500. get : function() {
  17501. if (!Fullscreen.supportsFullscreen()) {
  17502. return undefined;
  17503. }
  17504. return document[_names.fullscreenEnabled];
  17505. }
  17506. },
  17507. /**
  17508. * Determines if the browser is currently in fullscreen mode.
  17509. * @memberof Fullscreen
  17510. * @type {Boolean}
  17511. * @readonly
  17512. */
  17513. fullscreen : {
  17514. get : function() {
  17515. if (!Fullscreen.supportsFullscreen()) {
  17516. return undefined;
  17517. }
  17518. return Fullscreen.element !== null;
  17519. }
  17520. }
  17521. });
  17522. /**
  17523. * Detects whether the browser supports the standard fullscreen API.
  17524. *
  17525. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  17526. * <code>false</code> otherwise.
  17527. */
  17528. Fullscreen.supportsFullscreen = function() {
  17529. if (defined(_supportsFullscreen)) {
  17530. return _supportsFullscreen;
  17531. }
  17532. _supportsFullscreen = false;
  17533. var body = document.body;
  17534. if (typeof body.requestFullscreen === 'function') {
  17535. // go with the unprefixed, standard set of names
  17536. _names.requestFullscreen = 'requestFullscreen';
  17537. _names.exitFullscreen = 'exitFullscreen';
  17538. _names.fullscreenEnabled = 'fullscreenEnabled';
  17539. _names.fullscreenElement = 'fullscreenElement';
  17540. _names.fullscreenchange = 'fullscreenchange';
  17541. _names.fullscreenerror = 'fullscreenerror';
  17542. _supportsFullscreen = true;
  17543. return _supportsFullscreen;
  17544. }
  17545. //check for the correct combination of prefix plus the various names that browsers use
  17546. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  17547. var name;
  17548. for (var i = 0, len = prefixes.length; i < len; ++i) {
  17549. var prefix = prefixes[i];
  17550. // casing of Fullscreen differs across browsers
  17551. name = prefix + 'RequestFullscreen';
  17552. if (typeof body[name] === 'function') {
  17553. _names.requestFullscreen = name;
  17554. _supportsFullscreen = true;
  17555. } else {
  17556. name = prefix + 'RequestFullScreen';
  17557. if (typeof body[name] === 'function') {
  17558. _names.requestFullscreen = name;
  17559. _supportsFullscreen = true;
  17560. }
  17561. }
  17562. // disagreement about whether it's "exit" as per spec, or "cancel"
  17563. name = prefix + 'ExitFullscreen';
  17564. if (typeof document[name] === 'function') {
  17565. _names.exitFullscreen = name;
  17566. } else {
  17567. name = prefix + 'CancelFullScreen';
  17568. if (typeof document[name] === 'function') {
  17569. _names.exitFullscreen = name;
  17570. }
  17571. }
  17572. // casing of Fullscreen differs across browsers
  17573. name = prefix + 'FullscreenEnabled';
  17574. if (document[name] !== undefined) {
  17575. _names.fullscreenEnabled = name;
  17576. } else {
  17577. name = prefix + 'FullScreenEnabled';
  17578. if (document[name] !== undefined) {
  17579. _names.fullscreenEnabled = name;
  17580. }
  17581. }
  17582. // casing of Fullscreen differs across browsers
  17583. name = prefix + 'FullscreenElement';
  17584. if (document[name] !== undefined) {
  17585. _names.fullscreenElement = name;
  17586. } else {
  17587. name = prefix + 'FullScreenElement';
  17588. if (document[name] !== undefined) {
  17589. _names.fullscreenElement = name;
  17590. }
  17591. }
  17592. // thankfully, event names are all lowercase per spec
  17593. name = prefix + 'fullscreenchange';
  17594. // event names do not have 'on' in the front, but the property on the document does
  17595. if (document['on' + name] !== undefined) {
  17596. //except on IE
  17597. if (prefix === 'ms') {
  17598. name = 'MSFullscreenChange';
  17599. }
  17600. _names.fullscreenchange = name;
  17601. }
  17602. name = prefix + 'fullscreenerror';
  17603. if (document['on' + name] !== undefined) {
  17604. //except on IE
  17605. if (prefix === 'ms') {
  17606. name = 'MSFullscreenError';
  17607. }
  17608. _names.fullscreenerror = name;
  17609. }
  17610. }
  17611. return _supportsFullscreen;
  17612. };
  17613. /**
  17614. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  17615. * If fullscreen mode is not supported by the browser, does nothing.
  17616. *
  17617. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  17618. * @param {HMDVRDevice} [vrDevice] The VR device.
  17619. *
  17620. * @example
  17621. * // Put the entire page into fullscreen.
  17622. * Cesium.Fullscreen.requestFullscreen(document.body)
  17623. *
  17624. * // Place only the Cesium canvas into fullscreen.
  17625. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  17626. */
  17627. Fullscreen.requestFullscreen = function(element, vrDevice) {
  17628. if (!Fullscreen.supportsFullscreen()) {
  17629. return;
  17630. }
  17631. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  17632. };
  17633. /**
  17634. * Asynchronously exits fullscreen mode. If the browser is not currently
  17635. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  17636. */
  17637. Fullscreen.exitFullscreen = function() {
  17638. if (!Fullscreen.supportsFullscreen()) {
  17639. return;
  17640. }
  17641. document[_names.exitFullscreen]();
  17642. };
  17643. return Fullscreen;
  17644. });
  17645. /*global define*/
  17646. define('Core/FeatureDetection',[
  17647. './defaultValue',
  17648. './defined',
  17649. './Fullscreen'
  17650. ], function(
  17651. defaultValue,
  17652. defined,
  17653. Fullscreen) {
  17654. 'use strict';
  17655. var theNavigator;
  17656. if (typeof navigator !== 'undefined') {
  17657. theNavigator = navigator;
  17658. } else {
  17659. theNavigator = {};
  17660. }
  17661. function extractVersion(versionString) {
  17662. var parts = versionString.split('.');
  17663. for (var i = 0, len = parts.length; i < len; ++i) {
  17664. parts[i] = parseInt(parts[i], 10);
  17665. }
  17666. return parts;
  17667. }
  17668. var isChromeResult;
  17669. var chromeVersionResult;
  17670. function isChrome() {
  17671. if (!defined(isChromeResult)) {
  17672. isChromeResult = false;
  17673. // Edge contains Chrome in the user agent too
  17674. if (!isEdge()) {
  17675. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  17676. if (fields !== null) {
  17677. isChromeResult = true;
  17678. chromeVersionResult = extractVersion(fields[1]);
  17679. }
  17680. }
  17681. }
  17682. return isChromeResult;
  17683. }
  17684. function chromeVersion() {
  17685. return isChrome() && chromeVersionResult;
  17686. }
  17687. var isSafariResult;
  17688. var safariVersionResult;
  17689. function isSafari() {
  17690. if (!defined(isSafariResult)) {
  17691. isSafariResult = false;
  17692. // Chrome and Edge contain Safari in the user agent too
  17693. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  17694. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  17695. if (fields !== null) {
  17696. isSafariResult = true;
  17697. safariVersionResult = extractVersion(fields[1]);
  17698. }
  17699. }
  17700. }
  17701. return isSafariResult;
  17702. }
  17703. function safariVersion() {
  17704. return isSafari() && safariVersionResult;
  17705. }
  17706. var isWebkitResult;
  17707. var webkitVersionResult;
  17708. function isWebkit() {
  17709. if (!defined(isWebkitResult)) {
  17710. isWebkitResult = false;
  17711. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  17712. if (fields !== null) {
  17713. isWebkitResult = true;
  17714. webkitVersionResult = extractVersion(fields[1]);
  17715. webkitVersionResult.isNightly = !!fields[2];
  17716. }
  17717. }
  17718. return isWebkitResult;
  17719. }
  17720. function webkitVersion() {
  17721. return isWebkit() && webkitVersionResult;
  17722. }
  17723. var isInternetExplorerResult;
  17724. var internetExplorerVersionResult;
  17725. function isInternetExplorer() {
  17726. if (!defined(isInternetExplorerResult)) {
  17727. isInternetExplorerResult = false;
  17728. var fields;
  17729. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  17730. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  17731. if (fields !== null) {
  17732. isInternetExplorerResult = true;
  17733. internetExplorerVersionResult = extractVersion(fields[1]);
  17734. }
  17735. } else if (theNavigator.appName === 'Netscape') {
  17736. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  17737. if (fields !== null) {
  17738. isInternetExplorerResult = true;
  17739. internetExplorerVersionResult = extractVersion(fields[1]);
  17740. }
  17741. }
  17742. }
  17743. return isInternetExplorerResult;
  17744. }
  17745. function internetExplorerVersion() {
  17746. return isInternetExplorer() && internetExplorerVersionResult;
  17747. }
  17748. var isEdgeResult;
  17749. var edgeVersionResult;
  17750. function isEdge() {
  17751. if (!defined(isEdgeResult)) {
  17752. isEdgeResult = false;
  17753. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  17754. if (fields !== null) {
  17755. isEdgeResult = true;
  17756. edgeVersionResult = extractVersion(fields[1]);
  17757. }
  17758. }
  17759. return isEdgeResult;
  17760. }
  17761. function edgeVersion() {
  17762. return isEdge() && edgeVersionResult;
  17763. }
  17764. var isFirefoxResult;
  17765. var firefoxVersionResult;
  17766. function isFirefox() {
  17767. if (!defined(isFirefoxResult)) {
  17768. isFirefoxResult = false;
  17769. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  17770. if (fields !== null) {
  17771. isFirefoxResult = true;
  17772. firefoxVersionResult = extractVersion(fields[1]);
  17773. }
  17774. }
  17775. return isFirefoxResult;
  17776. }
  17777. var isWindowsResult;
  17778. function isWindows() {
  17779. if (!defined(isWindowsResult)) {
  17780. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  17781. }
  17782. return isWindowsResult;
  17783. }
  17784. function firefoxVersion() {
  17785. return isFirefox() && firefoxVersionResult;
  17786. }
  17787. var hasPointerEvents;
  17788. function supportsPointerEvents() {
  17789. if (!defined(hasPointerEvents)) {
  17790. //While navigator.pointerEnabled is deprecated in the W3C specification
  17791. //we still need to use it if it exists in order to support browsers
  17792. //that rely on it, such as the Windows WebBrowser control which defines
  17793. //PointerEvent but sets navigator.pointerEnabled to false.
  17794. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  17795. }
  17796. return hasPointerEvents;
  17797. }
  17798. var imageRenderingValueResult;
  17799. var supportsImageRenderingPixelatedResult;
  17800. function supportsImageRenderingPixelated() {
  17801. if (!defined(supportsImageRenderingPixelatedResult)) {
  17802. var canvas = document.createElement('canvas');
  17803. canvas.setAttribute('style',
  17804. 'image-rendering: -moz-crisp-edges;' +
  17805. 'image-rendering: pixelated;');
  17806. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  17807. var tmp = canvas.style.imageRendering;
  17808. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  17809. if (supportsImageRenderingPixelatedResult) {
  17810. imageRenderingValueResult = tmp;
  17811. }
  17812. }
  17813. return supportsImageRenderingPixelatedResult;
  17814. }
  17815. function imageRenderingValue() {
  17816. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  17817. }
  17818. /**
  17819. * A set of functions to detect whether the current browser supports
  17820. * various features.
  17821. *
  17822. * @exports FeatureDetection
  17823. */
  17824. var FeatureDetection = {
  17825. isChrome : isChrome,
  17826. chromeVersion : chromeVersion,
  17827. isSafari : isSafari,
  17828. safariVersion : safariVersion,
  17829. isWebkit : isWebkit,
  17830. webkitVersion : webkitVersion,
  17831. isInternetExplorer : isInternetExplorer,
  17832. internetExplorerVersion : internetExplorerVersion,
  17833. isEdge : isEdge,
  17834. edgeVersion : edgeVersion,
  17835. isFirefox : isFirefox,
  17836. firefoxVersion : firefoxVersion,
  17837. isWindows : isWindows,
  17838. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  17839. supportsPointerEvents : supportsPointerEvents,
  17840. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  17841. imageRenderingValue: imageRenderingValue
  17842. };
  17843. /**
  17844. * Detects whether the current browser supports the full screen standard.
  17845. *
  17846. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  17847. *
  17848. * @see Fullscreen
  17849. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  17850. */
  17851. FeatureDetection.supportsFullscreen = function() {
  17852. return Fullscreen.supportsFullscreen();
  17853. };
  17854. /**
  17855. * Detects whether the current browser supports typed arrays.
  17856. *
  17857. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  17858. *
  17859. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  17860. */
  17861. FeatureDetection.supportsTypedArrays = function() {
  17862. return typeof ArrayBuffer !== 'undefined';
  17863. };
  17864. /**
  17865. * Detects whether the current browser supports Web Workers.
  17866. *
  17867. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  17868. *
  17869. * @see {@link http://www.w3.org/TR/workers/}
  17870. */
  17871. FeatureDetection.supportsWebWorkers = function() {
  17872. return typeof Worker !== 'undefined';
  17873. };
  17874. return FeatureDetection;
  17875. });
  17876. /*global define*/
  17877. define('Core/Quaternion',[
  17878. './Cartesian3',
  17879. './defaultValue',
  17880. './defined',
  17881. './DeveloperError',
  17882. './FeatureDetection',
  17883. './freezeObject',
  17884. './Math',
  17885. './Matrix3'
  17886. ], function(
  17887. Cartesian3,
  17888. defaultValue,
  17889. defined,
  17890. DeveloperError,
  17891. FeatureDetection,
  17892. freezeObject,
  17893. CesiumMath,
  17894. Matrix3) {
  17895. 'use strict';
  17896. /**
  17897. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  17898. * @alias Quaternion
  17899. * @constructor
  17900. *
  17901. * @param {Number} [x=0.0] The X component.
  17902. * @param {Number} [y=0.0] The Y component.
  17903. * @param {Number} [z=0.0] The Z component.
  17904. * @param {Number} [w=0.0] The W component.
  17905. *
  17906. * @see PackableForInterpolation
  17907. */
  17908. function Quaternion(x, y, z, w) {
  17909. /**
  17910. * The X component.
  17911. * @type {Number}
  17912. * @default 0.0
  17913. */
  17914. this.x = defaultValue(x, 0.0);
  17915. /**
  17916. * The Y component.
  17917. * @type {Number}
  17918. * @default 0.0
  17919. */
  17920. this.y = defaultValue(y, 0.0);
  17921. /**
  17922. * The Z component.
  17923. * @type {Number}
  17924. * @default 0.0
  17925. */
  17926. this.z = defaultValue(z, 0.0);
  17927. /**
  17928. * The W component.
  17929. * @type {Number}
  17930. * @default 0.0
  17931. */
  17932. this.w = defaultValue(w, 0.0);
  17933. }
  17934. var fromAxisAngleScratch = new Cartesian3();
  17935. /**
  17936. * Computes a quaternion representing a rotation around an axis.
  17937. *
  17938. * @param {Cartesian3} axis The axis of rotation.
  17939. * @param {Number} angle The angle in radians to rotate around the axis.
  17940. * @param {Quaternion} [result] The object onto which to store the result.
  17941. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17942. */
  17943. Quaternion.fromAxisAngle = function(axis, angle, result) {
  17944. if (!defined(axis)) {
  17945. throw new DeveloperError('axis is required.');
  17946. }
  17947. if (typeof angle !== 'number') {
  17948. throw new DeveloperError('angle is required and must be a number.');
  17949. }
  17950. var halfAngle = angle / 2.0;
  17951. var s = Math.sin(halfAngle);
  17952. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  17953. var x = fromAxisAngleScratch.x * s;
  17954. var y = fromAxisAngleScratch.y * s;
  17955. var z = fromAxisAngleScratch.z * s;
  17956. var w = Math.cos(halfAngle);
  17957. if (!defined(result)) {
  17958. return new Quaternion(x, y, z, w);
  17959. }
  17960. result.x = x;
  17961. result.y = y;
  17962. result.z = z;
  17963. result.w = w;
  17964. return result;
  17965. };
  17966. var fromRotationMatrixNext = [1, 2, 0];
  17967. var fromRotationMatrixQuat = new Array(3);
  17968. /**
  17969. * Computes a Quaternion from the provided Matrix3 instance.
  17970. *
  17971. * @param {Matrix3} matrix The rotation matrix.
  17972. * @param {Quaternion} [result] The object onto which to store the result.
  17973. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17974. *
  17975. * @see Matrix3.fromQuaternion
  17976. */
  17977. Quaternion.fromRotationMatrix = function(matrix, result) {
  17978. if (!defined(matrix)) {
  17979. throw new DeveloperError('matrix is required.');
  17980. }
  17981. var root;
  17982. var x;
  17983. var y;
  17984. var z;
  17985. var w;
  17986. var m00 = matrix[Matrix3.COLUMN0ROW0];
  17987. var m11 = matrix[Matrix3.COLUMN1ROW1];
  17988. var m22 = matrix[Matrix3.COLUMN2ROW2];
  17989. var trace = m00 + m11 + m22;
  17990. if (trace > 0.0) {
  17991. // |w| > 1/2, may as well choose w > 1/2
  17992. root = Math.sqrt(trace + 1.0); // 2w
  17993. w = 0.5 * root;
  17994. root = 0.5 / root; // 1/(4w)
  17995. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  17996. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  17997. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  17998. } else {
  17999. // |w| <= 1/2
  18000. var next = fromRotationMatrixNext;
  18001. var i = 0;
  18002. if (m11 > m00) {
  18003. i = 1;
  18004. }
  18005. if (m22 > m00 && m22 > m11) {
  18006. i = 2;
  18007. }
  18008. var j = next[i];
  18009. var k = next[j];
  18010. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  18011. var quat = fromRotationMatrixQuat;
  18012. quat[i] = 0.5 * root;
  18013. root = 0.5 / root;
  18014. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  18015. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  18016. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  18017. x = -quat[0];
  18018. y = -quat[1];
  18019. z = -quat[2];
  18020. }
  18021. if (!defined(result)) {
  18022. return new Quaternion(x, y, z, w);
  18023. }
  18024. result.x = x;
  18025. result.y = y;
  18026. result.z = z;
  18027. result.w = w;
  18028. return result;
  18029. };
  18030. var scratchHPRQuaternion = new Quaternion();
  18031. /**
  18032. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  18033. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  18034. * the positive x axis.
  18035. *
  18036. * @param {Number} heading The heading angle in radians.
  18037. * @param {Number} pitch The pitch angle in radians.
  18038. * @param {Number} roll The roll angle in radians.
  18039. * @param {Quaternion} [result] The object onto which to store the result.
  18040. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  18041. */
  18042. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  18043. if (!defined(heading)) {
  18044. throw new DeveloperError('heading is required.');
  18045. }
  18046. if (!defined(pitch)) {
  18047. throw new DeveloperError('pitch is required.');
  18048. }
  18049. if (!defined(roll)) {
  18050. throw new DeveloperError('roll is required.');
  18051. }
  18052. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  18053. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  18054. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  18055. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  18056. return Quaternion.multiply(headingQuaternion, result, result);
  18057. };
  18058. var sampledQuaternionAxis = new Cartesian3();
  18059. var sampledQuaternionRotation = new Cartesian3();
  18060. var sampledQuaternionTempQuaternion = new Quaternion();
  18061. var sampledQuaternionQuaternion0 = new Quaternion();
  18062. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  18063. /**
  18064. * The number of elements used to pack the object into an array.
  18065. * @type {Number}
  18066. */
  18067. Quaternion.packedLength = 4;
  18068. /**
  18069. * Stores the provided instance into the provided array.
  18070. *
  18071. * @param {Quaternion} value The value to pack.
  18072. * @param {Number[]} array The array to pack into.
  18073. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  18074. *
  18075. * @returns {Number[]} The array that was packed into
  18076. */
  18077. Quaternion.pack = function(value, array, startingIndex) {
  18078. if (!defined(value)) {
  18079. throw new DeveloperError('value is required');
  18080. }
  18081. if (!defined(array)) {
  18082. throw new DeveloperError('array is required');
  18083. }
  18084. startingIndex = defaultValue(startingIndex, 0);
  18085. array[startingIndex++] = value.x;
  18086. array[startingIndex++] = value.y;
  18087. array[startingIndex++] = value.z;
  18088. array[startingIndex] = value.w;
  18089. return array;
  18090. };
  18091. /**
  18092. * Retrieves an instance from a packed array.
  18093. *
  18094. * @param {Number[]} array The packed array.
  18095. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  18096. * @param {Quaternion} [result] The object into which to store the result.
  18097. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18098. */
  18099. Quaternion.unpack = function(array, startingIndex, result) {
  18100. if (!defined(array)) {
  18101. throw new DeveloperError('array is required');
  18102. }
  18103. startingIndex = defaultValue(startingIndex, 0);
  18104. if (!defined(result)) {
  18105. result = new Quaternion();
  18106. }
  18107. result.x = array[startingIndex];
  18108. result.y = array[startingIndex + 1];
  18109. result.z = array[startingIndex + 2];
  18110. result.w = array[startingIndex + 3];
  18111. return result;
  18112. };
  18113. /**
  18114. * The number of elements used to store the object into an array in its interpolatable form.
  18115. * @type {Number}
  18116. */
  18117. Quaternion.packedInterpolationLength = 3;
  18118. /**
  18119. * Converts a packed array into a form suitable for interpolation.
  18120. *
  18121. * @param {Number[]} packedArray The packed array.
  18122. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  18123. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  18124. * @param {Number[]} result The object into which to store the result.
  18125. */
  18126. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  18127. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  18128. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  18129. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  18130. var offset = i * 3;
  18131. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  18132. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  18133. if (sampledQuaternionTempQuaternion.w < 0) {
  18134. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  18135. }
  18136. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  18137. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  18138. result[offset] = sampledQuaternionAxis.x * angle;
  18139. result[offset + 1] = sampledQuaternionAxis.y * angle;
  18140. result[offset + 2] = sampledQuaternionAxis.z * angle;
  18141. }
  18142. };
  18143. /**
  18144. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  18145. *
  18146. * @param {Number[]} array The array previously packed for interpolation.
  18147. * @param {Number[]} sourceArray The original packed array.
  18148. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  18149. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  18150. * @param {Quaternion} [result] The object into which to store the result.
  18151. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18152. */
  18153. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  18154. if (!defined(result)) {
  18155. result = new Quaternion();
  18156. }
  18157. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  18158. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  18159. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  18160. if (magnitude === 0) {
  18161. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  18162. } else {
  18163. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  18164. }
  18165. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  18166. };
  18167. /**
  18168. * Duplicates a Quaternion instance.
  18169. *
  18170. * @param {Quaternion} quaternion The quaternion to duplicate.
  18171. * @param {Quaternion} [result] The object onto which to store the result.
  18172. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  18173. */
  18174. Quaternion.clone = function(quaternion, result) {
  18175. if (!defined(quaternion)) {
  18176. return undefined;
  18177. }
  18178. if (!defined(result)) {
  18179. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  18180. }
  18181. result.x = quaternion.x;
  18182. result.y = quaternion.y;
  18183. result.z = quaternion.z;
  18184. result.w = quaternion.w;
  18185. return result;
  18186. };
  18187. /**
  18188. * Computes the conjugate of the provided quaternion.
  18189. *
  18190. * @param {Quaternion} quaternion The quaternion to conjugate.
  18191. * @param {Quaternion} result The object onto which to store the result.
  18192. * @returns {Quaternion} The modified result parameter.
  18193. */
  18194. Quaternion.conjugate = function(quaternion, result) {
  18195. if (!defined(quaternion)) {
  18196. throw new DeveloperError('quaternion is required');
  18197. }
  18198. if (!defined(result)) {
  18199. throw new DeveloperError('result is required');
  18200. }
  18201. result.x = -quaternion.x;
  18202. result.y = -quaternion.y;
  18203. result.z = -quaternion.z;
  18204. result.w = quaternion.w;
  18205. return result;
  18206. };
  18207. /**
  18208. * Computes magnitude squared for the provided quaternion.
  18209. *
  18210. * @param {Quaternion} quaternion The quaternion to conjugate.
  18211. * @returns {Number} The magnitude squared.
  18212. */
  18213. Quaternion.magnitudeSquared = function(quaternion) {
  18214. if (!defined(quaternion)) {
  18215. throw new DeveloperError('quaternion is required');
  18216. }
  18217. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  18218. };
  18219. /**
  18220. * Computes magnitude for the provided quaternion.
  18221. *
  18222. * @param {Quaternion} quaternion The quaternion to conjugate.
  18223. * @returns {Number} The magnitude.
  18224. */
  18225. Quaternion.magnitude = function(quaternion) {
  18226. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  18227. };
  18228. /**
  18229. * Computes the normalized form of the provided quaternion.
  18230. *
  18231. * @param {Quaternion} quaternion The quaternion to normalize.
  18232. * @param {Quaternion} result The object onto which to store the result.
  18233. * @returns {Quaternion} The modified result parameter.
  18234. */
  18235. Quaternion.normalize = function(quaternion, result) {
  18236. if (!defined(result)) {
  18237. throw new DeveloperError('result is required');
  18238. }
  18239. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  18240. var x = quaternion.x * inverseMagnitude;
  18241. var y = quaternion.y * inverseMagnitude;
  18242. var z = quaternion.z * inverseMagnitude;
  18243. var w = quaternion.w * inverseMagnitude;
  18244. result.x = x;
  18245. result.y = y;
  18246. result.z = z;
  18247. result.w = w;
  18248. return result;
  18249. };
  18250. /**
  18251. * Computes the inverse of the provided quaternion.
  18252. *
  18253. * @param {Quaternion} quaternion The quaternion to normalize.
  18254. * @param {Quaternion} result The object onto which to store the result.
  18255. * @returns {Quaternion} The modified result parameter.
  18256. */
  18257. Quaternion.inverse = function(quaternion, result) {
  18258. if (!defined(result)) {
  18259. throw new DeveloperError('result is required');
  18260. }
  18261. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  18262. result = Quaternion.conjugate(quaternion, result);
  18263. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  18264. };
  18265. /**
  18266. * Computes the componentwise sum of two quaternions.
  18267. *
  18268. * @param {Quaternion} left The first quaternion.
  18269. * @param {Quaternion} right The second quaternion.
  18270. * @param {Quaternion} result The object onto which to store the result.
  18271. * @returns {Quaternion} The modified result parameter.
  18272. */
  18273. Quaternion.add = function(left, right, result) {
  18274. if (!defined(left)) {
  18275. throw new DeveloperError('left is required');
  18276. }
  18277. if (!defined(right)) {
  18278. throw new DeveloperError('right is required');
  18279. }
  18280. if (!defined(result)) {
  18281. throw new DeveloperError('result is required');
  18282. }
  18283. result.x = left.x + right.x;
  18284. result.y = left.y + right.y;
  18285. result.z = left.z + right.z;
  18286. result.w = left.w + right.w;
  18287. return result;
  18288. };
  18289. /**
  18290. * Computes the componentwise difference of two quaternions.
  18291. *
  18292. * @param {Quaternion} left The first quaternion.
  18293. * @param {Quaternion} right The second quaternion.
  18294. * @param {Quaternion} result The object onto which to store the result.
  18295. * @returns {Quaternion} The modified result parameter.
  18296. */
  18297. Quaternion.subtract = function(left, right, result) {
  18298. if (!defined(left)) {
  18299. throw new DeveloperError('left is required');
  18300. }
  18301. if (!defined(right)) {
  18302. throw new DeveloperError('right is required');
  18303. }
  18304. if (!defined(result)) {
  18305. throw new DeveloperError('result is required');
  18306. }
  18307. result.x = left.x - right.x;
  18308. result.y = left.y - right.y;
  18309. result.z = left.z - right.z;
  18310. result.w = left.w - right.w;
  18311. return result;
  18312. };
  18313. /**
  18314. * Negates the provided quaternion.
  18315. *
  18316. * @param {Quaternion} quaternion The quaternion to be negated.
  18317. * @param {Quaternion} result The object onto which to store the result.
  18318. * @returns {Quaternion} The modified result parameter.
  18319. */
  18320. Quaternion.negate = function(quaternion, result) {
  18321. if (!defined(quaternion)) {
  18322. throw new DeveloperError('quaternion is required');
  18323. }
  18324. if (!defined(result)) {
  18325. throw new DeveloperError('result is required');
  18326. }
  18327. result.x = -quaternion.x;
  18328. result.y = -quaternion.y;
  18329. result.z = -quaternion.z;
  18330. result.w = -quaternion.w;
  18331. return result;
  18332. };
  18333. /**
  18334. * Computes the dot (scalar) product of two quaternions.
  18335. *
  18336. * @param {Quaternion} left The first quaternion.
  18337. * @param {Quaternion} right The second quaternion.
  18338. * @returns {Number} The dot product.
  18339. */
  18340. Quaternion.dot = function(left, right) {
  18341. if (!defined(left)) {
  18342. throw new DeveloperError('left is required');
  18343. }
  18344. if (!defined(right)) {
  18345. throw new DeveloperError('right is required');
  18346. }
  18347. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  18348. };
  18349. /**
  18350. * Computes the product of two quaternions.
  18351. *
  18352. * @param {Quaternion} left The first quaternion.
  18353. * @param {Quaternion} right The second quaternion.
  18354. * @param {Quaternion} result The object onto which to store the result.
  18355. * @returns {Quaternion} The modified result parameter.
  18356. */
  18357. Quaternion.multiply = function(left, right, result) {
  18358. if (!defined(left)) {
  18359. throw new DeveloperError('left is required');
  18360. }
  18361. if (!defined(right)) {
  18362. throw new DeveloperError('right is required');
  18363. }
  18364. if (!defined(result)) {
  18365. throw new DeveloperError('result is required');
  18366. }
  18367. var leftX = left.x;
  18368. var leftY = left.y;
  18369. var leftZ = left.z;
  18370. var leftW = left.w;
  18371. var rightX = right.x;
  18372. var rightY = right.y;
  18373. var rightZ = right.z;
  18374. var rightW = right.w;
  18375. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  18376. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  18377. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  18378. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  18379. result.x = x;
  18380. result.y = y;
  18381. result.z = z;
  18382. result.w = w;
  18383. return result;
  18384. };
  18385. /**
  18386. * Multiplies the provided quaternion componentwise by the provided scalar.
  18387. *
  18388. * @param {Quaternion} quaternion The quaternion to be scaled.
  18389. * @param {Number} scalar The scalar to multiply with.
  18390. * @param {Quaternion} result The object onto which to store the result.
  18391. * @returns {Quaternion} The modified result parameter.
  18392. */
  18393. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  18394. if (!defined(quaternion)) {
  18395. throw new DeveloperError('quaternion is required');
  18396. }
  18397. if (typeof scalar !== 'number') {
  18398. throw new DeveloperError('scalar is required and must be a number.');
  18399. }
  18400. if (!defined(result)) {
  18401. throw new DeveloperError('result is required');
  18402. }
  18403. result.x = quaternion.x * scalar;
  18404. result.y = quaternion.y * scalar;
  18405. result.z = quaternion.z * scalar;
  18406. result.w = quaternion.w * scalar;
  18407. return result;
  18408. };
  18409. /**
  18410. * Divides the provided quaternion componentwise by the provided scalar.
  18411. *
  18412. * @param {Quaternion} quaternion The quaternion to be divided.
  18413. * @param {Number} scalar The scalar to divide by.
  18414. * @param {Quaternion} result The object onto which to store the result.
  18415. * @returns {Quaternion} The modified result parameter.
  18416. */
  18417. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  18418. if (!defined(quaternion)) {
  18419. throw new DeveloperError('quaternion is required');
  18420. }
  18421. if (typeof scalar !== 'number') {
  18422. throw new DeveloperError('scalar is required and must be a number.');
  18423. }
  18424. if (!defined(result)) {
  18425. throw new DeveloperError('result is required');
  18426. }
  18427. result.x = quaternion.x / scalar;
  18428. result.y = quaternion.y / scalar;
  18429. result.z = quaternion.z / scalar;
  18430. result.w = quaternion.w / scalar;
  18431. return result;
  18432. };
  18433. /**
  18434. * Computes the axis of rotation of the provided quaternion.
  18435. *
  18436. * @param {Quaternion} quaternion The quaternion to use.
  18437. * @param {Cartesian3} result The object onto which to store the result.
  18438. * @returns {Cartesian3} The modified result parameter.
  18439. */
  18440. Quaternion.computeAxis = function(quaternion, result) {
  18441. if (!defined(quaternion)) {
  18442. throw new DeveloperError('quaternion is required');
  18443. }
  18444. if (!defined(result)) {
  18445. throw new DeveloperError('result is required');
  18446. }
  18447. var w = quaternion.w;
  18448. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  18449. result.x = result.y = result.z = 0;
  18450. return result;
  18451. }
  18452. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  18453. result.x = quaternion.x * scalar;
  18454. result.y = quaternion.y * scalar;
  18455. result.z = quaternion.z * scalar;
  18456. return result;
  18457. };
  18458. /**
  18459. * Computes the angle of rotation of the provided quaternion.
  18460. *
  18461. * @param {Quaternion} quaternion The quaternion to use.
  18462. * @returns {Number} The angle of rotation.
  18463. */
  18464. Quaternion.computeAngle = function(quaternion) {
  18465. if (!defined(quaternion)) {
  18466. throw new DeveloperError('quaternion is required');
  18467. }
  18468. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  18469. return 0.0;
  18470. }
  18471. return 2.0 * Math.acos(quaternion.w);
  18472. };
  18473. var lerpScratch = new Quaternion();
  18474. /**
  18475. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  18476. *
  18477. * @param {Quaternion} start The value corresponding to t at 0.0.
  18478. * @param {Quaternion} end The value corresponding to t at 1.0.
  18479. * @param {Number} t The point along t at which to interpolate.
  18480. * @param {Quaternion} result The object onto which to store the result.
  18481. * @returns {Quaternion} The modified result parameter.
  18482. */
  18483. Quaternion.lerp = function(start, end, t, result) {
  18484. if (!defined(start)) {
  18485. throw new DeveloperError('start is required.');
  18486. }
  18487. if (!defined(end)) {
  18488. throw new DeveloperError('end is required.');
  18489. }
  18490. if (typeof t !== 'number') {
  18491. throw new DeveloperError('t is required and must be a number.');
  18492. }
  18493. if (!defined(result)) {
  18494. throw new DeveloperError('result is required');
  18495. }
  18496. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  18497. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  18498. return Quaternion.add(lerpScratch, result, result);
  18499. };
  18500. var slerpEndNegated = new Quaternion();
  18501. var slerpScaledP = new Quaternion();
  18502. var slerpScaledR = new Quaternion();
  18503. /**
  18504. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18505. *
  18506. * @param {Quaternion} start The value corresponding to t at 0.0.
  18507. * @param {Quaternion} end The value corresponding to t at 1.0.
  18508. * @param {Number} t The point along t at which to interpolate.
  18509. * @param {Quaternion} result The object onto which to store the result.
  18510. * @returns {Quaternion} The modified result parameter.
  18511. *
  18512. * @see Quaternion#fastSlerp
  18513. */
  18514. Quaternion.slerp = function(start, end, t, result) {
  18515. if (!defined(start)) {
  18516. throw new DeveloperError('start is required.');
  18517. }
  18518. if (!defined(end)) {
  18519. throw new DeveloperError('end is required.');
  18520. }
  18521. if (typeof t !== 'number') {
  18522. throw new DeveloperError('t is required and must be a number.');
  18523. }
  18524. if (!defined(result)) {
  18525. throw new DeveloperError('result is required');
  18526. }
  18527. var dot = Quaternion.dot(start, end);
  18528. // The angle between start must be acute. Since q and -q represent
  18529. // the same rotation, negate q to get the acute angle.
  18530. var r = end;
  18531. if (dot < 0.0) {
  18532. dot = -dot;
  18533. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  18534. }
  18535. // dot > 0, as the dot product approaches 1, the angle between the
  18536. // quaternions vanishes. use linear interpolation.
  18537. if (1.0 - dot < CesiumMath.EPSILON6) {
  18538. return Quaternion.lerp(start, r, t, result);
  18539. }
  18540. var theta = Math.acos(dot);
  18541. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  18542. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  18543. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  18544. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  18545. };
  18546. /**
  18547. * The logarithmic quaternion function.
  18548. *
  18549. * @param {Quaternion} quaternion The unit quaternion.
  18550. * @param {Cartesian3} result The object onto which to store the result.
  18551. * @returns {Cartesian3} The modified result parameter.
  18552. */
  18553. Quaternion.log = function(quaternion, result) {
  18554. if (!defined(quaternion)) {
  18555. throw new DeveloperError('quaternion is required.');
  18556. }
  18557. if (!defined(result)) {
  18558. throw new DeveloperError('result is required');
  18559. }
  18560. var theta = CesiumMath.acosClamped(quaternion.w);
  18561. var thetaOverSinTheta = 0.0;
  18562. if (theta !== 0.0) {
  18563. thetaOverSinTheta = theta / Math.sin(theta);
  18564. }
  18565. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  18566. };
  18567. /**
  18568. * The exponential quaternion function.
  18569. *
  18570. * @param {Cartesian3} cartesian The cartesian.
  18571. * @param {Quaternion} result The object onto which to store the result.
  18572. * @returns {Quaternion} The modified result parameter.
  18573. */
  18574. Quaternion.exp = function(cartesian, result) {
  18575. if (!defined(cartesian)) {
  18576. throw new DeveloperError('cartesian is required.');
  18577. }
  18578. if (!defined(result)) {
  18579. throw new DeveloperError('result is required');
  18580. }
  18581. var theta = Cartesian3.magnitude(cartesian);
  18582. var sinThetaOverTheta = 0.0;
  18583. if (theta !== 0.0) {
  18584. sinThetaOverTheta = Math.sin(theta) / theta;
  18585. }
  18586. result.x = cartesian.x * sinThetaOverTheta;
  18587. result.y = cartesian.y * sinThetaOverTheta;
  18588. result.z = cartesian.z * sinThetaOverTheta;
  18589. result.w = Math.cos(theta);
  18590. return result;
  18591. };
  18592. var squadScratchCartesian0 = new Cartesian3();
  18593. var squadScratchCartesian1 = new Cartesian3();
  18594. var squadScratchQuaternion0 = new Quaternion();
  18595. var squadScratchQuaternion1 = new Quaternion();
  18596. /**
  18597. * Computes an inner quadrangle point.
  18598. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  18599. *
  18600. * @param {Quaternion} q0 The first quaternion.
  18601. * @param {Quaternion} q1 The second quaternion.
  18602. * @param {Quaternion} q2 The third quaternion.
  18603. * @param {Quaternion} result The object onto which to store the result.
  18604. * @returns {Quaternion} The modified result parameter.
  18605. *
  18606. * @see Quaternion#squad
  18607. */
  18608. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  18609. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  18610. throw new DeveloperError('q0, q1, and q2 are required.');
  18611. }
  18612. if (!defined(result)) {
  18613. throw new DeveloperError('result is required');
  18614. }
  18615. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  18616. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  18617. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  18618. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  18619. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  18620. Cartesian3.add(cart0, cart1, cart0);
  18621. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  18622. Cartesian3.negate(cart0, cart0);
  18623. Quaternion.exp(cart0, squadScratchQuaternion0);
  18624. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  18625. };
  18626. /**
  18627. * Computes the spherical quadrangle interpolation between quaternions.
  18628. *
  18629. * @param {Quaternion} q0 The first quaternion.
  18630. * @param {Quaternion} q1 The second quaternion.
  18631. * @param {Quaternion} s0 The first inner quadrangle.
  18632. * @param {Quaternion} s1 The second inner quadrangle.
  18633. * @param {Number} t The time in [0,1] used to interpolate.
  18634. * @param {Quaternion} result The object onto which to store the result.
  18635. * @returns {Quaternion} The modified result parameter.
  18636. *
  18637. *
  18638. * @example
  18639. * // 1. compute the squad interpolation between two quaternions on a curve
  18640. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  18641. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  18642. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  18643. *
  18644. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  18645. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  18646. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  18647. *
  18648. * @see Quaternion#computeInnerQuadrangle
  18649. */
  18650. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  18651. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18652. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18653. }
  18654. if (typeof t !== 'number') {
  18655. throw new DeveloperError('t is required and must be a number.');
  18656. }
  18657. if (!defined(result)) {
  18658. throw new DeveloperError('result is required');
  18659. }
  18660. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  18661. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  18662. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18663. };
  18664. var fastSlerpScratchQuaternion = new Quaternion();
  18665. var opmu = 1.90110745351730037;
  18666. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18667. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18668. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18669. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18670. for (var i = 0; i < 7; ++i) {
  18671. var s = i + 1.0;
  18672. var t = 2.0 * s + 1.0;
  18673. u[i] = 1.0 / (s * t);
  18674. v[i] = s / t;
  18675. }
  18676. u[7] = opmu / (8.0 * 17.0);
  18677. v[7] = opmu * 8.0 / 17.0;
  18678. /**
  18679. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18680. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  18681. *
  18682. * @param {Quaternion} start The value corresponding to t at 0.0.
  18683. * @param {Quaternion} end The value corresponding to t at 1.0.
  18684. * @param {Number} t The point along t at which to interpolate.
  18685. * @param {Quaternion} result The object onto which to store the result.
  18686. * @returns {Quaternion} The modified result parameter.
  18687. *
  18688. * @see Quaternion#slerp
  18689. */
  18690. Quaternion.fastSlerp = function(start, end, t, result) {
  18691. if (!defined(start)) {
  18692. throw new DeveloperError('start is required.');
  18693. }
  18694. if (!defined(end)) {
  18695. throw new DeveloperError('end is required.');
  18696. }
  18697. if (typeof t !== 'number') {
  18698. throw new DeveloperError('t is required and must be a number.');
  18699. }
  18700. if (!defined(result)) {
  18701. throw new DeveloperError('result is required');
  18702. }
  18703. var x = Quaternion.dot(start, end);
  18704. var sign;
  18705. if (x >= 0) {
  18706. sign = 1.0;
  18707. } else {
  18708. sign = -1.0;
  18709. x = -x;
  18710. }
  18711. var xm1 = x - 1.0;
  18712. var d = 1.0 - t;
  18713. var sqrT = t * t;
  18714. var sqrD = d * d;
  18715. for (var i = 7; i >= 0; --i) {
  18716. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  18717. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  18718. }
  18719. var cT = sign * t * (
  18720. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  18721. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  18722. var cD = d * (
  18723. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  18724. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  18725. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  18726. Quaternion.multiplyByScalar(end, cT, result);
  18727. return Quaternion.add(temp, result, result);
  18728. };
  18729. /**
  18730. * Computes the spherical quadrangle interpolation between quaternions.
  18731. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  18732. *
  18733. * @param {Quaternion} q0 The first quaternion.
  18734. * @param {Quaternion} q1 The second quaternion.
  18735. * @param {Quaternion} s0 The first inner quadrangle.
  18736. * @param {Quaternion} s1 The second inner quadrangle.
  18737. * @param {Number} t The time in [0,1] used to interpolate.
  18738. * @param {Quaternion} result The object onto which to store the result.
  18739. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  18740. *
  18741. * @see Quaternion#squad
  18742. */
  18743. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  18744. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18745. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18746. }
  18747. if (typeof t !== 'number') {
  18748. throw new DeveloperError('t is required and must be a number.');
  18749. }
  18750. if (!defined(result)) {
  18751. throw new DeveloperError('result is required');
  18752. }
  18753. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  18754. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  18755. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18756. };
  18757. /**
  18758. * Compares the provided quaternions componentwise and returns
  18759. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18760. *
  18761. * @param {Quaternion} [left] The first quaternion.
  18762. * @param {Quaternion} [right] The second quaternion.
  18763. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18764. */
  18765. Quaternion.equals = function(left, right) {
  18766. return (left === right) ||
  18767. ((defined(left)) &&
  18768. (defined(right)) &&
  18769. (left.x === right.x) &&
  18770. (left.y === right.y) &&
  18771. (left.z === right.z) &&
  18772. (left.w === right.w));
  18773. };
  18774. /**
  18775. * Compares the provided quaternions componentwise and returns
  18776. * <code>true</code> if they are within the provided epsilon,
  18777. * <code>false</code> otherwise.
  18778. *
  18779. * @param {Quaternion} [left] The first quaternion.
  18780. * @param {Quaternion} [right] The second quaternion.
  18781. * @param {Number} epsilon The epsilon to use for equality testing.
  18782. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18783. */
  18784. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  18785. if (typeof epsilon !== 'number') {
  18786. throw new DeveloperError('epsilon is required and must be a number.');
  18787. }
  18788. return (left === right) ||
  18789. ((defined(left)) &&
  18790. (defined(right)) &&
  18791. (Math.abs(left.x - right.x) <= epsilon) &&
  18792. (Math.abs(left.y - right.y) <= epsilon) &&
  18793. (Math.abs(left.z - right.z) <= epsilon) &&
  18794. (Math.abs(left.w - right.w) <= epsilon));
  18795. };
  18796. /**
  18797. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  18798. *
  18799. * @type {Quaternion}
  18800. * @constant
  18801. */
  18802. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  18803. /**
  18804. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  18805. *
  18806. * @type {Quaternion}
  18807. * @constant
  18808. */
  18809. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  18810. /**
  18811. * Duplicates this Quaternion instance.
  18812. *
  18813. * @param {Quaternion} [result] The object onto which to store the result.
  18814. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18815. */
  18816. Quaternion.prototype.clone = function(result) {
  18817. return Quaternion.clone(this, result);
  18818. };
  18819. /**
  18820. * Compares this and the provided quaternion componentwise and returns
  18821. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18822. *
  18823. * @param {Quaternion} [right] The right hand side quaternion.
  18824. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18825. */
  18826. Quaternion.prototype.equals = function(right) {
  18827. return Quaternion.equals(this, right);
  18828. };
  18829. /**
  18830. * Compares this and the provided quaternion componentwise and returns
  18831. * <code>true</code> if they are within the provided epsilon,
  18832. * <code>false</code> otherwise.
  18833. *
  18834. * @param {Quaternion} [right] The right hand side quaternion.
  18835. * @param {Number} epsilon The epsilon to use for equality testing.
  18836. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18837. */
  18838. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  18839. return Quaternion.equalsEpsilon(this, right, epsilon);
  18840. };
  18841. /**
  18842. * Returns a string representing this quaternion in the format (x, y, z, w).
  18843. *
  18844. * @returns {String} A string representing this Quaternion.
  18845. */
  18846. Quaternion.prototype.toString = function() {
  18847. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  18848. };
  18849. return Quaternion;
  18850. });
  18851. /*global define*/
  18852. define('Core/Transforms',[
  18853. '../ThirdParty/when',
  18854. './Cartesian2',
  18855. './Cartesian3',
  18856. './Cartesian4',
  18857. './Cartographic',
  18858. './defaultValue',
  18859. './defined',
  18860. './deprecationWarning',
  18861. './DeveloperError',
  18862. './EarthOrientationParameters',
  18863. './EarthOrientationParametersSample',
  18864. './Ellipsoid',
  18865. './HeadingPitchRoll',
  18866. './Iau2006XysData',
  18867. './Iau2006XysSample',
  18868. './JulianDate',
  18869. './Math',
  18870. './Matrix3',
  18871. './Matrix4',
  18872. './Quaternion',
  18873. './TimeConstants'
  18874. ], function(
  18875. when,
  18876. Cartesian2,
  18877. Cartesian3,
  18878. Cartesian4,
  18879. Cartographic,
  18880. defaultValue,
  18881. defined,
  18882. deprecationWarning,
  18883. DeveloperError,
  18884. EarthOrientationParameters,
  18885. EarthOrientationParametersSample,
  18886. Ellipsoid,
  18887. HeadingPitchRoll,
  18888. Iau2006XysData,
  18889. Iau2006XysSample,
  18890. JulianDate,
  18891. CesiumMath,
  18892. Matrix3,
  18893. Matrix4,
  18894. Quaternion,
  18895. TimeConstants) {
  18896. 'use strict';
  18897. /**
  18898. * Contains functions for transforming positions to various reference frames.
  18899. *
  18900. * @exports Transforms
  18901. */
  18902. var Transforms = {};
  18903. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  18904. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  18905. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  18906. /**
  18907. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  18908. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18909. * The local axes are defined as:
  18910. * <ul>
  18911. * <li>The <code>x</code> axis points in the local east direction.</li>
  18912. * <li>The <code>y</code> axis points in the local north direction.</li>
  18913. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  18914. * </ul>
  18915. *
  18916. * @param {Cartesian3} origin The center point of the local reference frame.
  18917. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18918. * @param {Matrix4} [result] The object onto which to store the result.
  18919. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18920. *
  18921. * @example
  18922. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  18923. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18924. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  18925. */
  18926. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  18927. if (!defined(origin)) {
  18928. throw new DeveloperError('origin is required.');
  18929. }
  18930. // If x and y are zero, assume origin is at a pole, which is a special case.
  18931. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18932. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18933. var sign = CesiumMath.sign(origin.z);
  18934. if (!defined(result)) {
  18935. return new Matrix4(
  18936. 0.0, -sign, 0.0, origin.x,
  18937. 1.0, 0.0, 0.0, origin.y,
  18938. 0.0, 0.0, sign, origin.z,
  18939. 0.0, 0.0, 0.0, 1.0);
  18940. }
  18941. result[0] = 0.0;
  18942. result[1] = 1.0;
  18943. result[2] = 0.0;
  18944. result[3] = 0.0;
  18945. result[4] = -sign;
  18946. result[5] = 0.0;
  18947. result[6] = 0.0;
  18948. result[7] = 0.0;
  18949. result[8] = 0.0;
  18950. result[9] = 0.0;
  18951. result[10] = sign;
  18952. result[11] = 0.0;
  18953. result[12] = origin.x;
  18954. result[13] = origin.y;
  18955. result[14] = origin.z;
  18956. result[15] = 1.0;
  18957. return result;
  18958. }
  18959. var normal = eastNorthUpToFixedFrameNormal;
  18960. var tangent = eastNorthUpToFixedFrameTangent;
  18961. var bitangent = eastNorthUpToFixedFrameBitangent;
  18962. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18963. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18964. tangent.x = -origin.y;
  18965. tangent.y = origin.x;
  18966. tangent.z = 0.0;
  18967. Cartesian3.normalize(tangent, tangent);
  18968. Cartesian3.cross(normal, tangent, bitangent);
  18969. if (!defined(result)) {
  18970. return new Matrix4(
  18971. tangent.x, bitangent.x, normal.x, origin.x,
  18972. tangent.y, bitangent.y, normal.y, origin.y,
  18973. tangent.z, bitangent.z, normal.z, origin.z,
  18974. 0.0, 0.0, 0.0, 1.0);
  18975. }
  18976. result[0] = tangent.x;
  18977. result[1] = tangent.y;
  18978. result[2] = tangent.z;
  18979. result[3] = 0.0;
  18980. result[4] = bitangent.x;
  18981. result[5] = bitangent.y;
  18982. result[6] = bitangent.z;
  18983. result[7] = 0.0;
  18984. result[8] = normal.x;
  18985. result[9] = normal.y;
  18986. result[10] = normal.z;
  18987. result[11] = 0.0;
  18988. result[12] = origin.x;
  18989. result[13] = origin.y;
  18990. result[14] = origin.z;
  18991. result[15] = 1.0;
  18992. return result;
  18993. };
  18994. var northEastDownToFixedFrameNormal = new Cartesian3();
  18995. var northEastDownToFixedFrameTangent = new Cartesian3();
  18996. var northEastDownToFixedFrameBitangent = new Cartesian3();
  18997. /**
  18998. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  18999. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19000. * The local axes are defined as:
  19001. * <ul>
  19002. * <li>The <code>x</code> axis points in the local north direction.</li>
  19003. * <li>The <code>y</code> axis points in the local east direction.</li>
  19004. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  19005. * </ul>
  19006. *
  19007. * @param {Cartesian3} origin The center point of the local reference frame.
  19008. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19009. * @param {Matrix4} [result] The object onto which to store the result.
  19010. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19011. *
  19012. * @example
  19013. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  19014. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19015. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  19016. */
  19017. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  19018. if (!defined(origin)) {
  19019. throw new DeveloperError('origin is required.');
  19020. }
  19021. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19022. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19023. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  19024. var sign = CesiumMath.sign(origin.z);
  19025. if (!defined(result)) {
  19026. return new Matrix4(
  19027. -sign, 0.0, 0.0, origin.x,
  19028. 0.0, 1.0, 0.0, origin.y,
  19029. 0.0, 0.0, -sign, origin.z,
  19030. 0.0, 0.0, 0.0, 1.0);
  19031. }
  19032. result[0] = -sign;
  19033. result[1] = 0.0;
  19034. result[2] = 0.0;
  19035. result[3] = 0.0;
  19036. result[4] = 0.0;
  19037. result[5] = 1.0;
  19038. result[6] = 0.0;
  19039. result[7] = 0.0;
  19040. result[8] = 0.0;
  19041. result[9] = 0.0;
  19042. result[10] = -sign;
  19043. result[11] = 0.0;
  19044. result[12] = origin.x;
  19045. result[13] = origin.y;
  19046. result[14] = origin.z;
  19047. result[15] = 1.0;
  19048. return result;
  19049. }
  19050. var normal = northEastDownToFixedFrameNormal;
  19051. var tangent = northEastDownToFixedFrameTangent;
  19052. var bitangent = northEastDownToFixedFrameBitangent;
  19053. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19054. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19055. tangent.x = -origin.y;
  19056. tangent.y = origin.x;
  19057. tangent.z = 0.0;
  19058. Cartesian3.normalize(tangent, tangent);
  19059. Cartesian3.cross(normal, tangent, bitangent);
  19060. if (!defined(result)) {
  19061. return new Matrix4(
  19062. bitangent.x, tangent.x, -normal.x, origin.x,
  19063. bitangent.y, tangent.y, -normal.y, origin.y,
  19064. bitangent.z, tangent.z, -normal.z, origin.z,
  19065. 0.0, 0.0, 0.0, 1.0);
  19066. }
  19067. result[0] = bitangent.x;
  19068. result[1] = bitangent.y;
  19069. result[2] = bitangent.z;
  19070. result[3] = 0.0;
  19071. result[4] = tangent.x;
  19072. result[5] = tangent.y;
  19073. result[6] = tangent.z;
  19074. result[7] = 0.0;
  19075. result[8] = -normal.x;
  19076. result[9] = -normal.y;
  19077. result[10] = -normal.z;
  19078. result[11] = 0.0;
  19079. result[12] = origin.x;
  19080. result[13] = origin.y;
  19081. result[14] = origin.z;
  19082. result[15] = 1.0;
  19083. return result;
  19084. };
  19085. /**
  19086. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  19087. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19088. * The local axes are defined as:
  19089. * <ul>
  19090. * <li>The <code>x</code> axis points in the local north direction.</li>
  19091. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19092. * <li>The <code>z</code> axis points in the local east direction.</li>
  19093. * </ul>
  19094. *
  19095. * @param {Cartesian3} origin The center point of the local reference frame.
  19096. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19097. * @param {Matrix4} [result] The object onto which to store the result.
  19098. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19099. *
  19100. * @example
  19101. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  19102. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19103. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  19104. */
  19105. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  19106. if (!defined(origin)) {
  19107. throw new DeveloperError('origin is required.');
  19108. }
  19109. // If x and y are zero, assume origin is at a pole, which is a special case.
  19110. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19111. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19112. var sign = CesiumMath.sign(origin.z);
  19113. if (!defined(result)) {
  19114. return new Matrix4(
  19115. -sign, 0.0, 0.0, origin.x,
  19116. 0.0, 0.0, 1.0, origin.y,
  19117. 0.0, sign, 0.0, origin.z,
  19118. 0.0, 0.0, 0.0, 1.0);
  19119. }
  19120. result[0] = -sign;
  19121. result[1] = 0.0;
  19122. result[2] = 0.0;
  19123. result[3] = 0.0;
  19124. result[4] = 0.0;
  19125. result[5] = 0.0;
  19126. result[6] = sign;
  19127. result[7] = 0.0;
  19128. result[8] = 0.0;
  19129. result[9] = 1.0;
  19130. result[10] = 0.0;
  19131. result[11] = 0.0;
  19132. result[12] = origin.x;
  19133. result[13] = origin.y;
  19134. result[14] = origin.z;
  19135. result[15] = 1.0;
  19136. return result;
  19137. }
  19138. var normal = eastNorthUpToFixedFrameNormal;
  19139. var tangent = eastNorthUpToFixedFrameTangent;
  19140. var bitangent = eastNorthUpToFixedFrameBitangent;
  19141. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19142. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19143. tangent.x = -origin.y;
  19144. tangent.y = origin.x;
  19145. tangent.z = 0.0;
  19146. Cartesian3.normalize(tangent, tangent);
  19147. Cartesian3.cross(normal, tangent, bitangent);
  19148. if (!defined(result)) {
  19149. return new Matrix4(
  19150. bitangent.x, normal.x, tangent.x, origin.x,
  19151. bitangent.y, normal.y, tangent.y, origin.y,
  19152. bitangent.z, normal.z, tangent.z, origin.z,
  19153. 0.0, 0.0, 0.0, 1.0);
  19154. }
  19155. result[0] = bitangent.x;
  19156. result[1] = bitangent.y;
  19157. result[2] = bitangent.z;
  19158. result[3] = 0.0;
  19159. result[4] = normal.x;
  19160. result[5] = normal.y;
  19161. result[6] = normal.z;
  19162. result[7] = 0.0;
  19163. result[8] = tangent.x;
  19164. result[9] = tangent.y;
  19165. result[10] = tangent.z;
  19166. result[11] = 0.0;
  19167. result[12] = origin.x;
  19168. result[13] = origin.y;
  19169. result[14] = origin.z;
  19170. result[15] = 1.0;
  19171. return result;
  19172. };
  19173. /**
  19174. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  19175. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19176. * The local axes are defined as:
  19177. * <ul>
  19178. * <li>The <code>x</code> axis points in the local north direction.</li>
  19179. * <li>The <code>y</code> axis points in the local west direction.</li>
  19180. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19181. * </ul>
  19182. *
  19183. * @param {Cartesian3} origin The center point of the local reference frame.
  19184. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19185. * @param {Matrix4} [result] The object onto which to store the result.
  19186. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19187. *
  19188. * @example
  19189. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  19190. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19191. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  19192. */
  19193. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  19194. if (!defined(origin)) {
  19195. throw new DeveloperError('origin is required.');
  19196. }
  19197. // If x and y are zero, assume origin is at a pole, which is a special case.
  19198. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19199. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19200. var sign = CesiumMath.sign(origin.z);
  19201. if (!defined(result)) {
  19202. return new Matrix4(
  19203. -sign, 0.0, 0.0, origin.x,
  19204. 0.0, -1.0, 0.0, origin.y,
  19205. 0.0, 0.0, sign, origin.z,
  19206. 0.0, 0.0, 0.0, 1.0);
  19207. }
  19208. result[0] = -sign;
  19209. result[1] = 0.0;
  19210. result[2] = 0.0;
  19211. result[3] = 0.0;
  19212. result[4] = 0.0;
  19213. result[5] = -1.0;
  19214. result[6] = 0.0;
  19215. result[7] = 0.0;
  19216. result[8] = 0.0;
  19217. result[9] = 0.0;
  19218. result[10] = sign;
  19219. result[11] = 0.0;
  19220. result[12] = origin.x;
  19221. result[13] = origin.y;
  19222. result[14] = origin.z;
  19223. result[15] = 1.0;
  19224. return result;
  19225. }
  19226. var normal = eastNorthUpToFixedFrameNormal;//Up
  19227. var tangent = eastNorthUpToFixedFrameTangent;//East
  19228. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  19229. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19230. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19231. tangent.x = -origin.y;
  19232. tangent.y = origin.x;
  19233. tangent.z = 0.0;
  19234. Cartesian3.normalize(tangent, tangent);
  19235. Cartesian3.cross(normal, tangent, bitangent);
  19236. if (!defined(result)) {
  19237. return new Matrix4(
  19238. bitangent.x, -tangent.x, normal.x, origin.x,
  19239. bitangent.y, -tangent.y, normal.y, origin.y,
  19240. bitangent.z, -tangent.z, normal.z, origin.z,
  19241. 0.0, 0.0, 0.0, 1.0);
  19242. }
  19243. result[0] = bitangent.x;
  19244. result[1] = bitangent.y;
  19245. result[2] = bitangent.z;
  19246. result[3] = 0.0;
  19247. result[4] = -tangent.x;
  19248. result[5] = -tangent.y;
  19249. result[6] = -tangent.z;
  19250. result[7] = 0.0;
  19251. result[8] = normal.x;
  19252. result[9] = normal.y;
  19253. result[10] = normal.z;
  19254. result[11] = 0.0;
  19255. result[12] = origin.x;
  19256. result[13] = origin.y;
  19257. result[14] = origin.z;
  19258. result[15] = 1.0;
  19259. return result;
  19260. };
  19261. var scratchHPRQuaternion = new Quaternion();
  19262. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  19263. var scratchHPRMatrix4 = new Matrix4();
  19264. /**
  19265. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  19266. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  19267. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19268. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19269. *
  19270. * @param {Cartesian3} origin The center point of the local reference frame.
  19271. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19272. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19273. * @param {Matrix4} [result] The object onto which to store the result.
  19274. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19275. *
  19276. * @example
  19277. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19278. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19279. * var heading = -Cesium.Math.PI_OVER_TWO;
  19280. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19281. * var roll = 0.0;
  19282. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  19283. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  19284. */
  19285. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19286. var heading;
  19287. if (typeof headingPitchRoll === 'object') {
  19288. // Shift arguments using assignments to encourage JIT optimization.
  19289. ellipsoid = pitch;
  19290. result = roll;
  19291. heading = headingPitchRoll.heading;
  19292. pitch = headingPitchRoll.pitch;
  19293. roll = headingPitchRoll.roll;
  19294. } else {
  19295. 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.');
  19296. heading = headingPitchRoll;
  19297. }
  19298. // checks for required parameters happen in the called functions
  19299. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  19300. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  19301. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  19302. return Matrix4.multiply(result, hprMatrix, result);
  19303. };
  19304. var scratchHPR = new HeadingPitchRoll();
  19305. var scratchENUMatrix4 = new Matrix4();
  19306. var scratchHPRMatrix3 = new Matrix3();
  19307. /**
  19308. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  19309. * centered at the provided origin. Heading is the rotation from the local north
  19310. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19311. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19312. *
  19313. * @param {Cartesian3} origin The center point of the local reference frame.
  19314. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19315. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19316. * @param {Quaternion} [result] The object onto which to store the result.
  19317. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  19318. *
  19319. * @example
  19320. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19321. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19322. * var heading = -Cesium.Math.PI_OVER_TWO;
  19323. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19324. * var roll = 0.0;
  19325. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  19326. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  19327. */
  19328. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19329. var hpr;
  19330. if (typeof headingPitchRoll === 'object') {
  19331. // Shift arguments using assignment to encourage JIT optimization.
  19332. hpr = headingPitchRoll;
  19333. ellipsoid = pitch;
  19334. result = roll;
  19335. } else {
  19336. 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.');
  19337. scratchHPR.heading = headingPitchRoll;
  19338. scratchHPR.pitch = pitch;
  19339. scratchHPR.roll = roll;
  19340. hpr = scratchHPR;
  19341. }
  19342. // checks for required parameters happen in the called functions
  19343. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  19344. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  19345. return Quaternion.fromRotationMatrix(rotation, result);
  19346. };
  19347. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  19348. var gmstConstant1 = 8640184.812866;
  19349. var gmstConstant2 = 0.093104;
  19350. var gmstConstant3 = -6.2E-6;
  19351. var rateCoef = 1.1772758384668e-19;
  19352. var wgs84WRPrecessing = 7.2921158553E-5;
  19353. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  19354. var dateInUtc = new JulianDate();
  19355. /**
  19356. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  19357. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  19358. *
  19359. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19360. * @param {Matrix3} [result] The object onto which to store the result.
  19361. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  19362. *
  19363. * @example
  19364. * //Set the view to in the inertial frame.
  19365. * scene.preRender.addEventListener(function(scene, time) {
  19366. * var now = Cesium.JulianDate.now();
  19367. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19368. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  19369. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19370. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19371. * camera.lookAtTransform(transform, offset);
  19372. * });
  19373. */
  19374. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  19375. if (!defined(date)) {
  19376. throw new DeveloperError('date is required.');
  19377. }
  19378. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  19379. // We do not want to use the function like convertTaiToUtc in JulianDate because
  19380. // we explicitly do not want to fail when inside the leap second.
  19381. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  19382. var utcDayNumber = dateInUtc.dayNumber;
  19383. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  19384. var t;
  19385. var diffDays = utcDayNumber - 2451545;
  19386. if (utcSecondsIntoDay >= 43200.0) {
  19387. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19388. } else {
  19389. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19390. }
  19391. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  19392. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  19393. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  19394. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  19395. var gha = angle + (ratio * secondsSinceMidnight);
  19396. var cosGha = Math.cos(gha);
  19397. var sinGha = Math.sin(gha);
  19398. if (!defined(result)) {
  19399. return new Matrix3(cosGha, sinGha, 0.0,
  19400. -sinGha, cosGha, 0.0,
  19401. 0.0, 0.0, 1.0);
  19402. }
  19403. result[0] = cosGha;
  19404. result[1] = -sinGha;
  19405. result[2] = 0.0;
  19406. result[3] = sinGha;
  19407. result[4] = cosGha;
  19408. result[5] = 0.0;
  19409. result[6] = 0.0;
  19410. result[7] = 0.0;
  19411. result[8] = 1.0;
  19412. return result;
  19413. };
  19414. /**
  19415. * The source of IAU 2006 XYS data, used for computing the transformation between the
  19416. * Fixed and ICRF axes.
  19417. * @type {Iau2006XysData}
  19418. *
  19419. * @see Transforms.computeIcrfToFixedMatrix
  19420. * @see Transforms.computeFixedToIcrfMatrix
  19421. *
  19422. * @private
  19423. */
  19424. Transforms.iau2006XysData = new Iau2006XysData();
  19425. /**
  19426. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  19427. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  19428. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  19429. * @type {EarthOrientationParameters}
  19430. *
  19431. * @see Transforms.computeIcrfToFixedMatrix
  19432. * @see Transforms.computeFixedToIcrfMatrix
  19433. *
  19434. * @private
  19435. */
  19436. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  19437. var ttMinusTai = 32.184;
  19438. var j2000ttDays = 2451545.0;
  19439. /**
  19440. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  19441. * direction, over a given interval. This function returns a promise that, when resolved,
  19442. * indicates that the preload has completed.
  19443. *
  19444. * @param {TimeInterval} timeInterval The interval to preload.
  19445. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  19446. * and evaluation of the transformation between the fixed and ICRF axes will
  19447. * no longer return undefined for a time inside the interval.
  19448. *
  19449. *
  19450. * @example
  19451. * var interval = new Cesium.TimeInterval(...);
  19452. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  19453. * // the data is now loaded
  19454. * });
  19455. *
  19456. * @see Transforms.computeIcrfToFixedMatrix
  19457. * @see Transforms.computeFixedToIcrfMatrix
  19458. * @see when
  19459. */
  19460. Transforms.preloadIcrfFixed = function(timeInterval) {
  19461. var startDayTT = timeInterval.start.dayNumber;
  19462. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  19463. var stopDayTT = timeInterval.stop.dayNumber;
  19464. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  19465. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  19466. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  19467. return when.all([xysPromise, eopPromise]);
  19468. };
  19469. /**
  19470. * Computes a rotation matrix to transform a point or vector from the International Celestial
  19471. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  19472. * at a given time. This function may return undefined if the data necessary to
  19473. * do the transformation is not yet loaded.
  19474. *
  19475. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19476. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19477. * not specified, a new instance is created and returned.
  19478. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19479. * transformation is not yet loaded.
  19480. *
  19481. *
  19482. * @example
  19483. * scene.preRender.addEventListener(function(scene, time) {
  19484. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  19485. * if (Cesium.defined(icrfToFixed)) {
  19486. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19487. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  19488. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19489. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19490. * camera.lookAtTransform(transform, offset);
  19491. * }
  19492. * });
  19493. *
  19494. * @see Transforms.preloadIcrfFixed
  19495. */
  19496. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  19497. if (!defined(date)) {
  19498. throw new DeveloperError('date is required.');
  19499. }
  19500. if (!defined(result)) {
  19501. result = new Matrix3();
  19502. }
  19503. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  19504. if (!defined(fixedToIcrfMtx)) {
  19505. return undefined;
  19506. }
  19507. return Matrix3.transpose(fixedToIcrfMtx, result);
  19508. };
  19509. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  19510. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  19511. var rotation1Scratch = new Matrix3();
  19512. var rotation2Scratch = new Matrix3();
  19513. /**
  19514. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  19515. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  19516. * at a given time. This function may return undefined if the data necessary to
  19517. * do the transformation is not yet loaded.
  19518. *
  19519. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19520. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19521. * not specified, a new instance is created and returned.
  19522. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19523. * transformation is not yet loaded.
  19524. *
  19525. *
  19526. * @example
  19527. * // Transform a point from the ICRF axes to the Fixed axes.
  19528. * var now = Cesium.JulianDate.now();
  19529. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19530. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  19531. * var pointInInertial = new Cesium.Cartesian3();
  19532. * if (Cesium.defined(fixedToIcrf)) {
  19533. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  19534. * }
  19535. *
  19536. * @see Transforms.preloadIcrfFixed
  19537. */
  19538. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  19539. if (!defined(date)) {
  19540. throw new DeveloperError('date is required.');
  19541. }
  19542. if (!defined(result)) {
  19543. result = new Matrix3();
  19544. }
  19545. // Compute pole wander
  19546. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  19547. if (!defined(eop)) {
  19548. return undefined;
  19549. }
  19550. // There is no external conversion to Terrestrial Time (TT).
  19551. // So use International Atomic Time (TAI) and convert using offsets.
  19552. // Here we are assuming that dayTT and secondTT are positive
  19553. var dayTT = date.dayNumber;
  19554. // It's possible here that secondTT could roll over 86400
  19555. // This does not seem to affect the precision (unit tests check for this)
  19556. var secondTT = date.secondsOfDay + ttMinusTai;
  19557. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  19558. if (!defined(xys)) {
  19559. return undefined;
  19560. }
  19561. var x = xys.x + eop.xPoleOffset;
  19562. var y = xys.y + eop.yPoleOffset;
  19563. // Compute XYS rotation
  19564. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  19565. var rotation1 = rotation1Scratch;
  19566. rotation1[0] = 1.0 - a * x * x;
  19567. rotation1[3] = -a * x * y;
  19568. rotation1[6] = x;
  19569. rotation1[1] = -a * x * y;
  19570. rotation1[4] = 1 - a * y * y;
  19571. rotation1[7] = y;
  19572. rotation1[2] = -x;
  19573. rotation1[5] = -y;
  19574. rotation1[8] = 1 - a * (x * x + y * y);
  19575. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  19576. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  19577. // Similar to TT conversions above
  19578. // It's possible here that secondTT could roll over 86400
  19579. // This does not seem to affect the precision (unit tests check for this)
  19580. var dateUt1day = date.dayNumber;
  19581. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  19582. // Compute Earth rotation angle
  19583. // The IERS standard for era is
  19584. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  19585. // where
  19586. // Tu = JulianDateInUt1 - 2451545.0
  19587. // However, you get much more precision if you make the following simplification
  19588. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  19589. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19590. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19591. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  19592. var daysSinceJ2000 = dateUt1day - 2451545;
  19593. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  19594. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  19595. era = (era % 1.0) * CesiumMath.TWO_PI;
  19596. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  19597. // pseudoFixed to ICRF
  19598. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  19599. // Compute pole wander matrix
  19600. var cosxp = Math.cos(eop.xPoleWander);
  19601. var cosyp = Math.cos(eop.yPoleWander);
  19602. var sinxp = Math.sin(eop.xPoleWander);
  19603. var sinyp = Math.sin(eop.yPoleWander);
  19604. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  19605. ttt /= 36525.0;
  19606. // approximate sp value in rad
  19607. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  19608. var cossp = Math.cos(sp);
  19609. var sinsp = Math.sin(sp);
  19610. var fToPfMtx = rotation2Scratch;
  19611. fToPfMtx[0] = cosxp * cossp;
  19612. fToPfMtx[1] = cosxp * sinsp;
  19613. fToPfMtx[2] = sinxp;
  19614. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  19615. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  19616. fToPfMtx[5] = -sinyp * cosxp;
  19617. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  19618. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  19619. fToPfMtx[8] = cosyp * cosxp;
  19620. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  19621. };
  19622. var pointToWindowCoordinatesTemp = new Cartesian4();
  19623. /**
  19624. * Transform a point from model coordinates to window coordinates.
  19625. *
  19626. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  19627. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  19628. * @param {Cartesian3} point The point to transform.
  19629. * @param {Cartesian2} [result] The object onto which to store the result.
  19630. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19631. */
  19632. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  19633. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  19634. result.y = 2.0 * viewportTransformation[5] - result.y;
  19635. return result;
  19636. };
  19637. /**
  19638. * @private
  19639. */
  19640. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  19641. if (!defined(modelViewProjectionMatrix)) {
  19642. throw new DeveloperError('modelViewProjectionMatrix is required.');
  19643. }
  19644. if (!defined(viewportTransformation)) {
  19645. throw new DeveloperError('viewportTransformation is required.');
  19646. }
  19647. if (!defined(point)) {
  19648. throw new DeveloperError('point is required.');
  19649. }
  19650. if (!defined(result)) {
  19651. result = new Cartesian2();
  19652. }
  19653. var tmp = pointToWindowCoordinatesTemp;
  19654. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  19655. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  19656. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  19657. return Cartesian2.fromCartesian4(tmp, result);
  19658. };
  19659. var normalScratch = new Cartesian3();
  19660. var rightScratch = new Cartesian3();
  19661. var upScratch = new Cartesian3();
  19662. /**
  19663. * @private
  19664. */
  19665. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  19666. if (!defined(position)) {
  19667. throw new DeveloperError('position is required.');
  19668. }
  19669. if (!defined(velocity)) {
  19670. throw new DeveloperError('velocity is required.');
  19671. }
  19672. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  19673. var right = Cartesian3.cross(velocity, normal, rightScratch);
  19674. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  19675. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  19676. }
  19677. var up = Cartesian3.cross(right, velocity, upScratch);
  19678. Cartesian3.cross(velocity, up, right);
  19679. Cartesian3.negate(right, right);
  19680. if (!defined(result)) {
  19681. result = new Matrix3();
  19682. }
  19683. result[0] = velocity.x;
  19684. result[1] = velocity.y;
  19685. result[2] = velocity.z;
  19686. result[3] = right.x;
  19687. result[4] = right.y;
  19688. result[5] = right.z;
  19689. result[6] = up.x;
  19690. result[7] = up.y;
  19691. result[8] = up.z;
  19692. return result;
  19693. };
  19694. var scratchCartographic = new Cartographic();
  19695. var scratchCartesian3Projection = new Cartesian3();
  19696. var scratchCartesian3 = new Cartesian3();
  19697. var scratchCartesian4Origin = new Cartesian4();
  19698. var scratchCartesian4NewOrigin = new Cartesian4();
  19699. var scratchCartesian4NewXAxis = new Cartesian4();
  19700. var scratchCartesian4NewYAxis = new Cartesian4();
  19701. var scratchCartesian4NewZAxis = new Cartesian4();
  19702. var scratchFromENU = new Matrix4();
  19703. var scratchToENU = new Matrix4();
  19704. /**
  19705. * @private
  19706. */
  19707. Transforms.basisTo2D = function(projection, matrix, result) {
  19708. if (!defined(projection)) {
  19709. throw new DeveloperError('projection is required.');
  19710. }
  19711. if (!defined(matrix)) {
  19712. throw new DeveloperError('matrix is required.');
  19713. }
  19714. if (!defined(result)) {
  19715. throw new DeveloperError('result is required.');
  19716. }
  19717. var ellipsoid = projection.ellipsoid;
  19718. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  19719. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  19720. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  19721. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  19722. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  19723. var newOrigin = scratchCartesian4NewOrigin;
  19724. newOrigin.x = projectedPosition.z;
  19725. newOrigin.y = projectedPosition.x;
  19726. newOrigin.z = projectedPosition.y;
  19727. newOrigin.w = 1.0;
  19728. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  19729. var xScale = Cartesian3.magnitude(xAxis);
  19730. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  19731. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  19732. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  19733. var yScale = Cartesian3.magnitude(yAxis);
  19734. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  19735. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  19736. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  19737. var zScale = Cartesian3.magnitude(zAxis);
  19738. var newZAxis = scratchCartesian4NewZAxis;
  19739. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  19740. Cartesian3.normalize(newZAxis, newZAxis);
  19741. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  19742. Cartesian3.normalize(newXAxis, newXAxis);
  19743. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  19744. Cartesian3.normalize(newYAxis, newYAxis);
  19745. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  19746. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  19747. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  19748. Matrix4.setColumn(result, 0, newXAxis, result);
  19749. Matrix4.setColumn(result, 1, newYAxis, result);
  19750. Matrix4.setColumn(result, 2, newZAxis, result);
  19751. Matrix4.setColumn(result, 3, newOrigin, result);
  19752. return result;
  19753. };
  19754. return Transforms;
  19755. });
  19756. /*global define*/
  19757. define('Core/EllipsoidTangentPlane',[
  19758. './AxisAlignedBoundingBox',
  19759. './Cartesian2',
  19760. './Cartesian3',
  19761. './Cartesian4',
  19762. './defaultValue',
  19763. './defined',
  19764. './defineProperties',
  19765. './DeveloperError',
  19766. './Ellipsoid',
  19767. './IntersectionTests',
  19768. './Matrix4',
  19769. './Plane',
  19770. './Ray',
  19771. './Transforms'
  19772. ], function(
  19773. AxisAlignedBoundingBox,
  19774. Cartesian2,
  19775. Cartesian3,
  19776. Cartesian4,
  19777. defaultValue,
  19778. defined,
  19779. defineProperties,
  19780. DeveloperError,
  19781. Ellipsoid,
  19782. IntersectionTests,
  19783. Matrix4,
  19784. Plane,
  19785. Ray,
  19786. Transforms) {
  19787. 'use strict';
  19788. var scratchCart4 = new Cartesian4();
  19789. /**
  19790. * A plane tangent to the provided ellipsoid at the provided origin.
  19791. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  19792. * If origin is at the center of the ellipsoid, an exception will be thrown.
  19793. * @alias EllipsoidTangentPlane
  19794. * @constructor
  19795. *
  19796. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  19797. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  19798. *
  19799. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  19800. */
  19801. function EllipsoidTangentPlane(origin, ellipsoid) {
  19802. if (!defined(origin)) {
  19803. throw new DeveloperError('origin is required.');
  19804. }
  19805. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19806. origin = ellipsoid.scaleToGeodeticSurface(origin);
  19807. if (!defined(origin)) {
  19808. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  19809. }
  19810. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  19811. this._ellipsoid = ellipsoid;
  19812. this._origin = origin;
  19813. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  19814. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  19815. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  19816. this._plane = Plane.fromPointNormal(origin, normal);
  19817. }
  19818. defineProperties(EllipsoidTangentPlane.prototype, {
  19819. /**
  19820. * Gets the ellipsoid.
  19821. * @memberof EllipsoidTangentPlane.prototype
  19822. * @type {Ellipsoid}
  19823. */
  19824. ellipsoid : {
  19825. get : function() {
  19826. return this._ellipsoid;
  19827. }
  19828. },
  19829. /**
  19830. * Gets the origin.
  19831. * @memberof EllipsoidTangentPlane.prototype
  19832. * @type {Cartesian3}
  19833. */
  19834. origin : {
  19835. get : function() {
  19836. return this._origin;
  19837. }
  19838. },
  19839. /**
  19840. * Gets the plane which is tangent to the ellipsoid.
  19841. * @memberof EllipsoidTangentPlane.prototype
  19842. * @readonly
  19843. * @type {Plane}
  19844. */
  19845. plane : {
  19846. get : function() {
  19847. return this._plane;
  19848. }
  19849. },
  19850. /**
  19851. * Gets the local X-axis (east) of the tangent plane.
  19852. * @memberof EllipsoidTangentPlane.prototype
  19853. * @readonly
  19854. * @type {Cartesian3}
  19855. */
  19856. xAxis : {
  19857. get : function() {
  19858. return this._xAxis;
  19859. }
  19860. },
  19861. /**
  19862. * Gets the local Y-axis (north) of the tangent plane.
  19863. * @memberof EllipsoidTangentPlane.prototype
  19864. * @readonly
  19865. * @type {Cartesian3}
  19866. */
  19867. yAxis : {
  19868. get : function() {
  19869. return this._yAxis;
  19870. }
  19871. },
  19872. /**
  19873. * Gets the local Z-axis (up) of the tangent plane.
  19874. * @member EllipsoidTangentPlane.prototype
  19875. * @readonly
  19876. * @type {Cartesian3}
  19877. */
  19878. zAxis : {
  19879. get : function() {
  19880. return this._plane.normal;
  19881. }
  19882. }
  19883. });
  19884. var tmp = new AxisAlignedBoundingBox();
  19885. /**
  19886. * Creates a new instance from the provided ellipsoid and the center
  19887. * point of the provided Cartesians.
  19888. *
  19889. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  19890. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  19891. */
  19892. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  19893. if (!defined(cartesians)) {
  19894. throw new DeveloperError('cartesians is required.');
  19895. }
  19896. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  19897. return new EllipsoidTangentPlane(box.center, ellipsoid);
  19898. };
  19899. var scratchProjectPointOntoPlaneRay = new Ray();
  19900. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  19901. /**
  19902. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  19903. *
  19904. * @param {Cartesian3} cartesian The point to project.
  19905. * @param {Cartesian2} [result] The object onto which to store the result.
  19906. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  19907. */
  19908. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  19909. if (!defined(cartesian)) {
  19910. throw new DeveloperError('cartesian is required.');
  19911. }
  19912. var ray = scratchProjectPointOntoPlaneRay;
  19913. ray.origin = cartesian;
  19914. Cartesian3.normalize(cartesian, ray.direction);
  19915. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19916. if (!defined(intersectionPoint)) {
  19917. Cartesian3.negate(ray.direction, ray.direction);
  19918. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19919. }
  19920. if (defined(intersectionPoint)) {
  19921. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19922. var x = Cartesian3.dot(this._xAxis, v);
  19923. var y = Cartesian3.dot(this._yAxis, v);
  19924. if (!defined(result)) {
  19925. return new Cartesian2(x, y);
  19926. }
  19927. result.x = x;
  19928. result.y = y;
  19929. return result;
  19930. }
  19931. return undefined;
  19932. };
  19933. /**
  19934. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  19935. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  19936. *
  19937. * @see EllipsoidTangentPlane.projectPointOntoPlane
  19938. *
  19939. * @param {Cartesian3[]} cartesians The array of points to project.
  19940. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19941. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  19942. */
  19943. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  19944. if (!defined(cartesians)) {
  19945. throw new DeveloperError('cartesians is required.');
  19946. }
  19947. if (!defined(result)) {
  19948. result = [];
  19949. }
  19950. var count = 0;
  19951. var length = cartesians.length;
  19952. for ( var i = 0; i < length; i++) {
  19953. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  19954. if (defined(p)) {
  19955. result[count] = p;
  19956. count++;
  19957. }
  19958. }
  19959. result.length = count;
  19960. return result;
  19961. };
  19962. /**
  19963. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  19964. *
  19965. * @param {Cartesian3} cartesian The point to project.
  19966. * @param {Cartesian2} [result] The object onto which to store the result.
  19967. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19968. */
  19969. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  19970. if (!defined(cartesian)) {
  19971. throw new DeveloperError('cartesian is required.');
  19972. }
  19973. if (!defined(result)) {
  19974. result = new Cartesian2();
  19975. }
  19976. var ray = scratchProjectPointOntoPlaneRay;
  19977. ray.origin = cartesian;
  19978. Cartesian3.clone(this._plane.normal, ray.direction);
  19979. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19980. if (!defined(intersectionPoint)) {
  19981. Cartesian3.negate(ray.direction, ray.direction);
  19982. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19983. }
  19984. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19985. var x = Cartesian3.dot(this._xAxis, v);
  19986. var y = Cartesian3.dot(this._yAxis, v);
  19987. result.x = x;
  19988. result.y = y;
  19989. return result;
  19990. };
  19991. /**
  19992. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  19993. *
  19994. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  19995. *
  19996. * @param {Cartesian3[]} cartesians The array of points to project.
  19997. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19998. * @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>.
  19999. */
  20000. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  20001. if (!defined(cartesians)) {
  20002. throw new DeveloperError('cartesians is required.');
  20003. }
  20004. if (!defined(result)) {
  20005. result = [];
  20006. }
  20007. var length = cartesians.length;
  20008. result.length = length;
  20009. for (var i = 0; i < length; i++) {
  20010. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  20011. }
  20012. return result;
  20013. };
  20014. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  20015. /**
  20016. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  20017. *
  20018. * @param {Cartesian2[]} cartesians The array of points to project.
  20019. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  20020. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  20021. */
  20022. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  20023. if (!defined(cartesians)) {
  20024. throw new DeveloperError('cartesians is required.');
  20025. }
  20026. var length = cartesians.length;
  20027. if (!defined(result)) {
  20028. result = new Array(length);
  20029. } else {
  20030. result.length = length;
  20031. }
  20032. var ellipsoid = this._ellipsoid;
  20033. var origin = this._origin;
  20034. var xAxis = this._xAxis;
  20035. var yAxis = this._yAxis;
  20036. var tmp = projectPointsOntoEllipsoidScratch;
  20037. for ( var i = 0; i < length; ++i) {
  20038. var position = cartesians[i];
  20039. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  20040. if (!defined(result[i])) {
  20041. result[i] = new Cartesian3();
  20042. }
  20043. var point = Cartesian3.add(origin, tmp, result[i]);
  20044. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  20045. Cartesian3.add(point, tmp, point);
  20046. ellipsoid.scaleToGeocentricSurface(point, point);
  20047. }
  20048. return result;
  20049. };
  20050. return EllipsoidTangentPlane;
  20051. });
  20052. /*global define*/
  20053. define('Core/OrientedBoundingBox',[
  20054. './BoundingSphere',
  20055. './Cartesian2',
  20056. './Cartesian3',
  20057. './Cartographic',
  20058. './defaultValue',
  20059. './defined',
  20060. './DeveloperError',
  20061. './Ellipsoid',
  20062. './EllipsoidTangentPlane',
  20063. './Intersect',
  20064. './Interval',
  20065. './Math',
  20066. './Matrix3',
  20067. './Plane',
  20068. './Rectangle'
  20069. ], function(
  20070. BoundingSphere,
  20071. Cartesian2,
  20072. Cartesian3,
  20073. Cartographic,
  20074. defaultValue,
  20075. defined,
  20076. DeveloperError,
  20077. Ellipsoid,
  20078. EllipsoidTangentPlane,
  20079. Intersect,
  20080. Interval,
  20081. CesiumMath,
  20082. Matrix3,
  20083. Plane,
  20084. Rectangle) {
  20085. 'use strict';
  20086. /**
  20087. * Creates an instance of an OrientedBoundingBox.
  20088. * An OrientedBoundingBox of some object is a closed and convex cuboid. It can provide a tighter bounding volume than {@link BoundingSphere} or {@link AxisAlignedBoundingBox} in many cases.
  20089. * @alias OrientedBoundingBox
  20090. * @constructor
  20091. *
  20092. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the box.
  20093. * @param {Matrix3} [halfAxes=Matrix3.ZERO] The three orthogonal half-axes of the bounding box.
  20094. * Equivalently, the transformation matrix, to rotate and scale a 2x2x2
  20095. * cube centered at the origin.
  20096. *
  20097. *
  20098. * @example
  20099. * // Create an OrientedBoundingBox using a transformation matrix, a position where the box will be translated, and a scale.
  20100. * var center = new Cesium.Cartesian3(1.0, 0.0, 0.0);
  20101. * var halfAxes = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(1.0, 3.0, 2.0), new Cesium.Matrix3());
  20102. *
  20103. * var obb = new Cesium.OrientedBoundingBox(center, halfAxes);
  20104. *
  20105. * @see BoundingSphere
  20106. * @see BoundingRectangle
  20107. */
  20108. function OrientedBoundingBox(center, halfAxes) {
  20109. /**
  20110. * The center of the box.
  20111. * @type {Cartesian3}
  20112. * @default {@link Cartesian3.ZERO}
  20113. */
  20114. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  20115. /**
  20116. * The transformation matrix, to rotate the box to the right position.
  20117. * @type {Matrix3}
  20118. * @default {@link Matrix3.IDENTITY}
  20119. */
  20120. this.halfAxes = Matrix3.clone(defaultValue(halfAxes, Matrix3.ZERO));
  20121. }
  20122. var scratchCartesian1 = new Cartesian3();
  20123. var scratchCartesian2 = new Cartesian3();
  20124. var scratchCartesian3 = new Cartesian3();
  20125. var scratchCartesian4 = new Cartesian3();
  20126. var scratchCartesian5 = new Cartesian3();
  20127. var scratchCartesian6 = new Cartesian3();
  20128. var scratchCovarianceResult = new Matrix3();
  20129. var scratchEigenResult = {
  20130. unitary : new Matrix3(),
  20131. diagonal : new Matrix3()
  20132. };
  20133. /**
  20134. * Computes an instance of an OrientedBoundingBox of the given positions.
  20135. * This is an implementation of Stefan Gottschalk's Collision Queries using Oriented Bounding Boxes solution (PHD thesis).
  20136. * Reference: http://gamma.cs.unc.edu/users/gottschalk/main.pdf
  20137. *
  20138. * @param {Cartesian3[]} positions List of {@link Cartesian3} points that the bounding box will enclose.
  20139. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  20140. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  20141. *
  20142. * @example
  20143. * // Compute an object oriented bounding box enclosing two points.
  20144. * var box = Cesium.OrientedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  20145. */
  20146. OrientedBoundingBox.fromPoints = function(positions, result) {
  20147. if (!defined(result)) {
  20148. result = new OrientedBoundingBox();
  20149. }
  20150. if (!defined(positions) || positions.length === 0) {
  20151. result.halfAxes = Matrix3.ZERO;
  20152. result.center = Cartesian3.ZERO;
  20153. return result;
  20154. }
  20155. var i;
  20156. var length = positions.length;
  20157. var meanPoint = Cartesian3.clone(positions[0], scratchCartesian1);
  20158. for (i = 1; i < length; i++) {
  20159. Cartesian3.add(meanPoint, positions[i], meanPoint);
  20160. }
  20161. var invLength = 1.0 / length;
  20162. Cartesian3.multiplyByScalar(meanPoint, invLength, meanPoint);
  20163. var exx = 0.0;
  20164. var exy = 0.0;
  20165. var exz = 0.0;
  20166. var eyy = 0.0;
  20167. var eyz = 0.0;
  20168. var ezz = 0.0;
  20169. var p;
  20170. for (i = 0; i < length; i++) {
  20171. p = Cartesian3.subtract(positions[i], meanPoint, scratchCartesian2);
  20172. exx += p.x * p.x;
  20173. exy += p.x * p.y;
  20174. exz += p.x * p.z;
  20175. eyy += p.y * p.y;
  20176. eyz += p.y * p.z;
  20177. ezz += p.z * p.z;
  20178. }
  20179. exx *= invLength;
  20180. exy *= invLength;
  20181. exz *= invLength;
  20182. eyy *= invLength;
  20183. eyz *= invLength;
  20184. ezz *= invLength;
  20185. var covarianceMatrix = scratchCovarianceResult;
  20186. covarianceMatrix[0] = exx;
  20187. covarianceMatrix[1] = exy;
  20188. covarianceMatrix[2] = exz;
  20189. covarianceMatrix[3] = exy;
  20190. covarianceMatrix[4] = eyy;
  20191. covarianceMatrix[5] = eyz;
  20192. covarianceMatrix[6] = exz;
  20193. covarianceMatrix[7] = eyz;
  20194. covarianceMatrix[8] = ezz;
  20195. var eigenDecomposition = Matrix3.computeEigenDecomposition(covarianceMatrix, scratchEigenResult);
  20196. var rotation = Matrix3.clone(eigenDecomposition.unitary, result.halfAxes);
  20197. var v1 = Matrix3.getColumn(rotation, 0, scratchCartesian4);
  20198. var v2 = Matrix3.getColumn(rotation, 1, scratchCartesian5);
  20199. var v3 = Matrix3.getColumn(rotation, 2, scratchCartesian6);
  20200. var u1 = -Number.MAX_VALUE;
  20201. var u2 = -Number.MAX_VALUE;
  20202. var u3 = -Number.MAX_VALUE;
  20203. var l1 = Number.MAX_VALUE;
  20204. var l2 = Number.MAX_VALUE;
  20205. var l3 = Number.MAX_VALUE;
  20206. for (i = 0; i < length; i++) {
  20207. p = positions[i];
  20208. u1 = Math.max(Cartesian3.dot(v1, p), u1);
  20209. u2 = Math.max(Cartesian3.dot(v2, p), u2);
  20210. u3 = Math.max(Cartesian3.dot(v3, p), u3);
  20211. l1 = Math.min(Cartesian3.dot(v1, p), l1);
  20212. l2 = Math.min(Cartesian3.dot(v2, p), l2);
  20213. l3 = Math.min(Cartesian3.dot(v3, p), l3);
  20214. }
  20215. v1 = Cartesian3.multiplyByScalar(v1, 0.5 * (l1 + u1), v1);
  20216. v2 = Cartesian3.multiplyByScalar(v2, 0.5 * (l2 + u2), v2);
  20217. v3 = Cartesian3.multiplyByScalar(v3, 0.5 * (l3 + u3), v3);
  20218. var center = Cartesian3.add(v1, v2, result.center);
  20219. center = Cartesian3.add(center, v3, center);
  20220. var scale = scratchCartesian3;
  20221. scale.x = u1 - l1;
  20222. scale.y = u2 - l2;
  20223. scale.z = u3 - l3;
  20224. Cartesian3.multiplyByScalar(scale, 0.5, scale);
  20225. Matrix3.multiplyByScale(result.halfAxes, scale, result.halfAxes);
  20226. return result;
  20227. };
  20228. var scratchOffset = new Cartesian3();
  20229. var scratchScale = new Cartesian3();
  20230. /**
  20231. * Computes an OrientedBoundingBox given extents in the east-north-up space of the tangent plane.
  20232. *
  20233. * @param {Number} minimumX Minimum X extent in tangent plane space.
  20234. * @param {Number} maximumX Maximum X extent in tangent plane space.
  20235. * @param {Number} minimumY Minimum Y extent in tangent plane space.
  20236. * @param {Number} maximumY Maximum Y extent in tangent plane space.
  20237. * @param {Number} minimumZ Minimum Z extent in tangent plane space.
  20238. * @param {Number} maximumZ Maximum Z extent in tangent plane space.
  20239. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  20240. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  20241. */
  20242. function fromTangentPlaneExtents(tangentPlane, minimumX, maximumX, minimumY, maximumY, minimumZ, maximumZ, result) {
  20243. if (!defined(minimumX) ||
  20244. !defined(maximumX) ||
  20245. !defined(minimumY) ||
  20246. !defined(maximumY) ||
  20247. !defined(minimumZ) ||
  20248. !defined(maximumZ)) {
  20249. throw new DeveloperError('all extents (minimum/maximum X/Y/Z) are required.');
  20250. }
  20251. if (!defined(result)) {
  20252. result = new OrientedBoundingBox();
  20253. }
  20254. var halfAxes = result.halfAxes;
  20255. Matrix3.setColumn(halfAxes, 0, tangentPlane.xAxis, halfAxes);
  20256. Matrix3.setColumn(halfAxes, 1, tangentPlane.yAxis, halfAxes);
  20257. Matrix3.setColumn(halfAxes, 2, tangentPlane.zAxis, halfAxes);
  20258. var centerOffset = scratchOffset;
  20259. centerOffset.x = (minimumX + maximumX) / 2.0;
  20260. centerOffset.y = (minimumY + maximumY) / 2.0;
  20261. centerOffset.z = (minimumZ + maximumZ) / 2.0;
  20262. var scale = scratchScale;
  20263. scale.x = (maximumX - minimumX) / 2.0;
  20264. scale.y = (maximumY - minimumY) / 2.0;
  20265. scale.z = (maximumZ - minimumZ) / 2.0;
  20266. var center = result.center;
  20267. centerOffset = Matrix3.multiplyByVector(halfAxes, centerOffset, centerOffset);
  20268. Cartesian3.add(tangentPlane.origin, centerOffset, center);
  20269. Matrix3.multiplyByScale(halfAxes, scale, halfAxes);
  20270. return result;
  20271. }
  20272. var scratchRectangleCenterCartographic = new Cartographic();
  20273. var scratchRectangleCenter = new Cartesian3();
  20274. var perimeterCartographicScratch = [new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic()];
  20275. var perimeterCartesianScratch = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
  20276. var perimeterProjectedScratch = [new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2()];
  20277. /**
  20278. * Computes an OrientedBoundingBox that bounds a {@link Rectangle} on the surface of an {@link Ellipsoid}.
  20279. * There are no guarantees about the orientation of the bounding box.
  20280. *
  20281. * @param {Rectangle} rectangle The cartographic rectangle on the surface of the ellipsoid.
  20282. * @param {Number} [minimumHeight=0.0] The minimum height (elevation) within the tile.
  20283. * @param {Number} [maximumHeight=0.0] The maximum height (elevation) within the tile.
  20284. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle is defined.
  20285. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  20286. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided.
  20287. *
  20288. * @exception {DeveloperError} rectangle.width must be between 0 and pi.
  20289. * @exception {DeveloperError} rectangle.height must be between 0 and pi.
  20290. * @exception {DeveloperError} ellipsoid must be an ellipsoid of revolution (<code>radii.x == radii.y</code>)
  20291. */
  20292. OrientedBoundingBox.fromRectangle = function(rectangle, minimumHeight, maximumHeight, ellipsoid, result) {
  20293. if (!defined(rectangle)) {
  20294. throw new DeveloperError('rectangle is required');
  20295. }
  20296. if (rectangle.width < 0.0 || rectangle.width > CesiumMath.PI) {
  20297. throw new DeveloperError('Rectangle width must be between 0 and pi');
  20298. }
  20299. if (rectangle.height < 0.0 || rectangle.height > CesiumMath.PI) {
  20300. throw new DeveloperError('Rectangle height must be between 0 and pi');
  20301. }
  20302. if (defined(ellipsoid) && !CesiumMath.equalsEpsilon(ellipsoid.radii.x, ellipsoid.radii.y, CesiumMath.EPSILON15)) {
  20303. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  20304. }
  20305. minimumHeight = defaultValue(minimumHeight, 0.0);
  20306. maximumHeight = defaultValue(maximumHeight, 0.0);
  20307. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  20308. // The bounding box will be aligned with the tangent plane at the center of the rectangle.
  20309. var tangentPointCartographic = Rectangle.center(rectangle, scratchRectangleCenterCartographic);
  20310. var tangentPoint = ellipsoid.cartographicToCartesian(tangentPointCartographic, scratchRectangleCenter);
  20311. var tangentPlane = new EllipsoidTangentPlane(tangentPoint, ellipsoid);
  20312. var plane = tangentPlane.plane;
  20313. // Corner arrangement:
  20314. // N/+y
  20315. // [0] [1] [2]
  20316. // W/-x [7] [3] E/+x
  20317. // [6] [5] [4]
  20318. // S/-y
  20319. // "C" refers to the central lat/long, which by default aligns with the tangent point (above).
  20320. // If the rectangle spans the equator, CW and CE are instead aligned with the equator.
  20321. var perimeterNW = perimeterCartographicScratch[0];
  20322. var perimeterNC = perimeterCartographicScratch[1];
  20323. var perimeterNE = perimeterCartographicScratch[2];
  20324. var perimeterCE = perimeterCartographicScratch[3];
  20325. var perimeterSE = perimeterCartographicScratch[4];
  20326. var perimeterSC = perimeterCartographicScratch[5];
  20327. var perimeterSW = perimeterCartographicScratch[6];
  20328. var perimeterCW = perimeterCartographicScratch[7];
  20329. var lonCenter = tangentPointCartographic.longitude;
  20330. var latCenter = (rectangle.south < 0.0 && rectangle.north > 0.0) ? 0.0 : tangentPointCartographic.latitude;
  20331. perimeterSW.latitude = perimeterSC.latitude = perimeterSE.latitude = rectangle.south;
  20332. perimeterCW.latitude = perimeterCE.latitude = latCenter;
  20333. perimeterNW.latitude = perimeterNC.latitude = perimeterNE.latitude = rectangle.north;
  20334. perimeterSW.longitude = perimeterCW.longitude = perimeterNW.longitude = rectangle.west;
  20335. perimeterSC.longitude = perimeterNC.longitude = lonCenter;
  20336. perimeterSE.longitude = perimeterCE.longitude = perimeterNE.longitude = rectangle.east;
  20337. // Compute XY extents using the rectangle at maximum height
  20338. perimeterNE.height = perimeterNC.height = perimeterNW.height = perimeterCW.height = perimeterSW.height = perimeterSC.height = perimeterSE.height = perimeterCE.height = maximumHeight;
  20339. ellipsoid.cartographicArrayToCartesianArray(perimeterCartographicScratch, perimeterCartesianScratch);
  20340. tangentPlane.projectPointsToNearestOnPlane(perimeterCartesianScratch, perimeterProjectedScratch);
  20341. // See the `perimeterXX` definitions above for what these are
  20342. var minX = Math.min(perimeterProjectedScratch[6].x, perimeterProjectedScratch[7].x, perimeterProjectedScratch[0].x);
  20343. var maxX = Math.max(perimeterProjectedScratch[2].x, perimeterProjectedScratch[3].x, perimeterProjectedScratch[4].x);
  20344. var minY = Math.min(perimeterProjectedScratch[4].y, perimeterProjectedScratch[5].y, perimeterProjectedScratch[6].y);
  20345. var maxY = Math.max(perimeterProjectedScratch[0].y, perimeterProjectedScratch[1].y, perimeterProjectedScratch[2].y);
  20346. // Compute minimum Z using the rectangle at minimum height
  20347. perimeterNE.height = perimeterNW.height = perimeterSE.height = perimeterSW.height = minimumHeight;
  20348. ellipsoid.cartographicArrayToCartesianArray(perimeterCartographicScratch, perimeterCartesianScratch);
  20349. var minZ = Math.min(Plane.getPointDistance(plane, perimeterCartesianScratch[0]),
  20350. Plane.getPointDistance(plane, perimeterCartesianScratch[2]),
  20351. Plane.getPointDistance(plane, perimeterCartesianScratch[4]),
  20352. Plane.getPointDistance(plane, perimeterCartesianScratch[6]));
  20353. var maxZ = maximumHeight; // Since the tangent plane touches the surface at height = 0, this is okay
  20354. return fromTangentPlaneExtents(tangentPlane, minX, maxX, minY, maxY, minZ, maxZ, result);
  20355. };
  20356. /**
  20357. * Duplicates a OrientedBoundingBox instance.
  20358. *
  20359. * @param {OrientedBoundingBox} box The bounding box to duplicate.
  20360. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  20361. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  20362. */
  20363. OrientedBoundingBox.clone = function(box, result) {
  20364. if (!defined(box)) {
  20365. return undefined;
  20366. }
  20367. if (!defined(result)) {
  20368. return new OrientedBoundingBox(box.center, box.halfAxes);
  20369. }
  20370. Cartesian3.clone(box.center, result.center);
  20371. Matrix3.clone(box.halfAxes, result.halfAxes);
  20372. return result;
  20373. };
  20374. /**
  20375. * Determines which side of a plane the oriented bounding box is located.
  20376. *
  20377. * @param {OrientedBoundingBox} box The oriented bounding box to test.
  20378. * @param {Plane} plane The plane to test against.
  20379. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  20380. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  20381. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  20382. * intersects the plane.
  20383. */
  20384. OrientedBoundingBox.intersectPlane = function(box, plane) {
  20385. if (!defined(box)) {
  20386. throw new DeveloperError('box is required.');
  20387. }
  20388. if (!defined(plane)) {
  20389. throw new DeveloperError('plane is required.');
  20390. }
  20391. var center = box.center;
  20392. var normal = plane.normal;
  20393. var halfAxes = box.halfAxes;
  20394. var normalX = normal.x, normalY = normal.y, normalZ = normal.z;
  20395. // plane is used as if it is its normal; the first three components are assumed to be normalized
  20396. var radEffective = Math.abs(normalX * halfAxes[Matrix3.COLUMN0ROW0] + normalY * halfAxes[Matrix3.COLUMN0ROW1] + normalZ * halfAxes[Matrix3.COLUMN0ROW2]) +
  20397. Math.abs(normalX * halfAxes[Matrix3.COLUMN1ROW0] + normalY * halfAxes[Matrix3.COLUMN1ROW1] + normalZ * halfAxes[Matrix3.COLUMN1ROW2]) +
  20398. Math.abs(normalX * halfAxes[Matrix3.COLUMN2ROW0] + normalY * halfAxes[Matrix3.COLUMN2ROW1] + normalZ * halfAxes[Matrix3.COLUMN2ROW2]);
  20399. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  20400. if (distanceToPlane <= -radEffective) {
  20401. // The entire box is on the negative side of the plane normal
  20402. return Intersect.OUTSIDE;
  20403. } else if (distanceToPlane >= radEffective) {
  20404. // The entire box is on the positive side of the plane normal
  20405. return Intersect.INSIDE;
  20406. }
  20407. return Intersect.INTERSECTING;
  20408. };
  20409. var scratchCartesianU = new Cartesian3();
  20410. var scratchCartesianV = new Cartesian3();
  20411. var scratchCartesianW = new Cartesian3();
  20412. var scratchPPrime = new Cartesian3();
  20413. /**
  20414. * Computes the estimated distance squared from the closest point on a bounding box to a point.
  20415. *
  20416. * @param {OrientedBoundingBox} box The box.
  20417. * @param {Cartesian3} cartesian The point
  20418. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  20419. *
  20420. * @example
  20421. * // Sort bounding boxes from back to front
  20422. * boxes.sort(function(a, b) {
  20423. * return Cesium.OrientedBoundingBox.distanceSquaredTo(b, camera.positionWC) - Cesium.OrientedBoundingBox.distanceSquaredTo(a, camera.positionWC);
  20424. * });
  20425. */
  20426. OrientedBoundingBox.distanceSquaredTo = function(box, cartesian) {
  20427. // See Geometric Tools for Computer Graphics 10.4.2
  20428. if (!defined(box)) {
  20429. throw new DeveloperError('box is required.');
  20430. }
  20431. if (!defined(cartesian)) {
  20432. throw new DeveloperError('cartesian is required.');
  20433. }
  20434. var offset = Cartesian3.subtract(cartesian, box.center, scratchOffset);
  20435. var halfAxes = box.halfAxes;
  20436. var u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
  20437. var v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
  20438. var w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);
  20439. var uHalf = Cartesian3.magnitude(u);
  20440. var vHalf = Cartesian3.magnitude(v);
  20441. var wHalf = Cartesian3.magnitude(w);
  20442. Cartesian3.normalize(u, u);
  20443. Cartesian3.normalize(v, v);
  20444. Cartesian3.normalize(w, w);
  20445. var pPrime = scratchPPrime;
  20446. pPrime.x = Cartesian3.dot(offset, u);
  20447. pPrime.y = Cartesian3.dot(offset, v);
  20448. pPrime.z = Cartesian3.dot(offset, w);
  20449. var distanceSquared = 0.0;
  20450. var d;
  20451. if (pPrime.x < -uHalf) {
  20452. d = pPrime.x + uHalf;
  20453. distanceSquared += d * d;
  20454. } else if (pPrime.x > uHalf) {
  20455. d = pPrime.x - uHalf;
  20456. distanceSquared += d * d;
  20457. }
  20458. if (pPrime.y < -vHalf) {
  20459. d = pPrime.y + vHalf;
  20460. distanceSquared += d * d;
  20461. } else if (pPrime.y > vHalf) {
  20462. d = pPrime.y - vHalf;
  20463. distanceSquared += d * d;
  20464. }
  20465. if (pPrime.z < -wHalf) {
  20466. d = pPrime.z + wHalf;
  20467. distanceSquared += d * d;
  20468. } else if (pPrime.z > wHalf) {
  20469. d = pPrime.z - wHalf;
  20470. distanceSquared += d * d;
  20471. }
  20472. return distanceSquared;
  20473. };
  20474. var scratchCorner = new Cartesian3();
  20475. var scratchToCenter = new Cartesian3();
  20476. /**
  20477. * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
  20478. * <br>
  20479. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  20480. * closest and farthest planes from position that intersect the bounding box.
  20481. *
  20482. * @param {OrientedBoundingBox} box The bounding box to calculate the distance to.
  20483. * @param {Cartesian3} position The position to calculate the distance from.
  20484. * @param {Cartesian3} direction The direction from position.
  20485. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  20486. * @returns {Interval} The nearest and farthest distances on the bounding box from position in direction.
  20487. */
  20488. OrientedBoundingBox.computePlaneDistances = function(box, position, direction, result) {
  20489. if (!defined(box)) {
  20490. throw new DeveloperError('box is required.');
  20491. }
  20492. if (!defined(position)) {
  20493. throw new DeveloperError('position is required.');
  20494. }
  20495. if (!defined(direction)) {
  20496. throw new DeveloperError('direction is required.');
  20497. }
  20498. if (!defined(result)) {
  20499. result = new Interval();
  20500. }
  20501. var minDist = Number.POSITIVE_INFINITY;
  20502. var maxDist = Number.NEGATIVE_INFINITY;
  20503. var center = box.center;
  20504. var halfAxes = box.halfAxes;
  20505. var u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
  20506. var v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
  20507. var w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);
  20508. // project first corner
  20509. var corner = Cartesian3.add(u, v, scratchCorner);
  20510. Cartesian3.add(corner, w, corner);
  20511. Cartesian3.add(corner, center, corner);
  20512. var toCenter = Cartesian3.subtract(corner, position, scratchToCenter);
  20513. var mag = Cartesian3.dot(direction, toCenter);
  20514. minDist = Math.min(mag, minDist);
  20515. maxDist = Math.max(mag, maxDist);
  20516. // project second corner
  20517. Cartesian3.add(center, u, corner);
  20518. Cartesian3.add(corner, v, corner);
  20519. Cartesian3.subtract(corner, w, corner);
  20520. Cartesian3.subtract(corner, position, toCenter);
  20521. mag = Cartesian3.dot(direction, toCenter);
  20522. minDist = Math.min(mag, minDist);
  20523. maxDist = Math.max(mag, maxDist);
  20524. // project third corner
  20525. Cartesian3.add(center, u, corner);
  20526. Cartesian3.subtract(corner, v, corner);
  20527. Cartesian3.add(corner, w, corner);
  20528. Cartesian3.subtract(corner, position, toCenter);
  20529. mag = Cartesian3.dot(direction, toCenter);
  20530. minDist = Math.min(mag, minDist);
  20531. maxDist = Math.max(mag, maxDist);
  20532. // project fourth corner
  20533. Cartesian3.add(center, u, corner);
  20534. Cartesian3.subtract(corner, v, corner);
  20535. Cartesian3.subtract(corner, w, corner);
  20536. Cartesian3.subtract(corner, position, toCenter);
  20537. mag = Cartesian3.dot(direction, toCenter);
  20538. minDist = Math.min(mag, minDist);
  20539. maxDist = Math.max(mag, maxDist);
  20540. // project fifth corner
  20541. Cartesian3.subtract(center, u, corner);
  20542. Cartesian3.add(corner, v, corner);
  20543. Cartesian3.add(corner, w, corner);
  20544. Cartesian3.subtract(corner, position, toCenter);
  20545. mag = Cartesian3.dot(direction, toCenter);
  20546. minDist = Math.min(mag, minDist);
  20547. maxDist = Math.max(mag, maxDist);
  20548. // project sixth corner
  20549. Cartesian3.subtract(center, u, corner);
  20550. Cartesian3.add(corner, v, corner);
  20551. Cartesian3.subtract(corner, w, corner);
  20552. Cartesian3.subtract(corner, position, toCenter);
  20553. mag = Cartesian3.dot(direction, toCenter);
  20554. minDist = Math.min(mag, minDist);
  20555. maxDist = Math.max(mag, maxDist);
  20556. // project seventh corner
  20557. Cartesian3.subtract(center, u, corner);
  20558. Cartesian3.subtract(corner, v, corner);
  20559. Cartesian3.add(corner, w, corner);
  20560. Cartesian3.subtract(corner, position, toCenter);
  20561. mag = Cartesian3.dot(direction, toCenter);
  20562. minDist = Math.min(mag, minDist);
  20563. maxDist = Math.max(mag, maxDist);
  20564. // project eighth corner
  20565. Cartesian3.subtract(center, u, corner);
  20566. Cartesian3.subtract(corner, v, corner);
  20567. Cartesian3.subtract(corner, w, corner);
  20568. Cartesian3.subtract(corner, position, toCenter);
  20569. mag = Cartesian3.dot(direction, toCenter);
  20570. minDist = Math.min(mag, minDist);
  20571. maxDist = Math.max(mag, maxDist);
  20572. result.start = minDist;
  20573. result.stop = maxDist;
  20574. return result;
  20575. };
  20576. var scratchBoundingSphere = new BoundingSphere();
  20577. /**
  20578. * Determines whether or not a bounding box is hidden from view by the occluder.
  20579. *
  20580. * @param {OrientedBoundingBox} box The bounding box surrounding the occludee object.
  20581. * @param {Occluder} occluder The occluder.
  20582. * @returns {Boolean} <code>true</code> if the box is not visible; otherwise <code>false</code>.
  20583. */
  20584. OrientedBoundingBox.isOccluded = function(box, occluder) {
  20585. if (!defined(box)) {
  20586. throw new DeveloperError('box is required.');
  20587. }
  20588. if (!defined(occluder)) {
  20589. throw new DeveloperError('occluder is required.');
  20590. }
  20591. var sphere = BoundingSphere.fromOrientedBoundingBox(box, scratchBoundingSphere);
  20592. return !occluder.isBoundingSphereVisible(sphere);
  20593. };
  20594. /**
  20595. * Determines which side of a plane the oriented bounding box is located.
  20596. *
  20597. * @param {Plane} plane The plane to test against.
  20598. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  20599. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  20600. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  20601. * intersects the plane.
  20602. */
  20603. OrientedBoundingBox.prototype.intersectPlane = function(plane) {
  20604. return OrientedBoundingBox.intersectPlane(this, plane);
  20605. };
  20606. /**
  20607. * Computes the estimated distance squared from the closest point on a bounding box to a point.
  20608. *
  20609. * @param {Cartesian3} cartesian The point
  20610. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  20611. *
  20612. * @example
  20613. * // Sort bounding boxes from back to front
  20614. * boxes.sort(function(a, b) {
  20615. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  20616. * });
  20617. */
  20618. OrientedBoundingBox.prototype.distanceSquaredTo = function(cartesian) {
  20619. return OrientedBoundingBox.distanceSquaredTo(this, cartesian);
  20620. };
  20621. /**
  20622. * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
  20623. * <br>
  20624. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  20625. * closest and farthest planes from position that intersect the bounding box.
  20626. *
  20627. * @param {Cartesian3} position The position to calculate the distance from.
  20628. * @param {Cartesian3} direction The direction from position.
  20629. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  20630. * @returns {Interval} The nearest and farthest distances on the bounding box from position in direction.
  20631. */
  20632. OrientedBoundingBox.prototype.computePlaneDistances = function(position, direction, result) {
  20633. return OrientedBoundingBox.computePlaneDistances(this, position, direction, result);
  20634. };
  20635. /**
  20636. * Determines whether or not a bounding box is hidden from view by the occluder.
  20637. *
  20638. * @param {Occluder} occluder The occluder.
  20639. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  20640. */
  20641. OrientedBoundingBox.prototype.isOccluded = function(occluder) {
  20642. return OrientedBoundingBox.isOccluded(this, occluder);
  20643. };
  20644. /**
  20645. * Compares the provided OrientedBoundingBox componentwise and returns
  20646. * <code>true</code> if they are equal, <code>false</code> otherwise.
  20647. *
  20648. * @param {OrientedBoundingBox} left The first OrientedBoundingBox.
  20649. * @param {OrientedBoundingBox} right The second OrientedBoundingBox.
  20650. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  20651. */
  20652. OrientedBoundingBox.equals = function(left, right) {
  20653. return (left === right) ||
  20654. ((defined(left)) &&
  20655. (defined(right)) &&
  20656. Cartesian3.equals(left.center, right.center) &&
  20657. Matrix3.equals(left.halfAxes, right.halfAxes));
  20658. };
  20659. /**
  20660. * Duplicates this OrientedBoundingBox instance.
  20661. *
  20662. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  20663. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  20664. */
  20665. OrientedBoundingBox.prototype.clone = function(result) {
  20666. return OrientedBoundingBox.clone(this, result);
  20667. };
  20668. /**
  20669. * Compares this OrientedBoundingBox against the provided OrientedBoundingBox componentwise and returns
  20670. * <code>true</code> if they are equal, <code>false</code> otherwise.
  20671. *
  20672. * @param {OrientedBoundingBox} [right] The right hand side OrientedBoundingBox.
  20673. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  20674. */
  20675. OrientedBoundingBox.prototype.equals = function(right) {
  20676. return OrientedBoundingBox.equals(this, right);
  20677. };
  20678. return OrientedBoundingBox;
  20679. });
  20680. /*global define*/
  20681. define('Core/ComponentDatatype',[
  20682. './defaultValue',
  20683. './defined',
  20684. './DeveloperError',
  20685. './FeatureDetection',
  20686. './freezeObject',
  20687. './WebGLConstants'
  20688. ], function(
  20689. defaultValue,
  20690. defined,
  20691. DeveloperError,
  20692. FeatureDetection,
  20693. freezeObject,
  20694. WebGLConstants) {
  20695. 'use strict';
  20696. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  20697. // from failing, since we won't be able to create a WebGL context anyway.
  20698. if (!FeatureDetection.supportsTypedArrays()) {
  20699. return {};
  20700. }
  20701. /**
  20702. * WebGL component datatypes. Components are intrinsics,
  20703. * which form attributes, which form vertices.
  20704. *
  20705. * @exports ComponentDatatype
  20706. */
  20707. var ComponentDatatype = {
  20708. /**
  20709. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  20710. * of an element in <code>Int8Array</code>.
  20711. *
  20712. * @type {Number}
  20713. * @constant
  20714. */
  20715. BYTE : WebGLConstants.BYTE,
  20716. /**
  20717. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  20718. * of an element in <code>Uint8Array</code>.
  20719. *
  20720. * @type {Number}
  20721. * @constant
  20722. */
  20723. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  20724. /**
  20725. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  20726. * of an element in <code>Int16Array</code>.
  20727. *
  20728. * @type {Number}
  20729. * @constant
  20730. */
  20731. SHORT : WebGLConstants.SHORT,
  20732. /**
  20733. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  20734. * of an element in <code>Uint16Array</code>.
  20735. *
  20736. * @type {Number}
  20737. * @constant
  20738. */
  20739. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  20740. /**
  20741. * 32-bit signed int corresponding to <code>INT</code> and the type
  20742. * of an element in <code>Int32Array</code>.
  20743. *
  20744. * @memberOf ComponentDatatype
  20745. *
  20746. * @type {Number}
  20747. * @constant
  20748. */
  20749. INT : WebGLConstants.INT,
  20750. /**
  20751. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  20752. * of an element in <code>Uint32Array</code>.
  20753. *
  20754. * @memberOf ComponentDatatype
  20755. *
  20756. * @type {Number}
  20757. * @constant
  20758. */
  20759. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  20760. /**
  20761. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  20762. * of an element in <code>Float32Array</code>.
  20763. *
  20764. * @type {Number}
  20765. * @constant
  20766. */
  20767. FLOAT : WebGLConstants.FLOAT,
  20768. /**
  20769. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  20770. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  20771. * and the type of an element in <code>Float64Array</code>.
  20772. *
  20773. * @memberOf ComponentDatatype
  20774. *
  20775. * @type {Number}
  20776. * @constant
  20777. * @default 0x140A
  20778. */
  20779. DOUBLE : WebGLConstants.DOUBLE
  20780. };
  20781. /**
  20782. * Returns the size, in bytes, of the corresponding datatype.
  20783. *
  20784. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  20785. * @returns {Number} The size in bytes.
  20786. *
  20787. * @exception {DeveloperError} componentDatatype is not a valid value.
  20788. *
  20789. * @example
  20790. * // Returns Int8Array.BYTES_PER_ELEMENT
  20791. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  20792. */
  20793. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  20794. if (!defined(componentDatatype)) {
  20795. throw new DeveloperError('value is required.');
  20796. }
  20797. switch (componentDatatype) {
  20798. case ComponentDatatype.BYTE:
  20799. return Int8Array.BYTES_PER_ELEMENT;
  20800. case ComponentDatatype.UNSIGNED_BYTE:
  20801. return Uint8Array.BYTES_PER_ELEMENT;
  20802. case ComponentDatatype.SHORT:
  20803. return Int16Array.BYTES_PER_ELEMENT;
  20804. case ComponentDatatype.UNSIGNED_SHORT:
  20805. return Uint16Array.BYTES_PER_ELEMENT;
  20806. case ComponentDatatype.INT:
  20807. return Int32Array.BYTES_PER_ELEMENT;
  20808. case ComponentDatatype.UNSIGNED_INT:
  20809. return Uint32Array.BYTES_PER_ELEMENT;
  20810. case ComponentDatatype.FLOAT:
  20811. return Float32Array.BYTES_PER_ELEMENT;
  20812. case ComponentDatatype.DOUBLE:
  20813. return Float64Array.BYTES_PER_ELEMENT;
  20814. default:
  20815. throw new DeveloperError('componentDatatype is not a valid value.');
  20816. }
  20817. };
  20818. /**
  20819. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  20820. *
  20821. * @param {TypedArray} array The typed array.
  20822. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  20823. */
  20824. ComponentDatatype.fromTypedArray = function(array) {
  20825. if (array instanceof Int8Array) {
  20826. return ComponentDatatype.BYTE;
  20827. }
  20828. if (array instanceof Uint8Array) {
  20829. return ComponentDatatype.UNSIGNED_BYTE;
  20830. }
  20831. if (array instanceof Int16Array) {
  20832. return ComponentDatatype.SHORT;
  20833. }
  20834. if (array instanceof Uint16Array) {
  20835. return ComponentDatatype.UNSIGNED_SHORT;
  20836. }
  20837. if (array instanceof Int32Array) {
  20838. return ComponentDatatype.INT;
  20839. }
  20840. if (array instanceof Uint32Array) {
  20841. return ComponentDatatype.UNSIGNED_INT;
  20842. }
  20843. if (array instanceof Float32Array) {
  20844. return ComponentDatatype.FLOAT;
  20845. }
  20846. if (array instanceof Float64Array) {
  20847. return ComponentDatatype.DOUBLE;
  20848. }
  20849. };
  20850. /**
  20851. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  20852. *
  20853. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  20854. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  20855. *
  20856. * @example
  20857. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  20858. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  20859. * }
  20860. */
  20861. ComponentDatatype.validate = function(componentDatatype) {
  20862. return defined(componentDatatype) &&
  20863. (componentDatatype === ComponentDatatype.BYTE ||
  20864. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  20865. componentDatatype === ComponentDatatype.SHORT ||
  20866. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  20867. componentDatatype === ComponentDatatype.INT ||
  20868. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  20869. componentDatatype === ComponentDatatype.FLOAT ||
  20870. componentDatatype === ComponentDatatype.DOUBLE);
  20871. };
  20872. /**
  20873. * Creates a typed array corresponding to component data type.
  20874. *
  20875. * @param {ComponentDatatype} componentDatatype The component data type.
  20876. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  20877. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  20878. *
  20879. * @exception {DeveloperError} componentDatatype is not a valid value.
  20880. *
  20881. * @example
  20882. * // creates a Float32Array with length of 100
  20883. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  20884. */
  20885. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  20886. if (!defined(componentDatatype)) {
  20887. throw new DeveloperError('componentDatatype is required.');
  20888. }
  20889. if (!defined(valuesOrLength)) {
  20890. throw new DeveloperError('valuesOrLength is required.');
  20891. }
  20892. switch (componentDatatype) {
  20893. case ComponentDatatype.BYTE:
  20894. return new Int8Array(valuesOrLength);
  20895. case ComponentDatatype.UNSIGNED_BYTE:
  20896. return new Uint8Array(valuesOrLength);
  20897. case ComponentDatatype.SHORT:
  20898. return new Int16Array(valuesOrLength);
  20899. case ComponentDatatype.UNSIGNED_SHORT:
  20900. return new Uint16Array(valuesOrLength);
  20901. case ComponentDatatype.INT:
  20902. return new Int32Array(valuesOrLength);
  20903. case ComponentDatatype.UNSIGNED_INT:
  20904. return new Uint32Array(valuesOrLength);
  20905. case ComponentDatatype.FLOAT:
  20906. return new Float32Array(valuesOrLength);
  20907. case ComponentDatatype.DOUBLE:
  20908. return new Float64Array(valuesOrLength);
  20909. default:
  20910. throw new DeveloperError('componentDatatype is not a valid value.');
  20911. }
  20912. };
  20913. /**
  20914. * Creates a typed view of an array of bytes.
  20915. *
  20916. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  20917. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  20918. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  20919. * @param {Number} [length] The number of elements in the view.
  20920. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  20921. *
  20922. * @exception {DeveloperError} componentDatatype is not a valid value.
  20923. */
  20924. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  20925. if (!defined(componentDatatype)) {
  20926. throw new DeveloperError('componentDatatype is required.');
  20927. }
  20928. if (!defined(buffer)) {
  20929. throw new DeveloperError('buffer is required.');
  20930. }
  20931. byteOffset = defaultValue(byteOffset, 0);
  20932. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  20933. switch (componentDatatype) {
  20934. case ComponentDatatype.BYTE:
  20935. return new Int8Array(buffer, byteOffset, length);
  20936. case ComponentDatatype.UNSIGNED_BYTE:
  20937. return new Uint8Array(buffer, byteOffset, length);
  20938. case ComponentDatatype.SHORT:
  20939. return new Int16Array(buffer, byteOffset, length);
  20940. case ComponentDatatype.UNSIGNED_SHORT:
  20941. return new Uint16Array(buffer, byteOffset, length);
  20942. case ComponentDatatype.INT:
  20943. return new Int32Array(buffer, byteOffset, length);
  20944. case ComponentDatatype.UNSIGNED_INT:
  20945. return new Uint32Array(buffer, byteOffset, length);
  20946. case ComponentDatatype.FLOAT:
  20947. return new Float32Array(buffer, byteOffset, length);
  20948. case ComponentDatatype.DOUBLE:
  20949. return new Float64Array(buffer, byteOffset, length);
  20950. default:
  20951. throw new DeveloperError('componentDatatype is not a valid value.');
  20952. }
  20953. };
  20954. /**
  20955. * Get the ComponentDatatype from its name.
  20956. *
  20957. * @param {String} name The name of the ComponentDatatype.
  20958. * @returns {ComponentDatatype} The ComponentDatatype.
  20959. *
  20960. * @exception {DeveloperError} name is not a valid value.
  20961. */
  20962. ComponentDatatype.fromName = function(name) {
  20963. switch (name) {
  20964. case 'BYTE':
  20965. return ComponentDatatype.BYTE;
  20966. case 'UNSIGNED_BYTE':
  20967. return ComponentDatatype.UNSIGNED_BYTE;
  20968. case 'SHORT':
  20969. return ComponentDatatype.SHORT;
  20970. case 'UNSIGNED_SHORT':
  20971. return ComponentDatatype.UNSIGNED_SHORT;
  20972. case 'INT':
  20973. return ComponentDatatype.INT;
  20974. case 'UNSIGNED_INT':
  20975. return ComponentDatatype.UNSIGNED_INT;
  20976. case 'FLOAT':
  20977. return ComponentDatatype.FLOAT;
  20978. case 'DOUBLE':
  20979. return ComponentDatatype.DOUBLE;
  20980. default:
  20981. throw new DeveloperError('name is not a valid value.');
  20982. }
  20983. };
  20984. return freezeObject(ComponentDatatype);
  20985. });
  20986. /*global define*/
  20987. define('Core/TerrainQuantization',[
  20988. './freezeObject'
  20989. ], function(
  20990. freezeObject) {
  20991. 'use strict';
  20992. /**
  20993. * This enumerated type is used to determine how the vertices of the terrain mesh are compressed.
  20994. *
  20995. * @exports TerrainQuantization
  20996. *
  20997. * @private
  20998. */
  20999. var TerrainQuantization = {
  21000. /**
  21001. * The vertices are not compressed.
  21002. *
  21003. * @type {Number}
  21004. * @constant
  21005. */
  21006. NONE : 0,
  21007. /**
  21008. * The vertices are compressed to 12 bits.
  21009. *
  21010. * @type {Number}
  21011. * @constant
  21012. */
  21013. BITS12 : 1
  21014. };
  21015. return freezeObject(TerrainQuantization);
  21016. });
  21017. /*global define*/
  21018. define('Core/TerrainEncoding',[
  21019. './AttributeCompression',
  21020. './Cartesian2',
  21021. './Cartesian3',
  21022. './ComponentDatatype',
  21023. './defaultValue',
  21024. './defined',
  21025. './Math',
  21026. './Matrix4',
  21027. './TerrainQuantization'
  21028. ], function(
  21029. AttributeCompression,
  21030. Cartesian2,
  21031. Cartesian3,
  21032. ComponentDatatype,
  21033. defaultValue,
  21034. defined,
  21035. CesiumMath,
  21036. Matrix4,
  21037. TerrainQuantization) {
  21038. 'use strict';
  21039. var cartesian3Scratch = new Cartesian3();
  21040. var cartesian3DimScratch = new Cartesian3();
  21041. var cartesian2Scratch = new Cartesian2();
  21042. var matrix4Scratch = new Matrix4();
  21043. var matrix4Scratch2 = new Matrix4();
  21044. var SHIFT_LEFT_12 = Math.pow(2.0, 12.0);
  21045. /**
  21046. * Data used to quantize and pack the terrain mesh. The position can be unpacked for picking and all attributes
  21047. * are unpacked in the vertex shader.
  21048. *
  21049. * @alias TerrainEncoding
  21050. * @constructor
  21051. *
  21052. * @param {AxisAlignedBoundingBox} axisAlignedBoundingBox The bounds of the tile in the east-north-up coordinates at the tiles center.
  21053. * @param {Number} minimumHeight The minimum height.
  21054. * @param {Number} maximumHeight The maximum height.
  21055. * @param {Matrix4} fromENU The east-north-up to fixed frame matrix at the center of the terrain mesh.
  21056. * @param {Boolean} hasVertexNormals If the mesh has vertex normals.
  21057. * @param {Boolean} [hasWebMercatorT=false] true if the terrain data includes a Web Mercator texture coordinate; otherwise, false.
  21058. *
  21059. * @private
  21060. */
  21061. function TerrainEncoding(axisAlignedBoundingBox, minimumHeight, maximumHeight, fromENU, hasVertexNormals, hasWebMercatorT) {
  21062. var quantization;
  21063. var center;
  21064. var toENU;
  21065. var matrix;
  21066. if (defined(axisAlignedBoundingBox) && defined(minimumHeight) && defined(maximumHeight) && defined(fromENU)) {
  21067. var minimum = axisAlignedBoundingBox.minimum;
  21068. var maximum = axisAlignedBoundingBox.maximum;
  21069. var dimensions = Cartesian3.subtract(maximum, minimum, cartesian3DimScratch);
  21070. var hDim = maximumHeight - minimumHeight;
  21071. var maxDim = Math.max(Cartesian3.maximumComponent(dimensions), hDim);
  21072. if (maxDim < SHIFT_LEFT_12 - 1.0) {
  21073. quantization = TerrainQuantization.BITS12;
  21074. } else {
  21075. quantization = TerrainQuantization.NONE;
  21076. }
  21077. center = axisAlignedBoundingBox.center;
  21078. toENU = Matrix4.inverseTransformation(fromENU, new Matrix4());
  21079. var translation = Cartesian3.negate(minimum, cartesian3Scratch);
  21080. Matrix4.multiply(Matrix4.fromTranslation(translation, matrix4Scratch), toENU, toENU);
  21081. var scale = cartesian3Scratch;
  21082. scale.x = 1.0 / dimensions.x;
  21083. scale.y = 1.0 / dimensions.y;
  21084. scale.z = 1.0 / dimensions.z;
  21085. Matrix4.multiply(Matrix4.fromScale(scale, matrix4Scratch), toENU, toENU);
  21086. matrix = Matrix4.clone(fromENU);
  21087. Matrix4.setTranslation(matrix, Cartesian3.ZERO, matrix);
  21088. fromENU = Matrix4.clone(fromENU, new Matrix4());
  21089. var translationMatrix = Matrix4.fromTranslation(minimum, matrix4Scratch);
  21090. var scaleMatrix = Matrix4.fromScale(dimensions, matrix4Scratch2);
  21091. var st = Matrix4.multiply(translationMatrix, scaleMatrix,matrix4Scratch);
  21092. Matrix4.multiply(fromENU, st, fromENU);
  21093. Matrix4.multiply(matrix, st, matrix);
  21094. }
  21095. /**
  21096. * How the vertices of the mesh were compressed.
  21097. * @type {TerrainQuantization}
  21098. */
  21099. this.quantization = quantization;
  21100. /**
  21101. * The minimum height of the tile including the skirts.
  21102. * @type {Number}
  21103. */
  21104. this.minimumHeight = minimumHeight;
  21105. /**
  21106. * The maximum height of the tile.
  21107. * @type {Number}
  21108. */
  21109. this.maximumHeight = maximumHeight;
  21110. /**
  21111. * The center of the tile.
  21112. * @type {Cartesian3}
  21113. */
  21114. this.center = center;
  21115. /**
  21116. * A matrix that takes a vertex from the tile, transforms it to east-north-up at the center and scales
  21117. * it so each component is in the [0, 1] range.
  21118. * @type {Matrix4}
  21119. */
  21120. this.toScaledENU = toENU;
  21121. /**
  21122. * A matrix that restores a vertex transformed with toScaledENU back to the earth fixed reference frame
  21123. * @type {Matrix4}
  21124. */
  21125. this.fromScaledENU = fromENU;
  21126. /**
  21127. * The matrix used to decompress the terrain vertices in the shader for RTE rendering.
  21128. * @type {Matrix4}
  21129. */
  21130. this.matrix = matrix;
  21131. /**
  21132. * The terrain mesh contains normals.
  21133. * @type {Boolean}
  21134. */
  21135. this.hasVertexNormals = hasVertexNormals;
  21136. /**
  21137. * The terrain mesh contains a vertical texture coordinate following the Web Mercator projection.
  21138. * @type {Boolean}
  21139. */
  21140. this.hasWebMercatorT = defaultValue(hasWebMercatorT, false);
  21141. }
  21142. TerrainEncoding.prototype.encode = function(vertexBuffer, bufferIndex, position, uv, height, normalToPack, webMercatorT) {
  21143. var u = uv.x;
  21144. var v = uv.y;
  21145. if (this.quantization === TerrainQuantization.BITS12) {
  21146. position = Matrix4.multiplyByPoint(this.toScaledENU, position, cartesian3Scratch);
  21147. position.x = CesiumMath.clamp(position.x, 0.0, 1.0);
  21148. position.y = CesiumMath.clamp(position.y, 0.0, 1.0);
  21149. position.z = CesiumMath.clamp(position.z, 0.0, 1.0);
  21150. var hDim = this.maximumHeight - this.minimumHeight;
  21151. var h = CesiumMath.clamp((height - this.minimumHeight) / hDim, 0.0, 1.0);
  21152. Cartesian2.fromElements(position.x, position.y, cartesian2Scratch);
  21153. var compressed0 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21154. Cartesian2.fromElements(position.z, h, cartesian2Scratch);
  21155. var compressed1 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21156. Cartesian2.fromElements(u, v, cartesian2Scratch);
  21157. var compressed2 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21158. vertexBuffer[bufferIndex++] = compressed0;
  21159. vertexBuffer[bufferIndex++] = compressed1;
  21160. vertexBuffer[bufferIndex++] = compressed2;
  21161. if (this.hasWebMercatorT) {
  21162. Cartesian2.fromElements(webMercatorT, 0.0, cartesian2Scratch);
  21163. var compressed3 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21164. vertexBuffer[bufferIndex++] = compressed3;
  21165. }
  21166. } else {
  21167. Cartesian3.subtract(position, this.center, cartesian3Scratch);
  21168. vertexBuffer[bufferIndex++] = cartesian3Scratch.x;
  21169. vertexBuffer[bufferIndex++] = cartesian3Scratch.y;
  21170. vertexBuffer[bufferIndex++] = cartesian3Scratch.z;
  21171. vertexBuffer[bufferIndex++] = height;
  21172. vertexBuffer[bufferIndex++] = u;
  21173. vertexBuffer[bufferIndex++] = v;
  21174. if (this.hasWebMercatorT) {
  21175. vertexBuffer[bufferIndex++] = webMercatorT;
  21176. }
  21177. }
  21178. if (this.hasVertexNormals) {
  21179. vertexBuffer[bufferIndex++] = AttributeCompression.octPackFloat(normalToPack);
  21180. }
  21181. return bufferIndex;
  21182. };
  21183. TerrainEncoding.prototype.decodePosition = function(buffer, index, result) {
  21184. if (!defined(result)) {
  21185. result = new Cartesian3();
  21186. }
  21187. index *= this.getStride();
  21188. if (this.quantization === TerrainQuantization.BITS12) {
  21189. var xy = AttributeCompression.decompressTextureCoordinates(buffer[index], cartesian2Scratch);
  21190. result.x = xy.x;
  21191. result.y = xy.y;
  21192. var zh = AttributeCompression.decompressTextureCoordinates(buffer[index + 1], cartesian2Scratch);
  21193. result.z = zh.x;
  21194. return Matrix4.multiplyByPoint(this.fromScaledENU, result, result);
  21195. }
  21196. result.x = buffer[index];
  21197. result.y = buffer[index + 1];
  21198. result.z = buffer[index + 2];
  21199. return Cartesian3.add(result, this.center, result);
  21200. };
  21201. TerrainEncoding.prototype.decodeTextureCoordinates = function(buffer, index, result) {
  21202. if (!defined(result)) {
  21203. result = new Cartesian2();
  21204. }
  21205. index *= this.getStride();
  21206. if (this.quantization === TerrainQuantization.BITS12) {
  21207. return AttributeCompression.decompressTextureCoordinates(buffer[index + 2], result);
  21208. }
  21209. return Cartesian2.fromElements(buffer[index + 4], buffer[index + 5], result);
  21210. };
  21211. TerrainEncoding.prototype.decodeHeight = function(buffer, index) {
  21212. index *= this.getStride();
  21213. if (this.quantization === TerrainQuantization.BITS12) {
  21214. var zh = AttributeCompression.decompressTextureCoordinates(buffer[index + 1], cartesian2Scratch);
  21215. return zh.y * (this.maximumHeight - this.minimumHeight) + this.minimumHeight;
  21216. }
  21217. return buffer[index + 3];
  21218. };
  21219. TerrainEncoding.prototype.getOctEncodedNormal = function(buffer, index, result) {
  21220. var stride = this.getStride();
  21221. index = (index + 1) * stride - 1;
  21222. var temp = buffer[index] / 256.0;
  21223. var x = Math.floor(temp);
  21224. var y = (temp - x) * 256.0;
  21225. return Cartesian2.fromElements(x, y, result);
  21226. };
  21227. TerrainEncoding.prototype.getStride = function() {
  21228. var vertexStride;
  21229. switch (this.quantization) {
  21230. case TerrainQuantization.BITS12:
  21231. vertexStride = 3;
  21232. break;
  21233. default:
  21234. vertexStride = 6;
  21235. }
  21236. if (this.hasWebMercatorT) {
  21237. ++vertexStride;
  21238. }
  21239. if (this.hasVertexNormals) {
  21240. ++vertexStride;
  21241. }
  21242. return vertexStride;
  21243. };
  21244. var attributesNone = {
  21245. position3DAndHeight : 0,
  21246. textureCoordAndEncodedNormals : 1
  21247. };
  21248. var attributes = {
  21249. compressed0 : 0,
  21250. compressed1 : 1
  21251. };
  21252. TerrainEncoding.prototype.getAttributes = function(buffer) {
  21253. var datatype = ComponentDatatype.FLOAT;
  21254. var sizeInBytes = ComponentDatatype.getSizeInBytes(datatype);
  21255. var stride;
  21256. if (this.quantization === TerrainQuantization.NONE) {
  21257. var position3DAndHeightLength = 4;
  21258. var numTexCoordComponents = 2;
  21259. if (this.hasWebMercatorT) {
  21260. ++numTexCoordComponents;
  21261. }
  21262. if (this.hasVertexNormals) {
  21263. ++numTexCoordComponents;
  21264. }
  21265. stride = (position3DAndHeightLength + numTexCoordComponents) * sizeInBytes;
  21266. return [{
  21267. index : attributesNone.position3DAndHeight,
  21268. vertexBuffer : buffer,
  21269. componentDatatype : datatype,
  21270. componentsPerAttribute : position3DAndHeightLength,
  21271. offsetInBytes : 0,
  21272. strideInBytes : stride
  21273. }, {
  21274. index : attributesNone.textureCoordAndEncodedNormals,
  21275. vertexBuffer : buffer,
  21276. componentDatatype : datatype,
  21277. componentsPerAttribute : numTexCoordComponents,
  21278. offsetInBytes : position3DAndHeightLength * sizeInBytes,
  21279. strideInBytes : stride
  21280. }];
  21281. }
  21282. var numCompressed0 = 3;
  21283. var numCompressed1 = 0;
  21284. if (this.hasWebMercatorT || this.hasVertexNormals) {
  21285. ++numCompressed0;
  21286. }
  21287. if (this.hasWebMercatorT && this.hasVertexNormals) {
  21288. ++numCompressed1;
  21289. stride = (numCompressed0 + numCompressed1) * sizeInBytes;
  21290. return [{
  21291. index : attributes.compressed0,
  21292. vertexBuffer : buffer,
  21293. componentDatatype : datatype,
  21294. componentsPerAttribute : numCompressed0,
  21295. offsetInBytes : 0,
  21296. strideInBytes : stride
  21297. }, {
  21298. index : attributes.compressed1,
  21299. vertexBuffer : buffer,
  21300. componentDatatype : datatype,
  21301. componentsPerAttribute : numCompressed1,
  21302. offsetInBytes : numCompressed0 * sizeInBytes,
  21303. strideInBytes : stride
  21304. }];
  21305. } else {
  21306. return [{
  21307. index : attributes.compressed0,
  21308. vertexBuffer : buffer,
  21309. componentDatatype : datatype,
  21310. componentsPerAttribute : numCompressed0
  21311. }];
  21312. }
  21313. };
  21314. TerrainEncoding.prototype.getAttributeLocations = function() {
  21315. if (this.quantization === TerrainQuantization.NONE) {
  21316. return attributesNone;
  21317. } else {
  21318. return attributes;
  21319. }
  21320. };
  21321. TerrainEncoding.clone = function(encoding, result) {
  21322. if (!defined(result)) {
  21323. result = new TerrainEncoding();
  21324. }
  21325. result.quantization = encoding.quantization;
  21326. result.minimumHeight = encoding.minimumHeight;
  21327. result.maximumHeight = encoding.maximumHeight;
  21328. result.center = Cartesian3.clone(encoding.center);
  21329. result.toScaledENU = Matrix4.clone(encoding.toScaledENU);
  21330. result.fromScaledENU = Matrix4.clone(encoding.fromScaledENU);
  21331. result.matrix = Matrix4.clone(encoding.matrix);
  21332. result.hasVertexNormals = encoding.hasVertexNormals;
  21333. result.hasWebMercatorT = encoding.hasWebMercatorT;
  21334. return result;
  21335. };
  21336. return TerrainEncoding;
  21337. });
  21338. /*global define*/
  21339. define('Core/WebMercatorProjection',[
  21340. './Cartesian3',
  21341. './Cartographic',
  21342. './defaultValue',
  21343. './defined',
  21344. './defineProperties',
  21345. './DeveloperError',
  21346. './Ellipsoid',
  21347. './Math'
  21348. ], function(
  21349. Cartesian3,
  21350. Cartographic,
  21351. defaultValue,
  21352. defined,
  21353. defineProperties,
  21354. DeveloperError,
  21355. Ellipsoid,
  21356. CesiumMath) {
  21357. 'use strict';
  21358. /**
  21359. * The map projection used by Google Maps, Bing Maps, and most of ArcGIS Online, EPSG:3857. This
  21360. * projection use longitude and latitude expressed with the WGS84 and transforms them to Mercator using
  21361. * the spherical (rather than ellipsoidal) equations.
  21362. *
  21363. * @alias WebMercatorProjection
  21364. * @constructor
  21365. *
  21366. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  21367. *
  21368. * @see GeographicProjection
  21369. */
  21370. function WebMercatorProjection(ellipsoid) {
  21371. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  21372. this._semimajorAxis = this._ellipsoid.maximumRadius;
  21373. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  21374. }
  21375. defineProperties(WebMercatorProjection.prototype, {
  21376. /**
  21377. * Gets the {@link Ellipsoid}.
  21378. *
  21379. * @memberof WebMercatorProjection.prototype
  21380. *
  21381. * @type {Ellipsoid}
  21382. * @readonly
  21383. */
  21384. ellipsoid : {
  21385. get : function() {
  21386. return this._ellipsoid;
  21387. }
  21388. }
  21389. });
  21390. /**
  21391. * Converts a Mercator angle, in the range -PI to PI, to a geodetic latitude
  21392. * in the range -PI/2 to PI/2.
  21393. *
  21394. * @param {Number} mercatorAngle The angle to convert.
  21395. * @returns {Number} The geodetic latitude in radians.
  21396. */
  21397. WebMercatorProjection.mercatorAngleToGeodeticLatitude = function(mercatorAngle) {
  21398. return CesiumMath.PI_OVER_TWO - (2.0 * Math.atan(Math.exp(-mercatorAngle)));
  21399. };
  21400. /**
  21401. * Converts a geodetic latitude in radians, in the range -PI/2 to PI/2, to a Mercator
  21402. * angle in the range -PI to PI.
  21403. *
  21404. * @param {Number} latitude The geodetic latitude in radians.
  21405. * @returns {Number} The Mercator angle.
  21406. */
  21407. WebMercatorProjection.geodeticLatitudeToMercatorAngle = function(latitude) {
  21408. // Clamp the latitude coordinate to the valid Mercator bounds.
  21409. if (latitude > WebMercatorProjection.MaximumLatitude) {
  21410. latitude = WebMercatorProjection.MaximumLatitude;
  21411. } else if (latitude < -WebMercatorProjection.MaximumLatitude) {
  21412. latitude = -WebMercatorProjection.MaximumLatitude;
  21413. }
  21414. var sinLatitude = Math.sin(latitude);
  21415. return 0.5 * Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude));
  21416. };
  21417. /**
  21418. * The maximum latitude (both North and South) supported by a Web Mercator
  21419. * (EPSG:3857) projection. Technically, the Mercator projection is defined
  21420. * for any latitude up to (but not including) 90 degrees, but it makes sense
  21421. * to cut it off sooner because it grows exponentially with increasing latitude.
  21422. * The logic behind this particular cutoff value, which is the one used by
  21423. * Google Maps, Bing Maps, and Esri, is that it makes the projection
  21424. * square. That is, the rectangle is equal in the X and Y directions.
  21425. *
  21426. * The constant value is computed by calling:
  21427. * WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI)
  21428. *
  21429. * @type {Number}
  21430. */
  21431. WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI);
  21432. /**
  21433. * Converts geodetic ellipsoid coordinates, in radians, to the equivalent Web Mercator
  21434. * X, Y, Z coordinates expressed in meters and returned in a {@link Cartesian3}. The height
  21435. * is copied unmodified to the Z coordinate.
  21436. *
  21437. * @param {Cartographic} cartographic The cartographic coordinates in radians.
  21438. * @param {Cartesian3} [result] The instance to which to copy the result, or undefined if a
  21439. * new instance should be created.
  21440. * @returns {Cartesian3} The equivalent web mercator X, Y, Z coordinates, in meters.
  21441. */
  21442. WebMercatorProjection.prototype.project = function(cartographic, result) {
  21443. var semimajorAxis = this._semimajorAxis;
  21444. var x = cartographic.longitude * semimajorAxis;
  21445. var y = WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographic.latitude) * semimajorAxis;
  21446. var z = cartographic.height;
  21447. if (!defined(result)) {
  21448. return new Cartesian3(x, y, z);
  21449. }
  21450. result.x = x;
  21451. result.y = y;
  21452. result.z = z;
  21453. return result;
  21454. };
  21455. /**
  21456. * Converts Web Mercator X, Y coordinates, expressed in meters, to a {@link Cartographic}
  21457. * containing geodetic ellipsoid coordinates. The Z coordinate is copied unmodified to the
  21458. * height.
  21459. *
  21460. * @param {Cartesian3} cartesian The web mercator Cartesian position to unrproject with height (z) in meters.
  21461. * @param {Cartographic} [result] The instance to which to copy the result, or undefined if a
  21462. * new instance should be created.
  21463. * @returns {Cartographic} The equivalent cartographic coordinates.
  21464. */
  21465. WebMercatorProjection.prototype.unproject = function(cartesian, result) {
  21466. if (!defined(cartesian)) {
  21467. throw new DeveloperError('cartesian is required');
  21468. }
  21469. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  21470. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  21471. var latitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(cartesian.y * oneOverEarthSemimajorAxis);
  21472. var height = cartesian.z;
  21473. if (!defined(result)) {
  21474. return new Cartographic(longitude, latitude, height);
  21475. }
  21476. result.longitude = longitude;
  21477. result.latitude = latitude;
  21478. result.height = height;
  21479. return result;
  21480. };
  21481. return WebMercatorProjection;
  21482. });
  21483. /*global define*/
  21484. define('Core/formatError',[
  21485. './defined'
  21486. ], function(
  21487. defined) {
  21488. 'use strict';
  21489. /**
  21490. * Formats an error object into a String. If available, uses name, message, and stack
  21491. * properties, otherwise, falls back on toString().
  21492. *
  21493. * @exports formatError
  21494. *
  21495. * @param {Object} object The item to find in the array.
  21496. * @returns {String} A string containing the formatted error.
  21497. */
  21498. function formatError(object) {
  21499. var result;
  21500. var name = object.name;
  21501. var message = object.message;
  21502. if (defined(name) && defined(message)) {
  21503. result = name + ': ' + message;
  21504. } else {
  21505. result = object.toString();
  21506. }
  21507. var stack = object.stack;
  21508. if (defined(stack)) {
  21509. result += '\n' + stack;
  21510. }
  21511. return result;
  21512. }
  21513. return formatError;
  21514. });
  21515. /*global define*/
  21516. define('Workers/createTaskProcessorWorker',[
  21517. '../Core/defaultValue',
  21518. '../Core/defined',
  21519. '../Core/formatError'
  21520. ], function(
  21521. defaultValue,
  21522. defined,
  21523. formatError) {
  21524. 'use strict';
  21525. /**
  21526. * Creates an adapter function to allow a calculation function to operate as a Web Worker,
  21527. * paired with TaskProcessor, to receive tasks and return results.
  21528. *
  21529. * @exports createTaskProcessorWorker
  21530. *
  21531. * @param {createTaskProcessorWorker~WorkerFunction} workerFunction The calculation function,
  21532. * which takes parameters and returns a result.
  21533. * @returns {createTaskProcessorWorker~TaskProcessorWorkerFunction} A function that adapts the
  21534. * calculation function to work as a Web Worker onmessage listener with TaskProcessor.
  21535. *
  21536. *
  21537. * @example
  21538. * function doCalculation(parameters, transferableObjects) {
  21539. * // calculate some result using the inputs in parameters
  21540. * return result;
  21541. * }
  21542. *
  21543. * return Cesium.createTaskProcessorWorker(doCalculation);
  21544. * // the resulting function is compatible with TaskProcessor
  21545. *
  21546. * @see TaskProcessor
  21547. * @see {@link http://www.w3.org/TR/workers/|Web Workers}
  21548. * @see {@link http://www.w3.org/TR/html5/common-dom-interfaces.html#transferable-objects|Transferable objects}
  21549. */
  21550. function createTaskProcessorWorker(workerFunction) {
  21551. var postMessage;
  21552. var transferableObjects = [];
  21553. var responseMessage = {
  21554. id : undefined,
  21555. result : undefined,
  21556. error : undefined
  21557. };
  21558. return function(event) {
  21559. /*global self*/
  21560. var data = event.data;
  21561. transferableObjects.length = 0;
  21562. responseMessage.id = data.id;
  21563. responseMessage.error = undefined;
  21564. responseMessage.result = undefined;
  21565. try {
  21566. responseMessage.result = workerFunction(data.parameters, transferableObjects);
  21567. } catch (e) {
  21568. if (e instanceof Error) {
  21569. // Errors can't be posted in a message, copy the properties
  21570. responseMessage.error = {
  21571. name : e.name,
  21572. message : e.message,
  21573. stack : e.stack
  21574. };
  21575. } else {
  21576. responseMessage.error = e;
  21577. }
  21578. }
  21579. if (!defined(postMessage)) {
  21580. postMessage = defaultValue(self.webkitPostMessage, self.postMessage);
  21581. }
  21582. if (!data.canTransferArrayBuffer) {
  21583. transferableObjects.length = 0;
  21584. }
  21585. try {
  21586. postMessage(responseMessage, transferableObjects);
  21587. } catch (e) {
  21588. // something went wrong trying to post the message, post a simpler
  21589. // error that we can be sure will be cloneable
  21590. responseMessage.result = undefined;
  21591. responseMessage.error = 'postMessage failed with error: ' + formatError(e) + '\n with responseMessage: ' + JSON.stringify(responseMessage);
  21592. postMessage(responseMessage);
  21593. }
  21594. };
  21595. }
  21596. /**
  21597. * A function that performs a calculation in a Web Worker.
  21598. * @callback createTaskProcessorWorker~WorkerFunction
  21599. *
  21600. * @param {Object} parameters Parameters to the calculation.
  21601. * @param {Array} transferableObjects An array that should be filled with references to objects inside
  21602. * the result that should be transferred back to the main document instead of copied.
  21603. * @returns {Object} The result of the calculation.
  21604. *
  21605. * @example
  21606. * function calculate(parameters, transferableObjects) {
  21607. * // perform whatever calculation is necessary.
  21608. * var typedArray = new Float32Array(0);
  21609. *
  21610. * // typed arrays are transferable
  21611. * transferableObjects.push(typedArray)
  21612. *
  21613. * return {
  21614. * typedArray : typedArray
  21615. * };
  21616. * }
  21617. */
  21618. /**
  21619. * A Web Worker message event handler function that handles the interaction with TaskProcessor,
  21620. * specifically, task ID management and posting a response message containing the result.
  21621. * @callback createTaskProcessorWorker~TaskProcessorWorkerFunction
  21622. *
  21623. * @param {Object} event The onmessage event object.
  21624. */
  21625. return createTaskProcessorWorker;
  21626. });
  21627. /*global define*/
  21628. define('Workers/createVerticesFromQuantizedTerrainMesh',[
  21629. '../Core/AttributeCompression',
  21630. '../Core/AxisAlignedBoundingBox',
  21631. '../Core/BoundingSphere',
  21632. '../Core/Cartesian2',
  21633. '../Core/Cartesian3',
  21634. '../Core/Cartographic',
  21635. '../Core/defined',
  21636. '../Core/Ellipsoid',
  21637. '../Core/IndexDatatype',
  21638. '../Core/Math',
  21639. '../Core/Matrix4',
  21640. '../Core/OrientedBoundingBox',
  21641. '../Core/TerrainEncoding',
  21642. '../Core/Transforms',
  21643. '../Core/WebMercatorProjection',
  21644. './createTaskProcessorWorker'
  21645. ], function(
  21646. AttributeCompression,
  21647. AxisAlignedBoundingBox,
  21648. BoundingSphere,
  21649. Cartesian2,
  21650. Cartesian3,
  21651. Cartographic,
  21652. defined,
  21653. Ellipsoid,
  21654. IndexDatatype,
  21655. CesiumMath,
  21656. Matrix4,
  21657. OrientedBoundingBox,
  21658. TerrainEncoding,
  21659. Transforms,
  21660. WebMercatorProjection,
  21661. createTaskProcessorWorker) {
  21662. 'use strict';
  21663. var maxShort = 32767;
  21664. var cartesian3Scratch = new Cartesian3();
  21665. var scratchMinimum = new Cartesian3();
  21666. var scratchMaximum = new Cartesian3();
  21667. var cartographicScratch = new Cartographic();
  21668. var toPack = new Cartesian2();
  21669. var scratchNormal = new Cartesian3();
  21670. var scratchToENU = new Matrix4();
  21671. var scratchFromENU = new Matrix4();
  21672. function createVerticesFromQuantizedTerrainMesh(parameters, transferableObjects) {
  21673. var quantizedVertices = parameters.quantizedVertices;
  21674. var quantizedVertexCount = quantizedVertices.length / 3;
  21675. var octEncodedNormals = parameters.octEncodedNormals;
  21676. var edgeVertexCount = parameters.westIndices.length + parameters.eastIndices.length +
  21677. parameters.southIndices.length + parameters.northIndices.length;
  21678. var includeWebMercatorT = parameters.includeWebMercatorT;
  21679. var rectangle = parameters.rectangle;
  21680. var west = rectangle.west;
  21681. var south = rectangle.south;
  21682. var east = rectangle.east;
  21683. var north = rectangle.north;
  21684. var ellipsoid = Ellipsoid.clone(parameters.ellipsoid);
  21685. var exaggeration = parameters.exaggeration;
  21686. var minimumHeight = parameters.minimumHeight * exaggeration;
  21687. var maximumHeight = parameters.maximumHeight * exaggeration;
  21688. var center = parameters.relativeToCenter;
  21689. var fromENU = Transforms.eastNorthUpToFixedFrame(center, ellipsoid);
  21690. var toENU = Matrix4.inverseTransformation(fromENU, new Matrix4());
  21691. var southMercatorY;
  21692. var oneOverMercatorHeight;
  21693. if (includeWebMercatorT) {
  21694. southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(south);
  21695. oneOverMercatorHeight = 1.0 / (WebMercatorProjection.geodeticLatitudeToMercatorAngle(north) - southMercatorY);
  21696. }
  21697. var uBuffer = quantizedVertices.subarray(0, quantizedVertexCount);
  21698. var vBuffer = quantizedVertices.subarray(quantizedVertexCount, 2 * quantizedVertexCount);
  21699. var heightBuffer = quantizedVertices.subarray(quantizedVertexCount * 2, 3 * quantizedVertexCount);
  21700. var hasVertexNormals = defined(octEncodedNormals);
  21701. var uvs = new Array(quantizedVertexCount);
  21702. var heights = new Array(quantizedVertexCount);
  21703. var positions = new Array(quantizedVertexCount);
  21704. var webMercatorTs = includeWebMercatorT ? new Array(quantizedVertexCount) : [];
  21705. var minimum = scratchMinimum;
  21706. minimum.x = Number.POSITIVE_INFINITY;
  21707. minimum.y = Number.POSITIVE_INFINITY;
  21708. minimum.z = Number.POSITIVE_INFINITY;
  21709. var maximum = scratchMaximum;
  21710. maximum.x = Number.NEGATIVE_INFINITY;
  21711. maximum.y = Number.NEGATIVE_INFINITY;
  21712. maximum.z = Number.NEGATIVE_INFINITY;
  21713. for (var i = 0; i < quantizedVertexCount; ++i) {
  21714. var u = uBuffer[i] / maxShort;
  21715. var v = vBuffer[i] / maxShort;
  21716. var height = CesiumMath.lerp(minimumHeight, maximumHeight, heightBuffer[i] / maxShort);
  21717. cartographicScratch.longitude = CesiumMath.lerp(west, east, u);
  21718. cartographicScratch.latitude = CesiumMath.lerp(south, north, v);
  21719. cartographicScratch.height = height;
  21720. var position = ellipsoid.cartographicToCartesian(cartographicScratch);
  21721. uvs[i] = new Cartesian2(u, v);
  21722. heights[i] = height;
  21723. positions[i] = position;
  21724. if (includeWebMercatorT) {
  21725. webMercatorTs[i] = (WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographicScratch.latitude) - southMercatorY) * oneOverMercatorHeight;
  21726. }
  21727. Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch);
  21728. Cartesian3.minimumByComponent(cartesian3Scratch, minimum, minimum);
  21729. Cartesian3.maximumByComponent(cartesian3Scratch, maximum, maximum);
  21730. }
  21731. var orientedBoundingBox;
  21732. var boundingSphere;
  21733. if (exaggeration !== 1.0) {
  21734. // Bounding volumes and horizon culling point need to be recomputed since the tile payload assumes no exaggeration.
  21735. boundingSphere = BoundingSphere.fromPoints(positions);
  21736. orientedBoundingBox = OrientedBoundingBox.fromRectangle(rectangle, minimumHeight, maximumHeight, ellipsoid);
  21737. }
  21738. var hMin = minimumHeight;
  21739. hMin = Math.min(hMin, findMinMaxSkirts(parameters.westIndices, parameters.westSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  21740. hMin = Math.min(hMin, findMinMaxSkirts(parameters.southIndices, parameters.southSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  21741. hMin = Math.min(hMin, findMinMaxSkirts(parameters.eastIndices, parameters.eastSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  21742. hMin = Math.min(hMin, findMinMaxSkirts(parameters.northIndices, parameters.northSkirtHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum));
  21743. var aaBox = new AxisAlignedBoundingBox(minimum, maximum, center);
  21744. var encoding = new TerrainEncoding(aaBox, hMin, maximumHeight, fromENU, hasVertexNormals, includeWebMercatorT);
  21745. var vertexStride = encoding.getStride();
  21746. var size = quantizedVertexCount * vertexStride + edgeVertexCount * vertexStride;
  21747. var vertexBuffer = new Float32Array(size);
  21748. var bufferIndex = 0;
  21749. for (var j = 0; j < quantizedVertexCount; ++j) {
  21750. if (hasVertexNormals) {
  21751. var n = j * 2.0;
  21752. toPack.x = octEncodedNormals[n];
  21753. toPack.y = octEncodedNormals[n + 1];
  21754. if (exaggeration !== 1.0) {
  21755. var normal = AttributeCompression.octDecode(toPack.x, toPack.y, scratchNormal);
  21756. var fromENUNormal = Transforms.eastNorthUpToFixedFrame(positions[j], ellipsoid, scratchFromENU);
  21757. var toENUNormal = Matrix4.inverseTransformation(fromENUNormal, scratchToENU);
  21758. Matrix4.multiplyByPointAsVector(toENUNormal, normal, normal);
  21759. normal.z *= exaggeration;
  21760. Cartesian3.normalize(normal, normal);
  21761. Matrix4.multiplyByPointAsVector(fromENUNormal, normal, normal);
  21762. Cartesian3.normalize(normal, normal);
  21763. AttributeCompression.octEncode(normal, toPack);
  21764. }
  21765. }
  21766. bufferIndex = encoding.encode(vertexBuffer, bufferIndex, positions[j], uvs[j], heights[j], toPack, webMercatorTs[j]);
  21767. }
  21768. var edgeTriangleCount = Math.max(0, (edgeVertexCount - 4) * 2);
  21769. var indexBufferLength = parameters.indices.length + edgeTriangleCount * 3;
  21770. var indexBuffer = IndexDatatype.createTypedArray(quantizedVertexCount + edgeVertexCount, indexBufferLength);
  21771. indexBuffer.set(parameters.indices, 0);
  21772. // Add skirts.
  21773. var vertexBufferIndex = quantizedVertexCount * vertexStride;
  21774. var indexBufferIndex = parameters.indices.length;
  21775. indexBufferIndex = addSkirt(vertexBuffer, vertexBufferIndex, indexBuffer, indexBufferIndex, parameters.westIndices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.westSkirtHeight, true, exaggeration, southMercatorY, oneOverMercatorHeight);
  21776. vertexBufferIndex += parameters.westIndices.length * vertexStride;
  21777. indexBufferIndex = addSkirt(vertexBuffer, vertexBufferIndex, indexBuffer, indexBufferIndex, parameters.southIndices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.southSkirtHeight, false, exaggeration, southMercatorY, oneOverMercatorHeight);
  21778. vertexBufferIndex += parameters.southIndices.length * vertexStride;
  21779. indexBufferIndex = addSkirt(vertexBuffer, vertexBufferIndex, indexBuffer, indexBufferIndex, parameters.eastIndices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.eastSkirtHeight, false, exaggeration, southMercatorY, oneOverMercatorHeight);
  21780. vertexBufferIndex += parameters.eastIndices.length * vertexStride;
  21781. addSkirt(vertexBuffer, vertexBufferIndex, indexBuffer, indexBufferIndex, parameters.northIndices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, parameters.northSkirtHeight, true, exaggeration, southMercatorY, oneOverMercatorHeight);
  21782. transferableObjects.push(vertexBuffer.buffer, indexBuffer.buffer);
  21783. return {
  21784. vertices : vertexBuffer.buffer,
  21785. indices : indexBuffer.buffer,
  21786. vertexStride : vertexStride,
  21787. center : center,
  21788. minimumHeight : minimumHeight,
  21789. maximumHeight : maximumHeight,
  21790. boundingSphere : boundingSphere,
  21791. orientedBoundingBox : orientedBoundingBox,
  21792. encoding : encoding,
  21793. skirtIndex : parameters.indices.length
  21794. };
  21795. }
  21796. function findMinMaxSkirts(edgeIndices, edgeHeight, heights, uvs, rectangle, ellipsoid, toENU, minimum, maximum) {
  21797. var hMin = Number.POSITIVE_INFINITY;
  21798. var north = rectangle.north;
  21799. var south = rectangle.south;
  21800. var east = rectangle.east;
  21801. var west = rectangle.west;
  21802. if (east < west) {
  21803. east += CesiumMath.TWO_PI;
  21804. }
  21805. var length = edgeIndices.length;
  21806. for (var i = 0; i < length; ++i) {
  21807. var index = edgeIndices[i];
  21808. var h = heights[index];
  21809. var uv = uvs[index];
  21810. cartographicScratch.longitude = CesiumMath.lerp(west, east, uv.x);
  21811. cartographicScratch.latitude = CesiumMath.lerp(south, north, uv.y);
  21812. cartographicScratch.height = h - edgeHeight;
  21813. var position = ellipsoid.cartographicToCartesian(cartographicScratch, cartesian3Scratch);
  21814. Matrix4.multiplyByPoint(toENU, position, position);
  21815. Cartesian3.minimumByComponent(position, minimum, minimum);
  21816. Cartesian3.maximumByComponent(position, maximum, maximum);
  21817. hMin = Math.min(hMin, cartographicScratch.height);
  21818. }
  21819. return hMin;
  21820. }
  21821. function addSkirt(vertexBuffer, vertexBufferIndex, indexBuffer, indexBufferIndex, edgeVertices, encoding, heights, uvs, octEncodedNormals, ellipsoid, rectangle, skirtLength, isWestOrNorthEdge, exaggeration, southMercatorY, oneOverMercatorHeight) {
  21822. var start, end, increment;
  21823. if (isWestOrNorthEdge) {
  21824. start = edgeVertices.length - 1;
  21825. end = -1;
  21826. increment = -1;
  21827. } else {
  21828. start = 0;
  21829. end = edgeVertices.length;
  21830. increment = 1;
  21831. }
  21832. var previousIndex = -1;
  21833. var hasVertexNormals = defined(octEncodedNormals);
  21834. var vertexStride = encoding.getStride();
  21835. var vertexIndex = vertexBufferIndex / vertexStride;
  21836. var north = rectangle.north;
  21837. var south = rectangle.south;
  21838. var east = rectangle.east;
  21839. var west = rectangle.west;
  21840. if (east < west) {
  21841. east += CesiumMath.TWO_PI;
  21842. }
  21843. for (var i = start; i !== end; i += increment) {
  21844. var index = edgeVertices[i];
  21845. var h = heights[index];
  21846. var uv = uvs[index];
  21847. cartographicScratch.longitude = CesiumMath.lerp(west, east, uv.x);
  21848. cartographicScratch.latitude = CesiumMath.lerp(south, north, uv.y);
  21849. cartographicScratch.height = h - skirtLength;
  21850. var position = ellipsoid.cartographicToCartesian(cartographicScratch, cartesian3Scratch);
  21851. if (hasVertexNormals) {
  21852. var n = index * 2.0;
  21853. toPack.x = octEncodedNormals[n];
  21854. toPack.y = octEncodedNormals[n + 1];
  21855. if (exaggeration !== 1.0) {
  21856. var normal = AttributeCompression.octDecode(toPack.x, toPack.y, scratchNormal);
  21857. var fromENUNormal = Transforms.eastNorthUpToFixedFrame(cartesian3Scratch, ellipsoid, scratchFromENU);
  21858. var toENUNormal = Matrix4.inverseTransformation(fromENUNormal, scratchToENU);
  21859. Matrix4.multiplyByPointAsVector(toENUNormal, normal, normal);
  21860. normal.z *= exaggeration;
  21861. Cartesian3.normalize(normal, normal);
  21862. Matrix4.multiplyByPointAsVector(fromENUNormal, normal, normal);
  21863. Cartesian3.normalize(normal, normal);
  21864. AttributeCompression.octEncode(normal, toPack);
  21865. }
  21866. }
  21867. var webMercatorT;
  21868. if (encoding.hasWebMercatorT) {
  21869. webMercatorT = (WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographicScratch.latitude) - southMercatorY) * oneOverMercatorHeight;
  21870. }
  21871. vertexBufferIndex = encoding.encode(vertexBuffer, vertexBufferIndex, position, uv, cartographicScratch.height, toPack, webMercatorT);
  21872. if (previousIndex !== -1) {
  21873. indexBuffer[indexBufferIndex++] = previousIndex;
  21874. indexBuffer[indexBufferIndex++] = vertexIndex - 1;
  21875. indexBuffer[indexBufferIndex++] = index;
  21876. indexBuffer[indexBufferIndex++] = vertexIndex - 1;
  21877. indexBuffer[indexBufferIndex++] = vertexIndex;
  21878. indexBuffer[indexBufferIndex++] = index;
  21879. }
  21880. previousIndex = index;
  21881. ++vertexIndex;
  21882. }
  21883. return indexBufferIndex;
  21884. }
  21885. return createTaskProcessorWorker(createVerticesFromQuantizedTerrainMesh);
  21886. });
  21887. }());