createPolylineVolumeOutlineGeometry.js 959 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070
  1. /**
  2. * Cesium - https://github.com/AnalyticalGraphicsInc/cesium
  3. *
  4. * Copyright 2011-2016 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. (function () {
  24. /*global define*/
  25. define('Core/defined',[],function() {
  26. 'use strict';
  27. /**
  28. * @exports defined
  29. *
  30. * @param {Object} value The object.
  31. * @returns {Boolean} Returns true if the object is defined, returns false otherwise.
  32. *
  33. * @example
  34. * if (Cesium.defined(positions)) {
  35. * doSomething();
  36. * } else {
  37. * doSomethingElse();
  38. * }
  39. */
  40. function defined(value) {
  41. return value !== undefined && value !== null;
  42. }
  43. return defined;
  44. });
  45. /*global define*/
  46. define('Core/freezeObject',[
  47. './defined'
  48. ], function(
  49. defined) {
  50. 'use strict';
  51. /**
  52. * Freezes an object, using Object.freeze if available, otherwise returns
  53. * the object unchanged. This function should be used in setup code to prevent
  54. * errors from completely halting JavaScript execution in legacy browsers.
  55. *
  56. * @private
  57. *
  58. * @exports freezeObject
  59. */
  60. var freezeObject = Object.freeze;
  61. if (!defined(freezeObject)) {
  62. freezeObject = function(o) {
  63. return o;
  64. };
  65. }
  66. return freezeObject;
  67. });
  68. /*global define*/
  69. define('Core/defaultValue',[
  70. './freezeObject'
  71. ], function(
  72. freezeObject) {
  73. 'use strict';
  74. /**
  75. * Returns the first parameter if not undefined, otherwise the second parameter.
  76. * Useful for setting a default value for a parameter.
  77. *
  78. * @exports defaultValue
  79. *
  80. * @param {*} a
  81. * @param {*} b
  82. * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
  83. *
  84. * @example
  85. * param = Cesium.defaultValue(param, 'default');
  86. */
  87. function defaultValue(a, b) {
  88. if (a !== undefined) {
  89. return a;
  90. }
  91. return b;
  92. }
  93. /**
  94. * A frozen empty object that can be used as the default value for options passed as
  95. * an object literal.
  96. */
  97. defaultValue.EMPTY_OBJECT = freezeObject({});
  98. return defaultValue;
  99. });
  100. /*global define*/
  101. define('Core/DeveloperError',[
  102. './defined'
  103. ], function(
  104. defined) {
  105. 'use strict';
  106. /**
  107. * Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
  108. * argument out of range, etc. This exception should only be thrown during development;
  109. * it usually indicates a bug in the calling code. This exception should never be
  110. * caught; instead the calling code should strive not to generate it.
  111. * <br /><br />
  112. * On the other hand, a {@link RuntimeError} indicates an exception that may
  113. * be thrown at runtime, e.g., out of memory, that the calling code should be prepared
  114. * to catch.
  115. *
  116. * @alias DeveloperError
  117. * @constructor
  118. * @extends Error
  119. *
  120. * @param {String} [message] The error message for this exception.
  121. *
  122. * @see RuntimeError
  123. */
  124. function DeveloperError(message) {
  125. /**
  126. * 'DeveloperError' indicating that this exception was thrown due to a developer error.
  127. * @type {String}
  128. * @readonly
  129. */
  130. this.name = 'DeveloperError';
  131. /**
  132. * The explanation for why this exception was thrown.
  133. * @type {String}
  134. * @readonly
  135. */
  136. this.message = message;
  137. //Browsers such as IE don't have a stack property until you actually throw the error.
  138. var stack;
  139. try {
  140. throw new Error();
  141. } catch (e) {
  142. stack = e.stack;
  143. }
  144. /**
  145. * The stack trace of this exception, if available.
  146. * @type {String}
  147. * @readonly
  148. */
  149. this.stack = stack;
  150. }
  151. if (defined(Object.create)) {
  152. DeveloperError.prototype = Object.create(Error.prototype);
  153. DeveloperError.prototype.constructor = DeveloperError;
  154. }
  155. DeveloperError.prototype.toString = function() {
  156. var str = this.name + ': ' + this.message;
  157. if (defined(this.stack)) {
  158. str += '\n' + this.stack.toString();
  159. }
  160. return str;
  161. };
  162. /**
  163. * @private
  164. */
  165. DeveloperError.throwInstantiationError = function() {
  166. throw new DeveloperError('This function defines an interface and should not be called directly.');
  167. };
  168. return DeveloperError;
  169. });
  170. /*global define*/
  171. define('Core/isArray',[
  172. './defined'
  173. ], function(
  174. defined) {
  175. 'use strict';
  176. /**
  177. * Tests an object to see if it is an array.
  178. * @exports isArray
  179. *
  180. * @param {Object} value The value to test.
  181. * @returns {Boolean} true if the value is an array, false otherwise.
  182. */
  183. var isArray = Array.isArray;
  184. if (!defined(isArray)) {
  185. isArray = function(value) {
  186. return Object.prototype.toString.call(value) === '[object Array]';
  187. };
  188. }
  189. return isArray;
  190. });
  191. /*global define*/
  192. define('Core/Check',[
  193. './defaultValue',
  194. './defined',
  195. './DeveloperError',
  196. './isArray'
  197. ], function(
  198. defaultValue,
  199. defined,
  200. DeveloperError,
  201. isArray) {
  202. 'use strict';
  203. /**
  204. * Contains functions for checking that supplied arguments are of a specified type
  205. * or meet specified conditions
  206. * @private
  207. */
  208. var Check = {};
  209. /**
  210. * Contains type checking functions, all using the typeof operator
  211. */
  212. Check.typeOf = {};
  213. /**
  214. * Contains functions for checking numeric conditions such as minimum and maximum values
  215. */
  216. Check.numeric = {};
  217. function getUndefinedErrorMessage(name) {
  218. return name + ' was required but undefined.';
  219. }
  220. function getFailedTypeErrorMessage(actual, expected, name) {
  221. return 'Expected ' + name + ' to be typeof ' + expected + ', got ' + actual;
  222. }
  223. /**
  224. * Throws if test is not defined
  225. *
  226. * @param {*} test The value that is to be checked
  227. * @param {String} name The name of the variable being tested
  228. * @exception {DeveloperError} test must be defined
  229. */
  230. Check.defined = function (test, name) {
  231. if (!defined(test)) {
  232. throw new DeveloperError(getUndefinedErrorMessage(name));
  233. }
  234. };
  235. /**
  236. * Throws if test is greater than maximum
  237. *
  238. * @param {Number} test The value to test
  239. * @param {Number} maximum The maximum allowed value
  240. * @exception {DeveloperError} test must not be greater than maximum
  241. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  242. */
  243. Check.numeric.maximum = function (test, maximum) {
  244. Check.typeOf.number(test);
  245. Check.typeOf.number(maximum);
  246. if (test > maximum) {
  247. throw new DeveloperError('Expected ' + test + ' to be at most ' + maximum);
  248. }
  249. };
  250. /**
  251. * Throws if test is less than minimum
  252. *
  253. * @param {Number} test The value to test
  254. * @param {Number} minimum The minimum allowed value
  255. * @exception {DeveloperError} test must not be less than mininum
  256. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  257. */
  258. Check.numeric.minimum = function (test, minimum) {
  259. Check.typeOf.number(test);
  260. Check.typeOf.number(minimum);
  261. if (test < minimum) {
  262. throw new DeveloperError('Expected ' + test + ' to be at least ' + minimum);
  263. }
  264. };
  265. /**
  266. * Throws if test is not typeof 'function'
  267. *
  268. * @param {*} test The value to test
  269. * @param {String} name The name of the variable being tested
  270. * @exception {DeveloperError} test must be typeof 'function'
  271. */
  272. Check.typeOf.function = function (test, name) {
  273. if (typeof test !== 'function') {
  274. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'function', name));
  275. }
  276. };
  277. /**
  278. * Throws if test is not typeof 'string'
  279. *
  280. * @param {*} test The value to test
  281. * @param {String} name The name of the variable being tested
  282. * @exception {DeveloperError} test must be typeof 'string'
  283. */
  284. Check.typeOf.string = function (test, name) {
  285. if (typeof test !== 'string') {
  286. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'string', name));
  287. }
  288. };
  289. /**
  290. * Throws if test is not typeof 'number'
  291. *
  292. * @param {*} test The value to test
  293. * @param {String} name The name of the variable being tested
  294. * @exception {DeveloperError} test must be typeof 'number'
  295. */
  296. Check.typeOf.number = function (test, name) {
  297. if (typeof test !== 'number') {
  298. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'number', name));
  299. }
  300. };
  301. /**
  302. * Throws if test is not typeof 'object'
  303. *
  304. * @param {*} test The value to test
  305. * @param {String} name The name of the variable being tested
  306. * @exception {DeveloperError} test must be typeof 'object'
  307. */
  308. Check.typeOf.object = function (test, name) {
  309. if (typeof test !== 'object') {
  310. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'object', name));
  311. }
  312. };
  313. /**
  314. * Throws if test is not typeof 'boolean'
  315. *
  316. * @param {*} test The value to test
  317. * @param {String} name The name of the variable being tested
  318. * @exception {DeveloperError} test must be typeof 'boolean'
  319. */
  320. Check.typeOf.boolean = function (test, name) {
  321. if (typeof test !== 'boolean') {
  322. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'boolean', name));
  323. }
  324. };
  325. return Check;
  326. });
  327. /*
  328. I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  329. so it's better encapsulated. Now you can have multiple random number generators
  330. and they won't stomp all over eachother's state.
  331. If you want to use this as a substitute for Math.random(), use the random()
  332. method like so:
  333. var m = new MersenneTwister();
  334. var randomNumber = m.random();
  335. You can also call the other genrand_{foo}() methods on the instance.
  336. If you want to use a specific seed in order to get a repeatable random
  337. sequence, pass an integer into the constructor:
  338. var m = new MersenneTwister(123);
  339. and that will always produce the same random sequence.
  340. Sean McCullough (banksean@gmail.com)
  341. */
  342. /*
  343. A C-program for MT19937, with initialization improved 2002/1/26.
  344. Coded by Takuji Nishimura and Makoto Matsumoto.
  345. Before using, initialize the state by using init_genrand(seed)
  346. or init_by_array(init_key, key_length).
  347. */
  348. /**
  349. @license
  350. mersenne-twister.js - https://gist.github.com/banksean/300494
  351. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  352. All rights reserved.
  353. Redistribution and use in source and binary forms, with or without
  354. modification, are permitted provided that the following conditions
  355. are met:
  356. 1. Redistributions of source code must retain the above copyright
  357. notice, this list of conditions and the following disclaimer.
  358. 2. Redistributions in binary form must reproduce the above copyright
  359. notice, this list of conditions and the following disclaimer in the
  360. documentation and/or other materials provided with the distribution.
  361. 3. The names of its contributors may not be used to endorse or promote
  362. products derived from this software without specific prior written
  363. permission.
  364. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  365. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  366. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  367. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  368. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  369. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  370. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  371. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  372. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  373. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  374. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  375. */
  376. /*
  377. Any feedback is very welcome.
  378. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  379. email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
  380. */
  381. define('ThirdParty/mersenne-twister',[],function() {
  382. var MersenneTwister = function(seed) {
  383. if (seed == undefined) {
  384. seed = new Date().getTime();
  385. }
  386. /* Period parameters */
  387. this.N = 624;
  388. this.M = 397;
  389. this.MATRIX_A = 0x9908b0df; /* constant vector a */
  390. this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  391. this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
  392. this.mt = new Array(this.N); /* the array for the state vector */
  393. this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
  394. this.init_genrand(seed);
  395. }
  396. /* initializes mt[N] with a seed */
  397. MersenneTwister.prototype.init_genrand = function(s) {
  398. this.mt[0] = s >>> 0;
  399. for (this.mti=1; this.mti<this.N; this.mti++) {
  400. var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
  401. this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  402. + this.mti;
  403. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  404. /* In the previous versions, MSBs of the seed affect */
  405. /* only MSBs of the array mt[]. */
  406. /* 2002/01/09 modified by Makoto Matsumoto */
  407. this.mt[this.mti] >>>= 0;
  408. /* for >32 bit machines */
  409. }
  410. }
  411. /* initialize by an array with array-length */
  412. /* init_key is the array for initializing keys */
  413. /* key_length is its length */
  414. /* slight change for C++, 2004/2/26 */
  415. //MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  416. // var i, j, k;
  417. // this.init_genrand(19650218);
  418. // i=1; j=0;
  419. // k = (this.N>key_length ? this.N : key_length);
  420. // for (; k; k--) {
  421. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
  422. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
  423. // + init_key[j] + j; /* non linear */
  424. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  425. // i++; j++;
  426. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  427. // if (j>=key_length) j=0;
  428. // }
  429. // for (k=this.N-1; k; k--) {
  430. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  431. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
  432. // - i; /* non linear */
  433. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  434. // i++;
  435. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  436. // }
  437. //
  438. // this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
  439. //}
  440. /* generates a random number on [0,0xffffffff]-interval */
  441. MersenneTwister.prototype.genrand_int32 = function() {
  442. var y;
  443. var mag01 = new Array(0x0, this.MATRIX_A);
  444. /* mag01[x] = x * MATRIX_A for x=0,1 */
  445. if (this.mti >= this.N) { /* generate N words at one time */
  446. var kk;
  447. if (this.mti == this.N+1) /* if init_genrand() has not been called, */
  448. this.init_genrand(5489); /* a default initial seed is used */
  449. for (kk=0;kk<this.N-this.M;kk++) {
  450. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  451. this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
  452. }
  453. for (;kk<this.N-1;kk++) {
  454. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  455. this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
  456. }
  457. y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
  458. this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
  459. this.mti = 0;
  460. }
  461. y = this.mt[this.mti++];
  462. /* Tempering */
  463. y ^= (y >>> 11);
  464. y ^= (y << 7) & 0x9d2c5680;
  465. y ^= (y << 15) & 0xefc60000;
  466. y ^= (y >>> 18);
  467. return y >>> 0;
  468. }
  469. /* generates a random number on [0,0x7fffffff]-interval */
  470. //MersenneTwister.prototype.genrand_int31 = function() {
  471. // return (this.genrand_int32()>>>1);
  472. //}
  473. /* generates a random number on [0,1]-real-interval */
  474. //MersenneTwister.prototype.genrand_real1 = function() {
  475. // return this.genrand_int32()*(1.0/4294967295.0);
  476. // /* divided by 2^32-1 */
  477. //}
  478. /* generates a random number on [0,1)-real-interval */
  479. MersenneTwister.prototype.random = function() {
  480. return this.genrand_int32()*(1.0/4294967296.0);
  481. /* divided by 2^32 */
  482. }
  483. /* generates a random number on (0,1)-real-interval */
  484. //MersenneTwister.prototype.genrand_real3 = function() {
  485. // return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
  486. // /* divided by 2^32 */
  487. //}
  488. /* generates a random number on [0,1) with 53-bit resolution*/
  489. //MersenneTwister.prototype.genrand_res53 = function() {
  490. // var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
  491. // return(a*67108864.0+b)*(1.0/9007199254740992.0);
  492. //}
  493. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  494. return MersenneTwister;
  495. });
  496. /*global define*/
  497. define('Core/Math',[
  498. '../ThirdParty/mersenne-twister',
  499. './defaultValue',
  500. './defined',
  501. './DeveloperError'
  502. ], function(
  503. MersenneTwister,
  504. defaultValue,
  505. defined,
  506. DeveloperError) {
  507. 'use strict';
  508. /**
  509. * Math functions.
  510. *
  511. * @exports CesiumMath
  512. */
  513. var CesiumMath = {};
  514. /**
  515. * 0.1
  516. * @type {Number}
  517. * @constant
  518. */
  519. CesiumMath.EPSILON1 = 0.1;
  520. /**
  521. * 0.01
  522. * @type {Number}
  523. * @constant
  524. */
  525. CesiumMath.EPSILON2 = 0.01;
  526. /**
  527. * 0.001
  528. * @type {Number}
  529. * @constant
  530. */
  531. CesiumMath.EPSILON3 = 0.001;
  532. /**
  533. * 0.0001
  534. * @type {Number}
  535. * @constant
  536. */
  537. CesiumMath.EPSILON4 = 0.0001;
  538. /**
  539. * 0.00001
  540. * @type {Number}
  541. * @constant
  542. */
  543. CesiumMath.EPSILON5 = 0.00001;
  544. /**
  545. * 0.000001
  546. * @type {Number}
  547. * @constant
  548. */
  549. CesiumMath.EPSILON6 = 0.000001;
  550. /**
  551. * 0.0000001
  552. * @type {Number}
  553. * @constant
  554. */
  555. CesiumMath.EPSILON7 = 0.0000001;
  556. /**
  557. * 0.00000001
  558. * @type {Number}
  559. * @constant
  560. */
  561. CesiumMath.EPSILON8 = 0.00000001;
  562. /**
  563. * 0.000000001
  564. * @type {Number}
  565. * @constant
  566. */
  567. CesiumMath.EPSILON9 = 0.000000001;
  568. /**
  569. * 0.0000000001
  570. * @type {Number}
  571. * @constant
  572. */
  573. CesiumMath.EPSILON10 = 0.0000000001;
  574. /**
  575. * 0.00000000001
  576. * @type {Number}
  577. * @constant
  578. */
  579. CesiumMath.EPSILON11 = 0.00000000001;
  580. /**
  581. * 0.000000000001
  582. * @type {Number}
  583. * @constant
  584. */
  585. CesiumMath.EPSILON12 = 0.000000000001;
  586. /**
  587. * 0.0000000000001
  588. * @type {Number}
  589. * @constant
  590. */
  591. CesiumMath.EPSILON13 = 0.0000000000001;
  592. /**
  593. * 0.00000000000001
  594. * @type {Number}
  595. * @constant
  596. */
  597. CesiumMath.EPSILON14 = 0.00000000000001;
  598. /**
  599. * 0.000000000000001
  600. * @type {Number}
  601. * @constant
  602. */
  603. CesiumMath.EPSILON15 = 0.000000000000001;
  604. /**
  605. * 0.0000000000000001
  606. * @type {Number}
  607. * @constant
  608. */
  609. CesiumMath.EPSILON16 = 0.0000000000000001;
  610. /**
  611. * 0.00000000000000001
  612. * @type {Number}
  613. * @constant
  614. */
  615. CesiumMath.EPSILON17 = 0.00000000000000001;
  616. /**
  617. * 0.000000000000000001
  618. * @type {Number}
  619. * @constant
  620. */
  621. CesiumMath.EPSILON18 = 0.000000000000000001;
  622. /**
  623. * 0.0000000000000000001
  624. * @type {Number}
  625. * @constant
  626. */
  627. CesiumMath.EPSILON19 = 0.0000000000000000001;
  628. /**
  629. * 0.00000000000000000001
  630. * @type {Number}
  631. * @constant
  632. */
  633. CesiumMath.EPSILON20 = 0.00000000000000000001;
  634. /**
  635. * 3.986004418e14
  636. * @type {Number}
  637. * @constant
  638. */
  639. CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
  640. /**
  641. * Radius of the sun in meters: 6.955e8
  642. * @type {Number}
  643. * @constant
  644. */
  645. CesiumMath.SOLAR_RADIUS = 6.955e8;
  646. /**
  647. * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
  648. * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
  649. * Celestial Mechanics 82: 83-110, 2002.
  650. * @type {Number}
  651. * @constant
  652. */
  653. CesiumMath.LUNAR_RADIUS = 1737400.0;
  654. /**
  655. * 64 * 1024
  656. * @type {Number}
  657. * @constant
  658. */
  659. CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
  660. /**
  661. * Returns the sign of the value; 1 if the value is positive, -1 if the value is
  662. * negative, or 0 if the value is 0.
  663. *
  664. * @param {Number} value The value to return the sign of.
  665. * @returns {Number} The sign of value.
  666. */
  667. CesiumMath.sign = function(value) {
  668. if (value > 0) {
  669. return 1;
  670. }
  671. if (value < 0) {
  672. return -1;
  673. }
  674. return 0;
  675. };
  676. /**
  677. * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
  678. * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
  679. * 0.0 when the input value is 0.0.
  680. * @param {Number} value The value to return the sign of.
  681. * @returns {Number} The sign of value.
  682. */
  683. CesiumMath.signNotZero = function(value) {
  684. return value < 0.0 ? -1.0 : 1.0;
  685. };
  686. /**
  687. * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
  688. * @param {Number} value The scalar value in the range [-1.0, 1.0]
  689. * @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
  690. * @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
  691. *
  692. * @see CesiumMath.fromSNorm
  693. */
  694. CesiumMath.toSNorm = function(value, rangeMax) {
  695. rangeMax = defaultValue(rangeMax, 255);
  696. return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMax);
  697. };
  698. /**
  699. * Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
  700. * @param {Number} value SNORM value in the range [0, 255]
  701. * @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
  702. * @returns {Number} Scalar in the range [-1.0, 1.0].
  703. *
  704. * @see CesiumMath.toSNorm
  705. */
  706. CesiumMath.fromSNorm = function(value, rangeMax) {
  707. rangeMax = defaultValue(rangeMax, 255);
  708. return CesiumMath.clamp(value, 0.0, rangeMax) / rangeMax * 2.0 - 1.0;
  709. };
  710. /**
  711. * Returns the hyperbolic sine of a number.
  712. * The hyperbolic sine of <em>value</em> is defined to be
  713. * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
  714. * where <i>e</i> is Euler's number, approximately 2.71828183.
  715. *
  716. * <p>Special cases:
  717. * <ul>
  718. * <li>If the argument is NaN, then the result is NaN.</li>
  719. *
  720. * <li>If the argument is infinite, then the result is an infinity
  721. * with the same sign as the argument.</li>
  722. *
  723. * <li>If the argument is zero, then the result is a zero with the
  724. * same sign as the argument.</li>
  725. * </ul>
  726. *</p>
  727. *
  728. * @param {Number} value The number whose hyperbolic sine is to be returned.
  729. * @returns {Number} The hyperbolic sine of <code>value</code>.
  730. */
  731. CesiumMath.sinh = function(value) {
  732. var part1 = Math.pow(Math.E, value);
  733. var part2 = Math.pow(Math.E, -1.0 * value);
  734. return (part1 - part2) * 0.5;
  735. };
  736. /**
  737. * Returns the hyperbolic cosine of a number.
  738. * The hyperbolic cosine of <strong>value</strong> is defined to be
  739. * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
  740. * where <i>e</i> is Euler's number, approximately 2.71828183.
  741. *
  742. * <p>Special cases:
  743. * <ul>
  744. * <li>If the argument is NaN, then the result is NaN.</li>
  745. *
  746. * <li>If the argument is infinite, then the result is positive infinity.</li>
  747. *
  748. * <li>If the argument is zero, then the result is 1.0.</li>
  749. * </ul>
  750. *</p>
  751. *
  752. * @param {Number} value The number whose hyperbolic cosine is to be returned.
  753. * @returns {Number} The hyperbolic cosine of <code>value</code>.
  754. */
  755. CesiumMath.cosh = function(value) {
  756. var part1 = Math.pow(Math.E, value);
  757. var part2 = Math.pow(Math.E, -1.0 * value);
  758. return (part1 + part2) * 0.5;
  759. };
  760. /**
  761. * Computes the linear interpolation of two values.
  762. *
  763. * @param {Number} p The start value to interpolate.
  764. * @param {Number} q The end value to interpolate.
  765. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  766. * @returns {Number} The linearly interpolated value.
  767. *
  768. * @example
  769. * var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
  770. */
  771. CesiumMath.lerp = function(p, q, time) {
  772. return ((1.0 - time) * p) + (time * q);
  773. };
  774. /**
  775. * pi
  776. *
  777. * @type {Number}
  778. * @constant
  779. */
  780. CesiumMath.PI = Math.PI;
  781. /**
  782. * 1/pi
  783. *
  784. * @type {Number}
  785. * @constant
  786. */
  787. CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
  788. /**
  789. * pi/2
  790. *
  791. * @type {Number}
  792. * @constant
  793. */
  794. CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
  795. /**
  796. * pi/3
  797. *
  798. * @type {Number}
  799. * @constant
  800. */
  801. CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
  802. /**
  803. * pi/4
  804. *
  805. * @type {Number}
  806. * @constant
  807. */
  808. CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
  809. /**
  810. * pi/6
  811. *
  812. * @type {Number}
  813. * @constant
  814. */
  815. CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
  816. /**
  817. * 3pi/2
  818. *
  819. * @type {Number}
  820. * @constant
  821. */
  822. CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
  823. /**
  824. * 2pi
  825. *
  826. * @type {Number}
  827. * @constant
  828. */
  829. CesiumMath.TWO_PI = 2.0 * Math.PI;
  830. /**
  831. * 1/2pi
  832. *
  833. * @type {Number}
  834. * @constant
  835. */
  836. CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
  837. /**
  838. * The number of radians in a degree.
  839. *
  840. * @type {Number}
  841. * @constant
  842. * @default Math.PI / 180.0
  843. */
  844. CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
  845. /**
  846. * The number of degrees in a radian.
  847. *
  848. * @type {Number}
  849. * @constant
  850. * @default 180.0 / Math.PI
  851. */
  852. CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
  853. /**
  854. * The number of radians in an arc second.
  855. *
  856. * @type {Number}
  857. * @constant
  858. * @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
  859. */
  860. CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  861. /**
  862. * Converts degrees to radians.
  863. * @param {Number} degrees The angle to convert in degrees.
  864. * @returns {Number} The corresponding angle in radians.
  865. */
  866. CesiumMath.toRadians = function(degrees) {
  867. if (!defined(degrees)) {
  868. throw new DeveloperError('degrees is required.');
  869. }
  870. return degrees * CesiumMath.RADIANS_PER_DEGREE;
  871. };
  872. /**
  873. * Converts radians to degrees.
  874. * @param {Number} radians The angle to convert in radians.
  875. * @returns {Number} The corresponding angle in degrees.
  876. */
  877. CesiumMath.toDegrees = function(radians) {
  878. if (!defined(radians)) {
  879. throw new DeveloperError('radians is required.');
  880. }
  881. return radians * CesiumMath.DEGREES_PER_RADIAN;
  882. };
  883. /**
  884. * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  885. *
  886. * @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  887. * @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  888. *
  889. * @example
  890. * // Convert 270 degrees to -90 degrees longitude
  891. * var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
  892. */
  893. CesiumMath.convertLongitudeRange = function(angle) {
  894. if (!defined(angle)) {
  895. throw new DeveloperError('angle is required.');
  896. }
  897. var twoPi = CesiumMath.TWO_PI;
  898. var simplified = angle - Math.floor(angle / twoPi) * twoPi;
  899. if (simplified < -Math.PI) {
  900. return simplified + twoPi;
  901. }
  902. if (simplified >= Math.PI) {
  903. return simplified - twoPi;
  904. }
  905. return simplified;
  906. };
  907. /**
  908. * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  909. * Useful for sanitizing data before use in objects requiring correct range.
  910. *
  911. * @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  912. * @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  913. *
  914. * @example
  915. * // Clamp 108 degrees latitude to 90 degrees latitude
  916. * var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
  917. */
  918. CesiumMath.clampToLatitudeRange = function(angle) {
  919. if (!defined(angle)) {
  920. throw new DeveloperError('angle is required.');
  921. }
  922. return CesiumMath.clamp(angle, -1*CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
  923. };
  924. /**
  925. * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
  926. *
  927. * @param {Number} angle in radians
  928. * @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
  929. */
  930. CesiumMath.negativePiToPi = function(x) {
  931. if (!defined(x)) {
  932. throw new DeveloperError('x is required.');
  933. }
  934. return CesiumMath.zeroToTwoPi(x + CesiumMath.PI) - CesiumMath.PI;
  935. };
  936. /**
  937. * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
  938. *
  939. * @param {Number} angle in radians
  940. * @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
  941. */
  942. CesiumMath.zeroToTwoPi = function(x) {
  943. if (!defined(x)) {
  944. throw new DeveloperError('x is required.');
  945. }
  946. var mod = CesiumMath.mod(x, CesiumMath.TWO_PI);
  947. if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(x) > CesiumMath.EPSILON14) {
  948. return CesiumMath.TWO_PI;
  949. }
  950. return mod;
  951. };
  952. /**
  953. * The modulo operation that also works for negative dividends.
  954. *
  955. * @param {Number} m The dividend.
  956. * @param {Number} n The divisor.
  957. * @returns {Number} The remainder.
  958. */
  959. CesiumMath.mod = function(m, n) {
  960. if (!defined(m)) {
  961. throw new DeveloperError('m is required.');
  962. }
  963. if (!defined(n)) {
  964. throw new DeveloperError('n is required.');
  965. }
  966. return ((m % n) + n) % n;
  967. };
  968. /**
  969. * Determines if two values are equal using an absolute or relative tolerance test. This is useful
  970. * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
  971. * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
  972. * Use this test if you are unsure of the magnitudes of left and right.
  973. *
  974. * @param {Number} left The first value to compare.
  975. * @param {Number} right The other value to compare.
  976. * @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
  977. * @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
  978. * @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
  979. *
  980. * @example
  981. * var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
  982. * var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
  983. * var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
  984. * var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
  985. */
  986. CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  987. if (!defined(left)) {
  988. throw new DeveloperError('left is required.');
  989. }
  990. if (!defined(right)) {
  991. throw new DeveloperError('right is required.');
  992. }
  993. if (!defined(relativeEpsilon)) {
  994. throw new DeveloperError('relativeEpsilon is required.');
  995. }
  996. absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
  997. var absDiff = Math.abs(left - right);
  998. return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
  999. };
  1000. var factorials = [1];
  1001. /**
  1002. * Computes the factorial of the provided number.
  1003. *
  1004. * @param {Number} n The number whose factorial is to be computed.
  1005. * @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
  1006. *
  1007. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1008. *
  1009. *
  1010. * @example
  1011. * //Compute 7!, which is equal to 5040
  1012. * var computedFactorial = Cesium.Math.factorial(7);
  1013. *
  1014. * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
  1015. */
  1016. CesiumMath.factorial = function(n) {
  1017. if (typeof n !== 'number' || n < 0) {
  1018. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1019. }
  1020. var length = factorials.length;
  1021. if (n >= length) {
  1022. var sum = factorials[length - 1];
  1023. for (var i = length; i <= n; i++) {
  1024. factorials.push(sum * i);
  1025. }
  1026. }
  1027. return factorials[n];
  1028. };
  1029. /**
  1030. * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
  1031. *
  1032. * @param {Number} [n] The number to be incremented.
  1033. * @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
  1034. * @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
  1035. * @returns {Number} The incremented number.
  1036. *
  1037. * @exception {DeveloperError} Maximum value must be greater than minimum value.
  1038. *
  1039. * @example
  1040. * var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
  1041. * var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
  1042. */
  1043. CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
  1044. minimumValue = defaultValue(minimumValue, 0.0);
  1045. if (!defined(n)) {
  1046. throw new DeveloperError('n is required.');
  1047. }
  1048. if (maximumValue <= minimumValue) {
  1049. throw new DeveloperError('maximumValue must be greater than minimumValue.');
  1050. }
  1051. ++n;
  1052. if (n > maximumValue) {
  1053. n = minimumValue;
  1054. }
  1055. return n;
  1056. };
  1057. /**
  1058. * Determines if a positive integer is a power of two.
  1059. *
  1060. * @param {Number} n The positive integer to test.
  1061. * @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
  1062. *
  1063. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1064. *
  1065. * @example
  1066. * var t = Cesium.Math.isPowerOfTwo(16); // true
  1067. * var f = Cesium.Math.isPowerOfTwo(20); // false
  1068. */
  1069. CesiumMath.isPowerOfTwo = function(n) {
  1070. if (typeof n !== 'number' || n < 0) {
  1071. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1072. }
  1073. return (n !== 0) && ((n & (n - 1)) === 0);
  1074. };
  1075. /**
  1076. * Computes the next power-of-two integer greater than or equal to the provided positive integer.
  1077. *
  1078. * @param {Number} n The positive integer to test.
  1079. * @returns {Number} The next power-of-two integer.
  1080. *
  1081. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1082. *
  1083. * @example
  1084. * var n = Cesium.Math.nextPowerOfTwo(29); // 32
  1085. * var m = Cesium.Math.nextPowerOfTwo(32); // 32
  1086. */
  1087. CesiumMath.nextPowerOfTwo = function(n) {
  1088. if (typeof n !== 'number' || n < 0) {
  1089. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1090. }
  1091. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  1092. --n;
  1093. n |= n >> 1;
  1094. n |= n >> 2;
  1095. n |= n >> 4;
  1096. n |= n >> 8;
  1097. n |= n >> 16;
  1098. ++n;
  1099. return n;
  1100. };
  1101. /**
  1102. * Constraint a value to lie between two values.
  1103. *
  1104. * @param {Number} value The value to constrain.
  1105. * @param {Number} min The minimum value.
  1106. * @param {Number} max The maximum value.
  1107. * @returns {Number} The value clamped so that min <= value <= max.
  1108. */
  1109. CesiumMath.clamp = function(value, min, max) {
  1110. if (!defined(value)) {
  1111. throw new DeveloperError('value is required');
  1112. }
  1113. if (!defined(min)) {
  1114. throw new DeveloperError('min is required.');
  1115. }
  1116. if (!defined(max)) {
  1117. throw new DeveloperError('max is required.');
  1118. }
  1119. return value < min ? min : value > max ? max : value;
  1120. };
  1121. var randomNumberGenerator = new MersenneTwister();
  1122. /**
  1123. * Sets the seed used by the random number generator
  1124. * in {@link CesiumMath#nextRandomNumber}.
  1125. *
  1126. * @param {Number} seed An integer used as the seed.
  1127. */
  1128. CesiumMath.setRandomNumberSeed = function(seed) {
  1129. if (!defined(seed)) {
  1130. throw new DeveloperError('seed is required.');
  1131. }
  1132. randomNumberGenerator = new MersenneTwister(seed);
  1133. };
  1134. /**
  1135. * Generates a random number in the range of [0.0, 1.0)
  1136. * using a Mersenne twister.
  1137. *
  1138. * @returns {Number} A random number in the range of [0.0, 1.0).
  1139. *
  1140. * @see CesiumMath.setRandomNumberSeed
  1141. * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
  1142. */
  1143. CesiumMath.nextRandomNumber = function() {
  1144. return randomNumberGenerator.random();
  1145. };
  1146. /**
  1147. * Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1148. * so that the function will never return NaN.
  1149. *
  1150. * @param {Number} value The value for which to compute acos.
  1151. * @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
  1152. * whichever is closer, if the value is outside the range.
  1153. */
  1154. CesiumMath.acosClamped = function(value) {
  1155. if (!defined(value)) {
  1156. throw new DeveloperError('value is required.');
  1157. }
  1158. return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  1159. };
  1160. /**
  1161. * Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1162. * so that the function will never return NaN.
  1163. *
  1164. * @param {Number} value The value for which to compute asin.
  1165. * @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
  1166. * whichever is closer, if the value is outside the range.
  1167. */
  1168. CesiumMath.asinClamped = function(value) {
  1169. if (!defined(value)) {
  1170. throw new DeveloperError('value is required.');
  1171. }
  1172. return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  1173. };
  1174. /**
  1175. * Finds the chord length between two points given the circle's radius and the angle between the points.
  1176. *
  1177. * @param {Number} angle The angle between the two points.
  1178. * @param {Number} radius The radius of the circle.
  1179. * @returns {Number} The chord length.
  1180. */
  1181. CesiumMath.chordLength = function(angle, radius) {
  1182. if (!defined(angle)) {
  1183. throw new DeveloperError('angle is required.');
  1184. }
  1185. if (!defined(radius)) {
  1186. throw new DeveloperError('radius is required.');
  1187. }
  1188. return 2.0 * radius * Math.sin(angle * 0.5);
  1189. };
  1190. /**
  1191. * Finds the logarithm of a number to a base.
  1192. *
  1193. * @param {Number} number The number.
  1194. * @param {Number} base The base.
  1195. * @returns {Number} The result.
  1196. */
  1197. CesiumMath.logBase = function(number, base) {
  1198. if (!defined(number)) {
  1199. throw new DeveloperError('number is required.');
  1200. }
  1201. if (!defined(base)) {
  1202. throw new DeveloperError('base is required.');
  1203. }
  1204. return Math.log(number) / Math.log(base);
  1205. };
  1206. /**
  1207. * @private
  1208. */
  1209. CesiumMath.fog = function(distanceToCamera, density) {
  1210. var scalar = distanceToCamera * density;
  1211. return 1.0 - Math.exp(-(scalar * scalar));
  1212. };
  1213. return CesiumMath;
  1214. });
  1215. /*global define*/
  1216. define('Core/Cartesian3',[
  1217. './Check',
  1218. './defaultValue',
  1219. './defined',
  1220. './DeveloperError',
  1221. './freezeObject',
  1222. './Math'
  1223. ], function(
  1224. Check,
  1225. defaultValue,
  1226. defined,
  1227. DeveloperError,
  1228. freezeObject,
  1229. CesiumMath) {
  1230. 'use strict';
  1231. /**
  1232. * A 3D Cartesian point.
  1233. * @alias Cartesian3
  1234. * @constructor
  1235. *
  1236. * @param {Number} [x=0.0] The X component.
  1237. * @param {Number} [y=0.0] The Y component.
  1238. * @param {Number} [z=0.0] The Z component.
  1239. *
  1240. * @see Cartesian2
  1241. * @see Cartesian4
  1242. * @see Packable
  1243. */
  1244. function Cartesian3(x, y, z) {
  1245. /**
  1246. * The X component.
  1247. * @type {Number}
  1248. * @default 0.0
  1249. */
  1250. this.x = defaultValue(x, 0.0);
  1251. /**
  1252. * The Y component.
  1253. * @type {Number}
  1254. * @default 0.0
  1255. */
  1256. this.y = defaultValue(y, 0.0);
  1257. /**
  1258. * The Z component.
  1259. * @type {Number}
  1260. * @default 0.0
  1261. */
  1262. this.z = defaultValue(z, 0.0);
  1263. }
  1264. /**
  1265. * Converts the provided Spherical into Cartesian3 coordinates.
  1266. *
  1267. * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
  1268. * @param {Cartesian3} [result] The object onto which to store the result.
  1269. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1270. */
  1271. Cartesian3.fromSpherical = function(spherical, result) {
  1272. Check.typeOf.object(spherical, 'spherical');
  1273. if (!defined(result)) {
  1274. result = new Cartesian3();
  1275. }
  1276. var clock = spherical.clock;
  1277. var cone = spherical.cone;
  1278. var magnitude = defaultValue(spherical.magnitude, 1.0);
  1279. var radial = magnitude * Math.sin(cone);
  1280. result.x = radial * Math.cos(clock);
  1281. result.y = radial * Math.sin(clock);
  1282. result.z = magnitude * Math.cos(cone);
  1283. return result;
  1284. };
  1285. /**
  1286. * Creates a Cartesian3 instance from x, y and z coordinates.
  1287. *
  1288. * @param {Number} x The x coordinate.
  1289. * @param {Number} y The y coordinate.
  1290. * @param {Number} z The z coordinate.
  1291. * @param {Cartesian3} [result] The object onto which to store the result.
  1292. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1293. */
  1294. Cartesian3.fromElements = function(x, y, z, result) {
  1295. if (!defined(result)) {
  1296. return new Cartesian3(x, y, z);
  1297. }
  1298. result.x = x;
  1299. result.y = y;
  1300. result.z = z;
  1301. return result;
  1302. };
  1303. /**
  1304. * Duplicates a Cartesian3 instance.
  1305. *
  1306. * @param {Cartesian3} cartesian The Cartesian to duplicate.
  1307. * @param {Cartesian3} [result] The object onto which to store the result.
  1308. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1309. */
  1310. Cartesian3.clone = function(cartesian, result) {
  1311. if (!defined(cartesian)) {
  1312. return undefined;
  1313. }
  1314. if (!defined(result)) {
  1315. return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
  1316. }
  1317. result.x = cartesian.x;
  1318. result.y = cartesian.y;
  1319. result.z = cartesian.z;
  1320. return result;
  1321. };
  1322. /**
  1323. * Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
  1324. * x, y, and z properties of the Cartesian4 and drops w.
  1325. * @function
  1326. *
  1327. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
  1328. * @param {Cartesian3} [result] The object onto which to store the result.
  1329. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1330. */
  1331. Cartesian3.fromCartesian4 = Cartesian3.clone;
  1332. /**
  1333. * The number of elements used to pack the object into an array.
  1334. * @type {Number}
  1335. */
  1336. Cartesian3.packedLength = 3;
  1337. /**
  1338. * Stores the provided instance into the provided array.
  1339. *
  1340. * @param {Cartesian3} value The value to pack.
  1341. * @param {Number[]} array The array to pack into.
  1342. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1343. *
  1344. * @returns {Number[]} The array that was packed into
  1345. */
  1346. Cartesian3.pack = function(value, array, startingIndex) {
  1347. Check.typeOf.object(value, 'value');
  1348. Check.defined(array, 'array');
  1349. startingIndex = defaultValue(startingIndex, 0);
  1350. array[startingIndex++] = value.x;
  1351. array[startingIndex++] = value.y;
  1352. array[startingIndex] = value.z;
  1353. return array;
  1354. };
  1355. /**
  1356. * Retrieves an instance from a packed array.
  1357. *
  1358. * @param {Number[]} array The packed array.
  1359. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1360. * @param {Cartesian3} [result] The object into which to store the result.
  1361. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1362. */
  1363. Cartesian3.unpack = function(array, startingIndex, result) {
  1364. Check.defined(array, 'array');
  1365. startingIndex = defaultValue(startingIndex, 0);
  1366. if (!defined(result)) {
  1367. result = new Cartesian3();
  1368. }
  1369. result.x = array[startingIndex++];
  1370. result.y = array[startingIndex++];
  1371. result.z = array[startingIndex];
  1372. return result;
  1373. };
  1374. /**
  1375. * Flattens an array of Cartesian3s into an array of components.
  1376. *
  1377. * @param {Cartesian3[]} array The array of cartesians to pack.
  1378. * @param {Number[]} result The array onto which to store the result.
  1379. * @returns {Number[]} The packed array.
  1380. */
  1381. Cartesian3.packArray = function(array, result) {
  1382. Check.defined(array, 'array');
  1383. var length = array.length;
  1384. if (!defined(result)) {
  1385. result = new Array(length * 3);
  1386. } else {
  1387. result.length = length * 3;
  1388. }
  1389. for (var i = 0; i < length; ++i) {
  1390. Cartesian3.pack(array[i], result, i * 3);
  1391. }
  1392. return result;
  1393. };
  1394. /**
  1395. * Unpacks an array of cartesian components into an array of Cartesian3s.
  1396. *
  1397. * @param {Number[]} array The array of components to unpack.
  1398. * @param {Cartesian3[]} result The array onto which to store the result.
  1399. * @returns {Cartesian3[]} The unpacked array.
  1400. */
  1401. Cartesian3.unpackArray = function(array, result) {
  1402. Check.defined(array, 'array');
  1403. Check.numeric.minimum(array.length, 3);
  1404. if (array.length % 3 !== 0) {
  1405. throw new DeveloperError('array length must be a multiple of 3.');
  1406. }
  1407. var length = array.length;
  1408. if (!defined(result)) {
  1409. result = new Array(length / 3);
  1410. } else {
  1411. result.length = length / 3;
  1412. }
  1413. for (var i = 0; i < length; i += 3) {
  1414. var index = i / 3;
  1415. result[index] = Cartesian3.unpack(array, i, result[index]);
  1416. }
  1417. return result;
  1418. };
  1419. /**
  1420. * Creates a Cartesian3 from three consecutive elements in an array.
  1421. * @function
  1422. *
  1423. * @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
  1424. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1425. * @param {Cartesian3} [result] The object onto which to store the result.
  1426. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1427. *
  1428. * @example
  1429. * // Create a Cartesian3 with (1.0, 2.0, 3.0)
  1430. * var v = [1.0, 2.0, 3.0];
  1431. * var p = Cesium.Cartesian3.fromArray(v);
  1432. *
  1433. * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
  1434. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
  1435. * var p2 = Cesium.Cartesian3.fromArray(v2, 2);
  1436. */
  1437. Cartesian3.fromArray = Cartesian3.unpack;
  1438. /**
  1439. * Computes the value of the maximum component for the supplied Cartesian.
  1440. *
  1441. * @param {Cartesian3} cartesian The cartesian to use.
  1442. * @returns {Number} The value of the maximum component.
  1443. */
  1444. Cartesian3.maximumComponent = function(cartesian) {
  1445. Check.typeOf.object(cartesian, 'cartesian');
  1446. return Math.max(cartesian.x, cartesian.y, cartesian.z);
  1447. };
  1448. /**
  1449. * Computes the value of the minimum component for the supplied Cartesian.
  1450. *
  1451. * @param {Cartesian3} cartesian The cartesian to use.
  1452. * @returns {Number} The value of the minimum component.
  1453. */
  1454. Cartesian3.minimumComponent = function(cartesian) {
  1455. Check.typeOf.object(cartesian, 'cartesian');
  1456. return Math.min(cartesian.x, cartesian.y, cartesian.z);
  1457. };
  1458. /**
  1459. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1460. *
  1461. * @param {Cartesian3} first A cartesian to compare.
  1462. * @param {Cartesian3} second A cartesian to compare.
  1463. * @param {Cartesian3} result The object into which to store the result.
  1464. * @returns {Cartesian3} A cartesian with the minimum components.
  1465. */
  1466. Cartesian3.minimumByComponent = function(first, second, result) {
  1467. Check.typeOf.object(first, 'first');
  1468. Check.typeOf.object(second, 'second');
  1469. Check.typeOf.object(result, 'result');
  1470. result.x = Math.min(first.x, second.x);
  1471. result.y = Math.min(first.y, second.y);
  1472. result.z = Math.min(first.z, second.z);
  1473. return result;
  1474. };
  1475. /**
  1476. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1477. *
  1478. * @param {Cartesian3} first A cartesian to compare.
  1479. * @param {Cartesian3} second A cartesian to compare.
  1480. * @param {Cartesian3} result The object into which to store the result.
  1481. * @returns {Cartesian3} A cartesian with the maximum components.
  1482. */
  1483. Cartesian3.maximumByComponent = function(first, second, result) {
  1484. Check.typeOf.object(first, 'first');
  1485. Check.typeOf.object(second, 'second');
  1486. Check.typeOf.object(result, 'result');
  1487. result.x = Math.max(first.x, second.x);
  1488. result.y = Math.max(first.y, second.y);
  1489. result.z = Math.max(first.z, second.z);
  1490. return result;
  1491. };
  1492. /**
  1493. * Computes the provided Cartesian's squared magnitude.
  1494. *
  1495. * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1496. * @returns {Number} The squared magnitude.
  1497. */
  1498. Cartesian3.magnitudeSquared = function(cartesian) {
  1499. Check.typeOf.object(cartesian, 'cartesian');
  1500. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
  1501. };
  1502. /**
  1503. * Computes the Cartesian's magnitude (length).
  1504. *
  1505. * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
  1506. * @returns {Number} The magnitude.
  1507. */
  1508. Cartesian3.magnitude = function(cartesian) {
  1509. return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  1510. };
  1511. var distanceScratch = new Cartesian3();
  1512. /**
  1513. * Computes the distance between two points.
  1514. *
  1515. * @param {Cartesian3} left The first point to compute the distance from.
  1516. * @param {Cartesian3} right The second point to compute the distance to.
  1517. * @returns {Number} The distance between two points.
  1518. *
  1519. * @example
  1520. * // Returns 1.0
  1521. * var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
  1522. */
  1523. Cartesian3.distance = function(left, right) {
  1524. Check.typeOf.object(left, 'left');
  1525. Check.typeOf.object(right, 'right');
  1526. Cartesian3.subtract(left, right, distanceScratch);
  1527. return Cartesian3.magnitude(distanceScratch);
  1528. };
  1529. /**
  1530. * Computes the squared distance between two points. Comparing squared distances
  1531. * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
  1532. *
  1533. * @param {Cartesian3} left The first point to compute the distance from.
  1534. * @param {Cartesian3} right The second point to compute the distance to.
  1535. * @returns {Number} The distance between two points.
  1536. *
  1537. * @example
  1538. * // Returns 4.0, not 2.0
  1539. * var d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
  1540. */
  1541. Cartesian3.distanceSquared = function(left, right) {
  1542. Check.typeOf.object(left, 'left');
  1543. Check.typeOf.object(right, 'right');
  1544. Cartesian3.subtract(left, right, distanceScratch);
  1545. return Cartesian3.magnitudeSquared(distanceScratch);
  1546. };
  1547. /**
  1548. * Computes the normalized form of the supplied Cartesian.
  1549. *
  1550. * @param {Cartesian3} cartesian The Cartesian to be normalized.
  1551. * @param {Cartesian3} result The object onto which to store the result.
  1552. * @returns {Cartesian3} The modified result parameter.
  1553. */
  1554. Cartesian3.normalize = function(cartesian, result) {
  1555. Check.typeOf.object(cartesian, 'cartesian');
  1556. Check.typeOf.object(result, 'result');
  1557. var magnitude = Cartesian3.magnitude(cartesian);
  1558. result.x = cartesian.x / magnitude;
  1559. result.y = cartesian.y / magnitude;
  1560. result.z = cartesian.z / magnitude;
  1561. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
  1562. throw new DeveloperError('normalized result is not a number');
  1563. }
  1564. return result;
  1565. };
  1566. /**
  1567. * Computes the dot (scalar) product of two Cartesians.
  1568. *
  1569. * @param {Cartesian3} left The first Cartesian.
  1570. * @param {Cartesian3} right The second Cartesian.
  1571. * @returns {Number} The dot product.
  1572. */
  1573. Cartesian3.dot = function(left, right) {
  1574. Check.typeOf.object(left, 'left');
  1575. Check.typeOf.object(right, 'right');
  1576. return left.x * right.x + left.y * right.y + left.z * right.z;
  1577. };
  1578. /**
  1579. * Computes the componentwise product of two Cartesians.
  1580. *
  1581. * @param {Cartesian3} left The first Cartesian.
  1582. * @param {Cartesian3} right The second Cartesian.
  1583. * @param {Cartesian3} result The object onto which to store the result.
  1584. * @returns {Cartesian3} The modified result parameter.
  1585. */
  1586. Cartesian3.multiplyComponents = function(left, right, result) {
  1587. Check.typeOf.object(left, 'left');
  1588. Check.typeOf.object(right, 'right');
  1589. Check.typeOf.object(result, 'result');
  1590. result.x = left.x * right.x;
  1591. result.y = left.y * right.y;
  1592. result.z = left.z * right.z;
  1593. return result;
  1594. };
  1595. /**
  1596. * Computes the componentwise quotient of two Cartesians.
  1597. *
  1598. * @param {Cartesian3} left The first Cartesian.
  1599. * @param {Cartesian3} right The second Cartesian.
  1600. * @param {Cartesian3} result The object onto which to store the result.
  1601. * @returns {Cartesian3} The modified result parameter.
  1602. */
  1603. Cartesian3.divideComponents = function(left, right, result) {
  1604. if (!defined(left)) {
  1605. throw new DeveloperError('left is required');
  1606. }
  1607. if (!defined(right)) {
  1608. throw new DeveloperError('right is required');
  1609. }
  1610. if (!defined(result)) {
  1611. throw new DeveloperError('result is required');
  1612. }
  1613. result.x = left.x / right.x;
  1614. result.y = left.y / right.y;
  1615. result.z = left.z / right.z;
  1616. return result;
  1617. };
  1618. /**
  1619. * Computes the componentwise sum of two Cartesians.
  1620. *
  1621. * @param {Cartesian3} left The first Cartesian.
  1622. * @param {Cartesian3} right The second Cartesian.
  1623. * @param {Cartesian3} result The object onto which to store the result.
  1624. * @returns {Cartesian3} The modified result parameter.
  1625. */
  1626. Cartesian3.add = function(left, right, result) {
  1627. Check.typeOf.object(left, 'left');
  1628. Check.typeOf.object(right, 'right');
  1629. Check.typeOf.object(result, 'result');
  1630. result.x = left.x + right.x;
  1631. result.y = left.y + right.y;
  1632. result.z = left.z + right.z;
  1633. return result;
  1634. };
  1635. /**
  1636. * Computes the componentwise difference of two Cartesians.
  1637. *
  1638. * @param {Cartesian3} left The first Cartesian.
  1639. * @param {Cartesian3} right The second Cartesian.
  1640. * @param {Cartesian3} result The object onto which to store the result.
  1641. * @returns {Cartesian3} The modified result parameter.
  1642. */
  1643. Cartesian3.subtract = function(left, right, result) {
  1644. Check.typeOf.object(left, 'left');
  1645. Check.typeOf.object(right, 'right');
  1646. Check.typeOf.object(result, 'result');
  1647. result.x = left.x - right.x;
  1648. result.y = left.y - right.y;
  1649. result.z = left.z - right.z;
  1650. return result;
  1651. };
  1652. /**
  1653. * Multiplies the provided Cartesian componentwise by the provided scalar.
  1654. *
  1655. * @param {Cartesian3} cartesian The Cartesian to be scaled.
  1656. * @param {Number} scalar The scalar to multiply with.
  1657. * @param {Cartesian3} result The object onto which to store the result.
  1658. * @returns {Cartesian3} The modified result parameter.
  1659. */
  1660. Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
  1661. Check.typeOf.object(cartesian, 'cartesian');
  1662. Check.typeOf.number(scalar, 'scalar');
  1663. Check.typeOf.object(result, 'result');
  1664. result.x = cartesian.x * scalar;
  1665. result.y = cartesian.y * scalar;
  1666. result.z = cartesian.z * scalar;
  1667. return result;
  1668. };
  1669. /**
  1670. * Divides the provided Cartesian componentwise by the provided scalar.
  1671. *
  1672. * @param {Cartesian3} cartesian The Cartesian to be divided.
  1673. * @param {Number} scalar The scalar to divide by.
  1674. * @param {Cartesian3} result The object onto which to store the result.
  1675. * @returns {Cartesian3} The modified result parameter.
  1676. */
  1677. Cartesian3.divideByScalar = function(cartesian, scalar, result) {
  1678. Check.typeOf.object(cartesian, 'cartesian');
  1679. Check.typeOf.number(scalar, 'scalar');
  1680. Check.typeOf.object(result, 'result');
  1681. result.x = cartesian.x / scalar;
  1682. result.y = cartesian.y / scalar;
  1683. result.z = cartesian.z / scalar;
  1684. return result;
  1685. };
  1686. /**
  1687. * Negates the provided Cartesian.
  1688. *
  1689. * @param {Cartesian3} cartesian The Cartesian to be negated.
  1690. * @param {Cartesian3} result The object onto which to store the result.
  1691. * @returns {Cartesian3} The modified result parameter.
  1692. */
  1693. Cartesian3.negate = function(cartesian, result) {
  1694. Check.typeOf.object(cartesian, 'cartesian');
  1695. Check.typeOf.object(result, 'result');
  1696. result.x = -cartesian.x;
  1697. result.y = -cartesian.y;
  1698. result.z = -cartesian.z;
  1699. return result;
  1700. };
  1701. /**
  1702. * Computes the absolute value of the provided Cartesian.
  1703. *
  1704. * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
  1705. * @param {Cartesian3} result The object onto which to store the result.
  1706. * @returns {Cartesian3} The modified result parameter.
  1707. */
  1708. Cartesian3.abs = function(cartesian, result) {
  1709. Check.typeOf.object(cartesian, 'cartesian');
  1710. Check.typeOf.object(result, 'result');
  1711. result.x = Math.abs(cartesian.x);
  1712. result.y = Math.abs(cartesian.y);
  1713. result.z = Math.abs(cartesian.z);
  1714. return result;
  1715. };
  1716. var lerpScratch = new Cartesian3();
  1717. /**
  1718. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  1719. *
  1720. * @param {Cartesian3} start The value corresponding to t at 0.0.
  1721. * @param {Cartesian3} end The value corresponding to t at 1.0.
  1722. * @param {Number} t The point along t at which to interpolate.
  1723. * @param {Cartesian3} result The object onto which to store the result.
  1724. * @returns {Cartesian3} The modified result parameter.
  1725. */
  1726. Cartesian3.lerp = function(start, end, t, result) {
  1727. Check.typeOf.object(start, 'start');
  1728. Check.typeOf.object(end, 'end');
  1729. Check.typeOf.number(t, 't');
  1730. Check.typeOf.object(result, 'result');
  1731. Cartesian3.multiplyByScalar(end, t, lerpScratch);
  1732. result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
  1733. return Cartesian3.add(lerpScratch, result, result);
  1734. };
  1735. var angleBetweenScratch = new Cartesian3();
  1736. var angleBetweenScratch2 = new Cartesian3();
  1737. /**
  1738. * Returns the angle, in radians, between the provided Cartesians.
  1739. *
  1740. * @param {Cartesian3} left The first Cartesian.
  1741. * @param {Cartesian3} right The second Cartesian.
  1742. * @returns {Number} The angle between the Cartesians.
  1743. */
  1744. Cartesian3.angleBetween = function(left, right) {
  1745. Check.typeOf.object(left, 'left');
  1746. Check.typeOf.object(right, 'right');
  1747. Cartesian3.normalize(left, angleBetweenScratch);
  1748. Cartesian3.normalize(right, angleBetweenScratch2);
  1749. var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
  1750. var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
  1751. return Math.atan2(sine, cosine);
  1752. };
  1753. var mostOrthogonalAxisScratch = new Cartesian3();
  1754. /**
  1755. * Returns the axis that is most orthogonal to the provided Cartesian.
  1756. *
  1757. * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
  1758. * @param {Cartesian3} result The object onto which to store the result.
  1759. * @returns {Cartesian3} The most orthogonal axis.
  1760. */
  1761. Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
  1762. Check.typeOf.object(cartesian, 'cartesian');
  1763. Check.typeOf.object(result, 'result');
  1764. var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
  1765. Cartesian3.abs(f, f);
  1766. if (f.x <= f.y) {
  1767. if (f.x <= f.z) {
  1768. result = Cartesian3.clone(Cartesian3.UNIT_X, result);
  1769. } else {
  1770. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1771. }
  1772. } else {
  1773. if (f.y <= f.z) {
  1774. result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
  1775. } else {
  1776. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1777. }
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Compares the provided Cartesians componentwise and returns
  1783. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1784. *
  1785. * @param {Cartesian3} [left] The first Cartesian.
  1786. * @param {Cartesian3} [right] The second Cartesian.
  1787. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1788. */
  1789. Cartesian3.equals = function(left, right) {
  1790. return (left === right) ||
  1791. ((defined(left)) &&
  1792. (defined(right)) &&
  1793. (left.x === right.x) &&
  1794. (left.y === right.y) &&
  1795. (left.z === right.z));
  1796. };
  1797. /**
  1798. * @private
  1799. */
  1800. Cartesian3.equalsArray = function(cartesian, array, offset) {
  1801. return cartesian.x === array[offset] &&
  1802. cartesian.y === array[offset + 1] &&
  1803. cartesian.z === array[offset + 2];
  1804. };
  1805. /**
  1806. * Compares the provided Cartesians componentwise and returns
  1807. * <code>true</code> if they pass an absolute or relative tolerance test,
  1808. * <code>false</code> otherwise.
  1809. *
  1810. * @param {Cartesian3} [left] The first Cartesian.
  1811. * @param {Cartesian3} [right] The second Cartesian.
  1812. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  1813. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  1814. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1815. */
  1816. Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  1817. return (left === right) ||
  1818. (defined(left) &&
  1819. defined(right) &&
  1820. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  1821. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  1822. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
  1823. };
  1824. /**
  1825. * Computes the cross (outer) product of two Cartesians.
  1826. *
  1827. * @param {Cartesian3} left The first Cartesian.
  1828. * @param {Cartesian3} right The second Cartesian.
  1829. * @param {Cartesian3} result The object onto which to store the result.
  1830. * @returns {Cartesian3} The cross product.
  1831. */
  1832. Cartesian3.cross = function(left, right, result) {
  1833. Check.typeOf.object(left, 'left');
  1834. Check.typeOf.object(right, 'right');
  1835. Check.typeOf.object(result, 'result');
  1836. var leftX = left.x;
  1837. var leftY = left.y;
  1838. var leftZ = left.z;
  1839. var rightX = right.x;
  1840. var rightY = right.y;
  1841. var rightZ = right.z;
  1842. var x = leftY * rightZ - leftZ * rightY;
  1843. var y = leftZ * rightX - leftX * rightZ;
  1844. var z = leftX * rightY - leftY * rightX;
  1845. result.x = x;
  1846. result.y = y;
  1847. result.z = z;
  1848. return result;
  1849. };
  1850. /**
  1851. * Returns a Cartesian3 position from longitude and latitude values given in degrees.
  1852. *
  1853. * @param {Number} longitude The longitude, in degrees
  1854. * @param {Number} latitude The latitude, in degrees
  1855. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1856. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1857. * @param {Cartesian3} [result] The object onto which to store the result.
  1858. * @returns {Cartesian3} The position
  1859. *
  1860. * @example
  1861. * var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
  1862. */
  1863. Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
  1864. Check.typeOf.number(longitude, 'longitude');
  1865. Check.typeOf.number(latitude, 'latitude');
  1866. longitude = CesiumMath.toRadians(longitude);
  1867. latitude = CesiumMath.toRadians(latitude);
  1868. return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
  1869. };
  1870. var scratchN = new Cartesian3();
  1871. var scratchK = new Cartesian3();
  1872. var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
  1873. /**
  1874. * Returns a Cartesian3 position from longitude and latitude values given in radians.
  1875. *
  1876. * @param {Number} longitude The longitude, in radians
  1877. * @param {Number} latitude The latitude, in radians
  1878. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1879. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1880. * @param {Cartesian3} [result] The object onto which to store the result.
  1881. * @returns {Cartesian3} The position
  1882. *
  1883. * @example
  1884. * var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
  1885. */
  1886. Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
  1887. Check.typeOf.number(longitude, 'longitude');
  1888. Check.typeOf.number(latitude, 'latitude');
  1889. height = defaultValue(height, 0.0);
  1890. var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
  1891. var cosLatitude = Math.cos(latitude);
  1892. scratchN.x = cosLatitude * Math.cos(longitude);
  1893. scratchN.y = cosLatitude * Math.sin(longitude);
  1894. scratchN.z = Math.sin(latitude);
  1895. scratchN = Cartesian3.normalize(scratchN, scratchN);
  1896. Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
  1897. var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
  1898. scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
  1899. scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
  1900. if (!defined(result)) {
  1901. result = new Cartesian3();
  1902. }
  1903. return Cartesian3.add(scratchK, scratchN, result);
  1904. };
  1905. /**
  1906. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
  1907. *
  1908. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1909. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1910. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1911. * @returns {Cartesian3[]} The array of positions.
  1912. *
  1913. * @example
  1914. * var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
  1915. */
  1916. Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
  1917. Check.defined(coordinates, 'coordinates');
  1918. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1919. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1920. }
  1921. var length = coordinates.length;
  1922. if (!defined(result)) {
  1923. result = new Array(length / 2);
  1924. } else {
  1925. result.length = length / 2;
  1926. }
  1927. for (var i = 0; i < length; i += 2) {
  1928. var longitude = coordinates[i];
  1929. var latitude = coordinates[i + 1];
  1930. var index = i / 2;
  1931. result[index] = Cartesian3.fromDegrees(longitude, latitude, 0, ellipsoid, result[index]);
  1932. }
  1933. return result;
  1934. };
  1935. /**
  1936. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
  1937. *
  1938. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1939. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1940. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1941. * @returns {Cartesian3[]} The array of positions.
  1942. *
  1943. * @example
  1944. * var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
  1945. */
  1946. Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
  1947. Check.defined(coordinates, 'coordinates');
  1948. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1949. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1950. }
  1951. var length = coordinates.length;
  1952. if (!defined(result)) {
  1953. result = new Array(length / 2);
  1954. } else {
  1955. result.length = length / 2;
  1956. }
  1957. for (var i = 0; i < length; i += 2) {
  1958. var longitude = coordinates[i];
  1959. var latitude = coordinates[i + 1];
  1960. var index = i / 2;
  1961. result[index] = Cartesian3.fromRadians(longitude, latitude, 0, ellipsoid, result[index]);
  1962. }
  1963. return result;
  1964. };
  1965. /**
  1966. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
  1967. *
  1968. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  1969. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1970. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1971. * @returns {Cartesian3[]} The array of positions.
  1972. *
  1973. * @example
  1974. * var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
  1975. */
  1976. Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
  1977. Check.defined(coordinates, 'coordinates');
  1978. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  1979. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  1980. }
  1981. var length = coordinates.length;
  1982. if (!defined(result)) {
  1983. result = new Array(length / 3);
  1984. } else {
  1985. result.length = length / 3;
  1986. }
  1987. for (var i = 0; i < length; i += 3) {
  1988. var longitude = coordinates[i];
  1989. var latitude = coordinates[i + 1];
  1990. var height = coordinates[i + 2];
  1991. var index = i / 3;
  1992. result[index] = Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result[index]);
  1993. }
  1994. return result;
  1995. };
  1996. /**
  1997. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
  1998. *
  1999. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  2000. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2001. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2002. * @returns {Cartesian3[]} The array of positions.
  2003. *
  2004. * @example
  2005. * var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
  2006. */
  2007. Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
  2008. Check.defined(coordinates, 'coordinates');
  2009. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  2010. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  2011. }
  2012. var length = coordinates.length;
  2013. if (!defined(result)) {
  2014. result = new Array(length / 3);
  2015. } else {
  2016. result.length = length / 3;
  2017. }
  2018. for (var i = 0; i < length; i += 3) {
  2019. var longitude = coordinates[i];
  2020. var latitude = coordinates[i + 1];
  2021. var height = coordinates[i + 2];
  2022. var index = i / 3;
  2023. result[index] = Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result[index]);
  2024. }
  2025. return result;
  2026. };
  2027. /**
  2028. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
  2029. *
  2030. * @type {Cartesian3}
  2031. * @constant
  2032. */
  2033. Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
  2034. /**
  2035. * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
  2036. *
  2037. * @type {Cartesian3}
  2038. * @constant
  2039. */
  2040. Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
  2041. /**
  2042. * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
  2043. *
  2044. * @type {Cartesian3}
  2045. * @constant
  2046. */
  2047. Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
  2048. /**
  2049. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
  2050. *
  2051. * @type {Cartesian3}
  2052. * @constant
  2053. */
  2054. Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
  2055. /**
  2056. * Duplicates this Cartesian3 instance.
  2057. *
  2058. * @param {Cartesian3} [result] The object onto which to store the result.
  2059. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2060. */
  2061. Cartesian3.prototype.clone = function(result) {
  2062. return Cartesian3.clone(this, result);
  2063. };
  2064. /**
  2065. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2066. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2067. *
  2068. * @param {Cartesian3} [right] The right hand side Cartesian.
  2069. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2070. */
  2071. Cartesian3.prototype.equals = function(right) {
  2072. return Cartesian3.equals(this, right);
  2073. };
  2074. /**
  2075. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2076. * <code>true</code> if they pass an absolute or relative tolerance test,
  2077. * <code>false</code> otherwise.
  2078. *
  2079. * @param {Cartesian3} [right] The right hand side Cartesian.
  2080. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2081. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2082. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2083. */
  2084. Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  2085. return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  2086. };
  2087. /**
  2088. * Creates a string representing this Cartesian in the format '(x, y, z)'.
  2089. *
  2090. * @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
  2091. */
  2092. Cartesian3.prototype.toString = function() {
  2093. return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
  2094. };
  2095. return Cartesian3;
  2096. });
  2097. /*global define*/
  2098. define('Core/scaleToGeodeticSurface',[
  2099. './Cartesian3',
  2100. './defined',
  2101. './DeveloperError',
  2102. './Math'
  2103. ], function(
  2104. Cartesian3,
  2105. defined,
  2106. DeveloperError,
  2107. CesiumMath) {
  2108. 'use strict';
  2109. var scaleToGeodeticSurfaceIntersection = new Cartesian3();
  2110. var scaleToGeodeticSurfaceGradient = new Cartesian3();
  2111. /**
  2112. * Scales the provided Cartesian position along the geodetic surface normal
  2113. * so that it is on the surface of this ellipsoid. If the position is
  2114. * at the center of the ellipsoid, this function returns undefined.
  2115. *
  2116. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2117. * @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
  2118. * @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
  2119. * @param {Number} centerToleranceSquared Tolerance for closeness to the center.
  2120. * @param {Cartesian3} [result] The object onto which to store the result.
  2121. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2122. *
  2123. * @exports scaleToGeodeticSurface
  2124. *
  2125. * @private
  2126. */
  2127. function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
  2128. if (!defined(cartesian)) {
  2129. throw new DeveloperError('cartesian is required.');
  2130. }
  2131. if (!defined(oneOverRadii)) {
  2132. throw new DeveloperError('oneOverRadii is required.');
  2133. }
  2134. if (!defined(oneOverRadiiSquared)) {
  2135. throw new DeveloperError('oneOverRadiiSquared is required.');
  2136. }
  2137. if (!defined(centerToleranceSquared)) {
  2138. throw new DeveloperError('centerToleranceSquared is required.');
  2139. }
  2140. var positionX = cartesian.x;
  2141. var positionY = cartesian.y;
  2142. var positionZ = cartesian.z;
  2143. var oneOverRadiiX = oneOverRadii.x;
  2144. var oneOverRadiiY = oneOverRadii.y;
  2145. var oneOverRadiiZ = oneOverRadii.z;
  2146. var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  2147. var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  2148. var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  2149. // Compute the squared ellipsoid norm.
  2150. var squaredNorm = x2 + y2 + z2;
  2151. var ratio = Math.sqrt(1.0 / squaredNorm);
  2152. // As an initial approximation, assume that the radial intersection is the projection point.
  2153. var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
  2154. // If the position is near the center, the iteration will not converge.
  2155. if (squaredNorm < centerToleranceSquared) {
  2156. return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
  2157. }
  2158. var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  2159. var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  2160. var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  2161. // Use the gradient at the intersection point in place of the true unit normal.
  2162. // The difference in magnitude will be absorbed in the multiplier.
  2163. var gradient = scaleToGeodeticSurfaceGradient;
  2164. gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
  2165. gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
  2166. gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
  2167. // Compute the initial guess at the normal vector multiplier, lambda.
  2168. var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
  2169. var correction = 0.0;
  2170. var func;
  2171. var denominator;
  2172. var xMultiplier;
  2173. var yMultiplier;
  2174. var zMultiplier;
  2175. var xMultiplier2;
  2176. var yMultiplier2;
  2177. var zMultiplier2;
  2178. var xMultiplier3;
  2179. var yMultiplier3;
  2180. var zMultiplier3;
  2181. do {
  2182. lambda -= correction;
  2183. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  2184. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  2185. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  2186. xMultiplier2 = xMultiplier * xMultiplier;
  2187. yMultiplier2 = yMultiplier * yMultiplier;
  2188. zMultiplier2 = zMultiplier * zMultiplier;
  2189. xMultiplier3 = xMultiplier2 * xMultiplier;
  2190. yMultiplier3 = yMultiplier2 * yMultiplier;
  2191. zMultiplier3 = zMultiplier2 * zMultiplier;
  2192. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  2193. // "denominator" here refers to the use of this expression in the velocity and acceleration
  2194. // computations in the sections to follow.
  2195. denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  2196. var derivative = -2.0 * denominator;
  2197. correction = func / derivative;
  2198. } while (Math.abs(func) > CesiumMath.EPSILON12);
  2199. if (!defined(result)) {
  2200. return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
  2201. }
  2202. result.x = positionX * xMultiplier;
  2203. result.y = positionY * yMultiplier;
  2204. result.z = positionZ * zMultiplier;
  2205. return result;
  2206. }
  2207. return scaleToGeodeticSurface;
  2208. });
  2209. /*global define*/
  2210. define('Core/Cartographic',[
  2211. './Cartesian3',
  2212. './defaultValue',
  2213. './defined',
  2214. './DeveloperError',
  2215. './freezeObject',
  2216. './Math',
  2217. './scaleToGeodeticSurface'
  2218. ], function(
  2219. Cartesian3,
  2220. defaultValue,
  2221. defined,
  2222. DeveloperError,
  2223. freezeObject,
  2224. CesiumMath,
  2225. scaleToGeodeticSurface) {
  2226. 'use strict';
  2227. /**
  2228. * A position defined by longitude, latitude, and height.
  2229. * @alias Cartographic
  2230. * @constructor
  2231. *
  2232. * @param {Number} [longitude=0.0] The longitude, in radians.
  2233. * @param {Number} [latitude=0.0] The latitude, in radians.
  2234. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2235. *
  2236. * @see Ellipsoid
  2237. */
  2238. function Cartographic(longitude, latitude, height) {
  2239. /**
  2240. * The longitude, in radians.
  2241. * @type {Number}
  2242. * @default 0.0
  2243. */
  2244. this.longitude = defaultValue(longitude, 0.0);
  2245. /**
  2246. * The latitude, in radians.
  2247. * @type {Number}
  2248. * @default 0.0
  2249. */
  2250. this.latitude = defaultValue(latitude, 0.0);
  2251. /**
  2252. * The height, in meters, above the ellipsoid.
  2253. * @type {Number}
  2254. * @default 0.0
  2255. */
  2256. this.height = defaultValue(height, 0.0);
  2257. }
  2258. /**
  2259. * Creates a new Cartographic instance from longitude and latitude
  2260. * specified in radians.
  2261. *
  2262. * @param {Number} longitude The longitude, in radians.
  2263. * @param {Number} latitude The latitude, in radians.
  2264. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2265. * @param {Cartographic} [result] The object onto which to store the result.
  2266. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2267. */
  2268. Cartographic.fromRadians = function(longitude, latitude, height, result) {
  2269. if (!defined(longitude)) {
  2270. throw new DeveloperError('longitude is required.');
  2271. }
  2272. if (!defined(latitude)) {
  2273. throw new DeveloperError('latitude is required.');
  2274. }
  2275. height = defaultValue(height, 0.0);
  2276. if (!defined(result)) {
  2277. return new Cartographic(longitude, latitude, height);
  2278. }
  2279. result.longitude = longitude;
  2280. result.latitude = latitude;
  2281. result.height = height;
  2282. return result;
  2283. };
  2284. /**
  2285. * Creates a new Cartographic instance from longitude and latitude
  2286. * specified in degrees. The values in the resulting object will
  2287. * be in radians.
  2288. *
  2289. * @param {Number} longitude The longitude, in degrees.
  2290. * @param {Number} latitude The latitude, in degrees.
  2291. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2292. * @param {Cartographic} [result] The object onto which to store the result.
  2293. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2294. */
  2295. Cartographic.fromDegrees = function(longitude, latitude, height, result) {
  2296. if (!defined(longitude)) {
  2297. throw new DeveloperError('longitude is required.');
  2298. }
  2299. if (!defined(latitude)) {
  2300. throw new DeveloperError('latitude is required.');
  2301. }
  2302. longitude = CesiumMath.toRadians(longitude);
  2303. latitude = CesiumMath.toRadians(latitude);
  2304. return Cartographic.fromRadians(longitude, latitude, height, result);
  2305. };
  2306. var cartesianToCartographicN = new Cartesian3();
  2307. var cartesianToCartographicP = new Cartesian3();
  2308. var cartesianToCartographicH = new Cartesian3();
  2309. var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
  2310. var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
  2311. var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;
  2312. /**
  2313. * Creates a new Cartographic instance from a Cartesian position. The values in the
  2314. * resulting object will be in radians.
  2315. *
  2316. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2317. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2318. * @param {Cartographic} [result] The object onto which to store the result.
  2319. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2320. */
  2321. Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
  2322. var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
  2323. var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
  2324. var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
  2325. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2326. var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);
  2327. if (!defined(p)) {
  2328. return undefined;
  2329. }
  2330. var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
  2331. n = Cartesian3.normalize(n, n);
  2332. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2333. var longitude = Math.atan2(n.y, n.x);
  2334. var latitude = Math.asin(n.z);
  2335. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2336. if (!defined(result)) {
  2337. return new Cartographic(longitude, latitude, height);
  2338. }
  2339. result.longitude = longitude;
  2340. result.latitude = latitude;
  2341. result.height = height;
  2342. return result;
  2343. };
  2344. /**
  2345. * Duplicates a Cartographic instance.
  2346. *
  2347. * @param {Cartographic} cartographic The cartographic to duplicate.
  2348. * @param {Cartographic} [result] The object onto which to store the result.
  2349. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
  2350. */
  2351. Cartographic.clone = function(cartographic, result) {
  2352. if (!defined(cartographic)) {
  2353. return undefined;
  2354. }
  2355. if (!defined(result)) {
  2356. return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
  2357. }
  2358. result.longitude = cartographic.longitude;
  2359. result.latitude = cartographic.latitude;
  2360. result.height = cartographic.height;
  2361. return result;
  2362. };
  2363. /**
  2364. * Compares the provided cartographics componentwise and returns
  2365. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2366. *
  2367. * @param {Cartographic} [left] The first cartographic.
  2368. * @param {Cartographic} [right] The second cartographic.
  2369. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2370. */
  2371. Cartographic.equals = function(left, right) {
  2372. return (left === right) ||
  2373. ((defined(left)) &&
  2374. (defined(right)) &&
  2375. (left.longitude === right.longitude) &&
  2376. (left.latitude === right.latitude) &&
  2377. (left.height === right.height));
  2378. };
  2379. /**
  2380. * Compares the provided cartographics componentwise and returns
  2381. * <code>true</code> if they are within the provided epsilon,
  2382. * <code>false</code> otherwise.
  2383. *
  2384. * @param {Cartographic} [left] The first cartographic.
  2385. * @param {Cartographic} [right] The second cartographic.
  2386. * @param {Number} epsilon The epsilon to use for equality testing.
  2387. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2388. */
  2389. Cartographic.equalsEpsilon = function(left, right, epsilon) {
  2390. if (typeof epsilon !== 'number') {
  2391. throw new DeveloperError('epsilon is required and must be a number.');
  2392. }
  2393. return (left === right) ||
  2394. ((defined(left)) &&
  2395. (defined(right)) &&
  2396. (Math.abs(left.longitude - right.longitude) <= epsilon) &&
  2397. (Math.abs(left.latitude - right.latitude) <= epsilon) &&
  2398. (Math.abs(left.height - right.height) <= epsilon));
  2399. };
  2400. /**
  2401. * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
  2402. *
  2403. * @type {Cartographic}
  2404. * @constant
  2405. */
  2406. Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
  2407. /**
  2408. * Duplicates this instance.
  2409. *
  2410. * @param {Cartographic} [result] The object onto which to store the result.
  2411. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2412. */
  2413. Cartographic.prototype.clone = function(result) {
  2414. return Cartographic.clone(this, result);
  2415. };
  2416. /**
  2417. * Compares the provided against this cartographic componentwise and returns
  2418. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2419. *
  2420. * @param {Cartographic} [right] The second cartographic.
  2421. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2422. */
  2423. Cartographic.prototype.equals = function(right) {
  2424. return Cartographic.equals(this, right);
  2425. };
  2426. /**
  2427. * Compares the provided against this cartographic componentwise and returns
  2428. * <code>true</code> if they are within the provided epsilon,
  2429. * <code>false</code> otherwise.
  2430. *
  2431. * @param {Cartographic} [right] The second cartographic.
  2432. * @param {Number} epsilon The epsilon to use for equality testing.
  2433. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2434. */
  2435. Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
  2436. return Cartographic.equalsEpsilon(this, right, epsilon);
  2437. };
  2438. /**
  2439. * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
  2440. *
  2441. * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
  2442. */
  2443. Cartographic.prototype.toString = function() {
  2444. return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
  2445. };
  2446. return Cartographic;
  2447. });
  2448. /*global define*/
  2449. define('Core/defineProperties',[
  2450. './defined'
  2451. ], function(
  2452. defined) {
  2453. 'use strict';
  2454. var definePropertyWorks = (function() {
  2455. try {
  2456. return 'x' in Object.defineProperty({}, 'x', {});
  2457. } catch (e) {
  2458. return false;
  2459. }
  2460. })();
  2461. /**
  2462. * Defines properties on an object, using Object.defineProperties if available,
  2463. * otherwise returns the object unchanged. This function should be used in
  2464. * setup code to prevent errors from completely halting JavaScript execution
  2465. * in legacy browsers.
  2466. *
  2467. * @private
  2468. *
  2469. * @exports defineProperties
  2470. */
  2471. var defineProperties = Object.defineProperties;
  2472. if (!definePropertyWorks || !defined(defineProperties)) {
  2473. defineProperties = function(o) {
  2474. return o;
  2475. };
  2476. }
  2477. return defineProperties;
  2478. });
  2479. /*global define*/
  2480. define('Core/Ellipsoid',[
  2481. './Cartesian3',
  2482. './Cartographic',
  2483. './defaultValue',
  2484. './defined',
  2485. './defineProperties',
  2486. './DeveloperError',
  2487. './freezeObject',
  2488. './Math',
  2489. './scaleToGeodeticSurface'
  2490. ], function(
  2491. Cartesian3,
  2492. Cartographic,
  2493. defaultValue,
  2494. defined,
  2495. defineProperties,
  2496. DeveloperError,
  2497. freezeObject,
  2498. CesiumMath,
  2499. scaleToGeodeticSurface) {
  2500. 'use strict';
  2501. function initialize(ellipsoid, x, y, z) {
  2502. x = defaultValue(x, 0.0);
  2503. y = defaultValue(y, 0.0);
  2504. z = defaultValue(z, 0.0);
  2505. if (x < 0.0 || y < 0.0 || z < 0.0) {
  2506. throw new DeveloperError('All radii components must be greater than or equal to zero.');
  2507. }
  2508. ellipsoid._radii = new Cartesian3(x, y, z);
  2509. ellipsoid._radiiSquared = new Cartesian3(x * x,
  2510. y * y,
  2511. z * z);
  2512. ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
  2513. y * y * y * y,
  2514. z * z * z * z);
  2515. ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
  2516. y === 0.0 ? 0.0 : 1.0 / y,
  2517. z === 0.0 ? 0.0 : 1.0 / z);
  2518. ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
  2519. y === 0.0 ? 0.0 : 1.0 / (y * y),
  2520. z === 0.0 ? 0.0 : 1.0 / (z * z));
  2521. ellipsoid._minimumRadius = Math.min(x, y, z);
  2522. ellipsoid._maximumRadius = Math.max(x, y, z);
  2523. ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
  2524. if (ellipsoid._radiiSquared.z !== 0) {
  2525. ellipsoid._sqauredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
  2526. }
  2527. }
  2528. /**
  2529. * A quadratic surface defined in Cartesian coordinates by the equation
  2530. * <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
  2531. * by Cesium to represent the shape of planetary bodies.
  2532. *
  2533. * Rather than constructing this object directly, one of the provided
  2534. * constants is normally used.
  2535. * @alias Ellipsoid
  2536. * @constructor
  2537. *
  2538. * @param {Number} [x=0] The radius in the x direction.
  2539. * @param {Number} [y=0] The radius in the y direction.
  2540. * @param {Number} [z=0] The radius in the z direction.
  2541. *
  2542. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2543. *
  2544. * @see Ellipsoid.fromCartesian3
  2545. * @see Ellipsoid.WGS84
  2546. * @see Ellipsoid.UNIT_SPHERE
  2547. */
  2548. function Ellipsoid(x, y, z) {
  2549. this._radii = undefined;
  2550. this._radiiSquared = undefined;
  2551. this._radiiToTheFourth = undefined;
  2552. this._oneOverRadii = undefined;
  2553. this._oneOverRadiiSquared = undefined;
  2554. this._minimumRadius = undefined;
  2555. this._maximumRadius = undefined;
  2556. this._centerToleranceSquared = undefined;
  2557. this._sqauredXOverSquaredZ = undefined;
  2558. initialize(this, x, y, z);
  2559. }
  2560. defineProperties(Ellipsoid.prototype, {
  2561. /**
  2562. * Gets the radii of the ellipsoid.
  2563. * @memberof Ellipsoid.prototype
  2564. * @type {Cartesian3}
  2565. * @readonly
  2566. */
  2567. radii : {
  2568. get: function() {
  2569. return this._radii;
  2570. }
  2571. },
  2572. /**
  2573. * Gets the squared radii of the ellipsoid.
  2574. * @memberof Ellipsoid.prototype
  2575. * @type {Cartesian3}
  2576. * @readonly
  2577. */
  2578. radiiSquared : {
  2579. get : function() {
  2580. return this._radiiSquared;
  2581. }
  2582. },
  2583. /**
  2584. * Gets the radii of the ellipsoid raise to the fourth power.
  2585. * @memberof Ellipsoid.prototype
  2586. * @type {Cartesian3}
  2587. * @readonly
  2588. */
  2589. radiiToTheFourth : {
  2590. get : function() {
  2591. return this._radiiToTheFourth;
  2592. }
  2593. },
  2594. /**
  2595. * Gets one over the radii of the ellipsoid.
  2596. * @memberof Ellipsoid.prototype
  2597. * @type {Cartesian3}
  2598. * @readonly
  2599. */
  2600. oneOverRadii : {
  2601. get : function() {
  2602. return this._oneOverRadii;
  2603. }
  2604. },
  2605. /**
  2606. * Gets one over the squared radii of the ellipsoid.
  2607. * @memberof Ellipsoid.prototype
  2608. * @type {Cartesian3}
  2609. * @readonly
  2610. */
  2611. oneOverRadiiSquared : {
  2612. get : function() {
  2613. return this._oneOverRadiiSquared;
  2614. }
  2615. },
  2616. /**
  2617. * Gets the minimum radius of the ellipsoid.
  2618. * @memberof Ellipsoid.prototype
  2619. * @type {Number}
  2620. * @readonly
  2621. */
  2622. minimumRadius : {
  2623. get : function() {
  2624. return this._minimumRadius;
  2625. }
  2626. },
  2627. /**
  2628. * Gets the maximum radius of the ellipsoid.
  2629. * @memberof Ellipsoid.prototype
  2630. * @type {Number}
  2631. * @readonly
  2632. */
  2633. maximumRadius : {
  2634. get : function() {
  2635. return this._maximumRadius;
  2636. }
  2637. }
  2638. });
  2639. /**
  2640. * Duplicates an Ellipsoid instance.
  2641. *
  2642. * @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
  2643. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2644. * instance should be created.
  2645. * @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
  2646. */
  2647. Ellipsoid.clone = function(ellipsoid, result) {
  2648. if (!defined(ellipsoid)) {
  2649. return undefined;
  2650. }
  2651. var radii = ellipsoid._radii;
  2652. if (!defined(result)) {
  2653. return new Ellipsoid(radii.x, radii.y, radii.z);
  2654. }
  2655. Cartesian3.clone(radii, result._radii);
  2656. Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
  2657. Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
  2658. Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
  2659. Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
  2660. result._minimumRadius = ellipsoid._minimumRadius;
  2661. result._maximumRadius = ellipsoid._maximumRadius;
  2662. result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
  2663. return result;
  2664. };
  2665. /**
  2666. * Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
  2667. *
  2668. * @param {Cartesian3} [radii=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
  2669. * @returns {Ellipsoid} A new Ellipsoid instance.
  2670. *
  2671. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2672. *
  2673. * @see Ellipsoid.WGS84
  2674. * @see Ellipsoid.UNIT_SPHERE
  2675. */
  2676. Ellipsoid.fromCartesian3 = function(cartesian, result) {
  2677. if (!defined(result)) {
  2678. result = new Ellipsoid();
  2679. }
  2680. if (!defined(cartesian)) {
  2681. return result;
  2682. }
  2683. initialize(result, cartesian.x, cartesian.y, cartesian.z);
  2684. return result;
  2685. };
  2686. /**
  2687. * An Ellipsoid instance initialized to the WGS84 standard.
  2688. *
  2689. * @type {Ellipsoid}
  2690. * @constant
  2691. */
  2692. Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
  2693. /**
  2694. * An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
  2695. *
  2696. * @type {Ellipsoid}
  2697. * @constant
  2698. */
  2699. Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
  2700. /**
  2701. * An Ellipsoid instance initialized to a sphere with the lunar radius.
  2702. *
  2703. * @type {Ellipsoid}
  2704. * @constant
  2705. */
  2706. Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
  2707. /**
  2708. * Duplicates an Ellipsoid instance.
  2709. *
  2710. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2711. * instance should be created.
  2712. * @returns {Ellipsoid} The cloned Ellipsoid.
  2713. */
  2714. Ellipsoid.prototype.clone = function(result) {
  2715. return Ellipsoid.clone(this, result);
  2716. };
  2717. /**
  2718. * The number of elements used to pack the object into an array.
  2719. * @type {Number}
  2720. */
  2721. Ellipsoid.packedLength = Cartesian3.packedLength;
  2722. /**
  2723. * Stores the provided instance into the provided array.
  2724. *
  2725. * @param {Ellipsoid} value The value to pack.
  2726. * @param {Number[]} array The array to pack into.
  2727. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2728. *
  2729. * @returns {Number[]} The array that was packed into
  2730. */
  2731. Ellipsoid.pack = function(value, array, startingIndex) {
  2732. if (!defined(value)) {
  2733. throw new DeveloperError('value is required');
  2734. }
  2735. if (!defined(array)) {
  2736. throw new DeveloperError('array is required');
  2737. }
  2738. startingIndex = defaultValue(startingIndex, 0);
  2739. Cartesian3.pack(value._radii, array, startingIndex);
  2740. return array;
  2741. };
  2742. /**
  2743. * Retrieves an instance from a packed array.
  2744. *
  2745. * @param {Number[]} array The packed array.
  2746. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2747. * @param {Ellipsoid} [result] The object into which to store the result.
  2748. * @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
  2749. */
  2750. Ellipsoid.unpack = function(array, startingIndex, result) {
  2751. if (!defined(array)) {
  2752. throw new DeveloperError('array is required');
  2753. }
  2754. startingIndex = defaultValue(startingIndex, 0);
  2755. var radii = Cartesian3.unpack(array, startingIndex);
  2756. return Ellipsoid.fromCartesian3(radii, result);
  2757. };
  2758. /**
  2759. * Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
  2760. * @function
  2761. *
  2762. * @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
  2763. * @param {Cartesian3} [result] The object onto which to store the result.
  2764. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2765. */
  2766. Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
  2767. /**
  2768. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2769. *
  2770. * @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
  2771. * @param {Cartesian3} [result] The object onto which to store the result.
  2772. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2773. */
  2774. Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
  2775. if (!defined(cartographic)) {
  2776. throw new DeveloperError('cartographic is required.');
  2777. }
  2778. var longitude = cartographic.longitude;
  2779. var latitude = cartographic.latitude;
  2780. var cosLatitude = Math.cos(latitude);
  2781. var x = cosLatitude * Math.cos(longitude);
  2782. var y = cosLatitude * Math.sin(longitude);
  2783. var z = Math.sin(latitude);
  2784. if (!defined(result)) {
  2785. result = new Cartesian3();
  2786. }
  2787. result.x = x;
  2788. result.y = y;
  2789. result.z = z;
  2790. return Cartesian3.normalize(result, result);
  2791. };
  2792. /**
  2793. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2794. *
  2795. * @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
  2796. * @param {Cartesian3} [result] The object onto which to store the result.
  2797. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2798. */
  2799. Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
  2800. if (!defined(result)) {
  2801. result = new Cartesian3();
  2802. }
  2803. result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
  2804. return Cartesian3.normalize(result, result);
  2805. };
  2806. var cartographicToCartesianNormal = new Cartesian3();
  2807. var cartographicToCartesianK = new Cartesian3();
  2808. /**
  2809. * Converts the provided cartographic to Cartesian representation.
  2810. *
  2811. * @param {Cartographic} cartographic The cartographic position.
  2812. * @param {Cartesian3} [result] The object onto which to store the result.
  2813. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2814. *
  2815. * @example
  2816. * //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
  2817. * var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
  2818. * var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
  2819. */
  2820. Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
  2821. //`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
  2822. var n = cartographicToCartesianNormal;
  2823. var k = cartographicToCartesianK;
  2824. this.geodeticSurfaceNormalCartographic(cartographic, n);
  2825. Cartesian3.multiplyComponents(this._radiiSquared, n, k);
  2826. var gamma = Math.sqrt(Cartesian3.dot(n, k));
  2827. Cartesian3.divideByScalar(k, gamma, k);
  2828. Cartesian3.multiplyByScalar(n, cartographic.height, n);
  2829. if (!defined(result)) {
  2830. result = new Cartesian3();
  2831. }
  2832. return Cartesian3.add(k, n, result);
  2833. };
  2834. /**
  2835. * Converts the provided array of cartographics to an array of Cartesians.
  2836. *
  2837. * @param {Cartographic[]} cartographics An array of cartographic positions.
  2838. * @param {Cartesian3[]} [result] The object onto which to store the result.
  2839. * @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
  2840. *
  2841. * @example
  2842. * //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
  2843. * var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
  2844. * new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
  2845. * new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
  2846. * var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
  2847. */
  2848. Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
  2849. if (!defined(cartographics)) {
  2850. throw new DeveloperError('cartographics is required.');
  2851. }
  2852. var length = cartographics.length;
  2853. if (!defined(result)) {
  2854. result = new Array(length);
  2855. } else {
  2856. result.length = length;
  2857. }
  2858. for ( var i = 0; i < length; i++) {
  2859. result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
  2860. }
  2861. return result;
  2862. };
  2863. var cartesianToCartographicN = new Cartesian3();
  2864. var cartesianToCartographicP = new Cartesian3();
  2865. var cartesianToCartographicH = new Cartesian3();
  2866. /**
  2867. * Converts the provided cartesian to cartographic representation.
  2868. * The cartesian is undefined at the center of the ellipsoid.
  2869. *
  2870. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2871. * @param {Cartographic} [result] The object onto which to store the result.
  2872. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2873. *
  2874. * @example
  2875. * //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
  2876. * var position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
  2877. * var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
  2878. */
  2879. Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
  2880. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2881. var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
  2882. if (!defined(p)) {
  2883. return undefined;
  2884. }
  2885. var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
  2886. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2887. var longitude = Math.atan2(n.y, n.x);
  2888. var latitude = Math.asin(n.z);
  2889. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2890. if (!defined(result)) {
  2891. return new Cartographic(longitude, latitude, height);
  2892. }
  2893. result.longitude = longitude;
  2894. result.latitude = latitude;
  2895. result.height = height;
  2896. return result;
  2897. };
  2898. /**
  2899. * Converts the provided array of cartesians to an array of cartographics.
  2900. *
  2901. * @param {Cartesian3[]} cartesians An array of Cartesian positions.
  2902. * @param {Cartographic[]} [result] The object onto which to store the result.
  2903. * @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
  2904. *
  2905. * @example
  2906. * //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
  2907. * var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
  2908. * new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
  2909. * new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
  2910. * var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
  2911. */
  2912. Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
  2913. if (!defined(cartesians)) {
  2914. throw new DeveloperError('cartesians is required.');
  2915. }
  2916. var length = cartesians.length;
  2917. if (!defined(result)) {
  2918. result = new Array(length);
  2919. } else {
  2920. result.length = length;
  2921. }
  2922. for ( var i = 0; i < length; ++i) {
  2923. result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
  2924. }
  2925. return result;
  2926. };
  2927. /**
  2928. * Scales the provided Cartesian position along the geodetic surface normal
  2929. * so that it is on the surface of this ellipsoid. If the position is
  2930. * at the center of the ellipsoid, this function returns undefined.
  2931. *
  2932. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2933. * @param {Cartesian3} [result] The object onto which to store the result.
  2934. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2935. */
  2936. Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
  2937. return scaleToGeodeticSurface(cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result);
  2938. };
  2939. /**
  2940. * Scales the provided Cartesian position along the geocentric surface normal
  2941. * so that it is on the surface of this ellipsoid.
  2942. *
  2943. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2944. * @param {Cartesian3} [result] The object onto which to store the result.
  2945. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2946. */
  2947. Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
  2948. if (!defined(cartesian)) {
  2949. throw new DeveloperError('cartesian is required.');
  2950. }
  2951. if (!defined(result)) {
  2952. result = new Cartesian3();
  2953. }
  2954. var positionX = cartesian.x;
  2955. var positionY = cartesian.y;
  2956. var positionZ = cartesian.z;
  2957. var oneOverRadiiSquared = this._oneOverRadiiSquared;
  2958. var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
  2959. (positionY * positionY) * oneOverRadiiSquared.y +
  2960. (positionZ * positionZ) * oneOverRadiiSquared.z);
  2961. return Cartesian3.multiplyByScalar(cartesian, beta, result);
  2962. };
  2963. /**
  2964. * Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
  2965. * its components by the result of {@link Ellipsoid#oneOverRadii}.
  2966. *
  2967. * @param {Cartesian3} position The position to transform.
  2968. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2969. * return a new instance.
  2970. * @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
  2971. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2972. */
  2973. Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
  2974. if (!defined(result)) {
  2975. result = new Cartesian3();
  2976. }
  2977. return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
  2978. };
  2979. /**
  2980. * Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
  2981. * its components by the result of {@link Ellipsoid#radii}.
  2982. *
  2983. * @param {Cartesian3} position The position to transform.
  2984. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2985. * return a new instance.
  2986. * @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
  2987. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2988. */
  2989. Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
  2990. if (!defined(result)) {
  2991. result = new Cartesian3();
  2992. }
  2993. return Cartesian3.multiplyComponents(position, this._radii, result);
  2994. };
  2995. /**
  2996. * Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
  2997. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2998. *
  2999. * @param {Ellipsoid} [right] The other Ellipsoid.
  3000. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3001. */
  3002. Ellipsoid.prototype.equals = function(right) {
  3003. return (this === right) ||
  3004. (defined(right) &&
  3005. Cartesian3.equals(this._radii, right._radii));
  3006. };
  3007. /**
  3008. * Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3009. *
  3010. * @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3011. */
  3012. Ellipsoid.prototype.toString = function() {
  3013. return this._radii.toString();
  3014. };
  3015. /**
  3016. * Computes a point which is the intersection of the surface normal with the z-axis.
  3017. *
  3018. * @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
  3019. * @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
  3020. * In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
  3021. * In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
  3022. * Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
  3023. * @param {Cartesian} [result] The cartesian to which to copy the result, or undefined to create and
  3024. * return a new instance.
  3025. * @returns {Cartesian | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
  3026. *
  3027. * @exception {DeveloperError} position is required.
  3028. * @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
  3029. * @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
  3030. */
  3031. Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
  3032. if (!defined(position)) {
  3033. throw new DeveloperError('position is required.');
  3034. }
  3035. if (!CesiumMath.equalsEpsilon(this._radii.x, this._radii.y, CesiumMath.EPSILON15)) {
  3036. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  3037. }
  3038. if (this._radii.z === 0) {
  3039. throw new DeveloperError('Ellipsoid.radii.z must be greater than 0');
  3040. }
  3041. buffer = defaultValue(buffer, 0.0);
  3042. var sqauredXOverSquaredZ = this._sqauredXOverSquaredZ;
  3043. if (!defined(result)) {
  3044. result = new Cartesian3();
  3045. }
  3046. result.x = 0.0;
  3047. result.y = 0.0;
  3048. result.z = position.z * (1 - sqauredXOverSquaredZ);
  3049. if (Math.abs(result.z) >= this._radii.z - buffer) {
  3050. return undefined;
  3051. }
  3052. return result;
  3053. };
  3054. return Ellipsoid;
  3055. });
  3056. /*global define*/
  3057. define('Core/arrayRemoveDuplicates',[
  3058. './defaultValue',
  3059. './defined',
  3060. './DeveloperError',
  3061. './Math'
  3062. ], function(
  3063. defaultValue,
  3064. defined,
  3065. DeveloperError,
  3066. CesiumMath) {
  3067. 'use strict';
  3068. var removeDuplicatesEpsilon = CesiumMath.EPSILON10;
  3069. /**
  3070. * Removes adjacent duplicate values in an array of values.
  3071. *
  3072. * @param {Object[]} [values] The array of values.
  3073. * @param {Function} equalsEpsilon Function to compare values with an epsilon. Boolean equalsEpsilon(left, right, epsilon).
  3074. * @param {Boolean} [wrapAround=false] Compare the last value in the array against the first value.
  3075. * @returns {Object[]|undefined} A new array of values with no adjacent duplicate values or the input array if no duplicates were found.
  3076. *
  3077. * @example
  3078. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0), (1.0, 1.0, 1.0)]
  3079. * var values = [
  3080. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3081. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3082. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  3083. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  3084. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  3085. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon);
  3086. *
  3087. * @example
  3088. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)]
  3089. * var values = [
  3090. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3091. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3092. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  3093. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  3094. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  3095. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon, true);
  3096. *
  3097. * @private
  3098. */
  3099. function arrayRemoveDuplicates(values, equalsEpsilon, wrapAround) {
  3100. if (!defined(equalsEpsilon)) {
  3101. throw new DeveloperError('equalsEpsilon is required.');
  3102. }
  3103. if (!defined(values)) {
  3104. return undefined;
  3105. }
  3106. wrapAround = defaultValue(wrapAround, false);
  3107. var length = values.length;
  3108. if (length < 2) {
  3109. return values;
  3110. }
  3111. var i;
  3112. var v0;
  3113. var v1;
  3114. for (i = 1; i < length; ++i) {
  3115. v0 = values[i - 1];
  3116. v1 = values[i];
  3117. if (equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  3118. break;
  3119. }
  3120. }
  3121. if (i === length) {
  3122. if (wrapAround && equalsEpsilon(values[0], values[values.length - 1], removeDuplicatesEpsilon)) {
  3123. return values.slice(1);
  3124. }
  3125. return values;
  3126. }
  3127. var cleanedvalues = values.slice(0, i);
  3128. for (; i < length; ++i) {
  3129. // v0 is set by either the previous loop, or the previous clean point.
  3130. v1 = values[i];
  3131. if (!equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  3132. cleanedvalues.push(v1);
  3133. v0 = v1;
  3134. }
  3135. }
  3136. if (wrapAround && cleanedvalues.length > 1 && equalsEpsilon(cleanedvalues[0], cleanedvalues[cleanedvalues.length - 1], removeDuplicatesEpsilon)) {
  3137. cleanedvalues.shift();
  3138. }
  3139. return cleanedvalues;
  3140. }
  3141. return arrayRemoveDuplicates;
  3142. });
  3143. /*global define*/
  3144. define('Core/Cartesian2',[
  3145. './defaultValue',
  3146. './defined',
  3147. './DeveloperError',
  3148. './freezeObject',
  3149. './Math'
  3150. ], function(
  3151. defaultValue,
  3152. defined,
  3153. DeveloperError,
  3154. freezeObject,
  3155. CesiumMath) {
  3156. 'use strict';
  3157. /**
  3158. * A 2D Cartesian point.
  3159. * @alias Cartesian2
  3160. * @constructor
  3161. *
  3162. * @param {Number} [x=0.0] The X component.
  3163. * @param {Number} [y=0.0] The Y component.
  3164. *
  3165. * @see Cartesian3
  3166. * @see Cartesian4
  3167. * @see Packable
  3168. */
  3169. function Cartesian2(x, y) {
  3170. /**
  3171. * The X component.
  3172. * @type {Number}
  3173. * @default 0.0
  3174. */
  3175. this.x = defaultValue(x, 0.0);
  3176. /**
  3177. * The Y component.
  3178. * @type {Number}
  3179. * @default 0.0
  3180. */
  3181. this.y = defaultValue(y, 0.0);
  3182. }
  3183. /**
  3184. * Creates a Cartesian2 instance from x and y coordinates.
  3185. *
  3186. * @param {Number} x The x coordinate.
  3187. * @param {Number} y The y coordinate.
  3188. * @param {Cartesian2} [result] The object onto which to store the result.
  3189. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3190. */
  3191. Cartesian2.fromElements = function(x, y, result) {
  3192. if (!defined(result)) {
  3193. return new Cartesian2(x, y);
  3194. }
  3195. result.x = x;
  3196. result.y = y;
  3197. return result;
  3198. };
  3199. /**
  3200. * Duplicates a Cartesian2 instance.
  3201. *
  3202. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  3203. * @param {Cartesian2} [result] The object onto which to store the result.
  3204. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  3205. */
  3206. Cartesian2.clone = function(cartesian, result) {
  3207. if (!defined(cartesian)) {
  3208. return undefined;
  3209. }
  3210. if (!defined(result)) {
  3211. return new Cartesian2(cartesian.x, cartesian.y);
  3212. }
  3213. result.x = cartesian.x;
  3214. result.y = cartesian.y;
  3215. return result;
  3216. };
  3217. /**
  3218. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  3219. * x and y properties of the Cartesian3 and drops z.
  3220. * @function
  3221. *
  3222. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  3223. * @param {Cartesian2} [result] The object onto which to store the result.
  3224. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3225. */
  3226. Cartesian2.fromCartesian3 = Cartesian2.clone;
  3227. /**
  3228. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  3229. * x and y properties of the Cartesian4 and drops z and w.
  3230. * @function
  3231. *
  3232. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  3233. * @param {Cartesian2} [result] The object onto which to store the result.
  3234. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3235. */
  3236. Cartesian2.fromCartesian4 = Cartesian2.clone;
  3237. /**
  3238. * The number of elements used to pack the object into an array.
  3239. * @type {Number}
  3240. */
  3241. Cartesian2.packedLength = 2;
  3242. /**
  3243. * Stores the provided instance into the provided array.
  3244. *
  3245. * @param {Cartesian2} value The value to pack.
  3246. * @param {Number[]} array The array to pack into.
  3247. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3248. *
  3249. * @returns {Number[]} The array that was packed into
  3250. */
  3251. Cartesian2.pack = function(value, array, startingIndex) {
  3252. if (!defined(value)) {
  3253. throw new DeveloperError('value is required');
  3254. }
  3255. if (!defined(array)) {
  3256. throw new DeveloperError('array is required');
  3257. }
  3258. startingIndex = defaultValue(startingIndex, 0);
  3259. array[startingIndex++] = value.x;
  3260. array[startingIndex] = value.y;
  3261. return array;
  3262. };
  3263. /**
  3264. * Retrieves an instance from a packed array.
  3265. *
  3266. * @param {Number[]} array The packed array.
  3267. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3268. * @param {Cartesian2} [result] The object into which to store the result.
  3269. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3270. */
  3271. Cartesian2.unpack = function(array, startingIndex, result) {
  3272. if (!defined(array)) {
  3273. throw new DeveloperError('array is required');
  3274. }
  3275. startingIndex = defaultValue(startingIndex, 0);
  3276. if (!defined(result)) {
  3277. result = new Cartesian2();
  3278. }
  3279. result.x = array[startingIndex++];
  3280. result.y = array[startingIndex];
  3281. return result;
  3282. };
  3283. /**
  3284. * Flattens an array of Cartesian2s into and array of components.
  3285. *
  3286. * @param {Cartesian2[]} array The array of cartesians to pack.
  3287. * @param {Number[]} result The array onto which to store the result.
  3288. * @returns {Number[]} The packed array.
  3289. */
  3290. Cartesian2.packArray = function(array, result) {
  3291. if (!defined(array)) {
  3292. throw new DeveloperError('array is required');
  3293. }
  3294. var length = array.length;
  3295. if (!defined(result)) {
  3296. result = new Array(length * 2);
  3297. } else {
  3298. result.length = length * 2;
  3299. }
  3300. for (var i = 0; i < length; ++i) {
  3301. Cartesian2.pack(array[i], result, i * 2);
  3302. }
  3303. return result;
  3304. };
  3305. /**
  3306. * Unpacks an array of cartesian components into and array of Cartesian2s.
  3307. *
  3308. * @param {Number[]} array The array of components to unpack.
  3309. * @param {Cartesian2[]} result The array onto which to store the result.
  3310. * @returns {Cartesian2[]} The unpacked array.
  3311. */
  3312. Cartesian2.unpackArray = function(array, result) {
  3313. if (!defined(array)) {
  3314. throw new DeveloperError('array is required');
  3315. }
  3316. var length = array.length;
  3317. if (!defined(result)) {
  3318. result = new Array(length / 2);
  3319. } else {
  3320. result.length = length / 2;
  3321. }
  3322. for (var i = 0; i < length; i += 2) {
  3323. var index = i / 2;
  3324. result[index] = Cartesian2.unpack(array, i, result[index]);
  3325. }
  3326. return result;
  3327. };
  3328. /**
  3329. * Creates a Cartesian2 from two consecutive elements in an array.
  3330. * @function
  3331. *
  3332. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  3333. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  3334. * @param {Cartesian2} [result] The object onto which to store the result.
  3335. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3336. *
  3337. * @example
  3338. * // Create a Cartesian2 with (1.0, 2.0)
  3339. * var v = [1.0, 2.0];
  3340. * var p = Cesium.Cartesian2.fromArray(v);
  3341. *
  3342. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  3343. * var v2 = [0.0, 0.0, 1.0, 2.0];
  3344. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  3345. */
  3346. Cartesian2.fromArray = Cartesian2.unpack;
  3347. /**
  3348. * Computes the value of the maximum component for the supplied Cartesian.
  3349. *
  3350. * @param {Cartesian2} cartesian The cartesian to use.
  3351. * @returns {Number} The value of the maximum component.
  3352. */
  3353. Cartesian2.maximumComponent = function(cartesian) {
  3354. if (!defined(cartesian)) {
  3355. throw new DeveloperError('cartesian is required');
  3356. }
  3357. return Math.max(cartesian.x, cartesian.y);
  3358. };
  3359. /**
  3360. * Computes the value of the minimum component for the supplied Cartesian.
  3361. *
  3362. * @param {Cartesian2} cartesian The cartesian to use.
  3363. * @returns {Number} The value of the minimum component.
  3364. */
  3365. Cartesian2.minimumComponent = function(cartesian) {
  3366. if (!defined(cartesian)) {
  3367. throw new DeveloperError('cartesian is required');
  3368. }
  3369. return Math.min(cartesian.x, cartesian.y);
  3370. };
  3371. /**
  3372. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  3373. *
  3374. * @param {Cartesian2} first A cartesian to compare.
  3375. * @param {Cartesian2} second A cartesian to compare.
  3376. * @param {Cartesian2} result The object into which to store the result.
  3377. * @returns {Cartesian2} A cartesian with the minimum components.
  3378. */
  3379. Cartesian2.minimumByComponent = function(first, second, result) {
  3380. if (!defined(first)) {
  3381. throw new DeveloperError('first is required.');
  3382. }
  3383. if (!defined(second)) {
  3384. throw new DeveloperError('second is required.');
  3385. }
  3386. if (!defined(result)) {
  3387. throw new DeveloperError('result is required.');
  3388. }
  3389. result.x = Math.min(first.x, second.x);
  3390. result.y = Math.min(first.y, second.y);
  3391. return result;
  3392. };
  3393. /**
  3394. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  3395. *
  3396. * @param {Cartesian2} first A cartesian to compare.
  3397. * @param {Cartesian2} second A cartesian to compare.
  3398. * @param {Cartesian2} result The object into which to store the result.
  3399. * @returns {Cartesian2} A cartesian with the maximum components.
  3400. */
  3401. Cartesian2.maximumByComponent = function(first, second, result) {
  3402. if (!defined(first)) {
  3403. throw new DeveloperError('first is required.');
  3404. }
  3405. if (!defined(second)) {
  3406. throw new DeveloperError('second is required.');
  3407. }
  3408. if (!defined(result)) {
  3409. throw new DeveloperError('result is required.');
  3410. }
  3411. result.x = Math.max(first.x, second.x);
  3412. result.y = Math.max(first.y, second.y);
  3413. return result;
  3414. };
  3415. /**
  3416. * Computes the provided Cartesian's squared magnitude.
  3417. *
  3418. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  3419. * @returns {Number} The squared magnitude.
  3420. */
  3421. Cartesian2.magnitudeSquared = function(cartesian) {
  3422. if (!defined(cartesian)) {
  3423. throw new DeveloperError('cartesian is required');
  3424. }
  3425. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  3426. };
  3427. /**
  3428. * Computes the Cartesian's magnitude (length).
  3429. *
  3430. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  3431. * @returns {Number} The magnitude.
  3432. */
  3433. Cartesian2.magnitude = function(cartesian) {
  3434. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  3435. };
  3436. var distanceScratch = new Cartesian2();
  3437. /**
  3438. * Computes the distance between two points.
  3439. *
  3440. * @param {Cartesian2} left The first point to compute the distance from.
  3441. * @param {Cartesian2} right The second point to compute the distance to.
  3442. * @returns {Number} The distance between two points.
  3443. *
  3444. * @example
  3445. * // Returns 1.0
  3446. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  3447. */
  3448. Cartesian2.distance = function(left, right) {
  3449. if (!defined(left) || !defined(right)) {
  3450. throw new DeveloperError('left and right are required.');
  3451. }
  3452. Cartesian2.subtract(left, right, distanceScratch);
  3453. return Cartesian2.magnitude(distanceScratch);
  3454. };
  3455. /**
  3456. * Computes the squared distance between two points. Comparing squared distances
  3457. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  3458. *
  3459. * @param {Cartesian2} left The first point to compute the distance from.
  3460. * @param {Cartesian2} right The second point to compute the distance to.
  3461. * @returns {Number} The distance between two points.
  3462. *
  3463. * @example
  3464. * // Returns 4.0, not 2.0
  3465. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  3466. */
  3467. Cartesian2.distanceSquared = function(left, right) {
  3468. if (!defined(left) || !defined(right)) {
  3469. throw new DeveloperError('left and right are required.');
  3470. }
  3471. Cartesian2.subtract(left, right, distanceScratch);
  3472. return Cartesian2.magnitudeSquared(distanceScratch);
  3473. };
  3474. /**
  3475. * Computes the normalized form of the supplied Cartesian.
  3476. *
  3477. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  3478. * @param {Cartesian2} result The object onto which to store the result.
  3479. * @returns {Cartesian2} The modified result parameter.
  3480. */
  3481. Cartesian2.normalize = function(cartesian, result) {
  3482. if (!defined(cartesian)) {
  3483. throw new DeveloperError('cartesian is required');
  3484. }
  3485. if (!defined(result)) {
  3486. throw new DeveloperError('result is required');
  3487. }
  3488. var magnitude = Cartesian2.magnitude(cartesian);
  3489. result.x = cartesian.x / magnitude;
  3490. result.y = cartesian.y / magnitude;
  3491. if (isNaN(result.x) || isNaN(result.y)) {
  3492. throw new DeveloperError('normalized result is not a number');
  3493. }
  3494. return result;
  3495. };
  3496. /**
  3497. * Computes the dot (scalar) product of two Cartesians.
  3498. *
  3499. * @param {Cartesian2} left The first Cartesian.
  3500. * @param {Cartesian2} right The second Cartesian.
  3501. * @returns {Number} The dot product.
  3502. */
  3503. Cartesian2.dot = function(left, right) {
  3504. if (!defined(left)) {
  3505. throw new DeveloperError('left is required');
  3506. }
  3507. if (!defined(right)) {
  3508. throw new DeveloperError('right is required');
  3509. }
  3510. return left.x * right.x + left.y * right.y;
  3511. };
  3512. /**
  3513. * Computes the componentwise product of two Cartesians.
  3514. *
  3515. * @param {Cartesian2} left The first Cartesian.
  3516. * @param {Cartesian2} right The second Cartesian.
  3517. * @param {Cartesian2} result The object onto which to store the result.
  3518. * @returns {Cartesian2} The modified result parameter.
  3519. */
  3520. Cartesian2.multiplyComponents = function(left, right, result) {
  3521. if (!defined(left)) {
  3522. throw new DeveloperError('left is required');
  3523. }
  3524. if (!defined(right)) {
  3525. throw new DeveloperError('right is required');
  3526. }
  3527. if (!defined(result)) {
  3528. throw new DeveloperError('result is required');
  3529. }
  3530. result.x = left.x * right.x;
  3531. result.y = left.y * right.y;
  3532. return result;
  3533. };
  3534. /**
  3535. * Computes the componentwise quotient of two Cartesians.
  3536. *
  3537. * @param {Cartesian2} left The first Cartesian.
  3538. * @param {Cartesian2} right The second Cartesian.
  3539. * @param {Cartesian2} result The object onto which to store the result.
  3540. * @returns {Cartesian2} The modified result parameter.
  3541. */
  3542. Cartesian2.divideComponents = function(left, right, result) {
  3543. if (!defined(left)) {
  3544. throw new DeveloperError('left is required');
  3545. }
  3546. if (!defined(right)) {
  3547. throw new DeveloperError('right is required');
  3548. }
  3549. if (!defined(result)) {
  3550. throw new DeveloperError('result is required');
  3551. }
  3552. result.x = left.x / right.x;
  3553. result.y = left.y / right.y;
  3554. return result;
  3555. };
  3556. /**
  3557. * Computes the componentwise sum of two Cartesians.
  3558. *
  3559. * @param {Cartesian2} left The first Cartesian.
  3560. * @param {Cartesian2} right The second Cartesian.
  3561. * @param {Cartesian2} result The object onto which to store the result.
  3562. * @returns {Cartesian2} The modified result parameter.
  3563. */
  3564. Cartesian2.add = function(left, right, result) {
  3565. if (!defined(left)) {
  3566. throw new DeveloperError('left is required');
  3567. }
  3568. if (!defined(right)) {
  3569. throw new DeveloperError('right is required');
  3570. }
  3571. if (!defined(result)) {
  3572. throw new DeveloperError('result is required');
  3573. }
  3574. result.x = left.x + right.x;
  3575. result.y = left.y + right.y;
  3576. return result;
  3577. };
  3578. /**
  3579. * Computes the componentwise difference of two Cartesians.
  3580. *
  3581. * @param {Cartesian2} left The first Cartesian.
  3582. * @param {Cartesian2} right The second Cartesian.
  3583. * @param {Cartesian2} result The object onto which to store the result.
  3584. * @returns {Cartesian2} The modified result parameter.
  3585. */
  3586. Cartesian2.subtract = function(left, right, result) {
  3587. if (!defined(left)) {
  3588. throw new DeveloperError('left is required');
  3589. }
  3590. if (!defined(right)) {
  3591. throw new DeveloperError('right is required');
  3592. }
  3593. if (!defined(result)) {
  3594. throw new DeveloperError('result is required');
  3595. }
  3596. result.x = left.x - right.x;
  3597. result.y = left.y - right.y;
  3598. return result;
  3599. };
  3600. /**
  3601. * Multiplies the provided Cartesian componentwise by the provided scalar.
  3602. *
  3603. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  3604. * @param {Number} scalar The scalar to multiply with.
  3605. * @param {Cartesian2} result The object onto which to store the result.
  3606. * @returns {Cartesian2} The modified result parameter.
  3607. */
  3608. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  3609. if (!defined(cartesian)) {
  3610. throw new DeveloperError('cartesian is required');
  3611. }
  3612. if (typeof scalar !== 'number') {
  3613. throw new DeveloperError('scalar is required and must be a number.');
  3614. }
  3615. if (!defined(result)) {
  3616. throw new DeveloperError('result is required');
  3617. }
  3618. result.x = cartesian.x * scalar;
  3619. result.y = cartesian.y * scalar;
  3620. return result;
  3621. };
  3622. /**
  3623. * Divides the provided Cartesian componentwise by the provided scalar.
  3624. *
  3625. * @param {Cartesian2} cartesian The Cartesian to be divided.
  3626. * @param {Number} scalar The scalar to divide by.
  3627. * @param {Cartesian2} result The object onto which to store the result.
  3628. * @returns {Cartesian2} The modified result parameter.
  3629. */
  3630. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  3631. if (!defined(cartesian)) {
  3632. throw new DeveloperError('cartesian is required');
  3633. }
  3634. if (typeof scalar !== 'number') {
  3635. throw new DeveloperError('scalar is required and must be a number.');
  3636. }
  3637. if (!defined(result)) {
  3638. throw new DeveloperError('result is required');
  3639. }
  3640. result.x = cartesian.x / scalar;
  3641. result.y = cartesian.y / scalar;
  3642. return result;
  3643. };
  3644. /**
  3645. * Negates the provided Cartesian.
  3646. *
  3647. * @param {Cartesian2} cartesian The Cartesian to be negated.
  3648. * @param {Cartesian2} result The object onto which to store the result.
  3649. * @returns {Cartesian2} The modified result parameter.
  3650. */
  3651. Cartesian2.negate = function(cartesian, result) {
  3652. if (!defined(cartesian)) {
  3653. throw new DeveloperError('cartesian is required');
  3654. }
  3655. if (!defined(result)) {
  3656. throw new DeveloperError('result is required');
  3657. }
  3658. result.x = -cartesian.x;
  3659. result.y = -cartesian.y;
  3660. return result;
  3661. };
  3662. /**
  3663. * Computes the absolute value of the provided Cartesian.
  3664. *
  3665. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  3666. * @param {Cartesian2} result The object onto which to store the result.
  3667. * @returns {Cartesian2} The modified result parameter.
  3668. */
  3669. Cartesian2.abs = function(cartesian, result) {
  3670. if (!defined(cartesian)) {
  3671. throw new DeveloperError('cartesian is required');
  3672. }
  3673. if (!defined(result)) {
  3674. throw new DeveloperError('result is required');
  3675. }
  3676. result.x = Math.abs(cartesian.x);
  3677. result.y = Math.abs(cartesian.y);
  3678. return result;
  3679. };
  3680. var lerpScratch = new Cartesian2();
  3681. /**
  3682. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  3683. *
  3684. * @param {Cartesian2} start The value corresponding to t at 0.0.
  3685. * @param {Cartesian2} end The value corresponding to t at 1.0.
  3686. * @param {Number} t The point along t at which to interpolate.
  3687. * @param {Cartesian2} result The object onto which to store the result.
  3688. * @returns {Cartesian2} The modified result parameter.
  3689. */
  3690. Cartesian2.lerp = function(start, end, t, result) {
  3691. if (!defined(start)) {
  3692. throw new DeveloperError('start is required.');
  3693. }
  3694. if (!defined(end)) {
  3695. throw new DeveloperError('end is required.');
  3696. }
  3697. if (typeof t !== 'number') {
  3698. throw new DeveloperError('t is required and must be a number.');
  3699. }
  3700. if (!defined(result)) {
  3701. throw new DeveloperError('result is required.');
  3702. }
  3703. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  3704. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  3705. return Cartesian2.add(lerpScratch, result, result);
  3706. };
  3707. var angleBetweenScratch = new Cartesian2();
  3708. var angleBetweenScratch2 = new Cartesian2();
  3709. /**
  3710. * Returns the angle, in radians, between the provided Cartesians.
  3711. *
  3712. * @param {Cartesian2} left The first Cartesian.
  3713. * @param {Cartesian2} right The second Cartesian.
  3714. * @returns {Number} The angle between the Cartesians.
  3715. */
  3716. Cartesian2.angleBetween = function(left, right) {
  3717. if (!defined(left)) {
  3718. throw new DeveloperError('left is required');
  3719. }
  3720. if (!defined(right)) {
  3721. throw new DeveloperError('right is required');
  3722. }
  3723. Cartesian2.normalize(left, angleBetweenScratch);
  3724. Cartesian2.normalize(right, angleBetweenScratch2);
  3725. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  3726. };
  3727. var mostOrthogonalAxisScratch = new Cartesian2();
  3728. /**
  3729. * Returns the axis that is most orthogonal to the provided Cartesian.
  3730. *
  3731. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  3732. * @param {Cartesian2} result The object onto which to store the result.
  3733. * @returns {Cartesian2} The most orthogonal axis.
  3734. */
  3735. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  3736. if (!defined(cartesian)) {
  3737. throw new DeveloperError('cartesian is required.');
  3738. }
  3739. if (!defined(result)) {
  3740. throw new DeveloperError('result is required.');
  3741. }
  3742. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  3743. Cartesian2.abs(f, f);
  3744. if (f.x <= f.y) {
  3745. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  3746. } else {
  3747. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  3748. }
  3749. return result;
  3750. };
  3751. /**
  3752. * Compares the provided Cartesians componentwise and returns
  3753. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3754. *
  3755. * @param {Cartesian2} [left] The first Cartesian.
  3756. * @param {Cartesian2} [right] The second Cartesian.
  3757. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3758. */
  3759. Cartesian2.equals = function(left, right) {
  3760. return (left === right) ||
  3761. ((defined(left)) &&
  3762. (defined(right)) &&
  3763. (left.x === right.x) &&
  3764. (left.y === right.y));
  3765. };
  3766. /**
  3767. * @private
  3768. */
  3769. Cartesian2.equalsArray = function(cartesian, array, offset) {
  3770. return cartesian.x === array[offset] &&
  3771. cartesian.y === array[offset + 1];
  3772. };
  3773. /**
  3774. * Compares the provided Cartesians componentwise and returns
  3775. * <code>true</code> if they pass an absolute or relative tolerance test,
  3776. * <code>false</code> otherwise.
  3777. *
  3778. * @param {Cartesian2} [left] The first Cartesian.
  3779. * @param {Cartesian2} [right] The second Cartesian.
  3780. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3781. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3782. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3783. */
  3784. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  3785. return (left === right) ||
  3786. (defined(left) &&
  3787. defined(right) &&
  3788. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  3789. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  3790. };
  3791. /**
  3792. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  3793. *
  3794. * @type {Cartesian2}
  3795. * @constant
  3796. */
  3797. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  3798. /**
  3799. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  3800. *
  3801. * @type {Cartesian2}
  3802. * @constant
  3803. */
  3804. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  3805. /**
  3806. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  3807. *
  3808. * @type {Cartesian2}
  3809. * @constant
  3810. */
  3811. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  3812. /**
  3813. * Duplicates this Cartesian2 instance.
  3814. *
  3815. * @param {Cartesian2} [result] The object onto which to store the result.
  3816. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3817. */
  3818. Cartesian2.prototype.clone = function(result) {
  3819. return Cartesian2.clone(this, result);
  3820. };
  3821. /**
  3822. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3823. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3824. *
  3825. * @param {Cartesian2} [right] The right hand side Cartesian.
  3826. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3827. */
  3828. Cartesian2.prototype.equals = function(right) {
  3829. return Cartesian2.equals(this, right);
  3830. };
  3831. /**
  3832. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3833. * <code>true</code> if they pass an absolute or relative tolerance test,
  3834. * <code>false</code> otherwise.
  3835. *
  3836. * @param {Cartesian2} [right] The right hand side Cartesian.
  3837. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3838. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3839. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  3840. */
  3841. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  3842. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  3843. };
  3844. /**
  3845. * Creates a string representing this Cartesian in the format '(x, y)'.
  3846. *
  3847. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  3848. */
  3849. Cartesian2.prototype.toString = function() {
  3850. return '(' + this.x + ', ' + this.y + ')';
  3851. };
  3852. return Cartesian2;
  3853. });
  3854. /*global define*/
  3855. define('Core/GeographicProjection',[
  3856. './Cartesian3',
  3857. './Cartographic',
  3858. './defaultValue',
  3859. './defined',
  3860. './defineProperties',
  3861. './DeveloperError',
  3862. './Ellipsoid'
  3863. ], function(
  3864. Cartesian3,
  3865. Cartographic,
  3866. defaultValue,
  3867. defined,
  3868. defineProperties,
  3869. DeveloperError,
  3870. Ellipsoid) {
  3871. 'use strict';
  3872. /**
  3873. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3874. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3875. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3876. * is also known as EPSG:4326.
  3877. *
  3878. * @alias GeographicProjection
  3879. * @constructor
  3880. *
  3881. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3882. *
  3883. * @see WebMercatorProjection
  3884. */
  3885. function GeographicProjection(ellipsoid) {
  3886. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3887. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3888. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3889. }
  3890. defineProperties(GeographicProjection.prototype, {
  3891. /**
  3892. * Gets the {@link Ellipsoid}.
  3893. *
  3894. * @memberof GeographicProjection.prototype
  3895. *
  3896. * @type {Ellipsoid}
  3897. * @readonly
  3898. */
  3899. ellipsoid : {
  3900. get : function() {
  3901. return this._ellipsoid;
  3902. }
  3903. }
  3904. });
  3905. /**
  3906. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3907. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3908. * ellipsoid. Z is the unmodified height.
  3909. *
  3910. * @param {Cartographic} cartographic The coordinates to project.
  3911. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3912. * undefined, a new instance is created and returned.
  3913. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3914. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3915. * created and returned.
  3916. */
  3917. GeographicProjection.prototype.project = function(cartographic, result) {
  3918. // Actually this is the special case of equidistant cylindrical called the plate carree
  3919. var semimajorAxis = this._semimajorAxis;
  3920. var x = cartographic.longitude * semimajorAxis;
  3921. var y = cartographic.latitude * semimajorAxis;
  3922. var z = cartographic.height;
  3923. if (!defined(result)) {
  3924. return new Cartesian3(x, y, z);
  3925. }
  3926. result.x = x;
  3927. result.y = y;
  3928. result.z = z;
  3929. return result;
  3930. };
  3931. /**
  3932. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3933. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3934. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3935. *
  3936. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3937. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3938. * undefined, a new instance is created and returned.
  3939. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3940. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3941. * created and returned.
  3942. */
  3943. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3944. if (!defined(cartesian)) {
  3945. throw new DeveloperError('cartesian is required');
  3946. }
  3947. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3948. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3949. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3950. var height = cartesian.z;
  3951. if (!defined(result)) {
  3952. return new Cartographic(longitude, latitude, height);
  3953. }
  3954. result.longitude = longitude;
  3955. result.latitude = latitude;
  3956. result.height = height;
  3957. return result;
  3958. };
  3959. return GeographicProjection;
  3960. });
  3961. /*global define*/
  3962. define('Core/Intersect',[
  3963. './freezeObject'
  3964. ], function(
  3965. freezeObject) {
  3966. 'use strict';
  3967. /**
  3968. * This enumerated type is used in determining where, relative to the frustum, an
  3969. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3970. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3971. * outside of the frustum's 6 planes (OUTSIDE).
  3972. *
  3973. * @exports Intersect
  3974. */
  3975. var Intersect = {
  3976. /**
  3977. * Represents that an object is not contained within the frustum.
  3978. *
  3979. * @type {Number}
  3980. * @constant
  3981. */
  3982. OUTSIDE : -1,
  3983. /**
  3984. * Represents that an object intersects one of the frustum's planes.
  3985. *
  3986. * @type {Number}
  3987. * @constant
  3988. */
  3989. INTERSECTING : 0,
  3990. /**
  3991. * Represents that an object is fully within the frustum.
  3992. *
  3993. * @type {Number}
  3994. * @constant
  3995. */
  3996. INSIDE : 1
  3997. };
  3998. return freezeObject(Intersect);
  3999. });
  4000. /*global define*/
  4001. define('Core/Rectangle',[
  4002. './Cartographic',
  4003. './defaultValue',
  4004. './defined',
  4005. './defineProperties',
  4006. './DeveloperError',
  4007. './Ellipsoid',
  4008. './freezeObject',
  4009. './Math'
  4010. ], function(
  4011. Cartographic,
  4012. defaultValue,
  4013. defined,
  4014. defineProperties,
  4015. DeveloperError,
  4016. Ellipsoid,
  4017. freezeObject,
  4018. CesiumMath) {
  4019. 'use strict';
  4020. /**
  4021. * A two dimensional region specified as longitude and latitude coordinates.
  4022. *
  4023. * @alias Rectangle
  4024. * @constructor
  4025. *
  4026. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  4027. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  4028. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  4029. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  4030. *
  4031. * @see Packable
  4032. */
  4033. function Rectangle(west, south, east, north) {
  4034. /**
  4035. * The westernmost longitude in radians in the range [-Pi, Pi].
  4036. *
  4037. * @type {Number}
  4038. * @default 0.0
  4039. */
  4040. this.west = defaultValue(west, 0.0);
  4041. /**
  4042. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  4043. *
  4044. * @type {Number}
  4045. * @default 0.0
  4046. */
  4047. this.south = defaultValue(south, 0.0);
  4048. /**
  4049. * The easternmost longitude in radians in the range [-Pi, Pi].
  4050. *
  4051. * @type {Number}
  4052. * @default 0.0
  4053. */
  4054. this.east = defaultValue(east, 0.0);
  4055. /**
  4056. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  4057. *
  4058. * @type {Number}
  4059. * @default 0.0
  4060. */
  4061. this.north = defaultValue(north, 0.0);
  4062. }
  4063. defineProperties(Rectangle.prototype, {
  4064. /**
  4065. * Gets the width of the rectangle in radians.
  4066. * @memberof Rectangle.prototype
  4067. * @type {Number}
  4068. */
  4069. width : {
  4070. get : function() {
  4071. return Rectangle.computeWidth(this);
  4072. }
  4073. },
  4074. /**
  4075. * Gets the height of the rectangle in radians.
  4076. * @memberof Rectangle.prototype
  4077. * @type {Number}
  4078. */
  4079. height : {
  4080. get : function() {
  4081. return Rectangle.computeHeight(this);
  4082. }
  4083. }
  4084. });
  4085. /**
  4086. * The number of elements used to pack the object into an array.
  4087. * @type {Number}
  4088. */
  4089. Rectangle.packedLength = 4;
  4090. /**
  4091. * Stores the provided instance into the provided array.
  4092. *
  4093. * @param {Rectangle} value The value to pack.
  4094. * @param {Number[]} array The array to pack into.
  4095. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4096. *
  4097. * @returns {Number[]} The array that was packed into
  4098. */
  4099. Rectangle.pack = function(value, array, startingIndex) {
  4100. if (!defined(value)) {
  4101. throw new DeveloperError('value is required');
  4102. }
  4103. if (!defined(array)) {
  4104. throw new DeveloperError('array is required');
  4105. }
  4106. startingIndex = defaultValue(startingIndex, 0);
  4107. array[startingIndex++] = value.west;
  4108. array[startingIndex++] = value.south;
  4109. array[startingIndex++] = value.east;
  4110. array[startingIndex] = value.north;
  4111. return array;
  4112. };
  4113. /**
  4114. * Retrieves an instance from a packed array.
  4115. *
  4116. * @param {Number[]} array The packed array.
  4117. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4118. * @param {Rectangle} [result] The object into which to store the result.
  4119. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4120. */
  4121. Rectangle.unpack = function(array, startingIndex, result) {
  4122. if (!defined(array)) {
  4123. throw new DeveloperError('array is required');
  4124. }
  4125. startingIndex = defaultValue(startingIndex, 0);
  4126. if (!defined(result)) {
  4127. result = new Rectangle();
  4128. }
  4129. result.west = array[startingIndex++];
  4130. result.south = array[startingIndex++];
  4131. result.east = array[startingIndex++];
  4132. result.north = array[startingIndex];
  4133. return result;
  4134. };
  4135. /**
  4136. * Computes the width of a rectangle in radians.
  4137. * @param {Rectangle} rectangle The rectangle to compute the width of.
  4138. * @returns {Number} The width.
  4139. */
  4140. Rectangle.computeWidth = function(rectangle) {
  4141. if (!defined(rectangle)) {
  4142. throw new DeveloperError('rectangle is required.');
  4143. }
  4144. var east = rectangle.east;
  4145. var west = rectangle.west;
  4146. if (east < west) {
  4147. east += CesiumMath.TWO_PI;
  4148. }
  4149. return east - west;
  4150. };
  4151. /**
  4152. * Computes the height of a rectangle in radians.
  4153. * @param {Rectangle} rectangle The rectangle to compute the height of.
  4154. * @returns {Number} The height.
  4155. */
  4156. Rectangle.computeHeight = function(rectangle) {
  4157. if (!defined(rectangle)) {
  4158. throw new DeveloperError('rectangle is required.');
  4159. }
  4160. return rectangle.north - rectangle.south;
  4161. };
  4162. /**
  4163. * Creates an rectangle given the boundary longitude and latitude in degrees.
  4164. *
  4165. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  4166. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  4167. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  4168. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  4169. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4170. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4171. *
  4172. * @example
  4173. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  4174. */
  4175. Rectangle.fromDegrees = function(west, south, east, north, result) {
  4176. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  4177. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  4178. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  4179. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  4180. if (!defined(result)) {
  4181. return new Rectangle(west, south, east, north);
  4182. }
  4183. result.west = west;
  4184. result.south = south;
  4185. result.east = east;
  4186. result.north = north;
  4187. return result;
  4188. };
  4189. /**
  4190. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4191. *
  4192. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  4193. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4194. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4195. */
  4196. Rectangle.fromCartographicArray = function(cartographics, result) {
  4197. if (!defined(cartographics)) {
  4198. throw new DeveloperError('cartographics is required.');
  4199. }
  4200. var west = Number.MAX_VALUE;
  4201. var east = -Number.MAX_VALUE;
  4202. var westOverIDL = Number.MAX_VALUE;
  4203. var eastOverIDL = -Number.MAX_VALUE;
  4204. var south = Number.MAX_VALUE;
  4205. var north = -Number.MAX_VALUE;
  4206. for ( var i = 0, len = cartographics.length; i < len; i++) {
  4207. var position = cartographics[i];
  4208. west = Math.min(west, position.longitude);
  4209. east = Math.max(east, position.longitude);
  4210. south = Math.min(south, position.latitude);
  4211. north = Math.max(north, position.latitude);
  4212. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4213. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4214. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4215. }
  4216. if(east - west > eastOverIDL - westOverIDL) {
  4217. west = westOverIDL;
  4218. east = eastOverIDL;
  4219. if (east > CesiumMath.PI) {
  4220. east = east - CesiumMath.TWO_PI;
  4221. }
  4222. if (west > CesiumMath.PI) {
  4223. west = west - CesiumMath.TWO_PI;
  4224. }
  4225. }
  4226. if (!defined(result)) {
  4227. return new Rectangle(west, south, east, north);
  4228. }
  4229. result.west = west;
  4230. result.south = south;
  4231. result.east = east;
  4232. result.north = north;
  4233. return result;
  4234. };
  4235. /**
  4236. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4237. *
  4238. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  4239. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  4240. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4241. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4242. */
  4243. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  4244. if (!defined(cartesians)) {
  4245. throw new DeveloperError('cartesians is required.');
  4246. }
  4247. var west = Number.MAX_VALUE;
  4248. var east = -Number.MAX_VALUE;
  4249. var westOverIDL = Number.MAX_VALUE;
  4250. var eastOverIDL = -Number.MAX_VALUE;
  4251. var south = Number.MAX_VALUE;
  4252. var north = -Number.MAX_VALUE;
  4253. for ( var i = 0, len = cartesians.length; i < len; i++) {
  4254. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  4255. west = Math.min(west, position.longitude);
  4256. east = Math.max(east, position.longitude);
  4257. south = Math.min(south, position.latitude);
  4258. north = Math.max(north, position.latitude);
  4259. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4260. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4261. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4262. }
  4263. if(east - west > eastOverIDL - westOverIDL) {
  4264. west = westOverIDL;
  4265. east = eastOverIDL;
  4266. if (east > CesiumMath.PI) {
  4267. east = east - CesiumMath.TWO_PI;
  4268. }
  4269. if (west > CesiumMath.PI) {
  4270. west = west - CesiumMath.TWO_PI;
  4271. }
  4272. }
  4273. if (!defined(result)) {
  4274. return new Rectangle(west, south, east, north);
  4275. }
  4276. result.west = west;
  4277. result.south = south;
  4278. result.east = east;
  4279. result.north = north;
  4280. return result;
  4281. };
  4282. /**
  4283. * Duplicates an Rectangle.
  4284. *
  4285. * @param {Rectangle} rectangle The rectangle to clone.
  4286. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4287. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  4288. */
  4289. Rectangle.clone = function(rectangle, result) {
  4290. if (!defined(rectangle)) {
  4291. return undefined;
  4292. }
  4293. if (!defined(result)) {
  4294. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  4295. }
  4296. result.west = rectangle.west;
  4297. result.south = rectangle.south;
  4298. result.east = rectangle.east;
  4299. result.north = rectangle.north;
  4300. return result;
  4301. };
  4302. /**
  4303. * Duplicates this Rectangle.
  4304. *
  4305. * @param {Rectangle} [result] The object onto which to store the result.
  4306. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4307. */
  4308. Rectangle.prototype.clone = function(result) {
  4309. return Rectangle.clone(this, result);
  4310. };
  4311. /**
  4312. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4313. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4314. *
  4315. * @param {Rectangle} [other] The Rectangle to compare.
  4316. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  4317. */
  4318. Rectangle.prototype.equals = function(other) {
  4319. return Rectangle.equals(this, other);
  4320. };
  4321. /**
  4322. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  4323. * <code>false</code> otherwise.
  4324. *
  4325. * @param {Rectangle} [left] The first Rectangle.
  4326. * @param {Rectangle} [right] The second Rectangle.
  4327. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  4328. */
  4329. Rectangle.equals = function(left, right) {
  4330. return (left === right) ||
  4331. ((defined(left)) &&
  4332. (defined(right)) &&
  4333. (left.west === right.west) &&
  4334. (left.south === right.south) &&
  4335. (left.east === right.east) &&
  4336. (left.north === right.north));
  4337. };
  4338. /**
  4339. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4340. * <code>true</code> if they are within the provided epsilon,
  4341. * <code>false</code> otherwise.
  4342. *
  4343. * @param {Rectangle} [other] The Rectangle to compare.
  4344. * @param {Number} epsilon The epsilon to use for equality testing.
  4345. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  4346. */
  4347. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  4348. if (typeof epsilon !== 'number') {
  4349. throw new DeveloperError('epsilon is required and must be a number.');
  4350. }
  4351. return defined(other) &&
  4352. (Math.abs(this.west - other.west) <= epsilon) &&
  4353. (Math.abs(this.south - other.south) <= epsilon) &&
  4354. (Math.abs(this.east - other.east) <= epsilon) &&
  4355. (Math.abs(this.north - other.north) <= epsilon);
  4356. };
  4357. /**
  4358. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  4359. *
  4360. * @param {Rectangle} rectangle The rectangle to validate
  4361. *
  4362. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4363. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4364. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4365. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4366. */
  4367. Rectangle.validate = function(rectangle) {
  4368. if (!defined(rectangle)) {
  4369. throw new DeveloperError('rectangle is required');
  4370. }
  4371. var north = rectangle.north;
  4372. if (typeof north !== 'number') {
  4373. throw new DeveloperError('north is required to be a number.');
  4374. }
  4375. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  4376. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  4377. }
  4378. var south = rectangle.south;
  4379. if (typeof south !== 'number') {
  4380. throw new DeveloperError('south is required to be a number.');
  4381. }
  4382. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  4383. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  4384. }
  4385. var west = rectangle.west;
  4386. if (typeof west !== 'number') {
  4387. throw new DeveloperError('west is required to be a number.');
  4388. }
  4389. if (west < -Math.PI || west > Math.PI) {
  4390. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  4391. }
  4392. var east = rectangle.east;
  4393. if (typeof east !== 'number') {
  4394. throw new DeveloperError('east is required to be a number.');
  4395. }
  4396. if (east < -Math.PI || east > Math.PI) {
  4397. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  4398. }
  4399. };
  4400. /**
  4401. * Computes the southwest corner of an rectangle.
  4402. *
  4403. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4404. * @param {Cartographic} [result] The object onto which to store the result.
  4405. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4406. */
  4407. Rectangle.southwest = function(rectangle, result) {
  4408. if (!defined(rectangle)) {
  4409. throw new DeveloperError('rectangle is required');
  4410. }
  4411. if (!defined(result)) {
  4412. return new Cartographic(rectangle.west, rectangle.south);
  4413. }
  4414. result.longitude = rectangle.west;
  4415. result.latitude = rectangle.south;
  4416. result.height = 0.0;
  4417. return result;
  4418. };
  4419. /**
  4420. * Computes the northwest corner of an rectangle.
  4421. *
  4422. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4423. * @param {Cartographic} [result] The object onto which to store the result.
  4424. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4425. */
  4426. Rectangle.northwest = function(rectangle, result) {
  4427. if (!defined(rectangle)) {
  4428. throw new DeveloperError('rectangle is required');
  4429. }
  4430. if (!defined(result)) {
  4431. return new Cartographic(rectangle.west, rectangle.north);
  4432. }
  4433. result.longitude = rectangle.west;
  4434. result.latitude = rectangle.north;
  4435. result.height = 0.0;
  4436. return result;
  4437. };
  4438. /**
  4439. * Computes the northeast corner of an rectangle.
  4440. *
  4441. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4442. * @param {Cartographic} [result] The object onto which to store the result.
  4443. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4444. */
  4445. Rectangle.northeast = function(rectangle, result) {
  4446. if (!defined(rectangle)) {
  4447. throw new DeveloperError('rectangle is required');
  4448. }
  4449. if (!defined(result)) {
  4450. return new Cartographic(rectangle.east, rectangle.north);
  4451. }
  4452. result.longitude = rectangle.east;
  4453. result.latitude = rectangle.north;
  4454. result.height = 0.0;
  4455. return result;
  4456. };
  4457. /**
  4458. * Computes the southeast corner of an rectangle.
  4459. *
  4460. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4461. * @param {Cartographic} [result] The object onto which to store the result.
  4462. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4463. */
  4464. Rectangle.southeast = function(rectangle, result) {
  4465. if (!defined(rectangle)) {
  4466. throw new DeveloperError('rectangle is required');
  4467. }
  4468. if (!defined(result)) {
  4469. return new Cartographic(rectangle.east, rectangle.south);
  4470. }
  4471. result.longitude = rectangle.east;
  4472. result.latitude = rectangle.south;
  4473. result.height = 0.0;
  4474. return result;
  4475. };
  4476. /**
  4477. * Computes the center of an rectangle.
  4478. *
  4479. * @param {Rectangle} rectangle The rectangle for which to find the center
  4480. * @param {Cartographic} [result] The object onto which to store the result.
  4481. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4482. */
  4483. Rectangle.center = function(rectangle, result) {
  4484. if (!defined(rectangle)) {
  4485. throw new DeveloperError('rectangle is required');
  4486. }
  4487. var east = rectangle.east;
  4488. var west = rectangle.west;
  4489. if (east < west) {
  4490. east += CesiumMath.TWO_PI;
  4491. }
  4492. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  4493. var latitude = (rectangle.south + rectangle.north) * 0.5;
  4494. if (!defined(result)) {
  4495. return new Cartographic(longitude, latitude);
  4496. }
  4497. result.longitude = longitude;
  4498. result.latitude = latitude;
  4499. result.height = 0.0;
  4500. return result;
  4501. };
  4502. /**
  4503. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  4504. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  4505. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  4506. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  4507. * coordinates, see {@link Rectangle.simpleIntersection}.
  4508. *
  4509. * @param {Rectangle} rectangle On rectangle to find an intersection
  4510. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4511. * @param {Rectangle} [result] The object onto which to store the result.
  4512. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4513. */
  4514. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  4515. if (!defined(rectangle)) {
  4516. throw new DeveloperError('rectangle is required');
  4517. }
  4518. if (!defined(otherRectangle)) {
  4519. throw new DeveloperError('otherRectangle is required.');
  4520. }
  4521. var rectangleEast = rectangle.east;
  4522. var rectangleWest = rectangle.west;
  4523. var otherRectangleEast = otherRectangle.east;
  4524. var otherRectangleWest = otherRectangle.west;
  4525. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4526. rectangleEast += CesiumMath.TWO_PI;
  4527. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4528. otherRectangleEast += CesiumMath.TWO_PI;
  4529. }
  4530. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4531. otherRectangleWest += CesiumMath.TWO_PI;
  4532. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4533. rectangleWest += CesiumMath.TWO_PI;
  4534. }
  4535. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  4536. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  4537. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  4538. return undefined;
  4539. }
  4540. var south = Math.max(rectangle.south, otherRectangle.south);
  4541. var north = Math.min(rectangle.north, otherRectangle.north);
  4542. if (south >= north) {
  4543. return undefined;
  4544. }
  4545. if (!defined(result)) {
  4546. return new Rectangle(west, south, east, north);
  4547. }
  4548. result.west = west;
  4549. result.south = south;
  4550. result.east = east;
  4551. result.north = north;
  4552. return result;
  4553. };
  4554. /**
  4555. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  4556. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  4557. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  4558. * and longitude (i.e. projected coordinates).
  4559. *
  4560. * @param {Rectangle} rectangle On rectangle to find an intersection
  4561. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4562. * @param {Rectangle} [result] The object onto which to store the result.
  4563. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4564. */
  4565. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  4566. if (!defined(rectangle)) {
  4567. throw new DeveloperError('rectangle is required');
  4568. }
  4569. if (!defined(otherRectangle)) {
  4570. throw new DeveloperError('otherRectangle is required.');
  4571. }
  4572. var west = Math.max(rectangle.west, otherRectangle.west);
  4573. var south = Math.max(rectangle.south, otherRectangle.south);
  4574. var east = Math.min(rectangle.east, otherRectangle.east);
  4575. var north = Math.min(rectangle.north, otherRectangle.north);
  4576. if (south >= north || west >= east) {
  4577. return undefined;
  4578. }
  4579. if (!defined(result)) {
  4580. return new Rectangle(west, south, east, north);
  4581. }
  4582. result.west = west;
  4583. result.south = south;
  4584. result.east = east;
  4585. result.north = north;
  4586. return result;
  4587. };
  4588. /**
  4589. * Computes a rectangle that is the union of two rectangles.
  4590. *
  4591. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  4592. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  4593. * @param {Rectangle} [result] The object onto which to store the result.
  4594. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4595. */
  4596. Rectangle.union = function(rectangle, otherRectangle, result) {
  4597. if (!defined(rectangle)) {
  4598. throw new DeveloperError('rectangle is required');
  4599. }
  4600. if (!defined(otherRectangle)) {
  4601. throw new DeveloperError('otherRectangle is required.');
  4602. }
  4603. if (!defined(result)) {
  4604. result = new Rectangle();
  4605. }
  4606. var rectangleEast = rectangle.east;
  4607. var rectangleWest = rectangle.west;
  4608. var otherRectangleEast = otherRectangle.east;
  4609. var otherRectangleWest = otherRectangle.west;
  4610. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4611. rectangleEast += CesiumMath.TWO_PI;
  4612. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4613. otherRectangleEast += CesiumMath.TWO_PI;
  4614. }
  4615. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4616. otherRectangleWest += CesiumMath.TWO_PI;
  4617. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4618. rectangleWest += CesiumMath.TWO_PI;
  4619. }
  4620. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  4621. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  4622. result.west = west;
  4623. result.south = Math.min(rectangle.south, otherRectangle.south);
  4624. result.east = east;
  4625. result.north = Math.max(rectangle.north, otherRectangle.north);
  4626. return result;
  4627. };
  4628. /**
  4629. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  4630. *
  4631. * @param {Rectangle} rectangle A rectangle to expand.
  4632. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  4633. * @param {Rectangle} [result] The object onto which to store the result.
  4634. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4635. */
  4636. Rectangle.expand = function(rectangle, cartographic, result) {
  4637. if (!defined(rectangle)) {
  4638. throw new DeveloperError('rectangle is required.');
  4639. }
  4640. if (!defined(cartographic)) {
  4641. throw new DeveloperError('cartographic is required.');
  4642. }
  4643. if (!defined(result)) {
  4644. result = new Rectangle();
  4645. }
  4646. result.west = Math.min(rectangle.west, cartographic.longitude);
  4647. result.south = Math.min(rectangle.south, cartographic.latitude);
  4648. result.east = Math.max(rectangle.east, cartographic.longitude);
  4649. result.north = Math.max(rectangle.north, cartographic.latitude);
  4650. return result;
  4651. };
  4652. /**
  4653. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  4654. *
  4655. * @param {Rectangle} rectangle The rectangle
  4656. * @param {Cartographic} cartographic The cartographic to test.
  4657. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  4658. */
  4659. Rectangle.contains = function(rectangle, cartographic) {
  4660. if (!defined(rectangle)) {
  4661. throw new DeveloperError('rectangle is required');
  4662. }
  4663. if (!defined(cartographic)) {
  4664. throw new DeveloperError('cartographic is required.');
  4665. }
  4666. var longitude = cartographic.longitude;
  4667. var latitude = cartographic.latitude;
  4668. var west = rectangle.west;
  4669. var east = rectangle.east;
  4670. if (east < west) {
  4671. east += CesiumMath.TWO_PI;
  4672. if (longitude < 0.0) {
  4673. longitude += CesiumMath.TWO_PI;
  4674. }
  4675. }
  4676. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  4677. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  4678. latitude >= rectangle.south &&
  4679. latitude <= rectangle.north;
  4680. };
  4681. var subsampleLlaScratch = new Cartographic();
  4682. /**
  4683. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  4684. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  4685. * for rectangles that cover the poles or cross the equator.
  4686. *
  4687. * @param {Rectangle} rectangle The rectangle to subsample.
  4688. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  4689. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  4690. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  4691. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  4692. */
  4693. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  4694. if (!defined(rectangle)) {
  4695. throw new DeveloperError('rectangle is required');
  4696. }
  4697. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  4698. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  4699. if (!defined(result)) {
  4700. result = [];
  4701. }
  4702. var length = 0;
  4703. var north = rectangle.north;
  4704. var south = rectangle.south;
  4705. var east = rectangle.east;
  4706. var west = rectangle.west;
  4707. var lla = subsampleLlaScratch;
  4708. lla.height = surfaceHeight;
  4709. lla.longitude = west;
  4710. lla.latitude = north;
  4711. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4712. length++;
  4713. lla.longitude = east;
  4714. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4715. length++;
  4716. lla.latitude = south;
  4717. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4718. length++;
  4719. lla.longitude = west;
  4720. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4721. length++;
  4722. if (north < 0.0) {
  4723. lla.latitude = north;
  4724. } else if (south > 0.0) {
  4725. lla.latitude = south;
  4726. } else {
  4727. lla.latitude = 0.0;
  4728. }
  4729. for ( var i = 1; i < 8; ++i) {
  4730. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  4731. if (Rectangle.contains(rectangle, lla)) {
  4732. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4733. length++;
  4734. }
  4735. }
  4736. if (lla.latitude === 0.0) {
  4737. lla.longitude = west;
  4738. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4739. length++;
  4740. lla.longitude = east;
  4741. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4742. length++;
  4743. }
  4744. result.length = length;
  4745. return result;
  4746. };
  4747. /**
  4748. * The largest possible rectangle.
  4749. *
  4750. * @type {Rectangle}
  4751. * @constant
  4752. */
  4753. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  4754. return Rectangle;
  4755. });
  4756. /*global define*/
  4757. define('Core/BoundingRectangle',[
  4758. './Cartesian2',
  4759. './Cartographic',
  4760. './defaultValue',
  4761. './defined',
  4762. './DeveloperError',
  4763. './GeographicProjection',
  4764. './Intersect',
  4765. './Rectangle'
  4766. ], function(
  4767. Cartesian2,
  4768. Cartographic,
  4769. defaultValue,
  4770. defined,
  4771. DeveloperError,
  4772. GeographicProjection,
  4773. Intersect,
  4774. Rectangle) {
  4775. 'use strict';
  4776. /**
  4777. * A bounding rectangle given by a corner, width and height.
  4778. * @alias BoundingRectangle
  4779. * @constructor
  4780. *
  4781. * @param {Number} [x=0.0] The x coordinate of the rectangle.
  4782. * @param {Number} [y=0.0] The y coordinate of the rectangle.
  4783. * @param {Number} [width=0.0] The width of the rectangle.
  4784. * @param {Number} [height=0.0] The height of the rectangle.
  4785. *
  4786. * @see BoundingSphere
  4787. * @see Packable
  4788. */
  4789. function BoundingRectangle(x, y, width, height) {
  4790. /**
  4791. * The x coordinate of the rectangle.
  4792. * @type {Number}
  4793. * @default 0.0
  4794. */
  4795. this.x = defaultValue(x, 0.0);
  4796. /**
  4797. * The y coordinate of the rectangle.
  4798. * @type {Number}
  4799. * @default 0.0
  4800. */
  4801. this.y = defaultValue(y, 0.0);
  4802. /**
  4803. * The width of the rectangle.
  4804. * @type {Number}
  4805. * @default 0.0
  4806. */
  4807. this.width = defaultValue(width, 0.0);
  4808. /**
  4809. * The height of the rectangle.
  4810. * @type {Number}
  4811. * @default 0.0
  4812. */
  4813. this.height = defaultValue(height, 0.0);
  4814. }
  4815. /**
  4816. * The number of elements used to pack the object into an array.
  4817. * @type {Number}
  4818. */
  4819. BoundingRectangle.packedLength = 4;
  4820. /**
  4821. * Stores the provided instance into the provided array.
  4822. *
  4823. * @param {BoundingRectangle} value The value to pack.
  4824. * @param {Number[]} array The array to pack into.
  4825. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4826. *
  4827. * @returns {Number[]} The array that was packed into
  4828. */
  4829. BoundingRectangle.pack = function(value, array, startingIndex) {
  4830. if (!defined(value)) {
  4831. throw new DeveloperError('value is required');
  4832. }
  4833. if (!defined(array)) {
  4834. throw new DeveloperError('array is required');
  4835. }
  4836. startingIndex = defaultValue(startingIndex, 0);
  4837. array[startingIndex++] = value.x;
  4838. array[startingIndex++] = value.y;
  4839. array[startingIndex++] = value.width;
  4840. array[startingIndex] = value.height;
  4841. return array;
  4842. };
  4843. /**
  4844. * Retrieves an instance from a packed array.
  4845. *
  4846. * @param {Number[]} array The packed array.
  4847. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4848. * @param {BoundingRectangle} [result] The object into which to store the result.
  4849. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4850. */
  4851. BoundingRectangle.unpack = function(array, startingIndex, result) {
  4852. if (!defined(array)) {
  4853. throw new DeveloperError('array is required');
  4854. }
  4855. startingIndex = defaultValue(startingIndex, 0);
  4856. if (!defined(result)) {
  4857. result = new BoundingRectangle();
  4858. }
  4859. result.x = array[startingIndex++];
  4860. result.y = array[startingIndex++];
  4861. result.width = array[startingIndex++];
  4862. result.height = array[startingIndex];
  4863. return result;
  4864. };
  4865. /**
  4866. * Computes a bounding rectangle enclosing the list of 2D points.
  4867. * The rectangle is oriented with the corner at the bottom left.
  4868. *
  4869. * @param {Cartesian2[]} positions List of points that the bounding rectangle will enclose. Each point must have <code>x</code> and <code>y</code> properties.
  4870. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4871. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4872. */
  4873. BoundingRectangle.fromPoints = function(positions, result) {
  4874. if (!defined(result)) {
  4875. result = new BoundingRectangle();
  4876. }
  4877. if (!defined(positions) || positions.length === 0) {
  4878. result.x = 0;
  4879. result.y = 0;
  4880. result.width = 0;
  4881. result.height = 0;
  4882. return result;
  4883. }
  4884. var length = positions.length;
  4885. var minimumX = positions[0].x;
  4886. var minimumY = positions[0].y;
  4887. var maximumX = positions[0].x;
  4888. var maximumY = positions[0].y;
  4889. for ( var i = 1; i < length; i++) {
  4890. var p = positions[i];
  4891. var x = p.x;
  4892. var y = p.y;
  4893. minimumX = Math.min(x, minimumX);
  4894. maximumX = Math.max(x, maximumX);
  4895. minimumY = Math.min(y, minimumY);
  4896. maximumY = Math.max(y, maximumY);
  4897. }
  4898. result.x = minimumX;
  4899. result.y = minimumY;
  4900. result.width = maximumX - minimumX;
  4901. result.height = maximumY - minimumY;
  4902. return result;
  4903. };
  4904. var defaultProjection = new GeographicProjection();
  4905. var fromRectangleLowerLeft = new Cartographic();
  4906. var fromRectangleUpperRight = new Cartographic();
  4907. /**
  4908. * Computes a bounding rectangle from an rectangle.
  4909. *
  4910. * @param {Rectangle} rectangle The valid rectangle used to create a bounding rectangle.
  4911. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  4912. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4913. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4914. */
  4915. BoundingRectangle.fromRectangle = function(rectangle, projection, result) {
  4916. if (!defined(result)) {
  4917. result = new BoundingRectangle();
  4918. }
  4919. if (!defined(rectangle)) {
  4920. result.x = 0;
  4921. result.y = 0;
  4922. result.width = 0;
  4923. result.height = 0;
  4924. return result;
  4925. }
  4926. projection = defaultValue(projection, defaultProjection);
  4927. var lowerLeft = projection.project(Rectangle.southwest(rectangle, fromRectangleLowerLeft));
  4928. var upperRight = projection.project(Rectangle.northeast(rectangle, fromRectangleUpperRight));
  4929. Cartesian2.subtract(upperRight, lowerLeft, upperRight);
  4930. result.x = lowerLeft.x;
  4931. result.y = lowerLeft.y;
  4932. result.width = upperRight.x;
  4933. result.height = upperRight.y;
  4934. return result;
  4935. };
  4936. /**
  4937. * Duplicates a BoundingRectangle instance.
  4938. *
  4939. * @param {BoundingRectangle} rectangle The bounding rectangle to duplicate.
  4940. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4941. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. (Returns undefined if rectangle is undefined)
  4942. */
  4943. BoundingRectangle.clone = function(rectangle, result) {
  4944. if (!defined(rectangle)) {
  4945. return undefined;
  4946. }
  4947. if (!defined(result)) {
  4948. return new BoundingRectangle(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
  4949. }
  4950. result.x = rectangle.x;
  4951. result.y = rectangle.y;
  4952. result.width = rectangle.width;
  4953. result.height = rectangle.height;
  4954. return result;
  4955. };
  4956. /**
  4957. * Computes a bounding rectangle that is the union of the left and right bounding rectangles.
  4958. *
  4959. * @param {BoundingRectangle} left A rectangle to enclose in bounding rectangle.
  4960. * @param {BoundingRectangle} right A rectangle to enclose in a bounding rectangle.
  4961. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4962. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4963. */
  4964. BoundingRectangle.union = function(left, right, result) {
  4965. if (!defined(left)) {
  4966. throw new DeveloperError('left is required.');
  4967. }
  4968. if (!defined(right)) {
  4969. throw new DeveloperError('right is required.');
  4970. }
  4971. if (!defined(result)) {
  4972. result = new BoundingRectangle();
  4973. }
  4974. var lowerLeftX = Math.min(left.x, right.x);
  4975. var lowerLeftY = Math.min(left.y, right.y);
  4976. var upperRightX = Math.max(left.x + left.width, right.x + right.width);
  4977. var upperRightY = Math.max(left.y + left.height, right.y + right.height);
  4978. result.x = lowerLeftX;
  4979. result.y = lowerLeftY;
  4980. result.width = upperRightX - lowerLeftX;
  4981. result.height = upperRightY - lowerLeftY;
  4982. return result;
  4983. };
  4984. /**
  4985. * Computes a bounding rectangle by enlarging the provided rectangle until it contains the provided point.
  4986. *
  4987. * @param {BoundingRectangle} rectangle A rectangle to expand.
  4988. * @param {Cartesian2} point A point to enclose in a bounding rectangle.
  4989. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4990. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4991. */
  4992. BoundingRectangle.expand = function(rectangle, point, result) {
  4993. if (!defined(rectangle)) {
  4994. throw new DeveloperError('rectangle is required.');
  4995. }
  4996. if (!defined(point)) {
  4997. throw new DeveloperError('point is required.');
  4998. }
  4999. result = BoundingRectangle.clone(rectangle, result);
  5000. var width = point.x - result.x;
  5001. var height = point.y - result.y;
  5002. if (width > result.width) {
  5003. result.width = width;
  5004. } else if (width < 0) {
  5005. result.width -= width;
  5006. result.x = point.x;
  5007. }
  5008. if (height > result.height) {
  5009. result.height = height;
  5010. } else if (height < 0) {
  5011. result.height -= height;
  5012. result.y = point.y;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Determines if two rectangles intersect.
  5018. *
  5019. * @param {BoundingRectangle} left A rectangle to check for intersection.
  5020. * @param {BoundingRectangle} right The other rectangle to check for intersection.
  5021. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  5022. */
  5023. BoundingRectangle.intersect = function(left, right) {
  5024. if (!defined(left)) {
  5025. throw new DeveloperError('left is required.');
  5026. }
  5027. if (!defined(right)) {
  5028. throw new DeveloperError('right is required.');
  5029. }
  5030. var leftX = left.x;
  5031. var leftY = left.y;
  5032. var rightX = right.x;
  5033. var rightY = right.y;
  5034. if (!(leftX > rightX + right.width ||
  5035. leftX + left.width < rightX ||
  5036. leftY + left.height < rightY ||
  5037. leftY > rightY + right.height)) {
  5038. return Intersect.INTERSECTING;
  5039. }
  5040. return Intersect.OUTSIDE;
  5041. };
  5042. /**
  5043. * Compares the provided BoundingRectangles componentwise and returns
  5044. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5045. *
  5046. * @param {BoundingRectangle} [left] The first BoundingRectangle.
  5047. * @param {BoundingRectangle} [right] The second BoundingRectangle.
  5048. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5049. */
  5050. BoundingRectangle.equals = function(left, right) {
  5051. return (left === right) ||
  5052. ((defined(left)) &&
  5053. (defined(right)) &&
  5054. (left.x === right.x) &&
  5055. (left.y === right.y) &&
  5056. (left.width === right.width) &&
  5057. (left.height === right.height));
  5058. };
  5059. /**
  5060. * Duplicates this BoundingRectangle instance.
  5061. *
  5062. * @param {BoundingRectangle} [result] The object onto which to store the result.
  5063. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  5064. */
  5065. BoundingRectangle.prototype.clone = function(result) {
  5066. return BoundingRectangle.clone(this, result);
  5067. };
  5068. /**
  5069. * Determines if this rectangle intersects with another.
  5070. *
  5071. * @param {BoundingRectangle} right A rectangle to check for intersection.
  5072. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  5073. */
  5074. BoundingRectangle.prototype.intersect = function(right) {
  5075. return BoundingRectangle.intersect(this, right);
  5076. };
  5077. /**
  5078. * Compares this BoundingRectangle against the provided BoundingRectangle componentwise and returns
  5079. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5080. *
  5081. * @param {BoundingRectangle} [right] The right hand side BoundingRectangle.
  5082. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5083. */
  5084. BoundingRectangle.prototype.equals = function(right) {
  5085. return BoundingRectangle.equals(this, right);
  5086. };
  5087. return BoundingRectangle;
  5088. });
  5089. /*global define*/
  5090. define('Core/Interval',[
  5091. './defaultValue'
  5092. ], function(
  5093. defaultValue) {
  5094. 'use strict';
  5095. /**
  5096. * Represents the closed interval [start, stop].
  5097. * @alias Interval
  5098. * @constructor
  5099. *
  5100. * @param {Number} [start=0.0] The beginning of the interval.
  5101. * @param {Number} [stop=0.0] The end of the interval.
  5102. */
  5103. function Interval(start, stop) {
  5104. /**
  5105. * The beginning of the interval.
  5106. * @type {Number}
  5107. * @default 0.0
  5108. */
  5109. this.start = defaultValue(start, 0.0);
  5110. /**
  5111. * The end of the interval.
  5112. * @type {Number}
  5113. * @default 0.0
  5114. */
  5115. this.stop = defaultValue(stop, 0.0);
  5116. }
  5117. return Interval;
  5118. });
  5119. /*global define*/
  5120. define('Core/Matrix3',[
  5121. './Cartesian3',
  5122. './defaultValue',
  5123. './defined',
  5124. './defineProperties',
  5125. './DeveloperError',
  5126. './freezeObject',
  5127. './Math'
  5128. ], function(
  5129. Cartesian3,
  5130. defaultValue,
  5131. defined,
  5132. defineProperties,
  5133. DeveloperError,
  5134. freezeObject,
  5135. CesiumMath) {
  5136. 'use strict';
  5137. /**
  5138. * A 3x3 matrix, indexable as a column-major order array.
  5139. * Constructor parameters are in row-major order for code readability.
  5140. * @alias Matrix3
  5141. * @constructor
  5142. *
  5143. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5144. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5145. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5146. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5147. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5148. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5149. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5150. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5151. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5152. *
  5153. * @see Matrix3.fromColumnMajorArray
  5154. * @see Matrix3.fromRowMajorArray
  5155. * @see Matrix3.fromQuaternion
  5156. * @see Matrix3.fromScale
  5157. * @see Matrix3.fromUniformScale
  5158. * @see Matrix2
  5159. * @see Matrix4
  5160. */
  5161. function Matrix3(column0Row0, column1Row0, column2Row0,
  5162. column0Row1, column1Row1, column2Row1,
  5163. column0Row2, column1Row2, column2Row2) {
  5164. this[0] = defaultValue(column0Row0, 0.0);
  5165. this[1] = defaultValue(column0Row1, 0.0);
  5166. this[2] = defaultValue(column0Row2, 0.0);
  5167. this[3] = defaultValue(column1Row0, 0.0);
  5168. this[4] = defaultValue(column1Row1, 0.0);
  5169. this[5] = defaultValue(column1Row2, 0.0);
  5170. this[6] = defaultValue(column2Row0, 0.0);
  5171. this[7] = defaultValue(column2Row1, 0.0);
  5172. this[8] = defaultValue(column2Row2, 0.0);
  5173. }
  5174. /**
  5175. * The number of elements used to pack the object into an array.
  5176. * @type {Number}
  5177. */
  5178. Matrix3.packedLength = 9;
  5179. /**
  5180. * Stores the provided instance into the provided array.
  5181. *
  5182. * @param {Matrix3} value The value to pack.
  5183. * @param {Number[]} array The array to pack into.
  5184. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5185. *
  5186. * @returns {Number[]} The array that was packed into
  5187. */
  5188. Matrix3.pack = function(value, array, startingIndex) {
  5189. if (!defined(value)) {
  5190. throw new DeveloperError('value is required');
  5191. }
  5192. if (!defined(array)) {
  5193. throw new DeveloperError('array is required');
  5194. }
  5195. startingIndex = defaultValue(startingIndex, 0);
  5196. array[startingIndex++] = value[0];
  5197. array[startingIndex++] = value[1];
  5198. array[startingIndex++] = value[2];
  5199. array[startingIndex++] = value[3];
  5200. array[startingIndex++] = value[4];
  5201. array[startingIndex++] = value[5];
  5202. array[startingIndex++] = value[6];
  5203. array[startingIndex++] = value[7];
  5204. array[startingIndex++] = value[8];
  5205. return array;
  5206. };
  5207. /**
  5208. * Retrieves an instance from a packed array.
  5209. *
  5210. * @param {Number[]} array The packed array.
  5211. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5212. * @param {Matrix3} [result] The object into which to store the result.
  5213. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5214. */
  5215. Matrix3.unpack = function(array, startingIndex, result) {
  5216. if (!defined(array)) {
  5217. throw new DeveloperError('array is required');
  5218. }
  5219. startingIndex = defaultValue(startingIndex, 0);
  5220. if (!defined(result)) {
  5221. result = new Matrix3();
  5222. }
  5223. result[0] = array[startingIndex++];
  5224. result[1] = array[startingIndex++];
  5225. result[2] = array[startingIndex++];
  5226. result[3] = array[startingIndex++];
  5227. result[4] = array[startingIndex++];
  5228. result[5] = array[startingIndex++];
  5229. result[6] = array[startingIndex++];
  5230. result[7] = array[startingIndex++];
  5231. result[8] = array[startingIndex++];
  5232. return result;
  5233. };
  5234. /**
  5235. * Duplicates a Matrix3 instance.
  5236. *
  5237. * @param {Matrix3} matrix The matrix to duplicate.
  5238. * @param {Matrix3} [result] The object onto which to store the result.
  5239. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  5240. */
  5241. Matrix3.clone = function(values, result) {
  5242. if (!defined(values)) {
  5243. return undefined;
  5244. }
  5245. if (!defined(result)) {
  5246. return new Matrix3(values[0], values[3], values[6],
  5247. values[1], values[4], values[7],
  5248. values[2], values[5], values[8]);
  5249. }
  5250. result[0] = values[0];
  5251. result[1] = values[1];
  5252. result[2] = values[2];
  5253. result[3] = values[3];
  5254. result[4] = values[4];
  5255. result[5] = values[5];
  5256. result[6] = values[6];
  5257. result[7] = values[7];
  5258. result[8] = values[8];
  5259. return result;
  5260. };
  5261. /**
  5262. * Creates a Matrix3 from 9 consecutive elements in an array.
  5263. *
  5264. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5265. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5266. * @param {Matrix3} [result] The object onto which to store the result.
  5267. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5268. *
  5269. * @example
  5270. * // Create the Matrix3:
  5271. * // [1.0, 2.0, 3.0]
  5272. * // [1.0, 2.0, 3.0]
  5273. * // [1.0, 2.0, 3.0]
  5274. *
  5275. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5276. * var m = Cesium.Matrix3.fromArray(v);
  5277. *
  5278. * // Create same Matrix3 with using an offset into an array
  5279. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5280. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  5281. */
  5282. Matrix3.fromArray = function(array, startingIndex, result) {
  5283. if (!defined(array)) {
  5284. throw new DeveloperError('array is required');
  5285. }
  5286. startingIndex = defaultValue(startingIndex, 0);
  5287. if (!defined(result)) {
  5288. result = new Matrix3();
  5289. }
  5290. result[0] = array[startingIndex];
  5291. result[1] = array[startingIndex + 1];
  5292. result[2] = array[startingIndex + 2];
  5293. result[3] = array[startingIndex + 3];
  5294. result[4] = array[startingIndex + 4];
  5295. result[5] = array[startingIndex + 5];
  5296. result[6] = array[startingIndex + 6];
  5297. result[7] = array[startingIndex + 7];
  5298. result[8] = array[startingIndex + 8];
  5299. return result;
  5300. };
  5301. /**
  5302. * Creates a Matrix3 instance from a column-major order array.
  5303. *
  5304. * @param {Number[]} values The column-major order array.
  5305. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5306. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5307. */
  5308. Matrix3.fromColumnMajorArray = function(values, result) {
  5309. if (!defined(values)) {
  5310. throw new DeveloperError('values parameter is required');
  5311. }
  5312. return Matrix3.clone(values, result);
  5313. };
  5314. /**
  5315. * Creates a Matrix3 instance from a row-major order array.
  5316. * The resulting matrix will be in column-major order.
  5317. *
  5318. * @param {Number[]} values The row-major order array.
  5319. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5320. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5321. */
  5322. Matrix3.fromRowMajorArray = function(values, result) {
  5323. if (!defined(values)) {
  5324. throw new DeveloperError('values is required.');
  5325. }
  5326. if (!defined(result)) {
  5327. return new Matrix3(values[0], values[1], values[2],
  5328. values[3], values[4], values[5],
  5329. values[6], values[7], values[8]);
  5330. }
  5331. result[0] = values[0];
  5332. result[1] = values[3];
  5333. result[2] = values[6];
  5334. result[3] = values[1];
  5335. result[4] = values[4];
  5336. result[5] = values[7];
  5337. result[6] = values[2];
  5338. result[7] = values[5];
  5339. result[8] = values[8];
  5340. return result;
  5341. };
  5342. /**
  5343. * Computes a 3x3 rotation matrix from the provided quaternion.
  5344. *
  5345. * @param {Quaternion} quaternion the quaternion to use.
  5346. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5347. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  5348. */
  5349. Matrix3.fromQuaternion = function(quaternion, result) {
  5350. if (!defined(quaternion)) {
  5351. throw new DeveloperError('quaternion is required');
  5352. }
  5353. var x2 = quaternion.x * quaternion.x;
  5354. var xy = quaternion.x * quaternion.y;
  5355. var xz = quaternion.x * quaternion.z;
  5356. var xw = quaternion.x * quaternion.w;
  5357. var y2 = quaternion.y * quaternion.y;
  5358. var yz = quaternion.y * quaternion.z;
  5359. var yw = quaternion.y * quaternion.w;
  5360. var z2 = quaternion.z * quaternion.z;
  5361. var zw = quaternion.z * quaternion.w;
  5362. var w2 = quaternion.w * quaternion.w;
  5363. var m00 = x2 - y2 - z2 + w2;
  5364. var m01 = 2.0 * (xy - zw);
  5365. var m02 = 2.0 * (xz + yw);
  5366. var m10 = 2.0 * (xy + zw);
  5367. var m11 = -x2 + y2 - z2 + w2;
  5368. var m12 = 2.0 * (yz - xw);
  5369. var m20 = 2.0 * (xz - yw);
  5370. var m21 = 2.0 * (yz + xw);
  5371. var m22 = -x2 - y2 + z2 + w2;
  5372. if (!defined(result)) {
  5373. return new Matrix3(m00, m01, m02,
  5374. m10, m11, m12,
  5375. m20, m21, m22);
  5376. }
  5377. result[0] = m00;
  5378. result[1] = m10;
  5379. result[2] = m20;
  5380. result[3] = m01;
  5381. result[4] = m11;
  5382. result[5] = m21;
  5383. result[6] = m02;
  5384. result[7] = m12;
  5385. result[8] = m22;
  5386. return result;
  5387. };
  5388. /**
  5389. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  5390. *
  5391. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  5392. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5393. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  5394. */
  5395. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  5396. if (!defined(headingPitchRoll)) {
  5397. throw new DeveloperError('headingPitchRoll is required');
  5398. }
  5399. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  5400. var cosPsi = Math.cos(-headingPitchRoll.heading);
  5401. var cosPhi = Math.cos(headingPitchRoll.roll);
  5402. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  5403. var sinPsi = Math.sin(-headingPitchRoll.heading);
  5404. var sinPhi = Math.sin(headingPitchRoll.roll);
  5405. var m00 = cosTheta * cosPsi;
  5406. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  5407. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  5408. var m10 = cosTheta * sinPsi;
  5409. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  5410. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  5411. var m20 = -sinTheta;
  5412. var m21 = sinPhi * cosTheta;
  5413. var m22 = cosPhi * cosTheta;
  5414. if (!defined(result)) {
  5415. return new Matrix3(m00, m01, m02,
  5416. m10, m11, m12,
  5417. m20, m21, m22);
  5418. }
  5419. result[0] = m00;
  5420. result[1] = m10;
  5421. result[2] = m20;
  5422. result[3] = m01;
  5423. result[4] = m11;
  5424. result[5] = m21;
  5425. result[6] = m02;
  5426. result[7] = m12;
  5427. result[8] = m22;
  5428. return result;
  5429. };
  5430. /**
  5431. * Computes a Matrix3 instance representing a non-uniform scale.
  5432. *
  5433. * @param {Cartesian3} scale The x, y, and z scale factors.
  5434. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5435. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5436. *
  5437. * @example
  5438. * // Creates
  5439. * // [7.0, 0.0, 0.0]
  5440. * // [0.0, 8.0, 0.0]
  5441. * // [0.0, 0.0, 9.0]
  5442. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5443. */
  5444. Matrix3.fromScale = function(scale, result) {
  5445. if (!defined(scale)) {
  5446. throw new DeveloperError('scale is required.');
  5447. }
  5448. if (!defined(result)) {
  5449. return new Matrix3(
  5450. scale.x, 0.0, 0.0,
  5451. 0.0, scale.y, 0.0,
  5452. 0.0, 0.0, scale.z);
  5453. }
  5454. result[0] = scale.x;
  5455. result[1] = 0.0;
  5456. result[2] = 0.0;
  5457. result[3] = 0.0;
  5458. result[4] = scale.y;
  5459. result[5] = 0.0;
  5460. result[6] = 0.0;
  5461. result[7] = 0.0;
  5462. result[8] = scale.z;
  5463. return result;
  5464. };
  5465. /**
  5466. * Computes a Matrix3 instance representing a uniform scale.
  5467. *
  5468. * @param {Number} scale The uniform scale factor.
  5469. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5470. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5471. *
  5472. * @example
  5473. * // Creates
  5474. * // [2.0, 0.0, 0.0]
  5475. * // [0.0, 2.0, 0.0]
  5476. * // [0.0, 0.0, 2.0]
  5477. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  5478. */
  5479. Matrix3.fromUniformScale = function(scale, result) {
  5480. if (typeof scale !== 'number') {
  5481. throw new DeveloperError('scale is required.');
  5482. }
  5483. if (!defined(result)) {
  5484. return new Matrix3(
  5485. scale, 0.0, 0.0,
  5486. 0.0, scale, 0.0,
  5487. 0.0, 0.0, scale);
  5488. }
  5489. result[0] = scale;
  5490. result[1] = 0.0;
  5491. result[2] = 0.0;
  5492. result[3] = 0.0;
  5493. result[4] = scale;
  5494. result[5] = 0.0;
  5495. result[6] = 0.0;
  5496. result[7] = 0.0;
  5497. result[8] = scale;
  5498. return result;
  5499. };
  5500. /**
  5501. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  5502. *
  5503. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  5504. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5505. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5506. *
  5507. * @example
  5508. * // Creates
  5509. * // [0.0, -9.0, 8.0]
  5510. * // [9.0, 0.0, -7.0]
  5511. * // [-8.0, 7.0, 0.0]
  5512. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5513. */
  5514. Matrix3.fromCrossProduct = function(vector, result) {
  5515. if (!defined(vector)) {
  5516. throw new DeveloperError('vector is required.');
  5517. }
  5518. if (!defined(result)) {
  5519. return new Matrix3(
  5520. 0.0, -vector.z, vector.y,
  5521. vector.z, 0.0, -vector.x,
  5522. -vector.y, vector.x, 0.0);
  5523. }
  5524. result[0] = 0.0;
  5525. result[1] = vector.z;
  5526. result[2] = -vector.y;
  5527. result[3] = -vector.z;
  5528. result[4] = 0.0;
  5529. result[5] = vector.x;
  5530. result[6] = vector.y;
  5531. result[7] = -vector.x;
  5532. result[8] = 0.0;
  5533. return result;
  5534. };
  5535. /**
  5536. * Creates a rotation matrix around the x-axis.
  5537. *
  5538. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5539. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5540. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5541. *
  5542. * @example
  5543. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  5544. * var p = new Cesium.Cartesian3(5, 6, 7);
  5545. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  5546. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5547. */
  5548. Matrix3.fromRotationX = function(angle, result) {
  5549. if (!defined(angle)) {
  5550. throw new DeveloperError('angle is required.');
  5551. }
  5552. var cosAngle = Math.cos(angle);
  5553. var sinAngle = Math.sin(angle);
  5554. if (!defined(result)) {
  5555. return new Matrix3(
  5556. 1.0, 0.0, 0.0,
  5557. 0.0, cosAngle, -sinAngle,
  5558. 0.0, sinAngle, cosAngle);
  5559. }
  5560. result[0] = 1.0;
  5561. result[1] = 0.0;
  5562. result[2] = 0.0;
  5563. result[3] = 0.0;
  5564. result[4] = cosAngle;
  5565. result[5] = sinAngle;
  5566. result[6] = 0.0;
  5567. result[7] = -sinAngle;
  5568. result[8] = cosAngle;
  5569. return result;
  5570. };
  5571. /**
  5572. * Creates a rotation matrix around the y-axis.
  5573. *
  5574. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5575. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5576. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5577. *
  5578. * @example
  5579. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  5580. * var p = new Cesium.Cartesian3(5, 6, 7);
  5581. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  5582. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5583. */
  5584. Matrix3.fromRotationY = function(angle, result) {
  5585. if (!defined(angle)) {
  5586. throw new DeveloperError('angle is required.');
  5587. }
  5588. var cosAngle = Math.cos(angle);
  5589. var sinAngle = Math.sin(angle);
  5590. if (!defined(result)) {
  5591. return new Matrix3(
  5592. cosAngle, 0.0, sinAngle,
  5593. 0.0, 1.0, 0.0,
  5594. -sinAngle, 0.0, cosAngle);
  5595. }
  5596. result[0] = cosAngle;
  5597. result[1] = 0.0;
  5598. result[2] = -sinAngle;
  5599. result[3] = 0.0;
  5600. result[4] = 1.0;
  5601. result[5] = 0.0;
  5602. result[6] = sinAngle;
  5603. result[7] = 0.0;
  5604. result[8] = cosAngle;
  5605. return result;
  5606. };
  5607. /**
  5608. * Creates a rotation matrix around the z-axis.
  5609. *
  5610. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5611. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5612. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5613. *
  5614. * @example
  5615. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  5616. * var p = new Cesium.Cartesian3(5, 6, 7);
  5617. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  5618. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5619. */
  5620. Matrix3.fromRotationZ = function(angle, result) {
  5621. if (!defined(angle)) {
  5622. throw new DeveloperError('angle is required.');
  5623. }
  5624. var cosAngle = Math.cos(angle);
  5625. var sinAngle = Math.sin(angle);
  5626. if (!defined(result)) {
  5627. return new Matrix3(
  5628. cosAngle, -sinAngle, 0.0,
  5629. sinAngle, cosAngle, 0.0,
  5630. 0.0, 0.0, 1.0);
  5631. }
  5632. result[0] = cosAngle;
  5633. result[1] = sinAngle;
  5634. result[2] = 0.0;
  5635. result[3] = -sinAngle;
  5636. result[4] = cosAngle;
  5637. result[5] = 0.0;
  5638. result[6] = 0.0;
  5639. result[7] = 0.0;
  5640. result[8] = 1.0;
  5641. return result;
  5642. };
  5643. /**
  5644. * Creates an Array from the provided Matrix3 instance.
  5645. * The array will be in column-major order.
  5646. *
  5647. * @param {Matrix3} matrix The matrix to use..
  5648. * @param {Number[]} [result] The Array onto which to store the result.
  5649. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  5650. */
  5651. Matrix3.toArray = function(matrix, result) {
  5652. if (!defined(matrix)) {
  5653. throw new DeveloperError('matrix is required');
  5654. }
  5655. if (!defined(result)) {
  5656. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  5657. }
  5658. result[0] = matrix[0];
  5659. result[1] = matrix[1];
  5660. result[2] = matrix[2];
  5661. result[3] = matrix[3];
  5662. result[4] = matrix[4];
  5663. result[5] = matrix[5];
  5664. result[6] = matrix[6];
  5665. result[7] = matrix[7];
  5666. result[8] = matrix[8];
  5667. return result;
  5668. };
  5669. /**
  5670. * Computes the array index of the element at the provided row and column.
  5671. *
  5672. * @param {Number} row The zero-based index of the row.
  5673. * @param {Number} column The zero-based index of the column.
  5674. * @returns {Number} The index of the element at the provided row and column.
  5675. *
  5676. * @exception {DeveloperError} row must be 0, 1, or 2.
  5677. * @exception {DeveloperError} column must be 0, 1, or 2.
  5678. *
  5679. * @example
  5680. * var myMatrix = new Cesium.Matrix3();
  5681. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  5682. * var column1Row0 = myMatrix[column1Row0Index]
  5683. * myMatrix[column1Row0Index] = 10.0;
  5684. */
  5685. Matrix3.getElementIndex = function(column, row) {
  5686. if (typeof row !== 'number' || row < 0 || row > 2) {
  5687. throw new DeveloperError('row must be 0, 1, or 2.');
  5688. }
  5689. if (typeof column !== 'number' || column < 0 || column > 2) {
  5690. throw new DeveloperError('column must be 0, 1, or 2.');
  5691. }
  5692. return column * 3 + row;
  5693. };
  5694. /**
  5695. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  5696. *
  5697. * @param {Matrix3} matrix The matrix to use.
  5698. * @param {Number} index The zero-based index of the column to retrieve.
  5699. * @param {Cartesian3} result The object onto which to store the result.
  5700. * @returns {Cartesian3} The modified result parameter.
  5701. *
  5702. * @exception {DeveloperError} index must be 0, 1, or 2.
  5703. */
  5704. Matrix3.getColumn = function(matrix, index, result) {
  5705. if (!defined(matrix)) {
  5706. throw new DeveloperError('matrix is required.');
  5707. }
  5708. if (typeof index !== 'number' || index < 0 || index > 2) {
  5709. throw new DeveloperError('index must be 0, 1, or 2.');
  5710. }
  5711. if (!defined(result)) {
  5712. throw new DeveloperError('result is required');
  5713. }
  5714. var startIndex = index * 3;
  5715. var x = matrix[startIndex];
  5716. var y = matrix[startIndex + 1];
  5717. var z = matrix[startIndex + 2];
  5718. result.x = x;
  5719. result.y = y;
  5720. result.z = z;
  5721. return result;
  5722. };
  5723. /**
  5724. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  5725. *
  5726. * @param {Matrix3} matrix The matrix to use.
  5727. * @param {Number} index The zero-based index of the column to set.
  5728. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  5729. * @param {Matrix3} result The object onto which to store the result.
  5730. * @returns {Matrix3} The modified result parameter.
  5731. *
  5732. * @exception {DeveloperError} index must be 0, 1, or 2.
  5733. */
  5734. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  5735. if (!defined(matrix)) {
  5736. throw new DeveloperError('matrix is required');
  5737. }
  5738. if (!defined(cartesian)) {
  5739. throw new DeveloperError('cartesian is required');
  5740. }
  5741. if (typeof index !== 'number' || index < 0 || index > 2) {
  5742. throw new DeveloperError('index must be 0, 1, or 2.');
  5743. }
  5744. if (!defined(result)) {
  5745. throw new DeveloperError('result is required');
  5746. }
  5747. result = Matrix3.clone(matrix, result);
  5748. var startIndex = index * 3;
  5749. result[startIndex] = cartesian.x;
  5750. result[startIndex + 1] = cartesian.y;
  5751. result[startIndex + 2] = cartesian.z;
  5752. return result;
  5753. };
  5754. /**
  5755. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  5756. *
  5757. * @param {Matrix3} matrix The matrix to use.
  5758. * @param {Number} index The zero-based index of the row to retrieve.
  5759. * @param {Cartesian3} result The object onto which to store the result.
  5760. * @returns {Cartesian3} The modified result parameter.
  5761. *
  5762. * @exception {DeveloperError} index must be 0, 1, or 2.
  5763. */
  5764. Matrix3.getRow = function(matrix, index, result) {
  5765. if (!defined(matrix)) {
  5766. throw new DeveloperError('matrix is required.');
  5767. }
  5768. if (typeof index !== 'number' || index < 0 || index > 2) {
  5769. throw new DeveloperError('index must be 0, 1, or 2.');
  5770. }
  5771. if (!defined(result)) {
  5772. throw new DeveloperError('result is required');
  5773. }
  5774. var x = matrix[index];
  5775. var y = matrix[index + 3];
  5776. var z = matrix[index + 6];
  5777. result.x = x;
  5778. result.y = y;
  5779. result.z = z;
  5780. return result;
  5781. };
  5782. /**
  5783. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  5784. *
  5785. * @param {Matrix3} matrix The matrix to use.
  5786. * @param {Number} index The zero-based index of the row to set.
  5787. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  5788. * @param {Matrix3} result The object onto which to store the result.
  5789. * @returns {Matrix3} The modified result parameter.
  5790. *
  5791. * @exception {DeveloperError} index must be 0, 1, or 2.
  5792. */
  5793. Matrix3.setRow = function(matrix, index, cartesian, result) {
  5794. if (!defined(matrix)) {
  5795. throw new DeveloperError('matrix is required');
  5796. }
  5797. if (!defined(cartesian)) {
  5798. throw new DeveloperError('cartesian is required');
  5799. }
  5800. if (typeof index !== 'number' || index < 0 || index > 2) {
  5801. throw new DeveloperError('index must be 0, 1, or 2.');
  5802. }
  5803. if (!defined(result)) {
  5804. throw new DeveloperError('result is required');
  5805. }
  5806. result = Matrix3.clone(matrix, result);
  5807. result[index] = cartesian.x;
  5808. result[index + 3] = cartesian.y;
  5809. result[index + 6] = cartesian.z;
  5810. return result;
  5811. };
  5812. var scratchColumn = new Cartesian3();
  5813. /**
  5814. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  5815. *
  5816. * @param {Matrix3} matrix The matrix.
  5817. * @param {Cartesian3} result The object onto which to store the result.
  5818. * @returns {Cartesian3} The modified result parameter.
  5819. */
  5820. Matrix3.getScale = function(matrix, result) {
  5821. if (!defined(matrix)) {
  5822. throw new DeveloperError('matrix is required.');
  5823. }
  5824. if (!defined(result)) {
  5825. throw new DeveloperError('result is required');
  5826. }
  5827. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  5828. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  5829. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  5830. return result;
  5831. };
  5832. var scratchScale = new Cartesian3();
  5833. /**
  5834. * Computes the maximum scale assuming the matrix is an affine transformation.
  5835. * The maximum scale is the maximum length of the column vectors.
  5836. *
  5837. * @param {Matrix3} matrix The matrix.
  5838. * @returns {Number} The maximum scale.
  5839. */
  5840. Matrix3.getMaximumScale = function(matrix) {
  5841. Matrix3.getScale(matrix, scratchScale);
  5842. return Cartesian3.maximumComponent(scratchScale);
  5843. };
  5844. /**
  5845. * Computes the product of two matrices.
  5846. *
  5847. * @param {Matrix3} left The first matrix.
  5848. * @param {Matrix3} right The second matrix.
  5849. * @param {Matrix3} result The object onto which to store the result.
  5850. * @returns {Matrix3} The modified result parameter.
  5851. */
  5852. Matrix3.multiply = function(left, right, result) {
  5853. if (!defined(left)) {
  5854. throw new DeveloperError('left is required');
  5855. }
  5856. if (!defined(right)) {
  5857. throw new DeveloperError('right is required');
  5858. }
  5859. if (!defined(result)) {
  5860. throw new DeveloperError('result is required');
  5861. }
  5862. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  5863. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  5864. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  5865. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  5866. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  5867. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  5868. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  5869. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  5870. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  5871. result[0] = column0Row0;
  5872. result[1] = column0Row1;
  5873. result[2] = column0Row2;
  5874. result[3] = column1Row0;
  5875. result[4] = column1Row1;
  5876. result[5] = column1Row2;
  5877. result[6] = column2Row0;
  5878. result[7] = column2Row1;
  5879. result[8] = column2Row2;
  5880. return result;
  5881. };
  5882. /**
  5883. * Computes the sum of two matrices.
  5884. *
  5885. * @param {Matrix3} left The first matrix.
  5886. * @param {Matrix3} right The second matrix.
  5887. * @param {Matrix3} result The object onto which to store the result.
  5888. * @returns {Matrix3} The modified result parameter.
  5889. */
  5890. Matrix3.add = function(left, right, result) {
  5891. if (!defined(left)) {
  5892. throw new DeveloperError('left is required');
  5893. }
  5894. if (!defined(right)) {
  5895. throw new DeveloperError('right is required');
  5896. }
  5897. if (!defined(result)) {
  5898. throw new DeveloperError('result is required');
  5899. }
  5900. result[0] = left[0] + right[0];
  5901. result[1] = left[1] + right[1];
  5902. result[2] = left[2] + right[2];
  5903. result[3] = left[3] + right[3];
  5904. result[4] = left[4] + right[4];
  5905. result[5] = left[5] + right[5];
  5906. result[6] = left[6] + right[6];
  5907. result[7] = left[7] + right[7];
  5908. result[8] = left[8] + right[8];
  5909. return result;
  5910. };
  5911. /**
  5912. * Computes the difference of two matrices.
  5913. *
  5914. * @param {Matrix3} left The first matrix.
  5915. * @param {Matrix3} right The second matrix.
  5916. * @param {Matrix3} result The object onto which to store the result.
  5917. * @returns {Matrix3} The modified result parameter.
  5918. */
  5919. Matrix3.subtract = function(left, right, result) {
  5920. if (!defined(left)) {
  5921. throw new DeveloperError('left is required');
  5922. }
  5923. if (!defined(right)) {
  5924. throw new DeveloperError('right is required');
  5925. }
  5926. if (!defined(result)) {
  5927. throw new DeveloperError('result is required');
  5928. }
  5929. result[0] = left[0] - right[0];
  5930. result[1] = left[1] - right[1];
  5931. result[2] = left[2] - right[2];
  5932. result[3] = left[3] - right[3];
  5933. result[4] = left[4] - right[4];
  5934. result[5] = left[5] - right[5];
  5935. result[6] = left[6] - right[6];
  5936. result[7] = left[7] - right[7];
  5937. result[8] = left[8] - right[8];
  5938. return result;
  5939. };
  5940. /**
  5941. * Computes the product of a matrix and a column vector.
  5942. *
  5943. * @param {Matrix3} matrix The matrix.
  5944. * @param {Cartesian3} cartesian The column.
  5945. * @param {Cartesian3} result The object onto which to store the result.
  5946. * @returns {Cartesian3} The modified result parameter.
  5947. */
  5948. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  5949. if (!defined(matrix)) {
  5950. throw new DeveloperError('matrix is required');
  5951. }
  5952. if (!defined(cartesian)) {
  5953. throw new DeveloperError('cartesian is required');
  5954. }
  5955. if (!defined(result)) {
  5956. throw new DeveloperError('result is required');
  5957. }
  5958. var vX = cartesian.x;
  5959. var vY = cartesian.y;
  5960. var vZ = cartesian.z;
  5961. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  5962. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  5963. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  5964. result.x = x;
  5965. result.y = y;
  5966. result.z = z;
  5967. return result;
  5968. };
  5969. /**
  5970. * Computes the product of a matrix and a scalar.
  5971. *
  5972. * @param {Matrix3} matrix The matrix.
  5973. * @param {Number} scalar The number to multiply by.
  5974. * @param {Matrix3} result The object onto which to store the result.
  5975. * @returns {Matrix3} The modified result parameter.
  5976. */
  5977. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  5978. if (!defined(matrix)) {
  5979. throw new DeveloperError('matrix is required');
  5980. }
  5981. if (typeof scalar !== 'number') {
  5982. throw new DeveloperError('scalar must be a number');
  5983. }
  5984. if (!defined(result)) {
  5985. throw new DeveloperError('result is required');
  5986. }
  5987. result[0] = matrix[0] * scalar;
  5988. result[1] = matrix[1] * scalar;
  5989. result[2] = matrix[2] * scalar;
  5990. result[3] = matrix[3] * scalar;
  5991. result[4] = matrix[4] * scalar;
  5992. result[5] = matrix[5] * scalar;
  5993. result[6] = matrix[6] * scalar;
  5994. result[7] = matrix[7] * scalar;
  5995. result[8] = matrix[8] * scalar;
  5996. return result;
  5997. };
  5998. /**
  5999. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  6000. *
  6001. * @param {Matrix3} matrix The matrix on the left-hand side.
  6002. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  6003. * @param {Matrix3} result The object onto which to store the result.
  6004. * @returns {Matrix3} The modified result parameter.
  6005. *
  6006. *
  6007. * @example
  6008. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  6009. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  6010. *
  6011. * @see Matrix3.fromScale
  6012. * @see Matrix3.multiplyByUniformScale
  6013. */
  6014. Matrix3.multiplyByScale = function(matrix, scale, result) {
  6015. if (!defined(matrix)) {
  6016. throw new DeveloperError('matrix is required');
  6017. }
  6018. if (!defined(scale)) {
  6019. throw new DeveloperError('scale is required');
  6020. }
  6021. if (!defined(result)) {
  6022. throw new DeveloperError('result is required');
  6023. }
  6024. result[0] = matrix[0] * scale.x;
  6025. result[1] = matrix[1] * scale.x;
  6026. result[2] = matrix[2] * scale.x;
  6027. result[3] = matrix[3] * scale.y;
  6028. result[4] = matrix[4] * scale.y;
  6029. result[5] = matrix[5] * scale.y;
  6030. result[6] = matrix[6] * scale.z;
  6031. result[7] = matrix[7] * scale.z;
  6032. result[8] = matrix[8] * scale.z;
  6033. return result;
  6034. };
  6035. /**
  6036. * Creates a negated copy of the provided matrix.
  6037. *
  6038. * @param {Matrix3} matrix The matrix to negate.
  6039. * @param {Matrix3} result The object onto which to store the result.
  6040. * @returns {Matrix3} The modified result parameter.
  6041. */
  6042. Matrix3.negate = function(matrix, result) {
  6043. if (!defined(matrix)) {
  6044. throw new DeveloperError('matrix is required');
  6045. }
  6046. if (!defined(result)) {
  6047. throw new DeveloperError('result is required');
  6048. }
  6049. result[0] = -matrix[0];
  6050. result[1] = -matrix[1];
  6051. result[2] = -matrix[2];
  6052. result[3] = -matrix[3];
  6053. result[4] = -matrix[4];
  6054. result[5] = -matrix[5];
  6055. result[6] = -matrix[6];
  6056. result[7] = -matrix[7];
  6057. result[8] = -matrix[8];
  6058. return result;
  6059. };
  6060. /**
  6061. * Computes the transpose of the provided matrix.
  6062. *
  6063. * @param {Matrix3} matrix The matrix to transpose.
  6064. * @param {Matrix3} result The object onto which to store the result.
  6065. * @returns {Matrix3} The modified result parameter.
  6066. */
  6067. Matrix3.transpose = function(matrix, result) {
  6068. if (!defined(matrix)) {
  6069. throw new DeveloperError('matrix is required');
  6070. }
  6071. if (!defined(result)) {
  6072. throw new DeveloperError('result is required');
  6073. }
  6074. var column0Row0 = matrix[0];
  6075. var column0Row1 = matrix[3];
  6076. var column0Row2 = matrix[6];
  6077. var column1Row0 = matrix[1];
  6078. var column1Row1 = matrix[4];
  6079. var column1Row2 = matrix[7];
  6080. var column2Row0 = matrix[2];
  6081. var column2Row1 = matrix[5];
  6082. var column2Row2 = matrix[8];
  6083. result[0] = column0Row0;
  6084. result[1] = column0Row1;
  6085. result[2] = column0Row2;
  6086. result[3] = column1Row0;
  6087. result[4] = column1Row1;
  6088. result[5] = column1Row2;
  6089. result[6] = column2Row0;
  6090. result[7] = column2Row1;
  6091. result[8] = column2Row2;
  6092. return result;
  6093. };
  6094. function computeFrobeniusNorm(matrix) {
  6095. var norm = 0.0;
  6096. for (var i = 0; i < 9; ++i) {
  6097. var temp = matrix[i];
  6098. norm += temp * temp;
  6099. }
  6100. return Math.sqrt(norm);
  6101. }
  6102. var rowVal = [1, 0, 0];
  6103. var colVal = [2, 2, 1];
  6104. function offDiagonalFrobeniusNorm(matrix) {
  6105. // Computes the "off-diagonal" Frobenius norm.
  6106. // Assumes matrix is symmetric.
  6107. var norm = 0.0;
  6108. for (var i = 0; i < 3; ++i) {
  6109. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  6110. norm += 2.0 * temp * temp;
  6111. }
  6112. return Math.sqrt(norm);
  6113. }
  6114. function shurDecomposition(matrix, result) {
  6115. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6116. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  6117. //
  6118. // The routine takes a matrix, which is assumed to be symmetric, and
  6119. // finds the largest off-diagonal term, and then creates
  6120. // a matrix (result) which can be used to help reduce it
  6121. var tolerance = CesiumMath.EPSILON15;
  6122. var maxDiagonal = 0.0;
  6123. var rotAxis = 1;
  6124. // find pivot (rotAxis) based on max diagonal of matrix
  6125. for (var i = 0; i < 3; ++i) {
  6126. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  6127. if (temp > maxDiagonal) {
  6128. rotAxis = i;
  6129. maxDiagonal = temp;
  6130. }
  6131. }
  6132. var c = 1.0;
  6133. var s = 0.0;
  6134. var p = rowVal[rotAxis];
  6135. var q = colVal[rotAxis];
  6136. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  6137. var qq = matrix[Matrix3.getElementIndex(q, q)];
  6138. var pp = matrix[Matrix3.getElementIndex(p, p)];
  6139. var qp = matrix[Matrix3.getElementIndex(q, p)];
  6140. var tau = (qq - pp) / 2.0 / qp;
  6141. var t;
  6142. if (tau < 0.0) {
  6143. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  6144. } else {
  6145. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  6146. }
  6147. c = 1.0 / Math.sqrt(1.0 + t * t);
  6148. s = t * c;
  6149. }
  6150. result = Matrix3.clone(Matrix3.IDENTITY, result);
  6151. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  6152. result[Matrix3.getElementIndex(q, p)] = s;
  6153. result[Matrix3.getElementIndex(p, q)] = -s;
  6154. return result;
  6155. }
  6156. var jMatrix = new Matrix3();
  6157. var jMatrixTranspose = new Matrix3();
  6158. /**
  6159. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  6160. * <p>
  6161. * Returns a diagonal matrix and unitary matrix such that:
  6162. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  6163. * </p>
  6164. * <p>
  6165. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  6166. * of the unitary matrix are the corresponding eigenvectors.
  6167. * </p>
  6168. *
  6169. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  6170. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  6171. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  6172. *
  6173. * @example
  6174. * var a = //... symetric matrix
  6175. * var result = {
  6176. * unitary : new Cesium.Matrix3(),
  6177. * diagonal : new Cesium.Matrix3()
  6178. * };
  6179. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  6180. *
  6181. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  6182. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  6183. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  6184. *
  6185. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  6186. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  6187. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  6188. */
  6189. Matrix3.computeEigenDecomposition = function(matrix, result) {
  6190. if (!defined(matrix)) {
  6191. throw new DeveloperError('matrix is required.');
  6192. }
  6193. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6194. // section 8.4.3 The Classical Jacobi Algorithm
  6195. var tolerance = CesiumMath.EPSILON20;
  6196. var maxSweeps = 10;
  6197. var count = 0;
  6198. var sweep = 0;
  6199. if (!defined(result)) {
  6200. result = {};
  6201. }
  6202. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  6203. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  6204. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  6205. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  6206. shurDecomposition(diagMatrix, jMatrix);
  6207. Matrix3.transpose(jMatrix, jMatrixTranspose);
  6208. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  6209. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  6210. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  6211. if (++count > 2) {
  6212. ++sweep;
  6213. count = 0;
  6214. }
  6215. }
  6216. return result;
  6217. };
  6218. /**
  6219. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  6220. *
  6221. * @param {Matrix3} matrix The matrix with signed elements.
  6222. * @param {Matrix3} result The object onto which to store the result.
  6223. * @returns {Matrix3} The modified result parameter.
  6224. */
  6225. Matrix3.abs = function(matrix, result) {
  6226. if (!defined(matrix)) {
  6227. throw new DeveloperError('matrix is required');
  6228. }
  6229. if (!defined(result)) {
  6230. throw new DeveloperError('result is required');
  6231. }
  6232. result[0] = Math.abs(matrix[0]);
  6233. result[1] = Math.abs(matrix[1]);
  6234. result[2] = Math.abs(matrix[2]);
  6235. result[3] = Math.abs(matrix[3]);
  6236. result[4] = Math.abs(matrix[4]);
  6237. result[5] = Math.abs(matrix[5]);
  6238. result[6] = Math.abs(matrix[6]);
  6239. result[7] = Math.abs(matrix[7]);
  6240. result[8] = Math.abs(matrix[8]);
  6241. return result;
  6242. };
  6243. /**
  6244. * Computes the determinant of the provided matrix.
  6245. *
  6246. * @param {Matrix3} matrix The matrix to use.
  6247. * @returns {Number} The value of the determinant of the matrix.
  6248. */
  6249. Matrix3.determinant = function(matrix) {
  6250. if (!defined(matrix)) {
  6251. throw new DeveloperError('matrix is required');
  6252. }
  6253. var m11 = matrix[0];
  6254. var m21 = matrix[3];
  6255. var m31 = matrix[6];
  6256. var m12 = matrix[1];
  6257. var m22 = matrix[4];
  6258. var m32 = matrix[7];
  6259. var m13 = matrix[2];
  6260. var m23 = matrix[5];
  6261. var m33 = matrix[8];
  6262. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  6263. };
  6264. /**
  6265. * Computes the inverse of the provided matrix.
  6266. *
  6267. * @param {Matrix3} matrix The matrix to invert.
  6268. * @param {Matrix3} result The object onto which to store the result.
  6269. * @returns {Matrix3} The modified result parameter.
  6270. *
  6271. * @exception {DeveloperError} matrix is not invertible.
  6272. */
  6273. Matrix3.inverse = function(matrix, result) {
  6274. if (!defined(matrix)) {
  6275. throw new DeveloperError('matrix is required');
  6276. }
  6277. if (!defined(result)) {
  6278. throw new DeveloperError('result is required');
  6279. }
  6280. var m11 = matrix[0];
  6281. var m21 = matrix[1];
  6282. var m31 = matrix[2];
  6283. var m12 = matrix[3];
  6284. var m22 = matrix[4];
  6285. var m32 = matrix[5];
  6286. var m13 = matrix[6];
  6287. var m23 = matrix[7];
  6288. var m33 = matrix[8];
  6289. var determinant = Matrix3.determinant(matrix);
  6290. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  6291. throw new DeveloperError('matrix is not invertible');
  6292. }
  6293. result[0] = m22 * m33 - m23 * m32;
  6294. result[1] = m23 * m31 - m21 * m33;
  6295. result[2] = m21 * m32 - m22 * m31;
  6296. result[3] = m13 * m32 - m12 * m33;
  6297. result[4] = m11 * m33 - m13 * m31;
  6298. result[5] = m12 * m31 - m11 * m32;
  6299. result[6] = m12 * m23 - m13 * m22;
  6300. result[7] = m13 * m21 - m11 * m23;
  6301. result[8] = m11 * m22 - m12 * m21;
  6302. var scale = 1.0 / determinant;
  6303. return Matrix3.multiplyByScalar(result, scale, result);
  6304. };
  6305. /**
  6306. * Compares the provided matrices componentwise and returns
  6307. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6308. *
  6309. * @param {Matrix3} [left] The first matrix.
  6310. * @param {Matrix3} [right] The second matrix.
  6311. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  6312. */
  6313. Matrix3.equals = function(left, right) {
  6314. return (left === right) ||
  6315. (defined(left) &&
  6316. defined(right) &&
  6317. left[0] === right[0] &&
  6318. left[1] === right[1] &&
  6319. left[2] === right[2] &&
  6320. left[3] === right[3] &&
  6321. left[4] === right[4] &&
  6322. left[5] === right[5] &&
  6323. left[6] === right[6] &&
  6324. left[7] === right[7] &&
  6325. left[8] === right[8]);
  6326. };
  6327. /**
  6328. * Compares the provided matrices componentwise and returns
  6329. * <code>true</code> if they are within the provided epsilon,
  6330. * <code>false</code> otherwise.
  6331. *
  6332. * @param {Matrix3} [left] The first matrix.
  6333. * @param {Matrix3} [right] The second matrix.
  6334. * @param {Number} epsilon The epsilon to use for equality testing.
  6335. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  6336. */
  6337. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  6338. if (typeof epsilon !== 'number') {
  6339. throw new DeveloperError('epsilon must be a number');
  6340. }
  6341. return (left === right) ||
  6342. (defined(left) &&
  6343. defined(right) &&
  6344. Math.abs(left[0] - right[0]) <= epsilon &&
  6345. Math.abs(left[1] - right[1]) <= epsilon &&
  6346. Math.abs(left[2] - right[2]) <= epsilon &&
  6347. Math.abs(left[3] - right[3]) <= epsilon &&
  6348. Math.abs(left[4] - right[4]) <= epsilon &&
  6349. Math.abs(left[5] - right[5]) <= epsilon &&
  6350. Math.abs(left[6] - right[6]) <= epsilon &&
  6351. Math.abs(left[7] - right[7]) <= epsilon &&
  6352. Math.abs(left[8] - right[8]) <= epsilon);
  6353. };
  6354. /**
  6355. * An immutable Matrix3 instance initialized to the identity matrix.
  6356. *
  6357. * @type {Matrix3}
  6358. * @constant
  6359. */
  6360. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  6361. 0.0, 1.0, 0.0,
  6362. 0.0, 0.0, 1.0));
  6363. /**
  6364. * An immutable Matrix3 instance initialized to the zero matrix.
  6365. *
  6366. * @type {Matrix3}
  6367. * @constant
  6368. */
  6369. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  6370. 0.0, 0.0, 0.0,
  6371. 0.0, 0.0, 0.0));
  6372. /**
  6373. * The index into Matrix3 for column 0, row 0.
  6374. *
  6375. * @type {Number}
  6376. * @constant
  6377. */
  6378. Matrix3.COLUMN0ROW0 = 0;
  6379. /**
  6380. * The index into Matrix3 for column 0, row 1.
  6381. *
  6382. * @type {Number}
  6383. * @constant
  6384. */
  6385. Matrix3.COLUMN0ROW1 = 1;
  6386. /**
  6387. * The index into Matrix3 for column 0, row 2.
  6388. *
  6389. * @type {Number}
  6390. * @constant
  6391. */
  6392. Matrix3.COLUMN0ROW2 = 2;
  6393. /**
  6394. * The index into Matrix3 for column 1, row 0.
  6395. *
  6396. * @type {Number}
  6397. * @constant
  6398. */
  6399. Matrix3.COLUMN1ROW0 = 3;
  6400. /**
  6401. * The index into Matrix3 for column 1, row 1.
  6402. *
  6403. * @type {Number}
  6404. * @constant
  6405. */
  6406. Matrix3.COLUMN1ROW1 = 4;
  6407. /**
  6408. * The index into Matrix3 for column 1, row 2.
  6409. *
  6410. * @type {Number}
  6411. * @constant
  6412. */
  6413. Matrix3.COLUMN1ROW2 = 5;
  6414. /**
  6415. * The index into Matrix3 for column 2, row 0.
  6416. *
  6417. * @type {Number}
  6418. * @constant
  6419. */
  6420. Matrix3.COLUMN2ROW0 = 6;
  6421. /**
  6422. * The index into Matrix3 for column 2, row 1.
  6423. *
  6424. * @type {Number}
  6425. * @constant
  6426. */
  6427. Matrix3.COLUMN2ROW1 = 7;
  6428. /**
  6429. * The index into Matrix3 for column 2, row 2.
  6430. *
  6431. * @type {Number}
  6432. * @constant
  6433. */
  6434. Matrix3.COLUMN2ROW2 = 8;
  6435. defineProperties(Matrix3.prototype, {
  6436. /**
  6437. * Gets the number of items in the collection.
  6438. * @memberof Matrix3.prototype
  6439. *
  6440. * @type {Number}
  6441. */
  6442. length : {
  6443. get : function() {
  6444. return Matrix3.packedLength;
  6445. }
  6446. }
  6447. });
  6448. /**
  6449. * Duplicates the provided Matrix3 instance.
  6450. *
  6451. * @param {Matrix3} [result] The object onto which to store the result.
  6452. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  6453. */
  6454. Matrix3.prototype.clone = function(result) {
  6455. return Matrix3.clone(this, result);
  6456. };
  6457. /**
  6458. * Compares this matrix to the provided matrix componentwise and returns
  6459. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6460. *
  6461. * @param {Matrix3} [right] The right hand side matrix.
  6462. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  6463. */
  6464. Matrix3.prototype.equals = function(right) {
  6465. return Matrix3.equals(this, right);
  6466. };
  6467. /**
  6468. * @private
  6469. */
  6470. Matrix3.equalsArray = function(matrix, array, offset) {
  6471. return matrix[0] === array[offset] &&
  6472. matrix[1] === array[offset + 1] &&
  6473. matrix[2] === array[offset + 2] &&
  6474. matrix[3] === array[offset + 3] &&
  6475. matrix[4] === array[offset + 4] &&
  6476. matrix[5] === array[offset + 5] &&
  6477. matrix[6] === array[offset + 6] &&
  6478. matrix[7] === array[offset + 7] &&
  6479. matrix[8] === array[offset + 8];
  6480. };
  6481. /**
  6482. * Compares this matrix to the provided matrix componentwise and returns
  6483. * <code>true</code> if they are within the provided epsilon,
  6484. * <code>false</code> otherwise.
  6485. *
  6486. * @param {Matrix3} [right] The right hand side matrix.
  6487. * @param {Number} epsilon The epsilon to use for equality testing.
  6488. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  6489. */
  6490. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  6491. return Matrix3.equalsEpsilon(this, right, epsilon);
  6492. };
  6493. /**
  6494. * Creates a string representing this Matrix with each row being
  6495. * on a separate line and in the format '(column0, column1, column2)'.
  6496. *
  6497. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  6498. */
  6499. Matrix3.prototype.toString = function() {
  6500. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  6501. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  6502. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  6503. };
  6504. return Matrix3;
  6505. });
  6506. /*global define*/
  6507. define('Core/Cartesian4',[
  6508. './defaultValue',
  6509. './defined',
  6510. './DeveloperError',
  6511. './freezeObject',
  6512. './Math'
  6513. ], function(
  6514. defaultValue,
  6515. defined,
  6516. DeveloperError,
  6517. freezeObject,
  6518. CesiumMath) {
  6519. 'use strict';
  6520. /**
  6521. * A 4D Cartesian point.
  6522. * @alias Cartesian4
  6523. * @constructor
  6524. *
  6525. * @param {Number} [x=0.0] The X component.
  6526. * @param {Number} [y=0.0] The Y component.
  6527. * @param {Number} [z=0.0] The Z component.
  6528. * @param {Number} [w=0.0] The W component.
  6529. *
  6530. * @see Cartesian2
  6531. * @see Cartesian3
  6532. * @see Packable
  6533. */
  6534. function Cartesian4(x, y, z, w) {
  6535. /**
  6536. * The X component.
  6537. * @type {Number}
  6538. * @default 0.0
  6539. */
  6540. this.x = defaultValue(x, 0.0);
  6541. /**
  6542. * The Y component.
  6543. * @type {Number}
  6544. * @default 0.0
  6545. */
  6546. this.y = defaultValue(y, 0.0);
  6547. /**
  6548. * The Z component.
  6549. * @type {Number}
  6550. * @default 0.0
  6551. */
  6552. this.z = defaultValue(z, 0.0);
  6553. /**
  6554. * The W component.
  6555. * @type {Number}
  6556. * @default 0.0
  6557. */
  6558. this.w = defaultValue(w, 0.0);
  6559. }
  6560. /**
  6561. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  6562. *
  6563. * @param {Number} x The x coordinate.
  6564. * @param {Number} y The y coordinate.
  6565. * @param {Number} z The z coordinate.
  6566. * @param {Number} w The w coordinate.
  6567. * @param {Cartesian4} [result] The object onto which to store the result.
  6568. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6569. */
  6570. Cartesian4.fromElements = function(x, y, z, w, result) {
  6571. if (!defined(result)) {
  6572. return new Cartesian4(x, y, z, w);
  6573. }
  6574. result.x = x;
  6575. result.y = y;
  6576. result.z = z;
  6577. result.w = w;
  6578. return result;
  6579. };
  6580. /**
  6581. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  6582. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  6583. *
  6584. * @param {Color} color The source color.
  6585. * @param {Cartesian4} [result] The object onto which to store the result.
  6586. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6587. */
  6588. Cartesian4.fromColor = function(color, result) {
  6589. if (!defined(color)) {
  6590. throw new DeveloperError('color is required');
  6591. }
  6592. if (!defined(result)) {
  6593. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  6594. }
  6595. result.x = color.red;
  6596. result.y = color.green;
  6597. result.z = color.blue;
  6598. result.w = color.alpha;
  6599. return result;
  6600. };
  6601. /**
  6602. * Duplicates a Cartesian4 instance.
  6603. *
  6604. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  6605. * @param {Cartesian4} [result] The object onto which to store the result.
  6606. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  6607. */
  6608. Cartesian4.clone = function(cartesian, result) {
  6609. if (!defined(cartesian)) {
  6610. return undefined;
  6611. }
  6612. if (!defined(result)) {
  6613. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6614. }
  6615. result.x = cartesian.x;
  6616. result.y = cartesian.y;
  6617. result.z = cartesian.z;
  6618. result.w = cartesian.w;
  6619. return result;
  6620. };
  6621. /**
  6622. * The number of elements used to pack the object into an array.
  6623. * @type {Number}
  6624. */
  6625. Cartesian4.packedLength = 4;
  6626. /**
  6627. * Stores the provided instance into the provided array.
  6628. *
  6629. * @param {Cartesian4} value The value to pack.
  6630. * @param {Number[]} array The array to pack into.
  6631. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  6632. *
  6633. * @returns {Number[]} The array that was packed into
  6634. */
  6635. Cartesian4.pack = function(value, array, startingIndex) {
  6636. if (!defined(value)) {
  6637. throw new DeveloperError('value is required');
  6638. }
  6639. if (!defined(array)) {
  6640. throw new DeveloperError('array is required');
  6641. }
  6642. startingIndex = defaultValue(startingIndex, 0);
  6643. array[startingIndex++] = value.x;
  6644. array[startingIndex++] = value.y;
  6645. array[startingIndex++] = value.z;
  6646. array[startingIndex] = value.w;
  6647. return array;
  6648. };
  6649. /**
  6650. * Retrieves an instance from a packed array.
  6651. *
  6652. * @param {Number[]} array The packed array.
  6653. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  6654. * @param {Cartesian4} [result] The object into which to store the result.
  6655. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6656. */
  6657. Cartesian4.unpack = function(array, startingIndex, result) {
  6658. if (!defined(array)) {
  6659. throw new DeveloperError('array is required');
  6660. }
  6661. startingIndex = defaultValue(startingIndex, 0);
  6662. if (!defined(result)) {
  6663. result = new Cartesian4();
  6664. }
  6665. result.x = array[startingIndex++];
  6666. result.y = array[startingIndex++];
  6667. result.z = array[startingIndex++];
  6668. result.w = array[startingIndex];
  6669. return result;
  6670. };
  6671. /**
  6672. * Flattens an array of Cartesian4s into and array of components.
  6673. *
  6674. * @param {Cartesian4[]} array The array of cartesians to pack.
  6675. * @param {Number[]} result The array onto which to store the result.
  6676. * @returns {Number[]} The packed array.
  6677. */
  6678. Cartesian4.packArray = function(array, result) {
  6679. if (!defined(array)) {
  6680. throw new DeveloperError('array is required');
  6681. }
  6682. var length = array.length;
  6683. if (!defined(result)) {
  6684. result = new Array(length * 4);
  6685. } else {
  6686. result.length = length * 4;
  6687. }
  6688. for (var i = 0; i < length; ++i) {
  6689. Cartesian4.pack(array[i], result, i * 4);
  6690. }
  6691. return result;
  6692. };
  6693. /**
  6694. * Unpacks an array of cartesian components into and array of Cartesian4s.
  6695. *
  6696. * @param {Number[]} array The array of components to unpack.
  6697. * @param {Cartesian4[]} result The array onto which to store the result.
  6698. * @returns {Cartesian4[]} The unpacked array.
  6699. */
  6700. Cartesian4.unpackArray = function(array, result) {
  6701. if (!defined(array)) {
  6702. throw new DeveloperError('array is required');
  6703. }
  6704. var length = array.length;
  6705. if (!defined(result)) {
  6706. result = new Array(length / 4);
  6707. } else {
  6708. result.length = length / 4;
  6709. }
  6710. for (var i = 0; i < length; i += 4) {
  6711. var index = i / 4;
  6712. result[index] = Cartesian4.unpack(array, i, result[index]);
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Creates a Cartesian4 from four consecutive elements in an array.
  6718. * @function
  6719. *
  6720. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  6721. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  6722. * @param {Cartesian4} [result] The object onto which to store the result.
  6723. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6724. *
  6725. * @example
  6726. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  6727. * var v = [1.0, 2.0, 3.0, 4.0];
  6728. * var p = Cesium.Cartesian4.fromArray(v);
  6729. *
  6730. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  6731. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  6732. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  6733. */
  6734. Cartesian4.fromArray = Cartesian4.unpack;
  6735. /**
  6736. * Computes the value of the maximum component for the supplied Cartesian.
  6737. *
  6738. * @param {Cartesian4} cartesian The cartesian to use.
  6739. * @returns {Number} The value of the maximum component.
  6740. */
  6741. Cartesian4.maximumComponent = function(cartesian) {
  6742. if (!defined(cartesian)) {
  6743. throw new DeveloperError('cartesian is required');
  6744. }
  6745. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6746. };
  6747. /**
  6748. * Computes the value of the minimum component for the supplied Cartesian.
  6749. *
  6750. * @param {Cartesian4} cartesian The cartesian to use.
  6751. * @returns {Number} The value of the minimum component.
  6752. */
  6753. Cartesian4.minimumComponent = function(cartesian) {
  6754. if (!defined(cartesian)) {
  6755. throw new DeveloperError('cartesian is required');
  6756. }
  6757. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6758. };
  6759. /**
  6760. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  6761. *
  6762. * @param {Cartesian4} first A cartesian to compare.
  6763. * @param {Cartesian4} second A cartesian to compare.
  6764. * @param {Cartesian4} result The object into which to store the result.
  6765. * @returns {Cartesian4} A cartesian with the minimum components.
  6766. */
  6767. Cartesian4.minimumByComponent = function(first, second, result) {
  6768. if (!defined(first)) {
  6769. throw new DeveloperError('first is required.');
  6770. }
  6771. if (!defined(second)) {
  6772. throw new DeveloperError('second is required.');
  6773. }
  6774. if (!defined(result)) {
  6775. throw new DeveloperError('result is required.');
  6776. }
  6777. result.x = Math.min(first.x, second.x);
  6778. result.y = Math.min(first.y, second.y);
  6779. result.z = Math.min(first.z, second.z);
  6780. result.w = Math.min(first.w, second.w);
  6781. return result;
  6782. };
  6783. /**
  6784. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  6785. *
  6786. * @param {Cartesian4} first A cartesian to compare.
  6787. * @param {Cartesian4} second A cartesian to compare.
  6788. * @param {Cartesian4} result The object into which to store the result.
  6789. * @returns {Cartesian4} A cartesian with the maximum components.
  6790. */
  6791. Cartesian4.maximumByComponent = function(first, second, result) {
  6792. if (!defined(first)) {
  6793. throw new DeveloperError('first is required.');
  6794. }
  6795. if (!defined(second)) {
  6796. throw new DeveloperError('second is required.');
  6797. }
  6798. if (!defined(result)) {
  6799. throw new DeveloperError('result is required.');
  6800. }
  6801. result.x = Math.max(first.x, second.x);
  6802. result.y = Math.max(first.y, second.y);
  6803. result.z = Math.max(first.z, second.z);
  6804. result.w = Math.max(first.w, second.w);
  6805. return result;
  6806. };
  6807. /**
  6808. * Computes the provided Cartesian's squared magnitude.
  6809. *
  6810. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  6811. * @returns {Number} The squared magnitude.
  6812. */
  6813. Cartesian4.magnitudeSquared = function(cartesian) {
  6814. if (!defined(cartesian)) {
  6815. throw new DeveloperError('cartesian is required');
  6816. }
  6817. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  6818. };
  6819. /**
  6820. * Computes the Cartesian's magnitude (length).
  6821. *
  6822. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  6823. * @returns {Number} The magnitude.
  6824. */
  6825. Cartesian4.magnitude = function(cartesian) {
  6826. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  6827. };
  6828. var distanceScratch = new Cartesian4();
  6829. /**
  6830. * Computes the 4-space distance between two points.
  6831. *
  6832. * @param {Cartesian4} left The first point to compute the distance from.
  6833. * @param {Cartesian4} right The second point to compute the distance to.
  6834. * @returns {Number} The distance between two points.
  6835. *
  6836. * @example
  6837. * // Returns 1.0
  6838. * var d = Cesium.Cartesian4.distance(
  6839. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6840. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  6841. */
  6842. Cartesian4.distance = function(left, right) {
  6843. if (!defined(left) || !defined(right)) {
  6844. throw new DeveloperError('left and right are required.');
  6845. }
  6846. Cartesian4.subtract(left, right, distanceScratch);
  6847. return Cartesian4.magnitude(distanceScratch);
  6848. };
  6849. /**
  6850. * Computes the squared distance between two points. Comparing squared distances
  6851. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  6852. *
  6853. * @param {Cartesian4} left The first point to compute the distance from.
  6854. * @param {Cartesian4} right The second point to compute the distance to.
  6855. * @returns {Number} The distance between two points.
  6856. *
  6857. * @example
  6858. * // Returns 4.0, not 2.0
  6859. * var d = Cesium.Cartesian4.distance(
  6860. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6861. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  6862. */
  6863. Cartesian4.distanceSquared = function(left, right) {
  6864. if (!defined(left) || !defined(right)) {
  6865. throw new DeveloperError('left and right are required.');
  6866. }
  6867. Cartesian4.subtract(left, right, distanceScratch);
  6868. return Cartesian4.magnitudeSquared(distanceScratch);
  6869. };
  6870. /**
  6871. * Computes the normalized form of the supplied Cartesian.
  6872. *
  6873. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  6874. * @param {Cartesian4} result The object onto which to store the result.
  6875. * @returns {Cartesian4} The modified result parameter.
  6876. */
  6877. Cartesian4.normalize = function(cartesian, result) {
  6878. if (!defined(cartesian)) {
  6879. throw new DeveloperError('cartesian is required');
  6880. }
  6881. if (!defined(result)) {
  6882. throw new DeveloperError('result is required');
  6883. }
  6884. var magnitude = Cartesian4.magnitude(cartesian);
  6885. result.x = cartesian.x / magnitude;
  6886. result.y = cartesian.y / magnitude;
  6887. result.z = cartesian.z / magnitude;
  6888. result.w = cartesian.w / magnitude;
  6889. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  6890. throw new DeveloperError('normalized result is not a number');
  6891. }
  6892. return result;
  6893. };
  6894. /**
  6895. * Computes the dot (scalar) product of two Cartesians.
  6896. *
  6897. * @param {Cartesian4} left The first Cartesian.
  6898. * @param {Cartesian4} right The second Cartesian.
  6899. * @returns {Number} The dot product.
  6900. */
  6901. Cartesian4.dot = function(left, right) {
  6902. if (!defined(left)) {
  6903. throw new DeveloperError('left is required');
  6904. }
  6905. if (!defined(right)) {
  6906. throw new DeveloperError('right is required');
  6907. }
  6908. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  6909. };
  6910. /**
  6911. * Computes the componentwise product of two Cartesians.
  6912. *
  6913. * @param {Cartesian4} left The first Cartesian.
  6914. * @param {Cartesian4} right The second Cartesian.
  6915. * @param {Cartesian4} result The object onto which to store the result.
  6916. * @returns {Cartesian4} The modified result parameter.
  6917. */
  6918. Cartesian4.multiplyComponents = function(left, right, result) {
  6919. if (!defined(left)) {
  6920. throw new DeveloperError('left is required');
  6921. }
  6922. if (!defined(right)) {
  6923. throw new DeveloperError('right is required');
  6924. }
  6925. if (!defined(result)) {
  6926. throw new DeveloperError('result is required');
  6927. }
  6928. result.x = left.x * right.x;
  6929. result.y = left.y * right.y;
  6930. result.z = left.z * right.z;
  6931. result.w = left.w * right.w;
  6932. return result;
  6933. };
  6934. /**
  6935. * Computes the componentwise quotient of two Cartesians.
  6936. *
  6937. * @param {Cartesian4} left The first Cartesian.
  6938. * @param {Cartesian4} right The second Cartesian.
  6939. * @param {Cartesian4} result The object onto which to store the result.
  6940. * @returns {Cartesian4} The modified result parameter.
  6941. */
  6942. Cartesian4.divideComponents = function(left, right, result) {
  6943. if (!defined(left)) {
  6944. throw new DeveloperError('left is required');
  6945. }
  6946. if (!defined(right)) {
  6947. throw new DeveloperError('right is required');
  6948. }
  6949. if (!defined(result)) {
  6950. throw new DeveloperError('result is required');
  6951. }
  6952. result.x = left.x / right.x;
  6953. result.y = left.y / right.y;
  6954. result.z = left.z / right.z;
  6955. result.w = left.w / right.w;
  6956. return result;
  6957. };
  6958. /**
  6959. * Computes the componentwise sum of two Cartesians.
  6960. *
  6961. * @param {Cartesian4} left The first Cartesian.
  6962. * @param {Cartesian4} right The second Cartesian.
  6963. * @param {Cartesian4} result The object onto which to store the result.
  6964. * @returns {Cartesian4} The modified result parameter.
  6965. */
  6966. Cartesian4.add = function(left, right, result) {
  6967. if (!defined(left)) {
  6968. throw new DeveloperError('left is required');
  6969. }
  6970. if (!defined(right)) {
  6971. throw new DeveloperError('right is required');
  6972. }
  6973. if (!defined(result)) {
  6974. throw new DeveloperError('result is required');
  6975. }
  6976. result.x = left.x + right.x;
  6977. result.y = left.y + right.y;
  6978. result.z = left.z + right.z;
  6979. result.w = left.w + right.w;
  6980. return result;
  6981. };
  6982. /**
  6983. * Computes the componentwise difference of two Cartesians.
  6984. *
  6985. * @param {Cartesian4} left The first Cartesian.
  6986. * @param {Cartesian4} right The second Cartesian.
  6987. * @param {Cartesian4} result The object onto which to store the result.
  6988. * @returns {Cartesian4} The modified result parameter.
  6989. */
  6990. Cartesian4.subtract = function(left, right, result) {
  6991. if (!defined(left)) {
  6992. throw new DeveloperError('left is required');
  6993. }
  6994. if (!defined(right)) {
  6995. throw new DeveloperError('right is required');
  6996. }
  6997. if (!defined(result)) {
  6998. throw new DeveloperError('result is required');
  6999. }
  7000. result.x = left.x - right.x;
  7001. result.y = left.y - right.y;
  7002. result.z = left.z - right.z;
  7003. result.w = left.w - right.w;
  7004. return result;
  7005. };
  7006. /**
  7007. * Multiplies the provided Cartesian componentwise by the provided scalar.
  7008. *
  7009. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  7010. * @param {Number} scalar The scalar to multiply with.
  7011. * @param {Cartesian4} result The object onto which to store the result.
  7012. * @returns {Cartesian4} The modified result parameter.
  7013. */
  7014. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  7015. if (!defined(cartesian)) {
  7016. throw new DeveloperError('cartesian is required');
  7017. }
  7018. if (typeof scalar !== 'number') {
  7019. throw new DeveloperError('scalar is required and must be a number.');
  7020. }
  7021. if (!defined(result)) {
  7022. throw new DeveloperError('result is required');
  7023. }
  7024. result.x = cartesian.x * scalar;
  7025. result.y = cartesian.y * scalar;
  7026. result.z = cartesian.z * scalar;
  7027. result.w = cartesian.w * scalar;
  7028. return result;
  7029. };
  7030. /**
  7031. * Divides the provided Cartesian componentwise by the provided scalar.
  7032. *
  7033. * @param {Cartesian4} cartesian The Cartesian to be divided.
  7034. * @param {Number} scalar The scalar to divide by.
  7035. * @param {Cartesian4} result The object onto which to store the result.
  7036. * @returns {Cartesian4} The modified result parameter.
  7037. */
  7038. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  7039. if (!defined(cartesian)) {
  7040. throw new DeveloperError('cartesian is required');
  7041. }
  7042. if (typeof scalar !== 'number') {
  7043. throw new DeveloperError('scalar is required and must be a number.');
  7044. }
  7045. if (!defined(result)) {
  7046. throw new DeveloperError('result is required');
  7047. }
  7048. result.x = cartesian.x / scalar;
  7049. result.y = cartesian.y / scalar;
  7050. result.z = cartesian.z / scalar;
  7051. result.w = cartesian.w / scalar;
  7052. return result;
  7053. };
  7054. /**
  7055. * Negates the provided Cartesian.
  7056. *
  7057. * @param {Cartesian4} cartesian The Cartesian to be negated.
  7058. * @param {Cartesian4} result The object onto which to store the result.
  7059. * @returns {Cartesian4} The modified result parameter.
  7060. */
  7061. Cartesian4.negate = function(cartesian, result) {
  7062. if (!defined(cartesian)) {
  7063. throw new DeveloperError('cartesian is required');
  7064. }
  7065. if (!defined(result)) {
  7066. throw new DeveloperError('result is required');
  7067. }
  7068. result.x = -cartesian.x;
  7069. result.y = -cartesian.y;
  7070. result.z = -cartesian.z;
  7071. result.w = -cartesian.w;
  7072. return result;
  7073. };
  7074. /**
  7075. * Computes the absolute value of the provided Cartesian.
  7076. *
  7077. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  7078. * @param {Cartesian4} result The object onto which to store the result.
  7079. * @returns {Cartesian4} The modified result parameter.
  7080. */
  7081. Cartesian4.abs = function(cartesian, result) {
  7082. if (!defined(cartesian)) {
  7083. throw new DeveloperError('cartesian is required');
  7084. }
  7085. if (!defined(result)) {
  7086. throw new DeveloperError('result is required');
  7087. }
  7088. result.x = Math.abs(cartesian.x);
  7089. result.y = Math.abs(cartesian.y);
  7090. result.z = Math.abs(cartesian.z);
  7091. result.w = Math.abs(cartesian.w);
  7092. return result;
  7093. };
  7094. var lerpScratch = new Cartesian4();
  7095. /**
  7096. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  7097. *
  7098. * @param {Cartesian4} start The value corresponding to t at 0.0.
  7099. * @param {Cartesian4}end The value corresponding to t at 1.0.
  7100. * @param {Number} t The point along t at which to interpolate.
  7101. * @param {Cartesian4} result The object onto which to store the result.
  7102. * @returns {Cartesian4} The modified result parameter.
  7103. */
  7104. Cartesian4.lerp = function(start, end, t, result) {
  7105. if (!defined(start)) {
  7106. throw new DeveloperError('start is required.');
  7107. }
  7108. if (!defined(end)) {
  7109. throw new DeveloperError('end is required.');
  7110. }
  7111. if (typeof t !== 'number') {
  7112. throw new DeveloperError('t is required and must be a number.');
  7113. }
  7114. if (!defined(result)) {
  7115. throw new DeveloperError('result is required.');
  7116. }
  7117. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  7118. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  7119. return Cartesian4.add(lerpScratch, result, result);
  7120. };
  7121. var mostOrthogonalAxisScratch = new Cartesian4();
  7122. /**
  7123. * Returns the axis that is most orthogonal to the provided Cartesian.
  7124. *
  7125. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  7126. * @param {Cartesian4} result The object onto which to store the result.
  7127. * @returns {Cartesian4} The most orthogonal axis.
  7128. */
  7129. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  7130. if (!defined(cartesian)) {
  7131. throw new DeveloperError('cartesian is required.');
  7132. }
  7133. if (!defined(result)) {
  7134. throw new DeveloperError('result is required.');
  7135. }
  7136. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  7137. Cartesian4.abs(f, f);
  7138. if (f.x <= f.y) {
  7139. if (f.x <= f.z) {
  7140. if (f.x <= f.w) {
  7141. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  7142. } else {
  7143. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7144. }
  7145. } else if (f.z <= f.w) {
  7146. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7147. } else {
  7148. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7149. }
  7150. } else if (f.y <= f.z) {
  7151. if (f.y <= f.w) {
  7152. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  7153. } else {
  7154. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7155. }
  7156. } else if (f.z <= f.w) {
  7157. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7158. } else {
  7159. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7160. }
  7161. return result;
  7162. };
  7163. /**
  7164. * Compares the provided Cartesians componentwise and returns
  7165. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7166. *
  7167. * @param {Cartesian4} [left] The first Cartesian.
  7168. * @param {Cartesian4} [right] The second Cartesian.
  7169. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7170. */
  7171. Cartesian4.equals = function(left, right) {
  7172. return (left === right) ||
  7173. ((defined(left)) &&
  7174. (defined(right)) &&
  7175. (left.x === right.x) &&
  7176. (left.y === right.y) &&
  7177. (left.z === right.z) &&
  7178. (left.w === right.w));
  7179. };
  7180. /**
  7181. * @private
  7182. */
  7183. Cartesian4.equalsArray = function(cartesian, array, offset) {
  7184. return cartesian.x === array[offset] &&
  7185. cartesian.y === array[offset + 1] &&
  7186. cartesian.z === array[offset + 2] &&
  7187. cartesian.w === array[offset + 3];
  7188. };
  7189. /**
  7190. * Compares the provided Cartesians componentwise and returns
  7191. * <code>true</code> if they pass an absolute or relative tolerance test,
  7192. * <code>false</code> otherwise.
  7193. *
  7194. * @param {Cartesian4} [left] The first Cartesian.
  7195. * @param {Cartesian4} [right] The second Cartesian.
  7196. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7197. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7198. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7199. */
  7200. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  7201. return (left === right) ||
  7202. (defined(left) &&
  7203. defined(right) &&
  7204. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  7205. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  7206. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  7207. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  7208. };
  7209. /**
  7210. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  7211. *
  7212. * @type {Cartesian4}
  7213. * @constant
  7214. */
  7215. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  7216. /**
  7217. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  7218. *
  7219. * @type {Cartesian4}
  7220. * @constant
  7221. */
  7222. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  7223. /**
  7224. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  7225. *
  7226. * @type {Cartesian4}
  7227. * @constant
  7228. */
  7229. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  7230. /**
  7231. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  7232. *
  7233. * @type {Cartesian4}
  7234. * @constant
  7235. */
  7236. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  7237. /**
  7238. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  7239. *
  7240. * @type {Cartesian4}
  7241. * @constant
  7242. */
  7243. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  7244. /**
  7245. * Duplicates this Cartesian4 instance.
  7246. *
  7247. * @param {Cartesian4} [result] The object onto which to store the result.
  7248. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  7249. */
  7250. Cartesian4.prototype.clone = function(result) {
  7251. return Cartesian4.clone(this, result);
  7252. };
  7253. /**
  7254. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7255. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7256. *
  7257. * @param {Cartesian4} [right] The right hand side Cartesian.
  7258. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  7259. */
  7260. Cartesian4.prototype.equals = function(right) {
  7261. return Cartesian4.equals(this, right);
  7262. };
  7263. /**
  7264. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7265. * <code>true</code> if they pass an absolute or relative tolerance test,
  7266. * <code>false</code> otherwise.
  7267. *
  7268. * @param {Cartesian4} [right] The right hand side Cartesian.
  7269. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7270. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7271. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  7272. */
  7273. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  7274. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  7275. };
  7276. /**
  7277. * Creates a string representing this Cartesian in the format '(x, y)'.
  7278. *
  7279. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  7280. */
  7281. Cartesian4.prototype.toString = function() {
  7282. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  7283. };
  7284. return Cartesian4;
  7285. });
  7286. /*global define*/
  7287. define('Core/RuntimeError',[
  7288. './defined'
  7289. ], function(
  7290. defined) {
  7291. 'use strict';
  7292. /**
  7293. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  7294. * out of memory, could not compile shader, etc. If a function may throw this
  7295. * exception, the calling code should be prepared to catch it.
  7296. * <br /><br />
  7297. * On the other hand, a {@link DeveloperError} indicates an exception due
  7298. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  7299. * calling code.
  7300. *
  7301. * @alias RuntimeError
  7302. * @constructor
  7303. * @extends Error
  7304. *
  7305. * @param {String} [message] The error message for this exception.
  7306. *
  7307. * @see DeveloperError
  7308. */
  7309. function RuntimeError(message) {
  7310. /**
  7311. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  7312. * @type {String}
  7313. * @readonly
  7314. */
  7315. this.name = 'RuntimeError';
  7316. /**
  7317. * The explanation for why this exception was thrown.
  7318. * @type {String}
  7319. * @readonly
  7320. */
  7321. this.message = message;
  7322. //Browsers such as IE don't have a stack property until you actually throw the error.
  7323. var stack;
  7324. try {
  7325. throw new Error();
  7326. } catch (e) {
  7327. stack = e.stack;
  7328. }
  7329. /**
  7330. * The stack trace of this exception, if available.
  7331. * @type {String}
  7332. * @readonly
  7333. */
  7334. this.stack = stack;
  7335. }
  7336. if (defined(Object.create)) {
  7337. RuntimeError.prototype = Object.create(Error.prototype);
  7338. RuntimeError.prototype.constructor = RuntimeError;
  7339. }
  7340. RuntimeError.prototype.toString = function() {
  7341. var str = this.name + ': ' + this.message;
  7342. if (defined(this.stack)) {
  7343. str += '\n' + this.stack.toString();
  7344. }
  7345. return str;
  7346. };
  7347. return RuntimeError;
  7348. });
  7349. /*global define*/
  7350. define('Core/Matrix4',[
  7351. './Cartesian3',
  7352. './Cartesian4',
  7353. './defaultValue',
  7354. './defined',
  7355. './defineProperties',
  7356. './DeveloperError',
  7357. './freezeObject',
  7358. './Math',
  7359. './Matrix3',
  7360. './RuntimeError'
  7361. ], function(
  7362. Cartesian3,
  7363. Cartesian4,
  7364. defaultValue,
  7365. defined,
  7366. defineProperties,
  7367. DeveloperError,
  7368. freezeObject,
  7369. CesiumMath,
  7370. Matrix3,
  7371. RuntimeError) {
  7372. 'use strict';
  7373. /**
  7374. * A 4x4 matrix, indexable as a column-major order array.
  7375. * Constructor parameters are in row-major order for code readability.
  7376. * @alias Matrix4
  7377. * @constructor
  7378. *
  7379. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  7380. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  7381. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  7382. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  7383. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  7384. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  7385. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  7386. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  7387. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  7388. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  7389. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  7390. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  7391. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  7392. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  7393. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  7394. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  7395. *
  7396. * @see Matrix4.fromColumnMajorArray
  7397. * @see Matrix4.fromRowMajorArray
  7398. * @see Matrix4.fromRotationTranslation
  7399. * @see Matrix4.fromTranslationRotationScale
  7400. * @see Matrix4.fromTranslationQuaternionRotationScale
  7401. * @see Matrix4.fromTranslation
  7402. * @see Matrix4.fromScale
  7403. * @see Matrix4.fromUniformScale
  7404. * @see Matrix4.fromCamera
  7405. * @see Matrix4.computePerspectiveFieldOfView
  7406. * @see Matrix4.computeOrthographicOffCenter
  7407. * @see Matrix4.computePerspectiveOffCenter
  7408. * @see Matrix4.computeInfinitePerspectiveOffCenter
  7409. * @see Matrix4.computeViewportTransformation
  7410. * @see Matrix4.computeView
  7411. * @see Matrix2
  7412. * @see Matrix3
  7413. * @see Packable
  7414. */
  7415. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  7416. column0Row1, column1Row1, column2Row1, column3Row1,
  7417. column0Row2, column1Row2, column2Row2, column3Row2,
  7418. column0Row3, column1Row3, column2Row3, column3Row3) {
  7419. this[0] = defaultValue(column0Row0, 0.0);
  7420. this[1] = defaultValue(column0Row1, 0.0);
  7421. this[2] = defaultValue(column0Row2, 0.0);
  7422. this[3] = defaultValue(column0Row3, 0.0);
  7423. this[4] = defaultValue(column1Row0, 0.0);
  7424. this[5] = defaultValue(column1Row1, 0.0);
  7425. this[6] = defaultValue(column1Row2, 0.0);
  7426. this[7] = defaultValue(column1Row3, 0.0);
  7427. this[8] = defaultValue(column2Row0, 0.0);
  7428. this[9] = defaultValue(column2Row1, 0.0);
  7429. this[10] = defaultValue(column2Row2, 0.0);
  7430. this[11] = defaultValue(column2Row3, 0.0);
  7431. this[12] = defaultValue(column3Row0, 0.0);
  7432. this[13] = defaultValue(column3Row1, 0.0);
  7433. this[14] = defaultValue(column3Row2, 0.0);
  7434. this[15] = defaultValue(column3Row3, 0.0);
  7435. }
  7436. /**
  7437. * The number of elements used to pack the object into an array.
  7438. * @type {Number}
  7439. */
  7440. Matrix4.packedLength = 16;
  7441. /**
  7442. * Stores the provided instance into the provided array.
  7443. *
  7444. * @param {Matrix4} value The value to pack.
  7445. * @param {Number[]} array The array to pack into.
  7446. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  7447. *
  7448. * @returns {Number[]} The array that was packed into
  7449. */
  7450. Matrix4.pack = function(value, array, startingIndex) {
  7451. if (!defined(value)) {
  7452. throw new DeveloperError('value is required');
  7453. }
  7454. if (!defined(array)) {
  7455. throw new DeveloperError('array is required');
  7456. }
  7457. startingIndex = defaultValue(startingIndex, 0);
  7458. array[startingIndex++] = value[0];
  7459. array[startingIndex++] = value[1];
  7460. array[startingIndex++] = value[2];
  7461. array[startingIndex++] = value[3];
  7462. array[startingIndex++] = value[4];
  7463. array[startingIndex++] = value[5];
  7464. array[startingIndex++] = value[6];
  7465. array[startingIndex++] = value[7];
  7466. array[startingIndex++] = value[8];
  7467. array[startingIndex++] = value[9];
  7468. array[startingIndex++] = value[10];
  7469. array[startingIndex++] = value[11];
  7470. array[startingIndex++] = value[12];
  7471. array[startingIndex++] = value[13];
  7472. array[startingIndex++] = value[14];
  7473. array[startingIndex] = value[15];
  7474. return array;
  7475. };
  7476. /**
  7477. * Retrieves an instance from a packed array.
  7478. *
  7479. * @param {Number[]} array The packed array.
  7480. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  7481. * @param {Matrix4} [result] The object into which to store the result.
  7482. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7483. */
  7484. Matrix4.unpack = function(array, startingIndex, result) {
  7485. if (!defined(array)) {
  7486. throw new DeveloperError('array is required');
  7487. }
  7488. startingIndex = defaultValue(startingIndex, 0);
  7489. if (!defined(result)) {
  7490. result = new Matrix4();
  7491. }
  7492. result[0] = array[startingIndex++];
  7493. result[1] = array[startingIndex++];
  7494. result[2] = array[startingIndex++];
  7495. result[3] = array[startingIndex++];
  7496. result[4] = array[startingIndex++];
  7497. result[5] = array[startingIndex++];
  7498. result[6] = array[startingIndex++];
  7499. result[7] = array[startingIndex++];
  7500. result[8] = array[startingIndex++];
  7501. result[9] = array[startingIndex++];
  7502. result[10] = array[startingIndex++];
  7503. result[11] = array[startingIndex++];
  7504. result[12] = array[startingIndex++];
  7505. result[13] = array[startingIndex++];
  7506. result[14] = array[startingIndex++];
  7507. result[15] = array[startingIndex];
  7508. return result;
  7509. };
  7510. /**
  7511. * Duplicates a Matrix4 instance.
  7512. *
  7513. * @param {Matrix4} matrix The matrix to duplicate.
  7514. * @param {Matrix4} [result] The object onto which to store the result.
  7515. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  7516. */
  7517. Matrix4.clone = function(matrix, result) {
  7518. if (!defined(matrix)) {
  7519. return undefined;
  7520. }
  7521. if (!defined(result)) {
  7522. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  7523. matrix[1], matrix[5], matrix[9], matrix[13],
  7524. matrix[2], matrix[6], matrix[10], matrix[14],
  7525. matrix[3], matrix[7], matrix[11], matrix[15]);
  7526. }
  7527. result[0] = matrix[0];
  7528. result[1] = matrix[1];
  7529. result[2] = matrix[2];
  7530. result[3] = matrix[3];
  7531. result[4] = matrix[4];
  7532. result[5] = matrix[5];
  7533. result[6] = matrix[6];
  7534. result[7] = matrix[7];
  7535. result[8] = matrix[8];
  7536. result[9] = matrix[9];
  7537. result[10] = matrix[10];
  7538. result[11] = matrix[11];
  7539. result[12] = matrix[12];
  7540. result[13] = matrix[13];
  7541. result[14] = matrix[14];
  7542. result[15] = matrix[15];
  7543. return result;
  7544. };
  7545. /**
  7546. * Creates a Matrix4 from 16 consecutive elements in an array.
  7547. * @function
  7548. *
  7549. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  7550. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  7551. * @param {Matrix4} [result] The object onto which to store the result.
  7552. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7553. *
  7554. * @example
  7555. * // Create the Matrix4:
  7556. * // [1.0, 2.0, 3.0, 4.0]
  7557. * // [1.0, 2.0, 3.0, 4.0]
  7558. * // [1.0, 2.0, 3.0, 4.0]
  7559. * // [1.0, 2.0, 3.0, 4.0]
  7560. *
  7561. * var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  7562. * var m = Cesium.Matrix4.fromArray(v);
  7563. *
  7564. * // Create same Matrix4 with using an offset into an array
  7565. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  7566. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  7567. */
  7568. Matrix4.fromArray = Matrix4.unpack;
  7569. /**
  7570. * Computes a Matrix4 instance from a column-major order array.
  7571. *
  7572. * @param {Number[]} values The column-major order array.
  7573. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7574. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7575. */
  7576. Matrix4.fromColumnMajorArray = function(values, result) {
  7577. if (!defined(values)) {
  7578. throw new DeveloperError('values is required');
  7579. }
  7580. return Matrix4.clone(values, result);
  7581. };
  7582. /**
  7583. * Computes a Matrix4 instance from a row-major order array.
  7584. * The resulting matrix will be in column-major order.
  7585. *
  7586. * @param {Number[]} values The row-major order array.
  7587. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7588. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7589. */
  7590. Matrix4.fromRowMajorArray = function(values, result) {
  7591. if (!defined(values)) {
  7592. throw new DeveloperError('values is required.');
  7593. }
  7594. if (!defined(result)) {
  7595. return new Matrix4(values[0], values[1], values[2], values[3],
  7596. values[4], values[5], values[6], values[7],
  7597. values[8], values[9], values[10], values[11],
  7598. values[12], values[13], values[14], values[15]);
  7599. }
  7600. result[0] = values[0];
  7601. result[1] = values[4];
  7602. result[2] = values[8];
  7603. result[3] = values[12];
  7604. result[4] = values[1];
  7605. result[5] = values[5];
  7606. result[6] = values[9];
  7607. result[7] = values[13];
  7608. result[8] = values[2];
  7609. result[9] = values[6];
  7610. result[10] = values[10];
  7611. result[11] = values[14];
  7612. result[12] = values[3];
  7613. result[13] = values[7];
  7614. result[14] = values[11];
  7615. result[15] = values[15];
  7616. return result;
  7617. };
  7618. /**
  7619. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  7620. * and a Cartesian3 representing the translation.
  7621. *
  7622. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  7623. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  7624. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7625. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7626. */
  7627. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  7628. if (!defined(rotation)) {
  7629. throw new DeveloperError('rotation is required.');
  7630. }
  7631. translation = defaultValue(translation, Cartesian3.ZERO);
  7632. if (!defined(result)) {
  7633. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  7634. rotation[1], rotation[4], rotation[7], translation.y,
  7635. rotation[2], rotation[5], rotation[8], translation.z,
  7636. 0.0, 0.0, 0.0, 1.0);
  7637. }
  7638. result[0] = rotation[0];
  7639. result[1] = rotation[1];
  7640. result[2] = rotation[2];
  7641. result[3] = 0.0;
  7642. result[4] = rotation[3];
  7643. result[5] = rotation[4];
  7644. result[6] = rotation[5];
  7645. result[7] = 0.0;
  7646. result[8] = rotation[6];
  7647. result[9] = rotation[7];
  7648. result[10] = rotation[8];
  7649. result[11] = 0.0;
  7650. result[12] = translation.x;
  7651. result[13] = translation.y;
  7652. result[14] = translation.z;
  7653. result[15] = 1.0;
  7654. return result;
  7655. };
  7656. /**
  7657. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  7658. * representation with the rotation represented as a quaternion.
  7659. *
  7660. * @param {Cartesian3} translation The translation transformation.
  7661. * @param {Quaternion} rotation The rotation transformation.
  7662. * @param {Cartesian3} scale The non-uniform scale transformation.
  7663. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7664. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7665. *
  7666. * @example
  7667. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  7668. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  7669. * Cesium.Quaternion.IDENTITY, // rotation
  7670. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  7671. * result);
  7672. */
  7673. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  7674. if (!defined(translation)) {
  7675. throw new DeveloperError('translation is required.');
  7676. }
  7677. if (!defined(rotation)) {
  7678. throw new DeveloperError('rotation is required.');
  7679. }
  7680. if (!defined(scale)) {
  7681. throw new DeveloperError('scale is required.');
  7682. }
  7683. if (!defined(result)) {
  7684. result = new Matrix4();
  7685. }
  7686. var scaleX = scale.x;
  7687. var scaleY = scale.y;
  7688. var scaleZ = scale.z;
  7689. var x2 = rotation.x * rotation.x;
  7690. var xy = rotation.x * rotation.y;
  7691. var xz = rotation.x * rotation.z;
  7692. var xw = rotation.x * rotation.w;
  7693. var y2 = rotation.y * rotation.y;
  7694. var yz = rotation.y * rotation.z;
  7695. var yw = rotation.y * rotation.w;
  7696. var z2 = rotation.z * rotation.z;
  7697. var zw = rotation.z * rotation.w;
  7698. var w2 = rotation.w * rotation.w;
  7699. var m00 = x2 - y2 - z2 + w2;
  7700. var m01 = 2.0 * (xy - zw);
  7701. var m02 = 2.0 * (xz + yw);
  7702. var m10 = 2.0 * (xy + zw);
  7703. var m11 = -x2 + y2 - z2 + w2;
  7704. var m12 = 2.0 * (yz - xw);
  7705. var m20 = 2.0 * (xz - yw);
  7706. var m21 = 2.0 * (yz + xw);
  7707. var m22 = -x2 - y2 + z2 + w2;
  7708. result[0] = m00 * scaleX;
  7709. result[1] = m10 * scaleX;
  7710. result[2] = m20 * scaleX;
  7711. result[3] = 0.0;
  7712. result[4] = m01 * scaleY;
  7713. result[5] = m11 * scaleY;
  7714. result[6] = m21 * scaleY;
  7715. result[7] = 0.0;
  7716. result[8] = m02 * scaleZ;
  7717. result[9] = m12 * scaleZ;
  7718. result[10] = m22 * scaleZ;
  7719. result[11] = 0.0;
  7720. result[12] = translation.x;
  7721. result[13] = translation.y;
  7722. result[14] = translation.z;
  7723. result[15] = 1.0;
  7724. return result;
  7725. };
  7726. /**
  7727. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  7728. *
  7729. * @param {TranslationRotationScale} translationRotationScale The instance.
  7730. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7731. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7732. */
  7733. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  7734. if (!defined(translationRotationScale)) {
  7735. throw new DeveloperError('translationRotationScale is required.');
  7736. }
  7737. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  7738. };
  7739. /**
  7740. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  7741. *
  7742. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  7743. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7744. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7745. *
  7746. * @see Matrix4.multiplyByTranslation
  7747. */
  7748. Matrix4.fromTranslation = function(translation, result) {
  7749. if (!defined(translation)) {
  7750. throw new DeveloperError('translation is required.');
  7751. }
  7752. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  7753. };
  7754. /**
  7755. * Computes a Matrix4 instance representing a non-uniform scale.
  7756. *
  7757. * @param {Cartesian3} scale The x, y, and z scale factors.
  7758. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7759. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7760. *
  7761. * @example
  7762. * // Creates
  7763. * // [7.0, 0.0, 0.0, 0.0]
  7764. * // [0.0, 8.0, 0.0, 0.0]
  7765. * // [0.0, 0.0, 9.0, 0.0]
  7766. * // [0.0, 0.0, 0.0, 1.0]
  7767. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  7768. */
  7769. Matrix4.fromScale = function(scale, result) {
  7770. if (!defined(scale)) {
  7771. throw new DeveloperError('scale is required.');
  7772. }
  7773. if (!defined(result)) {
  7774. return new Matrix4(
  7775. scale.x, 0.0, 0.0, 0.0,
  7776. 0.0, scale.y, 0.0, 0.0,
  7777. 0.0, 0.0, scale.z, 0.0,
  7778. 0.0, 0.0, 0.0, 1.0);
  7779. }
  7780. result[0] = scale.x;
  7781. result[1] = 0.0;
  7782. result[2] = 0.0;
  7783. result[3] = 0.0;
  7784. result[4] = 0.0;
  7785. result[5] = scale.y;
  7786. result[6] = 0.0;
  7787. result[7] = 0.0;
  7788. result[8] = 0.0;
  7789. result[9] = 0.0;
  7790. result[10] = scale.z;
  7791. result[11] = 0.0;
  7792. result[12] = 0.0;
  7793. result[13] = 0.0;
  7794. result[14] = 0.0;
  7795. result[15] = 1.0;
  7796. return result;
  7797. };
  7798. /**
  7799. * Computes a Matrix4 instance representing a uniform scale.
  7800. *
  7801. * @param {Number} scale The uniform scale factor.
  7802. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7803. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7804. *
  7805. * @example
  7806. * // Creates
  7807. * // [2.0, 0.0, 0.0, 0.0]
  7808. * // [0.0, 2.0, 0.0, 0.0]
  7809. * // [0.0, 0.0, 2.0, 0.0]
  7810. * // [0.0, 0.0, 0.0, 1.0]
  7811. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  7812. */
  7813. Matrix4.fromUniformScale = function(scale, result) {
  7814. if (typeof scale !== 'number') {
  7815. throw new DeveloperError('scale is required.');
  7816. }
  7817. if (!defined(result)) {
  7818. return new Matrix4(scale, 0.0, 0.0, 0.0,
  7819. 0.0, scale, 0.0, 0.0,
  7820. 0.0, 0.0, scale, 0.0,
  7821. 0.0, 0.0, 0.0, 1.0);
  7822. }
  7823. result[0] = scale;
  7824. result[1] = 0.0;
  7825. result[2] = 0.0;
  7826. result[3] = 0.0;
  7827. result[4] = 0.0;
  7828. result[5] = scale;
  7829. result[6] = 0.0;
  7830. result[7] = 0.0;
  7831. result[8] = 0.0;
  7832. result[9] = 0.0;
  7833. result[10] = scale;
  7834. result[11] = 0.0;
  7835. result[12] = 0.0;
  7836. result[13] = 0.0;
  7837. result[14] = 0.0;
  7838. result[15] = 1.0;
  7839. return result;
  7840. };
  7841. var fromCameraF = new Cartesian3();
  7842. var fromCameraR = new Cartesian3();
  7843. var fromCameraU = new Cartesian3();
  7844. /**
  7845. * Computes a Matrix4 instance from a Camera.
  7846. *
  7847. * @param {Camera} camera The camera to use.
  7848. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7849. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7850. */
  7851. Matrix4.fromCamera = function(camera, result) {
  7852. if (!defined(camera)) {
  7853. throw new DeveloperError('camera is required.');
  7854. }
  7855. var position = camera.position;
  7856. var direction = camera.direction;
  7857. var up = camera.up;
  7858. if (!defined(position)) {
  7859. throw new DeveloperError('camera.position is required.');
  7860. }
  7861. if (!defined(direction)) {
  7862. throw new DeveloperError('camera.direction is required.');
  7863. }
  7864. if (!defined(up)) {
  7865. throw new DeveloperError('camera.up is required.');
  7866. }
  7867. Cartesian3.normalize(direction, fromCameraF);
  7868. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  7869. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  7870. var sX = fromCameraR.x;
  7871. var sY = fromCameraR.y;
  7872. var sZ = fromCameraR.z;
  7873. var fX = fromCameraF.x;
  7874. var fY = fromCameraF.y;
  7875. var fZ = fromCameraF.z;
  7876. var uX = fromCameraU.x;
  7877. var uY = fromCameraU.y;
  7878. var uZ = fromCameraU.z;
  7879. var positionX = position.x;
  7880. var positionY = position.y;
  7881. var positionZ = position.z;
  7882. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  7883. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  7884. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  7885. // The code below this comment is an optimized
  7886. // version of the commented lines.
  7887. // Rather that create two matrices and then multiply,
  7888. // we just bake in the multiplcation as part of creation.
  7889. // var rotation = new Matrix4(
  7890. // sX, sY, sZ, 0.0,
  7891. // uX, uY, uZ, 0.0,
  7892. // -fX, -fY, -fZ, 0.0,
  7893. // 0.0, 0.0, 0.0, 1.0);
  7894. // var translation = new Matrix4(
  7895. // 1.0, 0.0, 0.0, -position.x,
  7896. // 0.0, 1.0, 0.0, -position.y,
  7897. // 0.0, 0.0, 1.0, -position.z,
  7898. // 0.0, 0.0, 0.0, 1.0);
  7899. // return rotation.multiply(translation);
  7900. if (!defined(result)) {
  7901. return new Matrix4(
  7902. sX, sY, sZ, t0,
  7903. uX, uY, uZ, t1,
  7904. -fX, -fY, -fZ, t2,
  7905. 0.0, 0.0, 0.0, 1.0);
  7906. }
  7907. result[0] = sX;
  7908. result[1] = uX;
  7909. result[2] = -fX;
  7910. result[3] = 0.0;
  7911. result[4] = sY;
  7912. result[5] = uY;
  7913. result[6] = -fY;
  7914. result[7] = 0.0;
  7915. result[8] = sZ;
  7916. result[9] = uZ;
  7917. result[10] = -fZ;
  7918. result[11] = 0.0;
  7919. result[12] = t0;
  7920. result[13] = t1;
  7921. result[14] = t2;
  7922. result[15] = 1.0;
  7923. return result;
  7924. };
  7925. /**
  7926. * Computes a Matrix4 instance representing a perspective transformation matrix.
  7927. *
  7928. * @param {Number} fovY The field of view along the Y axis in radians.
  7929. * @param {Number} aspectRatio The aspect ratio.
  7930. * @param {Number} near The distance to the near plane in meters.
  7931. * @param {Number} far The distance to the far plane in meters.
  7932. * @param {Matrix4} result The object in which the result will be stored.
  7933. * @returns {Matrix4} The modified result parameter.
  7934. *
  7935. * @exception {DeveloperError} fovY must be in (0, PI].
  7936. * @exception {DeveloperError} aspectRatio must be greater than zero.
  7937. * @exception {DeveloperError} near must be greater than zero.
  7938. * @exception {DeveloperError} far must be greater than zero.
  7939. */
  7940. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  7941. if (fovY <= 0.0 || fovY > Math.PI) {
  7942. throw new DeveloperError('fovY must be in (0, PI].');
  7943. }
  7944. if (aspectRatio <= 0.0) {
  7945. throw new DeveloperError('aspectRatio must be greater than zero.');
  7946. }
  7947. if (near <= 0.0) {
  7948. throw new DeveloperError('near must be greater than zero.');
  7949. }
  7950. if (far <= 0.0) {
  7951. throw new DeveloperError('far must be greater than zero.');
  7952. }
  7953. if (!defined(result)) {
  7954. throw new DeveloperError('result is required');
  7955. }
  7956. var bottom = Math.tan(fovY * 0.5);
  7957. var column1Row1 = 1.0 / bottom;
  7958. var column0Row0 = column1Row1 / aspectRatio;
  7959. var column2Row2 = (far + near) / (near - far);
  7960. var column3Row2 = (2.0 * far * near) / (near - far);
  7961. result[0] = column0Row0;
  7962. result[1] = 0.0;
  7963. result[2] = 0.0;
  7964. result[3] = 0.0;
  7965. result[4] = 0.0;
  7966. result[5] = column1Row1;
  7967. result[6] = 0.0;
  7968. result[7] = 0.0;
  7969. result[8] = 0.0;
  7970. result[9] = 0.0;
  7971. result[10] = column2Row2;
  7972. result[11] = -1.0;
  7973. result[12] = 0.0;
  7974. result[13] = 0.0;
  7975. result[14] = column3Row2;
  7976. result[15] = 0.0;
  7977. return result;
  7978. };
  7979. /**
  7980. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  7981. *
  7982. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7983. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7984. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7985. * @param {Number} top The number of meters above of the camera that will be in view.
  7986. * @param {Number} near The distance to the near plane in meters.
  7987. * @param {Number} far The distance to the far plane in meters.
  7988. * @param {Matrix4} result The object in which the result will be stored.
  7989. * @returns {Matrix4} The modified result parameter.
  7990. */
  7991. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  7992. if (!defined(left)) {
  7993. throw new DeveloperError('left is required.');
  7994. }
  7995. if (!defined(right)) {
  7996. throw new DeveloperError('right is required.');
  7997. }
  7998. if (!defined(bottom)) {
  7999. throw new DeveloperError('bottom is required.');
  8000. }
  8001. if (!defined(top)) {
  8002. throw new DeveloperError('top is required.');
  8003. }
  8004. if (!defined(near)) {
  8005. throw new DeveloperError('near is required.');
  8006. }
  8007. if (!defined(far)) {
  8008. throw new DeveloperError('far is required.');
  8009. }
  8010. if (!defined(result)) {
  8011. throw new DeveloperError('result is required');
  8012. }
  8013. var a = 1.0 / (right - left);
  8014. var b = 1.0 / (top - bottom);
  8015. var c = 1.0 / (far - near);
  8016. var tx = -(right + left) * a;
  8017. var ty = -(top + bottom) * b;
  8018. var tz = -(far + near) * c;
  8019. a *= 2.0;
  8020. b *= 2.0;
  8021. c *= -2.0;
  8022. result[0] = a;
  8023. result[1] = 0.0;
  8024. result[2] = 0.0;
  8025. result[3] = 0.0;
  8026. result[4] = 0.0;
  8027. result[5] = b;
  8028. result[6] = 0.0;
  8029. result[7] = 0.0;
  8030. result[8] = 0.0;
  8031. result[9] = 0.0;
  8032. result[10] = c;
  8033. result[11] = 0.0;
  8034. result[12] = tx;
  8035. result[13] = ty;
  8036. result[14] = tz;
  8037. result[15] = 1.0;
  8038. return result;
  8039. };
  8040. /**
  8041. * Computes a Matrix4 instance representing an off center perspective transformation.
  8042. *
  8043. * @param {Number} left The number of meters to the left of the camera that will be in view.
  8044. * @param {Number} right The number of meters to the right of the camera that will be in view.
  8045. * @param {Number} bottom The number of meters below of the camera that will be in view.
  8046. * @param {Number} top The number of meters above of the camera that will be in view.
  8047. * @param {Number} near The distance to the near plane in meters.
  8048. * @param {Number} far The distance to the far plane in meters.
  8049. * @param {Matrix4} result The object in which the result will be stored.
  8050. * @returns {Matrix4} The modified result parameter.
  8051. */
  8052. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  8053. if (!defined(left)) {
  8054. throw new DeveloperError('left is required.');
  8055. }
  8056. if (!defined(right)) {
  8057. throw new DeveloperError('right is required.');
  8058. }
  8059. if (!defined(bottom)) {
  8060. throw new DeveloperError('bottom is required.');
  8061. }
  8062. if (!defined(top)) {
  8063. throw new DeveloperError('top is required.');
  8064. }
  8065. if (!defined(near)) {
  8066. throw new DeveloperError('near is required.');
  8067. }
  8068. if (!defined(far)) {
  8069. throw new DeveloperError('far is required.');
  8070. }
  8071. if (!defined(result)) {
  8072. throw new DeveloperError('result is required');
  8073. }
  8074. var column0Row0 = 2.0 * near / (right - left);
  8075. var column1Row1 = 2.0 * near / (top - bottom);
  8076. var column2Row0 = (right + left) / (right - left);
  8077. var column2Row1 = (top + bottom) / (top - bottom);
  8078. var column2Row2 = -(far + near) / (far - near);
  8079. var column2Row3 = -1.0;
  8080. var column3Row2 = -2.0 * far * near / (far - near);
  8081. result[0] = column0Row0;
  8082. result[1] = 0.0;
  8083. result[2] = 0.0;
  8084. result[3] = 0.0;
  8085. result[4] = 0.0;
  8086. result[5] = column1Row1;
  8087. result[6] = 0.0;
  8088. result[7] = 0.0;
  8089. result[8] = column2Row0;
  8090. result[9] = column2Row1;
  8091. result[10] = column2Row2;
  8092. result[11] = column2Row3;
  8093. result[12] = 0.0;
  8094. result[13] = 0.0;
  8095. result[14] = column3Row2;
  8096. result[15] = 0.0;
  8097. return result;
  8098. };
  8099. /**
  8100. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  8101. *
  8102. * @param {Number} left The number of meters to the left of the camera that will be in view.
  8103. * @param {Number} right The number of meters to the right of the camera that will be in view.
  8104. * @param {Number} bottom The number of meters below of the camera that will be in view.
  8105. * @param {Number} top The number of meters above of the camera that will be in view.
  8106. * @param {Number} near The distance to the near plane in meters.
  8107. * @param {Matrix4} result The object in which the result will be stored.
  8108. * @returns {Matrix4} The modified result parameter.
  8109. */
  8110. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  8111. if (!defined(left)) {
  8112. throw new DeveloperError('left is required.');
  8113. }
  8114. if (!defined(right)) {
  8115. throw new DeveloperError('right is required.');
  8116. }
  8117. if (!defined(bottom)) {
  8118. throw new DeveloperError('bottom is required.');
  8119. }
  8120. if (!defined(top)) {
  8121. throw new DeveloperError('top is required.');
  8122. }
  8123. if (!defined(near)) {
  8124. throw new DeveloperError('near is required.');
  8125. }
  8126. if (!defined(result)) {
  8127. throw new DeveloperError('result is required');
  8128. }
  8129. var column0Row0 = 2.0 * near / (right - left);
  8130. var column1Row1 = 2.0 * near / (top - bottom);
  8131. var column2Row0 = (right + left) / (right - left);
  8132. var column2Row1 = (top + bottom) / (top - bottom);
  8133. var column2Row2 = -1.0;
  8134. var column2Row3 = -1.0;
  8135. var column3Row2 = -2.0 * near;
  8136. result[0] = column0Row0;
  8137. result[1] = 0.0;
  8138. result[2] = 0.0;
  8139. result[3] = 0.0;
  8140. result[4] = 0.0;
  8141. result[5] = column1Row1;
  8142. result[6] = 0.0;
  8143. result[7] = 0.0;
  8144. result[8] = column2Row0;
  8145. result[9] = column2Row1;
  8146. result[10] = column2Row2;
  8147. result[11] = column2Row3;
  8148. result[12] = 0.0;
  8149. result[13] = 0.0;
  8150. result[14] = column3Row2;
  8151. result[15] = 0.0;
  8152. return result;
  8153. };
  8154. /**
  8155. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  8156. *
  8157. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  8158. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  8159. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  8160. * @param {Matrix4} result The object in which the result will be stored.
  8161. * @returns {Matrix4} The modified result parameter.
  8162. *
  8163. * @example
  8164. * // Create viewport transformation using an explicit viewport and depth range.
  8165. * var m = Cesium.Matrix4.computeViewportTransformation({
  8166. * x : 0.0,
  8167. * y : 0.0,
  8168. * width : 1024.0,
  8169. * height : 768.0
  8170. * }, 0.0, 1.0, new Cesium.Matrix4());
  8171. */
  8172. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  8173. if (!defined(result)) {
  8174. throw new DeveloperError('result is required');
  8175. }
  8176. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  8177. var x = defaultValue(viewport.x, 0.0);
  8178. var y = defaultValue(viewport.y, 0.0);
  8179. var width = defaultValue(viewport.width, 0.0);
  8180. var height = defaultValue(viewport.height, 0.0);
  8181. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  8182. farDepthRange = defaultValue(farDepthRange, 1.0);
  8183. var halfWidth = width * 0.5;
  8184. var halfHeight = height * 0.5;
  8185. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  8186. var column0Row0 = halfWidth;
  8187. var column1Row1 = halfHeight;
  8188. var column2Row2 = halfDepth;
  8189. var column3Row0 = x + halfWidth;
  8190. var column3Row1 = y + halfHeight;
  8191. var column3Row2 = nearDepthRange + halfDepth;
  8192. var column3Row3 = 1.0;
  8193. result[0] = column0Row0;
  8194. result[1] = 0.0;
  8195. result[2] = 0.0;
  8196. result[3] = 0.0;
  8197. result[4] = 0.0;
  8198. result[5] = column1Row1;
  8199. result[6] = 0.0;
  8200. result[7] = 0.0;
  8201. result[8] = 0.0;
  8202. result[9] = 0.0;
  8203. result[10] = column2Row2;
  8204. result[11] = 0.0;
  8205. result[12] = column3Row0;
  8206. result[13] = column3Row1;
  8207. result[14] = column3Row2;
  8208. result[15] = column3Row3;
  8209. return result;
  8210. };
  8211. /**
  8212. * Computes a Matrix4 instance that transforms from world space to view space.
  8213. *
  8214. * @param {Cartesian3} position The position of the camera.
  8215. * @param {Cartesian3} direction The forward direction.
  8216. * @param {Cartesian3} up The up direction.
  8217. * @param {Cartesian3} right The right direction.
  8218. * @param {Matrix4} result The object in which the result will be stored.
  8219. * @returns {Matrix4} The modified result parameter.
  8220. */
  8221. Matrix4.computeView = function(position, direction, up, right, result) {
  8222. if (!defined(position)) {
  8223. throw new DeveloperError('position is required');
  8224. }
  8225. if (!defined(direction)) {
  8226. throw new DeveloperError('direction is required');
  8227. }
  8228. if (!defined(up)) {
  8229. throw new DeveloperError('up is required');
  8230. }
  8231. if (!defined(right)) {
  8232. throw new DeveloperError('right is required');
  8233. }
  8234. if (!defined(result)) {
  8235. throw new DeveloperError('result is required');
  8236. }
  8237. result[0] = right.x;
  8238. result[1] = up.x;
  8239. result[2] = -direction.x;
  8240. result[3] = 0.0;
  8241. result[4] = right.y;
  8242. result[5] = up.y;
  8243. result[6] = -direction.y;
  8244. result[7] = 0.0;
  8245. result[8] = right.z;
  8246. result[9] = up.z;
  8247. result[10] = -direction.z;
  8248. result[11] = 0.0;
  8249. result[12] = -Cartesian3.dot(right, position);
  8250. result[13] = -Cartesian3.dot(up, position);
  8251. result[14] = Cartesian3.dot(direction, position);
  8252. result[15] = 1.0;
  8253. return result;
  8254. };
  8255. /**
  8256. * Computes an Array from the provided Matrix4 instance.
  8257. * The array will be in column-major order.
  8258. *
  8259. * @param {Matrix4} matrix The matrix to use..
  8260. * @param {Number[]} [result] The Array onto which to store the result.
  8261. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  8262. *
  8263. * @example
  8264. * //create an array from an instance of Matrix4
  8265. * // m = [10.0, 14.0, 18.0, 22.0]
  8266. * // [11.0, 15.0, 19.0, 23.0]
  8267. * // [12.0, 16.0, 20.0, 24.0]
  8268. * // [13.0, 17.0, 21.0, 25.0]
  8269. * var a = Cesium.Matrix4.toArray(m);
  8270. *
  8271. * // m remains the same
  8272. * //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
  8273. */
  8274. Matrix4.toArray = function(matrix, result) {
  8275. if (!defined(matrix)) {
  8276. throw new DeveloperError('matrix is required');
  8277. }
  8278. if (!defined(result)) {
  8279. return [matrix[0], matrix[1], matrix[2], matrix[3],
  8280. matrix[4], matrix[5], matrix[6], matrix[7],
  8281. matrix[8], matrix[9], matrix[10], matrix[11],
  8282. matrix[12], matrix[13], matrix[14], matrix[15]];
  8283. }
  8284. result[0] = matrix[0];
  8285. result[1] = matrix[1];
  8286. result[2] = matrix[2];
  8287. result[3] = matrix[3];
  8288. result[4] = matrix[4];
  8289. result[5] = matrix[5];
  8290. result[6] = matrix[6];
  8291. result[7] = matrix[7];
  8292. result[8] = matrix[8];
  8293. result[9] = matrix[9];
  8294. result[10] = matrix[10];
  8295. result[11] = matrix[11];
  8296. result[12] = matrix[12];
  8297. result[13] = matrix[13];
  8298. result[14] = matrix[14];
  8299. result[15] = matrix[15];
  8300. return result;
  8301. };
  8302. /**
  8303. * Computes the array index of the element at the provided row and column.
  8304. *
  8305. * @param {Number} row The zero-based index of the row.
  8306. * @param {Number} column The zero-based index of the column.
  8307. * @returns {Number} The index of the element at the provided row and column.
  8308. *
  8309. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  8310. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  8311. *
  8312. * @example
  8313. * var myMatrix = new Cesium.Matrix4();
  8314. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  8315. * var column1Row0 = myMatrix[column1Row0Index];
  8316. * myMatrix[column1Row0Index] = 10.0;
  8317. */
  8318. Matrix4.getElementIndex = function(column, row) {
  8319. if (typeof row !== 'number' || row < 0 || row > 3) {
  8320. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  8321. }
  8322. if (typeof column !== 'number' || column < 0 || column > 3) {
  8323. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  8324. }
  8325. return column * 4 + row;
  8326. };
  8327. /**
  8328. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  8329. *
  8330. * @param {Matrix4} matrix The matrix to use.
  8331. * @param {Number} index The zero-based index of the column to retrieve.
  8332. * @param {Cartesian4} result The object onto which to store the result.
  8333. * @returns {Cartesian4} The modified result parameter.
  8334. *
  8335. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8336. *
  8337. * @example
  8338. * //returns a Cartesian4 instance with values from the specified column
  8339. * // m = [10.0, 11.0, 12.0, 13.0]
  8340. * // [14.0, 15.0, 16.0, 17.0]
  8341. * // [18.0, 19.0, 20.0, 21.0]
  8342. * // [22.0, 23.0, 24.0, 25.0]
  8343. *
  8344. * //Example 1: Creates an instance of Cartesian
  8345. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  8346. *
  8347. * @example
  8348. * //Example 2: Sets values for Cartesian instance
  8349. * var a = new Cesium.Cartesian4();
  8350. * Cesium.Matrix4.getColumn(m, 2, a);
  8351. *
  8352. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  8353. */
  8354. Matrix4.getColumn = function(matrix, index, result) {
  8355. if (!defined(matrix)) {
  8356. throw new DeveloperError('matrix is required.');
  8357. }
  8358. if (typeof index !== 'number' || index < 0 || index > 3) {
  8359. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8360. }
  8361. if (!defined(result)) {
  8362. throw new DeveloperError('result is required');
  8363. }
  8364. var startIndex = index * 4;
  8365. var x = matrix[startIndex];
  8366. var y = matrix[startIndex + 1];
  8367. var z = matrix[startIndex + 2];
  8368. var w = matrix[startIndex + 3];
  8369. result.x = x;
  8370. result.y = y;
  8371. result.z = z;
  8372. result.w = w;
  8373. return result;
  8374. };
  8375. /**
  8376. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  8377. *
  8378. * @param {Matrix4} matrix The matrix to use.
  8379. * @param {Number} index The zero-based index of the column to set.
  8380. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  8381. * @param {Matrix4} result The object onto which to store the result.
  8382. * @returns {Matrix4} The modified result parameter.
  8383. *
  8384. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8385. *
  8386. * @example
  8387. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  8388. * // m = [10.0, 11.0, 12.0, 13.0]
  8389. * // [14.0, 15.0, 16.0, 17.0]
  8390. * // [18.0, 19.0, 20.0, 21.0]
  8391. * // [22.0, 23.0, 24.0, 25.0]
  8392. *
  8393. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8394. *
  8395. * // m remains the same
  8396. * // a = [10.0, 11.0, 99.0, 13.0]
  8397. * // [14.0, 15.0, 98.0, 17.0]
  8398. * // [18.0, 19.0, 97.0, 21.0]
  8399. * // [22.0, 23.0, 96.0, 25.0]
  8400. */
  8401. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  8402. if (!defined(matrix)) {
  8403. throw new DeveloperError('matrix is required');
  8404. }
  8405. if (!defined(cartesian)) {
  8406. throw new DeveloperError('cartesian is required');
  8407. }
  8408. if (typeof index !== 'number' || index < 0 || index > 3) {
  8409. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8410. }
  8411. if (!defined(result)) {
  8412. throw new DeveloperError('result is required');
  8413. }
  8414. result = Matrix4.clone(matrix, result);
  8415. var startIndex = index * 4;
  8416. result[startIndex] = cartesian.x;
  8417. result[startIndex + 1] = cartesian.y;
  8418. result[startIndex + 2] = cartesian.z;
  8419. result[startIndex + 3] = cartesian.w;
  8420. return result;
  8421. };
  8422. /**
  8423. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  8424. * matrix with the provided translation. This assumes the matrix is an affine transformation
  8425. *
  8426. * @param {Matrix4} matrix The matrix to use.
  8427. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  8428. * @param {Cartesian4} result The object onto which to store the result.
  8429. * @returns {Matrix4} The modified result parameter.
  8430. */
  8431. Matrix4.setTranslation = function(matrix, translation, result) {
  8432. if (!defined(matrix)) {
  8433. throw new DeveloperError('matrix is required');
  8434. }
  8435. if (!defined(translation)) {
  8436. throw new DeveloperError('translation is required');
  8437. }
  8438. if (!defined(result)) {
  8439. throw new DeveloperError('result is required');
  8440. }
  8441. result[0] = matrix[0];
  8442. result[1] = matrix[1];
  8443. result[2] = matrix[2];
  8444. result[3] = matrix[3];
  8445. result[4] = matrix[4];
  8446. result[5] = matrix[5];
  8447. result[6] = matrix[6];
  8448. result[7] = matrix[7];
  8449. result[8] = matrix[8];
  8450. result[9] = matrix[9];
  8451. result[10] = matrix[10];
  8452. result[11] = matrix[11];
  8453. result[12] = translation.x;
  8454. result[13] = translation.y;
  8455. result[14] = translation.z;
  8456. result[15] = matrix[15];
  8457. return result;
  8458. };
  8459. /**
  8460. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  8461. *
  8462. * @param {Matrix4} matrix The matrix to use.
  8463. * @param {Number} index The zero-based index of the row to retrieve.
  8464. * @param {Cartesian4} result The object onto which to store the result.
  8465. * @returns {Cartesian4} The modified result parameter.
  8466. *
  8467. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8468. *
  8469. * @example
  8470. * //returns a Cartesian4 instance with values from the specified column
  8471. * // m = [10.0, 11.0, 12.0, 13.0]
  8472. * // [14.0, 15.0, 16.0, 17.0]
  8473. * // [18.0, 19.0, 20.0, 21.0]
  8474. * // [22.0, 23.0, 24.0, 25.0]
  8475. *
  8476. * //Example 1: Returns an instance of Cartesian
  8477. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  8478. *
  8479. * @example
  8480. * //Example 2: Sets values for a Cartesian instance
  8481. * var a = new Cesium.Cartesian4();
  8482. * Cesium.Matrix4.getRow(m, 2, a);
  8483. *
  8484. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  8485. */
  8486. Matrix4.getRow = function(matrix, index, result) {
  8487. if (!defined(matrix)) {
  8488. throw new DeveloperError('matrix is required.');
  8489. }
  8490. if (typeof index !== 'number' || index < 0 || index > 3) {
  8491. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8492. }
  8493. if (!defined(result)) {
  8494. throw new DeveloperError('result is required');
  8495. }
  8496. var x = matrix[index];
  8497. var y = matrix[index + 4];
  8498. var z = matrix[index + 8];
  8499. var w = matrix[index + 12];
  8500. result.x = x;
  8501. result.y = y;
  8502. result.z = z;
  8503. result.w = w;
  8504. return result;
  8505. };
  8506. /**
  8507. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  8508. *
  8509. * @param {Matrix4} matrix The matrix to use.
  8510. * @param {Number} index The zero-based index of the row to set.
  8511. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  8512. * @param {Matrix4} result The object onto which to store the result.
  8513. * @returns {Matrix4} The modified result parameter.
  8514. *
  8515. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8516. *
  8517. * @example
  8518. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  8519. * // m = [10.0, 11.0, 12.0, 13.0]
  8520. * // [14.0, 15.0, 16.0, 17.0]
  8521. * // [18.0, 19.0, 20.0, 21.0]
  8522. * // [22.0, 23.0, 24.0, 25.0]
  8523. *
  8524. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8525. *
  8526. * // m remains the same
  8527. * // a = [10.0, 11.0, 12.0, 13.0]
  8528. * // [14.0, 15.0, 16.0, 17.0]
  8529. * // [99.0, 98.0, 97.0, 96.0]
  8530. * // [22.0, 23.0, 24.0, 25.0]
  8531. */
  8532. Matrix4.setRow = function(matrix, index, cartesian, result) {
  8533. if (!defined(matrix)) {
  8534. throw new DeveloperError('matrix is required');
  8535. }
  8536. if (!defined(cartesian)) {
  8537. throw new DeveloperError('cartesian is required');
  8538. }
  8539. if (typeof index !== 'number' || index < 0 || index > 3) {
  8540. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8541. }
  8542. if (!defined(result)) {
  8543. throw new DeveloperError('result is required');
  8544. }
  8545. result = Matrix4.clone(matrix, result);
  8546. result[index] = cartesian.x;
  8547. result[index + 4] = cartesian.y;
  8548. result[index + 8] = cartesian.z;
  8549. result[index + 12] = cartesian.w;
  8550. return result;
  8551. };
  8552. var scratchColumn = new Cartesian3();
  8553. /**
  8554. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  8555. *
  8556. * @param {Matrix4} matrix The matrix.
  8557. * @param {Cartesian3} result The object onto which to store the result.
  8558. * @returns {Cartesian3} The modified result parameter
  8559. */
  8560. Matrix4.getScale = function(matrix, result) {
  8561. if (!defined(matrix)) {
  8562. throw new DeveloperError('matrix is required.');
  8563. }
  8564. if (!defined(result)) {
  8565. throw new DeveloperError('result is required');
  8566. }
  8567. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  8568. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  8569. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  8570. return result;
  8571. };
  8572. var scratchScale = new Cartesian3();
  8573. /**
  8574. * Computes the maximum scale assuming the matrix is an affine transformation.
  8575. * The maximum scale is the maximum length of the column vectors in the upper-left
  8576. * 3x3 matrix.
  8577. *
  8578. * @param {Matrix4} matrix The matrix.
  8579. * @returns {Number} The maximum scale.
  8580. */
  8581. Matrix4.getMaximumScale = function(matrix) {
  8582. Matrix4.getScale(matrix, scratchScale);
  8583. return Cartesian3.maximumComponent(scratchScale);
  8584. };
  8585. /**
  8586. * Computes the product of two matrices.
  8587. *
  8588. * @param {Matrix4} left The first matrix.
  8589. * @param {Matrix4} right The second matrix.
  8590. * @param {Matrix4} result The object onto which to store the result.
  8591. * @returns {Matrix4} The modified result parameter.
  8592. */
  8593. Matrix4.multiply = function(left, right, result) {
  8594. if (!defined(left)) {
  8595. throw new DeveloperError('left is required');
  8596. }
  8597. if (!defined(right)) {
  8598. throw new DeveloperError('right is required');
  8599. }
  8600. if (!defined(result)) {
  8601. throw new DeveloperError('result is required');
  8602. }
  8603. var left0 = left[0];
  8604. var left1 = left[1];
  8605. var left2 = left[2];
  8606. var left3 = left[3];
  8607. var left4 = left[4];
  8608. var left5 = left[5];
  8609. var left6 = left[6];
  8610. var left7 = left[7];
  8611. var left8 = left[8];
  8612. var left9 = left[9];
  8613. var left10 = left[10];
  8614. var left11 = left[11];
  8615. var left12 = left[12];
  8616. var left13 = left[13];
  8617. var left14 = left[14];
  8618. var left15 = left[15];
  8619. var right0 = right[0];
  8620. var right1 = right[1];
  8621. var right2 = right[2];
  8622. var right3 = right[3];
  8623. var right4 = right[4];
  8624. var right5 = right[5];
  8625. var right6 = right[6];
  8626. var right7 = right[7];
  8627. var right8 = right[8];
  8628. var right9 = right[9];
  8629. var right10 = right[10];
  8630. var right11 = right[11];
  8631. var right12 = right[12];
  8632. var right13 = right[13];
  8633. var right14 = right[14];
  8634. var right15 = right[15];
  8635. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  8636. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  8637. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  8638. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  8639. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  8640. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  8641. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  8642. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  8643. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  8644. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  8645. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  8646. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  8647. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  8648. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  8649. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  8650. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  8651. result[0] = column0Row0;
  8652. result[1] = column0Row1;
  8653. result[2] = column0Row2;
  8654. result[3] = column0Row3;
  8655. result[4] = column1Row0;
  8656. result[5] = column1Row1;
  8657. result[6] = column1Row2;
  8658. result[7] = column1Row3;
  8659. result[8] = column2Row0;
  8660. result[9] = column2Row1;
  8661. result[10] = column2Row2;
  8662. result[11] = column2Row3;
  8663. result[12] = column3Row0;
  8664. result[13] = column3Row1;
  8665. result[14] = column3Row2;
  8666. result[15] = column3Row3;
  8667. return result;
  8668. };
  8669. /**
  8670. * Computes the sum of two matrices.
  8671. *
  8672. * @param {Matrix4} left The first matrix.
  8673. * @param {Matrix4} right The second matrix.
  8674. * @param {Matrix4} result The object onto which to store the result.
  8675. * @returns {Matrix4} The modified result parameter.
  8676. */
  8677. Matrix4.add = function(left, right, result) {
  8678. if (!defined(left)) {
  8679. throw new DeveloperError('left is required');
  8680. }
  8681. if (!defined(right)) {
  8682. throw new DeveloperError('right is required');
  8683. }
  8684. if (!defined(result)) {
  8685. throw new DeveloperError('result is required');
  8686. }
  8687. result[0] = left[0] + right[0];
  8688. result[1] = left[1] + right[1];
  8689. result[2] = left[2] + right[2];
  8690. result[3] = left[3] + right[3];
  8691. result[4] = left[4] + right[4];
  8692. result[5] = left[5] + right[5];
  8693. result[6] = left[6] + right[6];
  8694. result[7] = left[7] + right[7];
  8695. result[8] = left[8] + right[8];
  8696. result[9] = left[9] + right[9];
  8697. result[10] = left[10] + right[10];
  8698. result[11] = left[11] + right[11];
  8699. result[12] = left[12] + right[12];
  8700. result[13] = left[13] + right[13];
  8701. result[14] = left[14] + right[14];
  8702. result[15] = left[15] + right[15];
  8703. return result;
  8704. };
  8705. /**
  8706. * Computes the difference of two matrices.
  8707. *
  8708. * @param {Matrix4} left The first matrix.
  8709. * @param {Matrix4} right The second matrix.
  8710. * @param {Matrix4} result The object onto which to store the result.
  8711. * @returns {Matrix4} The modified result parameter.
  8712. */
  8713. Matrix4.subtract = function(left, right, result) {
  8714. if (!defined(left)) {
  8715. throw new DeveloperError('left is required');
  8716. }
  8717. if (!defined(right)) {
  8718. throw new DeveloperError('right is required');
  8719. }
  8720. if (!defined(result)) {
  8721. throw new DeveloperError('result is required');
  8722. }
  8723. result[0] = left[0] - right[0];
  8724. result[1] = left[1] - right[1];
  8725. result[2] = left[2] - right[2];
  8726. result[3] = left[3] - right[3];
  8727. result[4] = left[4] - right[4];
  8728. result[5] = left[5] - right[5];
  8729. result[6] = left[6] - right[6];
  8730. result[7] = left[7] - right[7];
  8731. result[8] = left[8] - right[8];
  8732. result[9] = left[9] - right[9];
  8733. result[10] = left[10] - right[10];
  8734. result[11] = left[11] - right[11];
  8735. result[12] = left[12] - right[12];
  8736. result[13] = left[13] - right[13];
  8737. result[14] = left[14] - right[14];
  8738. result[15] = left[15] - right[15];
  8739. return result;
  8740. };
  8741. /**
  8742. * Computes the product of two matrices assuming the matrices are
  8743. * affine transformation matrices, where the upper left 3x3 elements
  8744. * are a rotation matrix, and the upper three elements in the fourth
  8745. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  8746. * The matrix is not verified to be in the proper form.
  8747. * This method is faster than computing the product for general 4x4
  8748. * matrices using {@link Matrix4.multiply}.
  8749. *
  8750. * @param {Matrix4} left The first matrix.
  8751. * @param {Matrix4} right The second matrix.
  8752. * @param {Matrix4} result The object onto which to store the result.
  8753. * @returns {Matrix4} The modified result parameter.
  8754. *
  8755. * @example
  8756. * var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  8757. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  8758. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  8759. */
  8760. Matrix4.multiplyTransformation = function(left, right, result) {
  8761. if (!defined(left)) {
  8762. throw new DeveloperError('left is required');
  8763. }
  8764. if (!defined(right)) {
  8765. throw new DeveloperError('right is required');
  8766. }
  8767. if (!defined(result)) {
  8768. throw new DeveloperError('result is required');
  8769. }
  8770. var left0 = left[0];
  8771. var left1 = left[1];
  8772. var left2 = left[2];
  8773. var left4 = left[4];
  8774. var left5 = left[5];
  8775. var left6 = left[6];
  8776. var left8 = left[8];
  8777. var left9 = left[9];
  8778. var left10 = left[10];
  8779. var left12 = left[12];
  8780. var left13 = left[13];
  8781. var left14 = left[14];
  8782. var right0 = right[0];
  8783. var right1 = right[1];
  8784. var right2 = right[2];
  8785. var right4 = right[4];
  8786. var right5 = right[5];
  8787. var right6 = right[6];
  8788. var right8 = right[8];
  8789. var right9 = right[9];
  8790. var right10 = right[10];
  8791. var right12 = right[12];
  8792. var right13 = right[13];
  8793. var right14 = right[14];
  8794. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8795. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8796. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8797. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8798. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8799. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8800. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8801. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8802. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8803. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  8804. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  8805. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  8806. result[0] = column0Row0;
  8807. result[1] = column0Row1;
  8808. result[2] = column0Row2;
  8809. result[3] = 0.0;
  8810. result[4] = column1Row0;
  8811. result[5] = column1Row1;
  8812. result[6] = column1Row2;
  8813. result[7] = 0.0;
  8814. result[8] = column2Row0;
  8815. result[9] = column2Row1;
  8816. result[10] = column2Row2;
  8817. result[11] = 0.0;
  8818. result[12] = column3Row0;
  8819. result[13] = column3Row1;
  8820. result[14] = column3Row2;
  8821. result[15] = 1.0;
  8822. return result;
  8823. };
  8824. /**
  8825. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8826. * by a 3x3 rotation matrix. This is an optimization
  8827. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  8828. *
  8829. * @param {Matrix4} matrix The matrix on the left-hand side.
  8830. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  8831. * @param {Matrix4} result The object onto which to store the result.
  8832. * @returns {Matrix4} The modified result parameter.
  8833. *
  8834. * @example
  8835. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  8836. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  8837. */
  8838. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  8839. if (!defined(matrix)) {
  8840. throw new DeveloperError('matrix is required');
  8841. }
  8842. if (!defined(rotation)) {
  8843. throw new DeveloperError('rotation is required');
  8844. }
  8845. if (!defined(result)) {
  8846. throw new DeveloperError('result is required');
  8847. }
  8848. var left0 = matrix[0];
  8849. var left1 = matrix[1];
  8850. var left2 = matrix[2];
  8851. var left4 = matrix[4];
  8852. var left5 = matrix[5];
  8853. var left6 = matrix[6];
  8854. var left8 = matrix[8];
  8855. var left9 = matrix[9];
  8856. var left10 = matrix[10];
  8857. var right0 = rotation[0];
  8858. var right1 = rotation[1];
  8859. var right2 = rotation[2];
  8860. var right4 = rotation[3];
  8861. var right5 = rotation[4];
  8862. var right6 = rotation[5];
  8863. var right8 = rotation[6];
  8864. var right9 = rotation[7];
  8865. var right10 = rotation[8];
  8866. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8867. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8868. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8869. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8870. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8871. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8872. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8873. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8874. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8875. result[0] = column0Row0;
  8876. result[1] = column0Row1;
  8877. result[2] = column0Row2;
  8878. result[3] = 0.0;
  8879. result[4] = column1Row0;
  8880. result[5] = column1Row1;
  8881. result[6] = column1Row2;
  8882. result[7] = 0.0;
  8883. result[8] = column2Row0;
  8884. result[9] = column2Row1;
  8885. result[10] = column2Row2;
  8886. result[11] = 0.0;
  8887. result[12] = matrix[12];
  8888. result[13] = matrix[13];
  8889. result[14] = matrix[14];
  8890. result[15] = matrix[15];
  8891. return result;
  8892. };
  8893. /**
  8894. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8895. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  8896. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  8897. *
  8898. * @param {Matrix4} matrix The matrix on the left-hand side.
  8899. * @param {Cartesian3} translation The translation on the right-hand side.
  8900. * @param {Matrix4} result The object onto which to store the result.
  8901. * @returns {Matrix4} The modified result parameter.
  8902. *
  8903. * @example
  8904. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  8905. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  8906. */
  8907. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  8908. if (!defined(matrix)) {
  8909. throw new DeveloperError('matrix is required');
  8910. }
  8911. if (!defined(translation)) {
  8912. throw new DeveloperError('translation is required');
  8913. }
  8914. if (!defined(result)) {
  8915. throw new DeveloperError('result is required');
  8916. }
  8917. var x = translation.x;
  8918. var y = translation.y;
  8919. var z = translation.z;
  8920. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  8921. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  8922. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  8923. result[0] = matrix[0];
  8924. result[1] = matrix[1];
  8925. result[2] = matrix[2];
  8926. result[3] = matrix[3];
  8927. result[4] = matrix[4];
  8928. result[5] = matrix[5];
  8929. result[6] = matrix[6];
  8930. result[7] = matrix[7];
  8931. result[8] = matrix[8];
  8932. result[9] = matrix[9];
  8933. result[10] = matrix[10];
  8934. result[11] = matrix[11];
  8935. result[12] = tx;
  8936. result[13] = ty;
  8937. result[14] = tz;
  8938. result[15] = matrix[15];
  8939. return result;
  8940. };
  8941. var uniformScaleScratch = new Cartesian3();
  8942. /**
  8943. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8944. * by an implicit uniform scale matrix. This is an optimization
  8945. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8946. * <code>m</code> must be an affine matrix.
  8947. * This function performs fewer allocations and arithmetic operations.
  8948. *
  8949. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8950. * @param {Number} scale The uniform scale on the right-hand side.
  8951. * @param {Matrix4} result The object onto which to store the result.
  8952. * @returns {Matrix4} The modified result parameter.
  8953. *
  8954. *
  8955. * @example
  8956. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  8957. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  8958. *
  8959. * @see Matrix4.fromUniformScale
  8960. * @see Matrix4.multiplyByScale
  8961. */
  8962. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  8963. if (!defined(matrix)) {
  8964. throw new DeveloperError('matrix is required');
  8965. }
  8966. if (typeof scale !== 'number') {
  8967. throw new DeveloperError('scale is required');
  8968. }
  8969. if (!defined(result)) {
  8970. throw new DeveloperError('result is required');
  8971. }
  8972. uniformScaleScratch.x = scale;
  8973. uniformScaleScratch.y = scale;
  8974. uniformScaleScratch.z = scale;
  8975. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  8976. };
  8977. /**
  8978. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8979. * by an implicit non-uniform scale matrix. This is an optimization
  8980. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8981. * <code>m</code> must be an affine matrix.
  8982. * This function performs fewer allocations and arithmetic operations.
  8983. *
  8984. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8985. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  8986. * @param {Matrix4} result The object onto which to store the result.
  8987. * @returns {Matrix4} The modified result parameter.
  8988. *
  8989. *
  8990. * @example
  8991. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  8992. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  8993. *
  8994. * @see Matrix4.fromScale
  8995. * @see Matrix4.multiplyByUniformScale
  8996. */
  8997. Matrix4.multiplyByScale = function(matrix, scale, result) {
  8998. if (!defined(matrix)) {
  8999. throw new DeveloperError('matrix is required');
  9000. }
  9001. if (!defined(scale)) {
  9002. throw new DeveloperError('scale is required');
  9003. }
  9004. if (!defined(result)) {
  9005. throw new DeveloperError('result is required');
  9006. }
  9007. var scaleX = scale.x;
  9008. var scaleY = scale.y;
  9009. var scaleZ = scale.z;
  9010. // Faster than Cartesian3.equals
  9011. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  9012. return Matrix4.clone(matrix, result);
  9013. }
  9014. result[0] = scaleX * matrix[0];
  9015. result[1] = scaleX * matrix[1];
  9016. result[2] = scaleX * matrix[2];
  9017. result[3] = 0.0;
  9018. result[4] = scaleY * matrix[4];
  9019. result[5] = scaleY * matrix[5];
  9020. result[6] = scaleY * matrix[6];
  9021. result[7] = 0.0;
  9022. result[8] = scaleZ * matrix[8];
  9023. result[9] = scaleZ * matrix[9];
  9024. result[10] = scaleZ * matrix[10];
  9025. result[11] = 0.0;
  9026. result[12] = matrix[12];
  9027. result[13] = matrix[13];
  9028. result[14] = matrix[14];
  9029. result[15] = 1.0;
  9030. return result;
  9031. };
  9032. /**
  9033. * Computes the product of a matrix and a column vector.
  9034. *
  9035. * @param {Matrix4} matrix The matrix.
  9036. * @param {Cartesian4} cartesian The vector.
  9037. * @param {Cartesian4} result The object onto which to store the result.
  9038. * @returns {Cartesian4} The modified result parameter.
  9039. */
  9040. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  9041. if (!defined(matrix)) {
  9042. throw new DeveloperError('matrix is required');
  9043. }
  9044. if (!defined(cartesian)) {
  9045. throw new DeveloperError('cartesian is required');
  9046. }
  9047. if (!defined(result)) {
  9048. throw new DeveloperError('result is required');
  9049. }
  9050. var vX = cartesian.x;
  9051. var vY = cartesian.y;
  9052. var vZ = cartesian.z;
  9053. var vW = cartesian.w;
  9054. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  9055. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  9056. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  9057. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  9058. result.x = x;
  9059. result.y = y;
  9060. result.z = z;
  9061. result.w = w;
  9062. return result;
  9063. };
  9064. /**
  9065. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  9066. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  9067. *
  9068. * @param {Matrix4} matrix The matrix.
  9069. * @param {Cartesian3} cartesian The point.
  9070. * @param {Cartesian3} result The object onto which to store the result.
  9071. * @returns {Cartesian3} The modified result parameter.
  9072. *
  9073. * @example
  9074. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9075. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  9076. * // A shortcut for
  9077. * // Cartesian3 p = ...
  9078. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  9079. */
  9080. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  9081. if (!defined(matrix)) {
  9082. throw new DeveloperError('matrix is required');
  9083. }
  9084. if (!defined(cartesian)) {
  9085. throw new DeveloperError('cartesian is required');
  9086. }
  9087. if (!defined(result)) {
  9088. throw new DeveloperError('result is required');
  9089. }
  9090. var vX = cartesian.x;
  9091. var vY = cartesian.y;
  9092. var vZ = cartesian.z;
  9093. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  9094. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  9095. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  9096. result.x = x;
  9097. result.y = y;
  9098. result.z = z;
  9099. return result;
  9100. };
  9101. /**
  9102. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  9103. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  9104. *
  9105. * @param {Matrix4} matrix The matrix.
  9106. * @param {Cartesian3} cartesian The point.
  9107. * @param {Cartesian3} result The object onto which to store the result.
  9108. * @returns {Cartesian3} The modified result parameter.
  9109. *
  9110. * @example
  9111. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9112. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  9113. */
  9114. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  9115. if (!defined(matrix)) {
  9116. throw new DeveloperError('matrix is required');
  9117. }
  9118. if (!defined(cartesian)) {
  9119. throw new DeveloperError('cartesian is required');
  9120. }
  9121. if (!defined(result)) {
  9122. throw new DeveloperError('result is required');
  9123. }
  9124. var vX = cartesian.x;
  9125. var vY = cartesian.y;
  9126. var vZ = cartesian.z;
  9127. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  9128. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  9129. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  9130. result.x = x;
  9131. result.y = y;
  9132. result.z = z;
  9133. return result;
  9134. };
  9135. /**
  9136. * Computes the product of a matrix and a scalar.
  9137. *
  9138. * @param {Matrix4} matrix The matrix.
  9139. * @param {Number} scalar The number to multiply by.
  9140. * @param {Matrix4} result The object onto which to store the result.
  9141. * @returns {Matrix4} The modified result parameter.
  9142. *
  9143. * @example
  9144. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  9145. * // m = [10.0, 11.0, 12.0, 13.0]
  9146. * // [14.0, 15.0, 16.0, 17.0]
  9147. * // [18.0, 19.0, 20.0, 21.0]
  9148. * // [22.0, 23.0, 24.0, 25.0]
  9149. *
  9150. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  9151. *
  9152. * // m remains the same
  9153. * // a = [-20.0, -22.0, -24.0, -26.0]
  9154. * // [-28.0, -30.0, -32.0, -34.0]
  9155. * // [-36.0, -38.0, -40.0, -42.0]
  9156. * // [-44.0, -46.0, -48.0, -50.0]
  9157. */
  9158. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  9159. if (!defined(matrix)) {
  9160. throw new DeveloperError('matrix is required');
  9161. }
  9162. if (typeof scalar !== 'number') {
  9163. throw new DeveloperError('scalar must be a number');
  9164. }
  9165. if (!defined(result)) {
  9166. throw new DeveloperError('result is required');
  9167. }
  9168. result[0] = matrix[0] * scalar;
  9169. result[1] = matrix[1] * scalar;
  9170. result[2] = matrix[2] * scalar;
  9171. result[3] = matrix[3] * scalar;
  9172. result[4] = matrix[4] * scalar;
  9173. result[5] = matrix[5] * scalar;
  9174. result[6] = matrix[6] * scalar;
  9175. result[7] = matrix[7] * scalar;
  9176. result[8] = matrix[8] * scalar;
  9177. result[9] = matrix[9] * scalar;
  9178. result[10] = matrix[10] * scalar;
  9179. result[11] = matrix[11] * scalar;
  9180. result[12] = matrix[12] * scalar;
  9181. result[13] = matrix[13] * scalar;
  9182. result[14] = matrix[14] * scalar;
  9183. result[15] = matrix[15] * scalar;
  9184. return result;
  9185. };
  9186. /**
  9187. * Computes a negated copy of the provided matrix.
  9188. *
  9189. * @param {Matrix4} matrix The matrix to negate.
  9190. * @param {Matrix4} result The object onto which to store the result.
  9191. * @returns {Matrix4} The modified result parameter.
  9192. *
  9193. * @example
  9194. * //create a new Matrix4 instance which is a negation of a Matrix4
  9195. * // m = [10.0, 11.0, 12.0, 13.0]
  9196. * // [14.0, 15.0, 16.0, 17.0]
  9197. * // [18.0, 19.0, 20.0, 21.0]
  9198. * // [22.0, 23.0, 24.0, 25.0]
  9199. *
  9200. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  9201. *
  9202. * // m remains the same
  9203. * // a = [-10.0, -11.0, -12.0, -13.0]
  9204. * // [-14.0, -15.0, -16.0, -17.0]
  9205. * // [-18.0, -19.0, -20.0, -21.0]
  9206. * // [-22.0, -23.0, -24.0, -25.0]
  9207. */
  9208. Matrix4.negate = function(matrix, result) {
  9209. if (!defined(matrix)) {
  9210. throw new DeveloperError('matrix is required');
  9211. }
  9212. if (!defined(result)) {
  9213. throw new DeveloperError('result is required');
  9214. }
  9215. result[0] = -matrix[0];
  9216. result[1] = -matrix[1];
  9217. result[2] = -matrix[2];
  9218. result[3] = -matrix[3];
  9219. result[4] = -matrix[4];
  9220. result[5] = -matrix[5];
  9221. result[6] = -matrix[6];
  9222. result[7] = -matrix[7];
  9223. result[8] = -matrix[8];
  9224. result[9] = -matrix[9];
  9225. result[10] = -matrix[10];
  9226. result[11] = -matrix[11];
  9227. result[12] = -matrix[12];
  9228. result[13] = -matrix[13];
  9229. result[14] = -matrix[14];
  9230. result[15] = -matrix[15];
  9231. return result;
  9232. };
  9233. /**
  9234. * Computes the transpose of the provided matrix.
  9235. *
  9236. * @param {Matrix4} matrix The matrix to transpose.
  9237. * @param {Matrix4} result The object onto which to store the result.
  9238. * @returns {Matrix4} The modified result parameter.
  9239. *
  9240. * @example
  9241. * //returns transpose of a Matrix4
  9242. * // m = [10.0, 11.0, 12.0, 13.0]
  9243. * // [14.0, 15.0, 16.0, 17.0]
  9244. * // [18.0, 19.0, 20.0, 21.0]
  9245. * // [22.0, 23.0, 24.0, 25.0]
  9246. *
  9247. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  9248. *
  9249. * // m remains the same
  9250. * // a = [10.0, 14.0, 18.0, 22.0]
  9251. * // [11.0, 15.0, 19.0, 23.0]
  9252. * // [12.0, 16.0, 20.0, 24.0]
  9253. * // [13.0, 17.0, 21.0, 25.0]
  9254. */
  9255. Matrix4.transpose = function(matrix, result) {
  9256. if (!defined(matrix)) {
  9257. throw new DeveloperError('matrix is required');
  9258. }
  9259. if (!defined(result)) {
  9260. throw new DeveloperError('result is required');
  9261. }
  9262. var matrix1 = matrix[1];
  9263. var matrix2 = matrix[2];
  9264. var matrix3 = matrix[3];
  9265. var matrix6 = matrix[6];
  9266. var matrix7 = matrix[7];
  9267. var matrix11 = matrix[11];
  9268. result[0] = matrix[0];
  9269. result[1] = matrix[4];
  9270. result[2] = matrix[8];
  9271. result[3] = matrix[12];
  9272. result[4] = matrix1;
  9273. result[5] = matrix[5];
  9274. result[6] = matrix[9];
  9275. result[7] = matrix[13];
  9276. result[8] = matrix2;
  9277. result[9] = matrix6;
  9278. result[10] = matrix[10];
  9279. result[11] = matrix[14];
  9280. result[12] = matrix3;
  9281. result[13] = matrix7;
  9282. result[14] = matrix11;
  9283. result[15] = matrix[15];
  9284. return result;
  9285. };
  9286. /**
  9287. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  9288. *
  9289. * @param {Matrix4} matrix The matrix with signed elements.
  9290. * @param {Matrix4} result The object onto which to store the result.
  9291. * @returns {Matrix4} The modified result parameter.
  9292. */
  9293. Matrix4.abs = function(matrix, result) {
  9294. if (!defined(matrix)) {
  9295. throw new DeveloperError('matrix is required');
  9296. }
  9297. if (!defined(result)) {
  9298. throw new DeveloperError('result is required');
  9299. }
  9300. result[0] = Math.abs(matrix[0]);
  9301. result[1] = Math.abs(matrix[1]);
  9302. result[2] = Math.abs(matrix[2]);
  9303. result[3] = Math.abs(matrix[3]);
  9304. result[4] = Math.abs(matrix[4]);
  9305. result[5] = Math.abs(matrix[5]);
  9306. result[6] = Math.abs(matrix[6]);
  9307. result[7] = Math.abs(matrix[7]);
  9308. result[8] = Math.abs(matrix[8]);
  9309. result[9] = Math.abs(matrix[9]);
  9310. result[10] = Math.abs(matrix[10]);
  9311. result[11] = Math.abs(matrix[11]);
  9312. result[12] = Math.abs(matrix[12]);
  9313. result[13] = Math.abs(matrix[13]);
  9314. result[14] = Math.abs(matrix[14]);
  9315. result[15] = Math.abs(matrix[15]);
  9316. return result;
  9317. };
  9318. /**
  9319. * Compares the provided matrices componentwise and returns
  9320. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9321. *
  9322. * @param {Matrix4} [left] The first matrix.
  9323. * @param {Matrix4} [right] The second matrix.
  9324. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  9325. *
  9326. * @example
  9327. * //compares two Matrix4 instances
  9328. *
  9329. * // a = [10.0, 14.0, 18.0, 22.0]
  9330. * // [11.0, 15.0, 19.0, 23.0]
  9331. * // [12.0, 16.0, 20.0, 24.0]
  9332. * // [13.0, 17.0, 21.0, 25.0]
  9333. *
  9334. * // b = [10.0, 14.0, 18.0, 22.0]
  9335. * // [11.0, 15.0, 19.0, 23.0]
  9336. * // [12.0, 16.0, 20.0, 24.0]
  9337. * // [13.0, 17.0, 21.0, 25.0]
  9338. *
  9339. * if(Cesium.Matrix4.equals(a,b)) {
  9340. * console.log("Both matrices are equal");
  9341. * } else {
  9342. * console.log("They are not equal");
  9343. * }
  9344. *
  9345. * //Prints "Both matrices are equal" on the console
  9346. */
  9347. Matrix4.equals = function(left, right) {
  9348. // Given that most matrices will be transformation matrices, the elements
  9349. // are tested in order such that the test is likely to fail as early
  9350. // as possible. I _think_ this is just as friendly to the L1 cache
  9351. // as testing in index order. It is certainty faster in practice.
  9352. return (left === right) ||
  9353. (defined(left) &&
  9354. defined(right) &&
  9355. // Translation
  9356. left[12] === right[12] &&
  9357. left[13] === right[13] &&
  9358. left[14] === right[14] &&
  9359. // Rotation/scale
  9360. left[0] === right[0] &&
  9361. left[1] === right[1] &&
  9362. left[2] === right[2] &&
  9363. left[4] === right[4] &&
  9364. left[5] === right[5] &&
  9365. left[6] === right[6] &&
  9366. left[8] === right[8] &&
  9367. left[9] === right[9] &&
  9368. left[10] === right[10] &&
  9369. // Bottom row
  9370. left[3] === right[3] &&
  9371. left[7] === right[7] &&
  9372. left[11] === right[11] &&
  9373. left[15] === right[15]);
  9374. };
  9375. /**
  9376. * Compares the provided matrices componentwise and returns
  9377. * <code>true</code> if they are within the provided epsilon,
  9378. * <code>false</code> otherwise.
  9379. *
  9380. * @param {Matrix4} [left] The first matrix.
  9381. * @param {Matrix4} [right] The second matrix.
  9382. * @param {Number} epsilon The epsilon to use for equality testing.
  9383. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  9384. *
  9385. * @example
  9386. * //compares two Matrix4 instances
  9387. *
  9388. * // a = [10.5, 14.5, 18.5, 22.5]
  9389. * // [11.5, 15.5, 19.5, 23.5]
  9390. * // [12.5, 16.5, 20.5, 24.5]
  9391. * // [13.5, 17.5, 21.5, 25.5]
  9392. *
  9393. * // b = [10.0, 14.0, 18.0, 22.0]
  9394. * // [11.0, 15.0, 19.0, 23.0]
  9395. * // [12.0, 16.0, 20.0, 24.0]
  9396. * // [13.0, 17.0, 21.0, 25.0]
  9397. *
  9398. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  9399. * console.log("Difference between both the matrices is less than 0.1");
  9400. * } else {
  9401. * console.log("Difference between both the matrices is not less than 0.1");
  9402. * }
  9403. *
  9404. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  9405. */
  9406. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  9407. if (typeof epsilon !== 'number') {
  9408. throw new DeveloperError('epsilon must be a number');
  9409. }
  9410. return (left === right) ||
  9411. (defined(left) &&
  9412. defined(right) &&
  9413. Math.abs(left[0] - right[0]) <= epsilon &&
  9414. Math.abs(left[1] - right[1]) <= epsilon &&
  9415. Math.abs(left[2] - right[2]) <= epsilon &&
  9416. Math.abs(left[3] - right[3]) <= epsilon &&
  9417. Math.abs(left[4] - right[4]) <= epsilon &&
  9418. Math.abs(left[5] - right[5]) <= epsilon &&
  9419. Math.abs(left[6] - right[6]) <= epsilon &&
  9420. Math.abs(left[7] - right[7]) <= epsilon &&
  9421. Math.abs(left[8] - right[8]) <= epsilon &&
  9422. Math.abs(left[9] - right[9]) <= epsilon &&
  9423. Math.abs(left[10] - right[10]) <= epsilon &&
  9424. Math.abs(left[11] - right[11]) <= epsilon &&
  9425. Math.abs(left[12] - right[12]) <= epsilon &&
  9426. Math.abs(left[13] - right[13]) <= epsilon &&
  9427. Math.abs(left[14] - right[14]) <= epsilon &&
  9428. Math.abs(left[15] - right[15]) <= epsilon);
  9429. };
  9430. /**
  9431. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  9432. *
  9433. * @param {Matrix4} matrix The matrix to use.
  9434. * @param {Cartesian3} result The object onto which to store the result.
  9435. * @returns {Cartesian3} The modified result parameter.
  9436. */
  9437. Matrix4.getTranslation = function(matrix, result) {
  9438. if (!defined(matrix)) {
  9439. throw new DeveloperError('matrix is required');
  9440. }
  9441. if (!defined(result)) {
  9442. throw new DeveloperError('result is required');
  9443. }
  9444. result.x = matrix[12];
  9445. result.y = matrix[13];
  9446. result.z = matrix[14];
  9447. return result;
  9448. };
  9449. /**
  9450. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  9451. *
  9452. * @param {Matrix4} matrix The matrix to use.
  9453. * @param {Matrix3} result The object onto which to store the result.
  9454. * @returns {Matrix3} The modified result parameter.
  9455. *
  9456. * @example
  9457. * // returns a Matrix3 instance from a Matrix4 instance
  9458. *
  9459. * // m = [10.0, 14.0, 18.0, 22.0]
  9460. * // [11.0, 15.0, 19.0, 23.0]
  9461. * // [12.0, 16.0, 20.0, 24.0]
  9462. * // [13.0, 17.0, 21.0, 25.0]
  9463. *
  9464. * var b = new Cesium.Matrix3();
  9465. * Cesium.Matrix4.getRotation(m,b);
  9466. *
  9467. * // b = [10.0, 14.0, 18.0]
  9468. * // [11.0, 15.0, 19.0]
  9469. * // [12.0, 16.0, 20.0]
  9470. */
  9471. Matrix4.getRotation = function(matrix, result) {
  9472. if (!defined(matrix)) {
  9473. throw new DeveloperError('matrix is required');
  9474. }
  9475. if (!defined(result)) {
  9476. throw new DeveloperError('result is required');
  9477. }
  9478. result[0] = matrix[0];
  9479. result[1] = matrix[1];
  9480. result[2] = matrix[2];
  9481. result[3] = matrix[4];
  9482. result[4] = matrix[5];
  9483. result[5] = matrix[6];
  9484. result[6] = matrix[8];
  9485. result[7] = matrix[9];
  9486. result[8] = matrix[10];
  9487. return result;
  9488. };
  9489. var scratchInverseRotation = new Matrix3();
  9490. var scratchMatrix3Zero = new Matrix3();
  9491. var scratchBottomRow = new Cartesian4();
  9492. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  9493. /**
  9494. * Computes the inverse of the provided matrix using Cramers Rule.
  9495. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  9496. * If the matrix is an affine transformation matrix, it is more efficient
  9497. * to invert it with {@link Matrix4.inverseTransformation}.
  9498. *
  9499. * @param {Matrix4} matrix The matrix to invert.
  9500. * @param {Matrix4} result The object onto which to store the result.
  9501. * @returns {Matrix4} The modified result parameter.
  9502. *
  9503. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  9504. */
  9505. Matrix4.inverse = function(matrix, result) {
  9506. if (!defined(matrix)) {
  9507. throw new DeveloperError('matrix is required');
  9508. }
  9509. if (!defined(result)) {
  9510. throw new DeveloperError('result is required');
  9511. }
  9512. // Special case for a zero scale matrix that can occur, for example,
  9513. // when a model's node has a [0, 0, 0] scale.
  9514. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  9515. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  9516. result[0] = 0.0;
  9517. result[1] = 0.0;
  9518. result[2] = 0.0;
  9519. result[3] = 0.0;
  9520. result[4] = 0.0;
  9521. result[5] = 0.0;
  9522. result[6] = 0.0;
  9523. result[7] = 0.0;
  9524. result[8] = 0.0;
  9525. result[9] = 0.0;
  9526. result[10] = 0.0;
  9527. result[11] = 0.0;
  9528. result[12] = -matrix[12];
  9529. result[13] = -matrix[13];
  9530. result[14] = -matrix[14];
  9531. result[15] = 1.0;
  9532. return result;
  9533. }
  9534. //
  9535. // Ported from:
  9536. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  9537. //
  9538. var src0 = matrix[0];
  9539. var src1 = matrix[4];
  9540. var src2 = matrix[8];
  9541. var src3 = matrix[12];
  9542. var src4 = matrix[1];
  9543. var src5 = matrix[5];
  9544. var src6 = matrix[9];
  9545. var src7 = matrix[13];
  9546. var src8 = matrix[2];
  9547. var src9 = matrix[6];
  9548. var src10 = matrix[10];
  9549. var src11 = matrix[14];
  9550. var src12 = matrix[3];
  9551. var src13 = matrix[7];
  9552. var src14 = matrix[11];
  9553. var src15 = matrix[15];
  9554. // calculate pairs for first 8 elements (cofactors)
  9555. var tmp0 = src10 * src15;
  9556. var tmp1 = src11 * src14;
  9557. var tmp2 = src9 * src15;
  9558. var tmp3 = src11 * src13;
  9559. var tmp4 = src9 * src14;
  9560. var tmp5 = src10 * src13;
  9561. var tmp6 = src8 * src15;
  9562. var tmp7 = src11 * src12;
  9563. var tmp8 = src8 * src14;
  9564. var tmp9 = src10 * src12;
  9565. var tmp10 = src8 * src13;
  9566. var tmp11 = src9 * src12;
  9567. // calculate first 8 elements (cofactors)
  9568. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  9569. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  9570. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  9571. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  9572. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  9573. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  9574. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  9575. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  9576. // calculate pairs for second 8 elements (cofactors)
  9577. tmp0 = src2 * src7;
  9578. tmp1 = src3 * src6;
  9579. tmp2 = src1 * src7;
  9580. tmp3 = src3 * src5;
  9581. tmp4 = src1 * src6;
  9582. tmp5 = src2 * src5;
  9583. tmp6 = src0 * src7;
  9584. tmp7 = src3 * src4;
  9585. tmp8 = src0 * src6;
  9586. tmp9 = src2 * src4;
  9587. tmp10 = src0 * src5;
  9588. tmp11 = src1 * src4;
  9589. // calculate second 8 elements (cofactors)
  9590. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  9591. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  9592. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  9593. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  9594. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  9595. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  9596. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  9597. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  9598. // calculate determinant
  9599. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  9600. if (Math.abs(det) < CesiumMath.EPSILON20) {
  9601. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  9602. }
  9603. // calculate matrix inverse
  9604. det = 1.0 / det;
  9605. result[0] = dst0 * det;
  9606. result[1] = dst1 * det;
  9607. result[2] = dst2 * det;
  9608. result[3] = dst3 * det;
  9609. result[4] = dst4 * det;
  9610. result[5] = dst5 * det;
  9611. result[6] = dst6 * det;
  9612. result[7] = dst7 * det;
  9613. result[8] = dst8 * det;
  9614. result[9] = dst9 * det;
  9615. result[10] = dst10 * det;
  9616. result[11] = dst11 * det;
  9617. result[12] = dst12 * det;
  9618. result[13] = dst13 * det;
  9619. result[14] = dst14 * det;
  9620. result[15] = dst15 * det;
  9621. return result;
  9622. };
  9623. /**
  9624. * Computes the inverse of the provided matrix assuming it is
  9625. * an affine transformation matrix, where the upper left 3x3 elements
  9626. * are a rotation matrix, and the upper three elements in the fourth
  9627. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  9628. * The matrix is not verified to be in the proper form.
  9629. * This method is faster than computing the inverse for a general 4x4
  9630. * matrix using {@link Matrix4.inverse}.
  9631. *
  9632. * @param {Matrix4} matrix The matrix to invert.
  9633. * @param {Matrix4} result The object onto which to store the result.
  9634. * @returns {Matrix4} The modified result parameter.
  9635. */
  9636. Matrix4.inverseTransformation = function(matrix, result) {
  9637. if (!defined(matrix)) {
  9638. throw new DeveloperError('matrix is required');
  9639. }
  9640. if (!defined(result)) {
  9641. throw new DeveloperError('result is required');
  9642. }
  9643. //This function is an optimized version of the below 4 lines.
  9644. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  9645. //var rTN = Matrix3.negate(rT);
  9646. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  9647. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  9648. var matrix0 = matrix[0];
  9649. var matrix1 = matrix[1];
  9650. var matrix2 = matrix[2];
  9651. var matrix4 = matrix[4];
  9652. var matrix5 = matrix[5];
  9653. var matrix6 = matrix[6];
  9654. var matrix8 = matrix[8];
  9655. var matrix9 = matrix[9];
  9656. var matrix10 = matrix[10];
  9657. var vX = matrix[12];
  9658. var vY = matrix[13];
  9659. var vZ = matrix[14];
  9660. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  9661. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  9662. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  9663. result[0] = matrix0;
  9664. result[1] = matrix4;
  9665. result[2] = matrix8;
  9666. result[3] = 0.0;
  9667. result[4] = matrix1;
  9668. result[5] = matrix5;
  9669. result[6] = matrix9;
  9670. result[7] = 0.0;
  9671. result[8] = matrix2;
  9672. result[9] = matrix6;
  9673. result[10] = matrix10;
  9674. result[11] = 0.0;
  9675. result[12] = x;
  9676. result[13] = y;
  9677. result[14] = z;
  9678. result[15] = 1.0;
  9679. return result;
  9680. };
  9681. /**
  9682. * An immutable Matrix4 instance initialized to the identity matrix.
  9683. *
  9684. * @type {Matrix4}
  9685. * @constant
  9686. */
  9687. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  9688. 0.0, 1.0, 0.0, 0.0,
  9689. 0.0, 0.0, 1.0, 0.0,
  9690. 0.0, 0.0, 0.0, 1.0));
  9691. /**
  9692. * An immutable Matrix4 instance initialized to the zero matrix.
  9693. *
  9694. * @type {Matrix4}
  9695. * @constant
  9696. */
  9697. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  9698. 0.0, 0.0, 0.0, 0.0,
  9699. 0.0, 0.0, 0.0, 0.0,
  9700. 0.0, 0.0, 0.0, 0.0));
  9701. /**
  9702. * The index into Matrix4 for column 0, row 0.
  9703. *
  9704. * @type {Number}
  9705. * @constant
  9706. */
  9707. Matrix4.COLUMN0ROW0 = 0;
  9708. /**
  9709. * The index into Matrix4 for column 0, row 1.
  9710. *
  9711. * @type {Number}
  9712. * @constant
  9713. */
  9714. Matrix4.COLUMN0ROW1 = 1;
  9715. /**
  9716. * The index into Matrix4 for column 0, row 2.
  9717. *
  9718. * @type {Number}
  9719. * @constant
  9720. */
  9721. Matrix4.COLUMN0ROW2 = 2;
  9722. /**
  9723. * The index into Matrix4 for column 0, row 3.
  9724. *
  9725. * @type {Number}
  9726. * @constant
  9727. */
  9728. Matrix4.COLUMN0ROW3 = 3;
  9729. /**
  9730. * The index into Matrix4 for column 1, row 0.
  9731. *
  9732. * @type {Number}
  9733. * @constant
  9734. */
  9735. Matrix4.COLUMN1ROW0 = 4;
  9736. /**
  9737. * The index into Matrix4 for column 1, row 1.
  9738. *
  9739. * @type {Number}
  9740. * @constant
  9741. */
  9742. Matrix4.COLUMN1ROW1 = 5;
  9743. /**
  9744. * The index into Matrix4 for column 1, row 2.
  9745. *
  9746. * @type {Number}
  9747. * @constant
  9748. */
  9749. Matrix4.COLUMN1ROW2 = 6;
  9750. /**
  9751. * The index into Matrix4 for column 1, row 3.
  9752. *
  9753. * @type {Number}
  9754. * @constant
  9755. */
  9756. Matrix4.COLUMN1ROW3 = 7;
  9757. /**
  9758. * The index into Matrix4 for column 2, row 0.
  9759. *
  9760. * @type {Number}
  9761. * @constant
  9762. */
  9763. Matrix4.COLUMN2ROW0 = 8;
  9764. /**
  9765. * The index into Matrix4 for column 2, row 1.
  9766. *
  9767. * @type {Number}
  9768. * @constant
  9769. */
  9770. Matrix4.COLUMN2ROW1 = 9;
  9771. /**
  9772. * The index into Matrix4 for column 2, row 2.
  9773. *
  9774. * @type {Number}
  9775. * @constant
  9776. */
  9777. Matrix4.COLUMN2ROW2 = 10;
  9778. /**
  9779. * The index into Matrix4 for column 2, row 3.
  9780. *
  9781. * @type {Number}
  9782. * @constant
  9783. */
  9784. Matrix4.COLUMN2ROW3 = 11;
  9785. /**
  9786. * The index into Matrix4 for column 3, row 0.
  9787. *
  9788. * @type {Number}
  9789. * @constant
  9790. */
  9791. Matrix4.COLUMN3ROW0 = 12;
  9792. /**
  9793. * The index into Matrix4 for column 3, row 1.
  9794. *
  9795. * @type {Number}
  9796. * @constant
  9797. */
  9798. Matrix4.COLUMN3ROW1 = 13;
  9799. /**
  9800. * The index into Matrix4 for column 3, row 2.
  9801. *
  9802. * @type {Number}
  9803. * @constant
  9804. */
  9805. Matrix4.COLUMN3ROW2 = 14;
  9806. /**
  9807. * The index into Matrix4 for column 3, row 3.
  9808. *
  9809. * @type {Number}
  9810. * @constant
  9811. */
  9812. Matrix4.COLUMN3ROW3 = 15;
  9813. defineProperties(Matrix4.prototype, {
  9814. /**
  9815. * Gets the number of items in the collection.
  9816. * @memberof Matrix4.prototype
  9817. *
  9818. * @type {Number}
  9819. */
  9820. length : {
  9821. get : function() {
  9822. return Matrix4.packedLength;
  9823. }
  9824. }
  9825. });
  9826. /**
  9827. * Duplicates the provided Matrix4 instance.
  9828. *
  9829. * @param {Matrix4} [result] The object onto which to store the result.
  9830. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  9831. */
  9832. Matrix4.prototype.clone = function(result) {
  9833. return Matrix4.clone(this, result);
  9834. };
  9835. /**
  9836. * Compares this matrix to the provided matrix componentwise and returns
  9837. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9838. *
  9839. * @param {Matrix4} [right] The right hand side matrix.
  9840. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9841. */
  9842. Matrix4.prototype.equals = function(right) {
  9843. return Matrix4.equals(this, right);
  9844. };
  9845. /**
  9846. * @private
  9847. */
  9848. Matrix4.equalsArray = function(matrix, array, offset) {
  9849. return matrix[0] === array[offset] &&
  9850. matrix[1] === array[offset + 1] &&
  9851. matrix[2] === array[offset + 2] &&
  9852. matrix[3] === array[offset + 3] &&
  9853. matrix[4] === array[offset + 4] &&
  9854. matrix[5] === array[offset + 5] &&
  9855. matrix[6] === array[offset + 6] &&
  9856. matrix[7] === array[offset + 7] &&
  9857. matrix[8] === array[offset + 8] &&
  9858. matrix[9] === array[offset + 9] &&
  9859. matrix[10] === array[offset + 10] &&
  9860. matrix[11] === array[offset + 11] &&
  9861. matrix[12] === array[offset + 12] &&
  9862. matrix[13] === array[offset + 13] &&
  9863. matrix[14] === array[offset + 14] &&
  9864. matrix[15] === array[offset + 15];
  9865. };
  9866. /**
  9867. * Compares this matrix to the provided matrix componentwise and returns
  9868. * <code>true</code> if they are within the provided epsilon,
  9869. * <code>false</code> otherwise.
  9870. *
  9871. * @param {Matrix4} [right] The right hand side matrix.
  9872. * @param {Number} epsilon The epsilon to use for equality testing.
  9873. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  9874. */
  9875. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  9876. return Matrix4.equalsEpsilon(this, right, epsilon);
  9877. };
  9878. /**
  9879. * Computes a string representing this Matrix with each row being
  9880. * on a separate line and in the format '(column0, column1, column2, column3)'.
  9881. *
  9882. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  9883. */
  9884. Matrix4.prototype.toString = function() {
  9885. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  9886. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  9887. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  9888. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  9889. };
  9890. return Matrix4;
  9891. });
  9892. /*global define*/
  9893. define('Core/BoundingSphere',[
  9894. './Cartesian3',
  9895. './Cartographic',
  9896. './defaultValue',
  9897. './defined',
  9898. './DeveloperError',
  9899. './Ellipsoid',
  9900. './GeographicProjection',
  9901. './Intersect',
  9902. './Interval',
  9903. './Matrix3',
  9904. './Matrix4',
  9905. './Rectangle'
  9906. ], function(
  9907. Cartesian3,
  9908. Cartographic,
  9909. defaultValue,
  9910. defined,
  9911. DeveloperError,
  9912. Ellipsoid,
  9913. GeographicProjection,
  9914. Intersect,
  9915. Interval,
  9916. Matrix3,
  9917. Matrix4,
  9918. Rectangle) {
  9919. 'use strict';
  9920. /**
  9921. * A bounding sphere with a center and a radius.
  9922. * @alias BoundingSphere
  9923. * @constructor
  9924. *
  9925. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  9926. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  9927. *
  9928. * @see AxisAlignedBoundingBox
  9929. * @see BoundingRectangle
  9930. * @see Packable
  9931. */
  9932. function BoundingSphere(center, radius) {
  9933. /**
  9934. * The center point of the sphere.
  9935. * @type {Cartesian3}
  9936. * @default {@link Cartesian3.ZERO}
  9937. */
  9938. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  9939. /**
  9940. * The radius of the sphere.
  9941. * @type {Number}
  9942. * @default 0.0
  9943. */
  9944. this.radius = defaultValue(radius, 0.0);
  9945. }
  9946. var fromPointsXMin = new Cartesian3();
  9947. var fromPointsYMin = new Cartesian3();
  9948. var fromPointsZMin = new Cartesian3();
  9949. var fromPointsXMax = new Cartesian3();
  9950. var fromPointsYMax = new Cartesian3();
  9951. var fromPointsZMax = new Cartesian3();
  9952. var fromPointsCurrentPos = new Cartesian3();
  9953. var fromPointsScratch = new Cartesian3();
  9954. var fromPointsRitterCenter = new Cartesian3();
  9955. var fromPointsMinBoxPt = new Cartesian3();
  9956. var fromPointsMaxBoxPt = new Cartesian3();
  9957. var fromPointsNaiveCenterScratch = new Cartesian3();
  9958. /**
  9959. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  9960. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  9961. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  9962. *
  9963. * @param {Cartesian3[]} positions An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
  9964. * @param {BoundingSphere} [result] The object onto which to store the result.
  9965. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9966. *
  9967. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9968. */
  9969. BoundingSphere.fromPoints = function(positions, result) {
  9970. if (!defined(result)) {
  9971. result = new BoundingSphere();
  9972. }
  9973. if (!defined(positions) || positions.length === 0) {
  9974. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9975. result.radius = 0.0;
  9976. return result;
  9977. }
  9978. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  9979. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9980. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9981. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9982. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9983. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9984. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9985. var numPositions = positions.length;
  9986. for (var i = 1; i < numPositions; i++) {
  9987. Cartesian3.clone(positions[i], currentPos);
  9988. var x = currentPos.x;
  9989. var y = currentPos.y;
  9990. var z = currentPos.z;
  9991. // Store points containing the the smallest and largest components
  9992. if (x < xMin.x) {
  9993. Cartesian3.clone(currentPos, xMin);
  9994. }
  9995. if (x > xMax.x) {
  9996. Cartesian3.clone(currentPos, xMax);
  9997. }
  9998. if (y < yMin.y) {
  9999. Cartesian3.clone(currentPos, yMin);
  10000. }
  10001. if (y > yMax.y) {
  10002. Cartesian3.clone(currentPos, yMax);
  10003. }
  10004. if (z < zMin.z) {
  10005. Cartesian3.clone(currentPos, zMin);
  10006. }
  10007. if (z > zMax.z) {
  10008. Cartesian3.clone(currentPos, zMax);
  10009. }
  10010. }
  10011. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10012. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10013. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10014. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10015. // Set the diameter endpoints to the largest span.
  10016. var diameter1 = xMin;
  10017. var diameter2 = xMax;
  10018. var maxSpan = xSpan;
  10019. if (ySpan > maxSpan) {
  10020. maxSpan = ySpan;
  10021. diameter1 = yMin;
  10022. diameter2 = yMax;
  10023. }
  10024. if (zSpan > maxSpan) {
  10025. maxSpan = zSpan;
  10026. diameter1 = zMin;
  10027. diameter2 = zMax;
  10028. }
  10029. // Calculate the center of the initial sphere found by Ritter's algorithm
  10030. var ritterCenter = fromPointsRitterCenter;
  10031. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10032. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10033. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10034. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10035. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10036. var ritterRadius = Math.sqrt(radiusSquared);
  10037. // Find the center of the sphere found using the Naive method.
  10038. var minBoxPt = fromPointsMinBoxPt;
  10039. minBoxPt.x = xMin.x;
  10040. minBoxPt.y = yMin.y;
  10041. minBoxPt.z = zMin.z;
  10042. var maxBoxPt = fromPointsMaxBoxPt;
  10043. maxBoxPt.x = xMax.x;
  10044. maxBoxPt.y = yMax.y;
  10045. maxBoxPt.z = zMax.z;
  10046. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10047. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10048. var naiveRadius = 0;
  10049. for (i = 0; i < numPositions; i++) {
  10050. Cartesian3.clone(positions[i], currentPos);
  10051. // Find the furthest point from the naive center to calculate the naive radius.
  10052. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10053. if (r > naiveRadius) {
  10054. naiveRadius = r;
  10055. }
  10056. // Make adjustments to the Ritter Sphere to include all points.
  10057. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10058. if (oldCenterToPointSquared > radiusSquared) {
  10059. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10060. // Calculate new radius to include the point that lies outside
  10061. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10062. radiusSquared = ritterRadius * ritterRadius;
  10063. // Calculate center of new Ritter sphere
  10064. var oldToNew = oldCenterToPoint - ritterRadius;
  10065. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10066. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10067. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10068. }
  10069. }
  10070. if (ritterRadius < naiveRadius) {
  10071. Cartesian3.clone(ritterCenter, result.center);
  10072. result.radius = ritterRadius;
  10073. } else {
  10074. Cartesian3.clone(naiveCenter, result.center);
  10075. result.radius = naiveRadius;
  10076. }
  10077. return result;
  10078. };
  10079. var defaultProjection = new GeographicProjection();
  10080. var fromRectangle2DLowerLeft = new Cartesian3();
  10081. var fromRectangle2DUpperRight = new Cartesian3();
  10082. var fromRectangle2DSouthwest = new Cartographic();
  10083. var fromRectangle2DNortheast = new Cartographic();
  10084. /**
  10085. * Computes a bounding sphere from an rectangle projected in 2D.
  10086. *
  10087. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10088. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10089. * @param {BoundingSphere} [result] The object onto which to store the result.
  10090. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10091. */
  10092. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  10093. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  10094. };
  10095. /**
  10096. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  10097. * object's minimum and maximum heights over the rectangle.
  10098. *
  10099. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10100. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10101. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  10102. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  10103. * @param {BoundingSphere} [result] The object onto which to store the result.
  10104. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10105. */
  10106. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  10107. if (!defined(result)) {
  10108. result = new BoundingSphere();
  10109. }
  10110. if (!defined(rectangle)) {
  10111. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10112. result.radius = 0.0;
  10113. return result;
  10114. }
  10115. projection = defaultValue(projection, defaultProjection);
  10116. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  10117. fromRectangle2DSouthwest.height = minimumHeight;
  10118. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  10119. fromRectangle2DNortheast.height = maximumHeight;
  10120. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  10121. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  10122. var width = upperRight.x - lowerLeft.x;
  10123. var height = upperRight.y - lowerLeft.y;
  10124. var elevation = upperRight.z - lowerLeft.z;
  10125. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  10126. var center = result.center;
  10127. center.x = lowerLeft.x + width * 0.5;
  10128. center.y = lowerLeft.y + height * 0.5;
  10129. center.z = lowerLeft.z + elevation * 0.5;
  10130. return result;
  10131. };
  10132. var fromRectangle3DScratch = [];
  10133. /**
  10134. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  10135. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  10136. *
  10137. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  10138. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  10139. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  10140. * @param {BoundingSphere} [result] The object onto which to store the result.
  10141. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10142. */
  10143. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  10144. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  10145. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  10146. var positions;
  10147. if (defined(rectangle)) {
  10148. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  10149. }
  10150. return BoundingSphere.fromPoints(positions, result);
  10151. };
  10152. /**
  10153. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  10154. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  10155. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10156. * ensure a tight fit.
  10157. *
  10158. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  10159. * is formed from three elements in the array in the order X, Y, Z.
  10160. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  10161. * origin of the coordinate system. This is useful when the positions are to be used for
  10162. * relative-to-center (RTC) rendering.
  10163. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  10164. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  10165. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  10166. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  10167. * the stride is 5, however, two array elements are skipped and the next position begins at array
  10168. * index 5.
  10169. * @param {BoundingSphere} [result] The object onto which to store the result.
  10170. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10171. *
  10172. * @example
  10173. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  10174. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  10175. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  10176. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  10177. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  10178. * 4.0, 5.0, 6.0, 0.1, 0.2,
  10179. * 7.0, 8.0, 9.0, 0.1, 0.2];
  10180. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  10181. *
  10182. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10183. */
  10184. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  10185. if (!defined(result)) {
  10186. result = new BoundingSphere();
  10187. }
  10188. if (!defined(positions) || positions.length === 0) {
  10189. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10190. result.radius = 0.0;
  10191. return result;
  10192. }
  10193. center = defaultValue(center, Cartesian3.ZERO);
  10194. stride = defaultValue(stride, 3);
  10195. if (stride < 3) {
  10196. throw new DeveloperError('stride must be 3 or greater.');
  10197. }
  10198. var currentPos = fromPointsCurrentPos;
  10199. currentPos.x = positions[0] + center.x;
  10200. currentPos.y = positions[1] + center.y;
  10201. currentPos.z = positions[2] + center.z;
  10202. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10203. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10204. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10205. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10206. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10207. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10208. var numElements = positions.length;
  10209. for (var i = 0; i < numElements; i += stride) {
  10210. var x = positions[i] + center.x;
  10211. var y = positions[i + 1] + center.y;
  10212. var z = positions[i + 2] + center.z;
  10213. currentPos.x = x;
  10214. currentPos.y = y;
  10215. currentPos.z = z;
  10216. // Store points containing the the smallest and largest components
  10217. if (x < xMin.x) {
  10218. Cartesian3.clone(currentPos, xMin);
  10219. }
  10220. if (x > xMax.x) {
  10221. Cartesian3.clone(currentPos, xMax);
  10222. }
  10223. if (y < yMin.y) {
  10224. Cartesian3.clone(currentPos, yMin);
  10225. }
  10226. if (y > yMax.y) {
  10227. Cartesian3.clone(currentPos, yMax);
  10228. }
  10229. if (z < zMin.z) {
  10230. Cartesian3.clone(currentPos, zMin);
  10231. }
  10232. if (z > zMax.z) {
  10233. Cartesian3.clone(currentPos, zMax);
  10234. }
  10235. }
  10236. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10237. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10238. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10239. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10240. // Set the diameter endpoints to the largest span.
  10241. var diameter1 = xMin;
  10242. var diameter2 = xMax;
  10243. var maxSpan = xSpan;
  10244. if (ySpan > maxSpan) {
  10245. maxSpan = ySpan;
  10246. diameter1 = yMin;
  10247. diameter2 = yMax;
  10248. }
  10249. if (zSpan > maxSpan) {
  10250. maxSpan = zSpan;
  10251. diameter1 = zMin;
  10252. diameter2 = zMax;
  10253. }
  10254. // Calculate the center of the initial sphere found by Ritter's algorithm
  10255. var ritterCenter = fromPointsRitterCenter;
  10256. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10257. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10258. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10259. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10260. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10261. var ritterRadius = Math.sqrt(radiusSquared);
  10262. // Find the center of the sphere found using the Naive method.
  10263. var minBoxPt = fromPointsMinBoxPt;
  10264. minBoxPt.x = xMin.x;
  10265. minBoxPt.y = yMin.y;
  10266. minBoxPt.z = zMin.z;
  10267. var maxBoxPt = fromPointsMaxBoxPt;
  10268. maxBoxPt.x = xMax.x;
  10269. maxBoxPt.y = yMax.y;
  10270. maxBoxPt.z = zMax.z;
  10271. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10272. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10273. var naiveRadius = 0;
  10274. for (i = 0; i < numElements; i += stride) {
  10275. currentPos.x = positions[i] + center.x;
  10276. currentPos.y = positions[i + 1] + center.y;
  10277. currentPos.z = positions[i + 2] + center.z;
  10278. // Find the furthest point from the naive center to calculate the naive radius.
  10279. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10280. if (r > naiveRadius) {
  10281. naiveRadius = r;
  10282. }
  10283. // Make adjustments to the Ritter Sphere to include all points.
  10284. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10285. if (oldCenterToPointSquared > radiusSquared) {
  10286. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10287. // Calculate new radius to include the point that lies outside
  10288. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10289. radiusSquared = ritterRadius * ritterRadius;
  10290. // Calculate center of new Ritter sphere
  10291. var oldToNew = oldCenterToPoint - ritterRadius;
  10292. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10293. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10294. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10295. }
  10296. }
  10297. if (ritterRadius < naiveRadius) {
  10298. Cartesian3.clone(ritterCenter, result.center);
  10299. result.radius = ritterRadius;
  10300. } else {
  10301. Cartesian3.clone(naiveCenter, result.center);
  10302. result.radius = naiveRadius;
  10303. }
  10304. return result;
  10305. };
  10306. /**
  10307. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  10308. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  10309. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10310. * ensure a tight fit.
  10311. *
  10312. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10313. * is formed from three elements in the array in the order X, Y, Z.
  10314. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10315. * is formed from three elements in the array in the order X, Y, Z.
  10316. * @param {BoundingSphere} [result] The object onto which to store the result.
  10317. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10318. *
  10319. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10320. */
  10321. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  10322. if (!defined(result)) {
  10323. result = new BoundingSphere();
  10324. }
  10325. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  10326. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10327. result.radius = 0.0;
  10328. return result;
  10329. }
  10330. var currentPos = fromPointsCurrentPos;
  10331. currentPos.x = positionsHigh[0] + positionsLow[0];
  10332. currentPos.y = positionsHigh[1] + positionsLow[1];
  10333. currentPos.z = positionsHigh[2] + positionsLow[2];
  10334. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10335. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10336. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10337. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10338. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10339. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10340. var numElements = positionsHigh.length;
  10341. for (var i = 0; i < numElements; i += 3) {
  10342. var x = positionsHigh[i] + positionsLow[i];
  10343. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  10344. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  10345. currentPos.x = x;
  10346. currentPos.y = y;
  10347. currentPos.z = z;
  10348. // Store points containing the the smallest and largest components
  10349. if (x < xMin.x) {
  10350. Cartesian3.clone(currentPos, xMin);
  10351. }
  10352. if (x > xMax.x) {
  10353. Cartesian3.clone(currentPos, xMax);
  10354. }
  10355. if (y < yMin.y) {
  10356. Cartesian3.clone(currentPos, yMin);
  10357. }
  10358. if (y > yMax.y) {
  10359. Cartesian3.clone(currentPos, yMax);
  10360. }
  10361. if (z < zMin.z) {
  10362. Cartesian3.clone(currentPos, zMin);
  10363. }
  10364. if (z > zMax.z) {
  10365. Cartesian3.clone(currentPos, zMax);
  10366. }
  10367. }
  10368. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10369. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10370. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10371. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10372. // Set the diameter endpoints to the largest span.
  10373. var diameter1 = xMin;
  10374. var diameter2 = xMax;
  10375. var maxSpan = xSpan;
  10376. if (ySpan > maxSpan) {
  10377. maxSpan = ySpan;
  10378. diameter1 = yMin;
  10379. diameter2 = yMax;
  10380. }
  10381. if (zSpan > maxSpan) {
  10382. maxSpan = zSpan;
  10383. diameter1 = zMin;
  10384. diameter2 = zMax;
  10385. }
  10386. // Calculate the center of the initial sphere found by Ritter's algorithm
  10387. var ritterCenter = fromPointsRitterCenter;
  10388. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10389. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10390. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10391. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10392. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10393. var ritterRadius = Math.sqrt(radiusSquared);
  10394. // Find the center of the sphere found using the Naive method.
  10395. var minBoxPt = fromPointsMinBoxPt;
  10396. minBoxPt.x = xMin.x;
  10397. minBoxPt.y = yMin.y;
  10398. minBoxPt.z = zMin.z;
  10399. var maxBoxPt = fromPointsMaxBoxPt;
  10400. maxBoxPt.x = xMax.x;
  10401. maxBoxPt.y = yMax.y;
  10402. maxBoxPt.z = zMax.z;
  10403. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10404. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10405. var naiveRadius = 0;
  10406. for (i = 0; i < numElements; i += 3) {
  10407. currentPos.x = positionsHigh[i] + positionsLow[i];
  10408. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  10409. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  10410. // Find the furthest point from the naive center to calculate the naive radius.
  10411. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10412. if (r > naiveRadius) {
  10413. naiveRadius = r;
  10414. }
  10415. // Make adjustments to the Ritter Sphere to include all points.
  10416. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10417. if (oldCenterToPointSquared > radiusSquared) {
  10418. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10419. // Calculate new radius to include the point that lies outside
  10420. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10421. radiusSquared = ritterRadius * ritterRadius;
  10422. // Calculate center of new Ritter sphere
  10423. var oldToNew = oldCenterToPoint - ritterRadius;
  10424. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10425. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10426. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10427. }
  10428. }
  10429. if (ritterRadius < naiveRadius) {
  10430. Cartesian3.clone(ritterCenter, result.center);
  10431. result.radius = ritterRadius;
  10432. } else {
  10433. Cartesian3.clone(naiveCenter, result.center);
  10434. result.radius = naiveRadius;
  10435. }
  10436. return result;
  10437. };
  10438. /**
  10439. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  10440. * tighly and fully encompases the box.
  10441. *
  10442. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  10443. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  10444. * @param {BoundingSphere} [result] The object onto which to store the result.
  10445. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10446. *
  10447. * @example
  10448. * // Create a bounding sphere around the unit cube
  10449. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  10450. */
  10451. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  10452. if (!defined(corner) || !defined(oppositeCorner)) {
  10453. throw new DeveloperError('corner and oppositeCorner are required.');
  10454. }
  10455. if (!defined(result)) {
  10456. result = new BoundingSphere();
  10457. }
  10458. var center = result.center;
  10459. Cartesian3.add(corner, oppositeCorner, center);
  10460. Cartesian3.multiplyByScalar(center, 0.5, center);
  10461. result.radius = Cartesian3.distance(center, oppositeCorner);
  10462. return result;
  10463. };
  10464. /**
  10465. * Creates a bounding sphere encompassing an ellipsoid.
  10466. *
  10467. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  10468. * @param {BoundingSphere} [result] The object onto which to store the result.
  10469. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10470. *
  10471. * @example
  10472. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  10473. */
  10474. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  10475. if (!defined(ellipsoid)) {
  10476. throw new DeveloperError('ellipsoid is required.');
  10477. }
  10478. if (!defined(result)) {
  10479. result = new BoundingSphere();
  10480. }
  10481. Cartesian3.clone(Cartesian3.ZERO, result.center);
  10482. result.radius = ellipsoid.maximumRadius;
  10483. return result;
  10484. };
  10485. var fromBoundingSpheresScratch = new Cartesian3();
  10486. /**
  10487. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  10488. *
  10489. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  10490. * @param {BoundingSphere} [result] The object onto which to store the result.
  10491. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10492. */
  10493. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  10494. if (!defined(result)) {
  10495. result = new BoundingSphere();
  10496. }
  10497. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  10498. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10499. result.radius = 0.0;
  10500. return result;
  10501. }
  10502. var length = boundingSpheres.length;
  10503. if (length === 1) {
  10504. return BoundingSphere.clone(boundingSpheres[0], result);
  10505. }
  10506. if (length === 2) {
  10507. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  10508. }
  10509. var positions = [];
  10510. for (var i = 0; i < length; i++) {
  10511. positions.push(boundingSpheres[i].center);
  10512. }
  10513. result = BoundingSphere.fromPoints(positions, result);
  10514. var center = result.center;
  10515. var radius = result.radius;
  10516. for (i = 0; i < length; i++) {
  10517. var tmp = boundingSpheres[i];
  10518. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  10519. }
  10520. result.radius = radius;
  10521. return result;
  10522. };
  10523. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  10524. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  10525. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  10526. /**
  10527. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  10528. *
  10529. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  10530. * @param {BoundingSphere} [result] The object onto which to store the result.
  10531. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10532. */
  10533. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  10534. if (!defined(result)) {
  10535. result = new BoundingSphere();
  10536. }
  10537. var halfAxes = orientedBoundingBox.halfAxes;
  10538. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  10539. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  10540. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  10541. var uHalf = Cartesian3.magnitude(u);
  10542. var vHalf = Cartesian3.magnitude(v);
  10543. var wHalf = Cartesian3.magnitude(w);
  10544. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  10545. result.radius = Math.max(uHalf, vHalf, wHalf);
  10546. return result;
  10547. };
  10548. /**
  10549. * Duplicates a BoundingSphere instance.
  10550. *
  10551. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  10552. * @param {BoundingSphere} [result] The object onto which to store the result.
  10553. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  10554. */
  10555. BoundingSphere.clone = function(sphere, result) {
  10556. if (!defined(sphere)) {
  10557. return undefined;
  10558. }
  10559. if (!defined(result)) {
  10560. return new BoundingSphere(sphere.center, sphere.radius);
  10561. }
  10562. result.center = Cartesian3.clone(sphere.center, result.center);
  10563. result.radius = sphere.radius;
  10564. return result;
  10565. };
  10566. /**
  10567. * The number of elements used to pack the object into an array.
  10568. * @type {Number}
  10569. */
  10570. BoundingSphere.packedLength = 4;
  10571. /**
  10572. * Stores the provided instance into the provided array.
  10573. *
  10574. * @param {BoundingSphere} value The value to pack.
  10575. * @param {Number[]} array The array to pack into.
  10576. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  10577. *
  10578. * @returns {Number[]} The array that was packed into
  10579. */
  10580. BoundingSphere.pack = function(value, array, startingIndex) {
  10581. if (!defined(value)) {
  10582. throw new DeveloperError('value is required');
  10583. }
  10584. if (!defined(array)) {
  10585. throw new DeveloperError('array is required');
  10586. }
  10587. startingIndex = defaultValue(startingIndex, 0);
  10588. var center = value.center;
  10589. array[startingIndex++] = center.x;
  10590. array[startingIndex++] = center.y;
  10591. array[startingIndex++] = center.z;
  10592. array[startingIndex] = value.radius;
  10593. return array;
  10594. };
  10595. /**
  10596. * Retrieves an instance from a packed array.
  10597. *
  10598. * @param {Number[]} array The packed array.
  10599. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10600. * @param {BoundingSphere} [result] The object into which to store the result.
  10601. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10602. */
  10603. BoundingSphere.unpack = function(array, startingIndex, result) {
  10604. if (!defined(array)) {
  10605. throw new DeveloperError('array is required');
  10606. }
  10607. startingIndex = defaultValue(startingIndex, 0);
  10608. if (!defined(result)) {
  10609. result = new BoundingSphere();
  10610. }
  10611. var center = result.center;
  10612. center.x = array[startingIndex++];
  10613. center.y = array[startingIndex++];
  10614. center.z = array[startingIndex++];
  10615. result.radius = array[startingIndex];
  10616. return result;
  10617. };
  10618. var unionScratch = new Cartesian3();
  10619. var unionScratchCenter = new Cartesian3();
  10620. /**
  10621. * Computes a bounding sphere that contains both the left and right bounding spheres.
  10622. *
  10623. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  10624. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  10625. * @param {BoundingSphere} [result] The object onto which to store the result.
  10626. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10627. */
  10628. BoundingSphere.union = function(left, right, result) {
  10629. if (!defined(left)) {
  10630. throw new DeveloperError('left is required.');
  10631. }
  10632. if (!defined(right)) {
  10633. throw new DeveloperError('right is required.');
  10634. }
  10635. if (!defined(result)) {
  10636. result = new BoundingSphere();
  10637. }
  10638. var leftCenter = left.center;
  10639. var leftRadius = left.radius;
  10640. var rightCenter = right.center;
  10641. var rightRadius = right.radius;
  10642. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  10643. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  10644. if (leftRadius >= (centerSeparation + rightRadius)) {
  10645. // Left sphere wins.
  10646. left.clone(result);
  10647. return result;
  10648. }
  10649. if (rightRadius >= (centerSeparation + leftRadius)) {
  10650. // Right sphere wins.
  10651. right.clone(result);
  10652. return result;
  10653. }
  10654. // There are two tangent points, one on far side of each sphere.
  10655. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  10656. // Compute the center point halfway between the two tangent points.
  10657. var center = Cartesian3.multiplyByScalar(toRightCenter,
  10658. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  10659. Cartesian3.add(center, leftCenter, center);
  10660. Cartesian3.clone(center, result.center);
  10661. result.radius = halfDistanceBetweenTangentPoints;
  10662. return result;
  10663. };
  10664. var expandScratch = new Cartesian3();
  10665. /**
  10666. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  10667. *
  10668. * @param {BoundingSphere} sphere A sphere to expand.
  10669. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  10670. * @param {BoundingSphere} [result] The object onto which to store the result.
  10671. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10672. */
  10673. BoundingSphere.expand = function(sphere, point, result) {
  10674. if (!defined(sphere)) {
  10675. throw new DeveloperError('sphere is required.');
  10676. }
  10677. if (!defined(point)) {
  10678. throw new DeveloperError('point is required.');
  10679. }
  10680. result = BoundingSphere.clone(sphere, result);
  10681. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  10682. if (radius > result.radius) {
  10683. result.radius = radius;
  10684. }
  10685. return result;
  10686. };
  10687. /**
  10688. * Determines which side of a plane a sphere is located.
  10689. *
  10690. * @param {BoundingSphere} sphere The bounding sphere to test.
  10691. * @param {Plane} plane The plane to test against.
  10692. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10693. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10694. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10695. * intersects the plane.
  10696. */
  10697. BoundingSphere.intersectPlane = function(sphere, plane) {
  10698. if (!defined(sphere)) {
  10699. throw new DeveloperError('sphere is required.');
  10700. }
  10701. if (!defined(plane)) {
  10702. throw new DeveloperError('plane is required.');
  10703. }
  10704. var center = sphere.center;
  10705. var radius = sphere.radius;
  10706. var normal = plane.normal;
  10707. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  10708. if (distanceToPlane < -radius) {
  10709. // The center point is negative side of the plane normal
  10710. return Intersect.OUTSIDE;
  10711. } else if (distanceToPlane < radius) {
  10712. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  10713. return Intersect.INTERSECTING;
  10714. }
  10715. return Intersect.INSIDE;
  10716. };
  10717. /**
  10718. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  10719. *
  10720. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10721. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10722. * @param {BoundingSphere} [result] The object onto which to store the result.
  10723. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10724. */
  10725. BoundingSphere.transform = function(sphere, transform, result) {
  10726. if (!defined(sphere)) {
  10727. throw new DeveloperError('sphere is required.');
  10728. }
  10729. if (!defined(transform)) {
  10730. throw new DeveloperError('transform is required.');
  10731. }
  10732. if (!defined(result)) {
  10733. result = new BoundingSphere();
  10734. }
  10735. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10736. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  10737. return result;
  10738. };
  10739. var distanceSquaredToScratch = new Cartesian3();
  10740. /**
  10741. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10742. *
  10743. * @param {BoundingSphere} sphere The sphere.
  10744. * @param {Cartesian3} cartesian The point
  10745. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10746. *
  10747. * @example
  10748. * // Sort bounding spheres from back to front
  10749. * spheres.sort(function(a, b) {
  10750. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  10751. * });
  10752. */
  10753. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  10754. if (!defined(sphere)) {
  10755. throw new DeveloperError('sphere is required.');
  10756. }
  10757. if (!defined(cartesian)) {
  10758. throw new DeveloperError('cartesian is required.');
  10759. }
  10760. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  10761. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  10762. };
  10763. /**
  10764. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  10765. * The transformation matrix is not verified to have a uniform scale of 1.
  10766. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  10767. *
  10768. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10769. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10770. * @param {BoundingSphere} [result] The object onto which to store the result.
  10771. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10772. *
  10773. * @example
  10774. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  10775. * var boundingSphere = new Cesium.BoundingSphere();
  10776. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  10777. */
  10778. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  10779. if (!defined(sphere)) {
  10780. throw new DeveloperError('sphere is required.');
  10781. }
  10782. if (!defined(transform)) {
  10783. throw new DeveloperError('transform is required.');
  10784. }
  10785. if (!defined(result)) {
  10786. result = new BoundingSphere();
  10787. }
  10788. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10789. result.radius = sphere.radius;
  10790. return result;
  10791. };
  10792. var scratchCartesian3 = new Cartesian3();
  10793. /**
  10794. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10795. * plus/minus the radius of the bounding sphere.
  10796. * <br>
  10797. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10798. * closest and farthest planes from position that intersect the bounding sphere.
  10799. *
  10800. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  10801. * @param {Cartesian3} position The position to calculate the distance from.
  10802. * @param {Cartesian3} direction The direction from position.
  10803. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10804. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10805. */
  10806. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  10807. if (!defined(sphere)) {
  10808. throw new DeveloperError('sphere is required.');
  10809. }
  10810. if (!defined(position)) {
  10811. throw new DeveloperError('position is required.');
  10812. }
  10813. if (!defined(direction)) {
  10814. throw new DeveloperError('direction is required.');
  10815. }
  10816. if (!defined(result)) {
  10817. result = new Interval();
  10818. }
  10819. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  10820. var mag = Cartesian3.dot(direction, toCenter);
  10821. result.start = mag - sphere.radius;
  10822. result.stop = mag + sphere.radius;
  10823. return result;
  10824. };
  10825. var projectTo2DNormalScratch = new Cartesian3();
  10826. var projectTo2DEastScratch = new Cartesian3();
  10827. var projectTo2DNorthScratch = new Cartesian3();
  10828. var projectTo2DWestScratch = new Cartesian3();
  10829. var projectTo2DSouthScratch = new Cartesian3();
  10830. var projectTo2DCartographicScratch = new Cartographic();
  10831. var projectTo2DPositionsScratch = new Array(8);
  10832. for (var n = 0; n < 8; ++n) {
  10833. projectTo2DPositionsScratch[n] = new Cartesian3();
  10834. }
  10835. var projectTo2DProjection = new GeographicProjection();
  10836. /**
  10837. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  10838. *
  10839. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  10840. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  10841. * @param {BoundingSphere} [result] The object onto which to store the result.
  10842. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10843. */
  10844. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  10845. if (!defined(sphere)) {
  10846. throw new DeveloperError('sphere is required.');
  10847. }
  10848. projection = defaultValue(projection, projectTo2DProjection);
  10849. var ellipsoid = projection.ellipsoid;
  10850. var center = sphere.center;
  10851. var radius = sphere.radius;
  10852. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  10853. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  10854. Cartesian3.normalize(east, east);
  10855. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  10856. Cartesian3.normalize(north, north);
  10857. Cartesian3.multiplyByScalar(normal, radius, normal);
  10858. Cartesian3.multiplyByScalar(north, radius, north);
  10859. Cartesian3.multiplyByScalar(east, radius, east);
  10860. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  10861. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  10862. var positions = projectTo2DPositionsScratch;
  10863. // top NE corner
  10864. var corner = positions[0];
  10865. Cartesian3.add(normal, north, corner);
  10866. Cartesian3.add(corner, east, corner);
  10867. // top NW corner
  10868. corner = positions[1];
  10869. Cartesian3.add(normal, north, corner);
  10870. Cartesian3.add(corner, west, corner);
  10871. // top SW corner
  10872. corner = positions[2];
  10873. Cartesian3.add(normal, south, corner);
  10874. Cartesian3.add(corner, west, corner);
  10875. // top SE corner
  10876. corner = positions[3];
  10877. Cartesian3.add(normal, south, corner);
  10878. Cartesian3.add(corner, east, corner);
  10879. Cartesian3.negate(normal, normal);
  10880. // bottom NE corner
  10881. corner = positions[4];
  10882. Cartesian3.add(normal, north, corner);
  10883. Cartesian3.add(corner, east, corner);
  10884. // bottom NW corner
  10885. corner = positions[5];
  10886. Cartesian3.add(normal, north, corner);
  10887. Cartesian3.add(corner, west, corner);
  10888. // bottom SW corner
  10889. corner = positions[6];
  10890. Cartesian3.add(normal, south, corner);
  10891. Cartesian3.add(corner, west, corner);
  10892. // bottom SE corner
  10893. corner = positions[7];
  10894. Cartesian3.add(normal, south, corner);
  10895. Cartesian3.add(corner, east, corner);
  10896. var length = positions.length;
  10897. for (var i = 0; i < length; ++i) {
  10898. var position = positions[i];
  10899. Cartesian3.add(center, position, position);
  10900. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  10901. projection.project(cartographic, position);
  10902. }
  10903. result = BoundingSphere.fromPoints(positions, result);
  10904. // swizzle center components
  10905. center = result.center;
  10906. var x = center.x;
  10907. var y = center.y;
  10908. var z = center.z;
  10909. center.x = z;
  10910. center.y = x;
  10911. center.z = y;
  10912. return result;
  10913. };
  10914. /**
  10915. * Determines whether or not a sphere is hidden from view by the occluder.
  10916. *
  10917. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  10918. * @param {Occluder} occluder The occluder.
  10919. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10920. */
  10921. BoundingSphere.isOccluded = function(sphere, occluder) {
  10922. if (!defined(sphere)) {
  10923. throw new DeveloperError('sphere is required.');
  10924. }
  10925. if (!defined(occluder)) {
  10926. throw new DeveloperError('occluder is required.');
  10927. }
  10928. return !occluder.isBoundingSphereVisible(sphere);
  10929. };
  10930. /**
  10931. * Compares the provided BoundingSphere componentwise and returns
  10932. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10933. *
  10934. * @param {BoundingSphere} [left] The first BoundingSphere.
  10935. * @param {BoundingSphere} [right] The second BoundingSphere.
  10936. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10937. */
  10938. BoundingSphere.equals = function(left, right) {
  10939. return (left === right) ||
  10940. ((defined(left)) &&
  10941. (defined(right)) &&
  10942. Cartesian3.equals(left.center, right.center) &&
  10943. left.radius === right.radius);
  10944. };
  10945. /**
  10946. * Determines which side of a plane the sphere is located.
  10947. *
  10948. * @param {Plane} plane The plane to test against.
  10949. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10950. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10951. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10952. * intersects the plane.
  10953. */
  10954. BoundingSphere.prototype.intersectPlane = function(plane) {
  10955. return BoundingSphere.intersectPlane(this, plane);
  10956. };
  10957. /**
  10958. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10959. *
  10960. * @param {Cartesian3} cartesian The point
  10961. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10962. *
  10963. * @example
  10964. * // Sort bounding spheres from back to front
  10965. * spheres.sort(function(a, b) {
  10966. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  10967. * });
  10968. */
  10969. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  10970. return BoundingSphere.distanceSquaredTo(this, cartesian);
  10971. };
  10972. /**
  10973. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10974. * plus/minus the radius of the bounding sphere.
  10975. * <br>
  10976. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10977. * closest and farthest planes from position that intersect the bounding sphere.
  10978. *
  10979. * @param {Cartesian3} position The position to calculate the distance from.
  10980. * @param {Cartesian3} direction The direction from position.
  10981. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10982. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10983. */
  10984. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  10985. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  10986. };
  10987. /**
  10988. * Determines whether or not a sphere is hidden from view by the occluder.
  10989. *
  10990. * @param {Occluder} occluder The occluder.
  10991. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10992. */
  10993. BoundingSphere.prototype.isOccluded = function(occluder) {
  10994. return BoundingSphere.isOccluded(this, occluder);
  10995. };
  10996. /**
  10997. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  10998. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10999. *
  11000. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  11001. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11002. */
  11003. BoundingSphere.prototype.equals = function(right) {
  11004. return BoundingSphere.equals(this, right);
  11005. };
  11006. /**
  11007. * Duplicates this BoundingSphere instance.
  11008. *
  11009. * @param {BoundingSphere} [result] The object onto which to store the result.
  11010. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  11011. */
  11012. BoundingSphere.prototype.clone = function(result) {
  11013. return BoundingSphere.clone(this, result);
  11014. };
  11015. return BoundingSphere;
  11016. });
  11017. /*global define*/
  11018. define('Core/Fullscreen',[
  11019. './defined',
  11020. './defineProperties'
  11021. ], function(
  11022. defined,
  11023. defineProperties) {
  11024. 'use strict';
  11025. var _supportsFullscreen;
  11026. var _names = {
  11027. requestFullscreen : undefined,
  11028. exitFullscreen : undefined,
  11029. fullscreenEnabled : undefined,
  11030. fullscreenElement : undefined,
  11031. fullscreenchange : undefined,
  11032. fullscreenerror : undefined
  11033. };
  11034. /**
  11035. * Browser-independent functions for working with the standard fullscreen API.
  11036. *
  11037. * @exports Fullscreen
  11038. *
  11039. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11040. */
  11041. var Fullscreen = {};
  11042. defineProperties(Fullscreen, {
  11043. /**
  11044. * The element that is currently fullscreen, if any. To simply check if the
  11045. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  11046. * @memberof Fullscreen
  11047. * @type {Object}
  11048. * @readonly
  11049. */
  11050. element : {
  11051. get : function() {
  11052. if (!Fullscreen.supportsFullscreen()) {
  11053. return undefined;
  11054. }
  11055. return document[_names.fullscreenElement];
  11056. }
  11057. },
  11058. /**
  11059. * The name of the event on the document that is fired when fullscreen is
  11060. * entered or exited. This event name is intended for use with addEventListener.
  11061. * In your event handler, to determine if the browser is in fullscreen mode or not,
  11062. * use {@link Fullscreen#fullscreen}.
  11063. * @memberof Fullscreen
  11064. * @type {String}
  11065. * @readonly
  11066. */
  11067. changeEventName : {
  11068. get : function() {
  11069. if (!Fullscreen.supportsFullscreen()) {
  11070. return undefined;
  11071. }
  11072. return _names.fullscreenchange;
  11073. }
  11074. },
  11075. /**
  11076. * The name of the event that is fired when a fullscreen error
  11077. * occurs. This event name is intended for use with addEventListener.
  11078. * @memberof Fullscreen
  11079. * @type {String}
  11080. * @readonly
  11081. */
  11082. errorEventName : {
  11083. get : function() {
  11084. if (!Fullscreen.supportsFullscreen()) {
  11085. return undefined;
  11086. }
  11087. return _names.fullscreenerror;
  11088. }
  11089. },
  11090. /**
  11091. * Determine whether the browser will allow an element to be made fullscreen, or not.
  11092. * For example, by default, iframes cannot go fullscreen unless the containing page
  11093. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  11094. * @memberof Fullscreen
  11095. * @type {Boolean}
  11096. * @readonly
  11097. */
  11098. enabled : {
  11099. get : function() {
  11100. if (!Fullscreen.supportsFullscreen()) {
  11101. return undefined;
  11102. }
  11103. return document[_names.fullscreenEnabled];
  11104. }
  11105. },
  11106. /**
  11107. * Determines if the browser is currently in fullscreen mode.
  11108. * @memberof Fullscreen
  11109. * @type {Boolean}
  11110. * @readonly
  11111. */
  11112. fullscreen : {
  11113. get : function() {
  11114. if (!Fullscreen.supportsFullscreen()) {
  11115. return undefined;
  11116. }
  11117. return Fullscreen.element !== null;
  11118. }
  11119. }
  11120. });
  11121. /**
  11122. * Detects whether the browser supports the standard fullscreen API.
  11123. *
  11124. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  11125. * <code>false</code> otherwise.
  11126. */
  11127. Fullscreen.supportsFullscreen = function() {
  11128. if (defined(_supportsFullscreen)) {
  11129. return _supportsFullscreen;
  11130. }
  11131. _supportsFullscreen = false;
  11132. var body = document.body;
  11133. if (typeof body.requestFullscreen === 'function') {
  11134. // go with the unprefixed, standard set of names
  11135. _names.requestFullscreen = 'requestFullscreen';
  11136. _names.exitFullscreen = 'exitFullscreen';
  11137. _names.fullscreenEnabled = 'fullscreenEnabled';
  11138. _names.fullscreenElement = 'fullscreenElement';
  11139. _names.fullscreenchange = 'fullscreenchange';
  11140. _names.fullscreenerror = 'fullscreenerror';
  11141. _supportsFullscreen = true;
  11142. return _supportsFullscreen;
  11143. }
  11144. //check for the correct combination of prefix plus the various names that browsers use
  11145. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  11146. var name;
  11147. for (var i = 0, len = prefixes.length; i < len; ++i) {
  11148. var prefix = prefixes[i];
  11149. // casing of Fullscreen differs across browsers
  11150. name = prefix + 'RequestFullscreen';
  11151. if (typeof body[name] === 'function') {
  11152. _names.requestFullscreen = name;
  11153. _supportsFullscreen = true;
  11154. } else {
  11155. name = prefix + 'RequestFullScreen';
  11156. if (typeof body[name] === 'function') {
  11157. _names.requestFullscreen = name;
  11158. _supportsFullscreen = true;
  11159. }
  11160. }
  11161. // disagreement about whether it's "exit" as per spec, or "cancel"
  11162. name = prefix + 'ExitFullscreen';
  11163. if (typeof document[name] === 'function') {
  11164. _names.exitFullscreen = name;
  11165. } else {
  11166. name = prefix + 'CancelFullScreen';
  11167. if (typeof document[name] === 'function') {
  11168. _names.exitFullscreen = name;
  11169. }
  11170. }
  11171. // casing of Fullscreen differs across browsers
  11172. name = prefix + 'FullscreenEnabled';
  11173. if (document[name] !== undefined) {
  11174. _names.fullscreenEnabled = name;
  11175. } else {
  11176. name = prefix + 'FullScreenEnabled';
  11177. if (document[name] !== undefined) {
  11178. _names.fullscreenEnabled = name;
  11179. }
  11180. }
  11181. // casing of Fullscreen differs across browsers
  11182. name = prefix + 'FullscreenElement';
  11183. if (document[name] !== undefined) {
  11184. _names.fullscreenElement = name;
  11185. } else {
  11186. name = prefix + 'FullScreenElement';
  11187. if (document[name] !== undefined) {
  11188. _names.fullscreenElement = name;
  11189. }
  11190. }
  11191. // thankfully, event names are all lowercase per spec
  11192. name = prefix + 'fullscreenchange';
  11193. // event names do not have 'on' in the front, but the property on the document does
  11194. if (document['on' + name] !== undefined) {
  11195. //except on IE
  11196. if (prefix === 'ms') {
  11197. name = 'MSFullscreenChange';
  11198. }
  11199. _names.fullscreenchange = name;
  11200. }
  11201. name = prefix + 'fullscreenerror';
  11202. if (document['on' + name] !== undefined) {
  11203. //except on IE
  11204. if (prefix === 'ms') {
  11205. name = 'MSFullscreenError';
  11206. }
  11207. _names.fullscreenerror = name;
  11208. }
  11209. }
  11210. return _supportsFullscreen;
  11211. };
  11212. /**
  11213. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  11214. * If fullscreen mode is not supported by the browser, does nothing.
  11215. *
  11216. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  11217. * @param {HMDVRDevice} [vrDevice] The VR device.
  11218. *
  11219. * @example
  11220. * // Put the entire page into fullscreen.
  11221. * Cesium.Fullscreen.requestFullscreen(document.body)
  11222. *
  11223. * // Place only the Cesium canvas into fullscreen.
  11224. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  11225. */
  11226. Fullscreen.requestFullscreen = function(element, vrDevice) {
  11227. if (!Fullscreen.supportsFullscreen()) {
  11228. return;
  11229. }
  11230. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  11231. };
  11232. /**
  11233. * Asynchronously exits fullscreen mode. If the browser is not currently
  11234. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  11235. */
  11236. Fullscreen.exitFullscreen = function() {
  11237. if (!Fullscreen.supportsFullscreen()) {
  11238. return;
  11239. }
  11240. document[_names.exitFullscreen]();
  11241. };
  11242. return Fullscreen;
  11243. });
  11244. /*global define*/
  11245. define('Core/FeatureDetection',[
  11246. './defaultValue',
  11247. './defined',
  11248. './Fullscreen'
  11249. ], function(
  11250. defaultValue,
  11251. defined,
  11252. Fullscreen) {
  11253. 'use strict';
  11254. var theNavigator;
  11255. if (typeof navigator !== 'undefined') {
  11256. theNavigator = navigator;
  11257. } else {
  11258. theNavigator = {};
  11259. }
  11260. function extractVersion(versionString) {
  11261. var parts = versionString.split('.');
  11262. for (var i = 0, len = parts.length; i < len; ++i) {
  11263. parts[i] = parseInt(parts[i], 10);
  11264. }
  11265. return parts;
  11266. }
  11267. var isChromeResult;
  11268. var chromeVersionResult;
  11269. function isChrome() {
  11270. if (!defined(isChromeResult)) {
  11271. isChromeResult = false;
  11272. // Edge contains Chrome in the user agent too
  11273. if (!isEdge()) {
  11274. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11275. if (fields !== null) {
  11276. isChromeResult = true;
  11277. chromeVersionResult = extractVersion(fields[1]);
  11278. }
  11279. }
  11280. }
  11281. return isChromeResult;
  11282. }
  11283. function chromeVersion() {
  11284. return isChrome() && chromeVersionResult;
  11285. }
  11286. var isSafariResult;
  11287. var safariVersionResult;
  11288. function isSafari() {
  11289. if (!defined(isSafariResult)) {
  11290. isSafariResult = false;
  11291. // Chrome and Edge contain Safari in the user agent too
  11292. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  11293. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11294. if (fields !== null) {
  11295. isSafariResult = true;
  11296. safariVersionResult = extractVersion(fields[1]);
  11297. }
  11298. }
  11299. }
  11300. return isSafariResult;
  11301. }
  11302. function safariVersion() {
  11303. return isSafari() && safariVersionResult;
  11304. }
  11305. var isWebkitResult;
  11306. var webkitVersionResult;
  11307. function isWebkit() {
  11308. if (!defined(isWebkitResult)) {
  11309. isWebkitResult = false;
  11310. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  11311. if (fields !== null) {
  11312. isWebkitResult = true;
  11313. webkitVersionResult = extractVersion(fields[1]);
  11314. webkitVersionResult.isNightly = !!fields[2];
  11315. }
  11316. }
  11317. return isWebkitResult;
  11318. }
  11319. function webkitVersion() {
  11320. return isWebkit() && webkitVersionResult;
  11321. }
  11322. var isInternetExplorerResult;
  11323. var internetExplorerVersionResult;
  11324. function isInternetExplorer() {
  11325. if (!defined(isInternetExplorerResult)) {
  11326. isInternetExplorerResult = false;
  11327. var fields;
  11328. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  11329. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11330. if (fields !== null) {
  11331. isInternetExplorerResult = true;
  11332. internetExplorerVersionResult = extractVersion(fields[1]);
  11333. }
  11334. } else if (theNavigator.appName === 'Netscape') {
  11335. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11336. if (fields !== null) {
  11337. isInternetExplorerResult = true;
  11338. internetExplorerVersionResult = extractVersion(fields[1]);
  11339. }
  11340. }
  11341. }
  11342. return isInternetExplorerResult;
  11343. }
  11344. function internetExplorerVersion() {
  11345. return isInternetExplorer() && internetExplorerVersionResult;
  11346. }
  11347. var isEdgeResult;
  11348. var edgeVersionResult;
  11349. function isEdge() {
  11350. if (!defined(isEdgeResult)) {
  11351. isEdgeResult = false;
  11352. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11353. if (fields !== null) {
  11354. isEdgeResult = true;
  11355. edgeVersionResult = extractVersion(fields[1]);
  11356. }
  11357. }
  11358. return isEdgeResult;
  11359. }
  11360. function edgeVersion() {
  11361. return isEdge() && edgeVersionResult;
  11362. }
  11363. var isFirefoxResult;
  11364. var firefoxVersionResult;
  11365. function isFirefox() {
  11366. if (!defined(isFirefoxResult)) {
  11367. isFirefoxResult = false;
  11368. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  11369. if (fields !== null) {
  11370. isFirefoxResult = true;
  11371. firefoxVersionResult = extractVersion(fields[1]);
  11372. }
  11373. }
  11374. return isFirefoxResult;
  11375. }
  11376. var isWindowsResult;
  11377. function isWindows() {
  11378. if (!defined(isWindowsResult)) {
  11379. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  11380. }
  11381. return isWindowsResult;
  11382. }
  11383. function firefoxVersion() {
  11384. return isFirefox() && firefoxVersionResult;
  11385. }
  11386. var hasPointerEvents;
  11387. function supportsPointerEvents() {
  11388. if (!defined(hasPointerEvents)) {
  11389. //While navigator.pointerEnabled is deprecated in the W3C specification
  11390. //we still need to use it if it exists in order to support browsers
  11391. //that rely on it, such as the Windows WebBrowser control which defines
  11392. //PointerEvent but sets navigator.pointerEnabled to false.
  11393. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  11394. }
  11395. return hasPointerEvents;
  11396. }
  11397. var imageRenderingValueResult;
  11398. var supportsImageRenderingPixelatedResult;
  11399. function supportsImageRenderingPixelated() {
  11400. if (!defined(supportsImageRenderingPixelatedResult)) {
  11401. var canvas = document.createElement('canvas');
  11402. canvas.setAttribute('style',
  11403. 'image-rendering: -moz-crisp-edges;' +
  11404. 'image-rendering: pixelated;');
  11405. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  11406. var tmp = canvas.style.imageRendering;
  11407. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  11408. if (supportsImageRenderingPixelatedResult) {
  11409. imageRenderingValueResult = tmp;
  11410. }
  11411. }
  11412. return supportsImageRenderingPixelatedResult;
  11413. }
  11414. function imageRenderingValue() {
  11415. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  11416. }
  11417. /**
  11418. * A set of functions to detect whether the current browser supports
  11419. * various features.
  11420. *
  11421. * @exports FeatureDetection
  11422. */
  11423. var FeatureDetection = {
  11424. isChrome : isChrome,
  11425. chromeVersion : chromeVersion,
  11426. isSafari : isSafari,
  11427. safariVersion : safariVersion,
  11428. isWebkit : isWebkit,
  11429. webkitVersion : webkitVersion,
  11430. isInternetExplorer : isInternetExplorer,
  11431. internetExplorerVersion : internetExplorerVersion,
  11432. isEdge : isEdge,
  11433. edgeVersion : edgeVersion,
  11434. isFirefox : isFirefox,
  11435. firefoxVersion : firefoxVersion,
  11436. isWindows : isWindows,
  11437. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  11438. supportsPointerEvents : supportsPointerEvents,
  11439. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  11440. imageRenderingValue: imageRenderingValue
  11441. };
  11442. /**
  11443. * Detects whether the current browser supports the full screen standard.
  11444. *
  11445. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  11446. *
  11447. * @see Fullscreen
  11448. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11449. */
  11450. FeatureDetection.supportsFullscreen = function() {
  11451. return Fullscreen.supportsFullscreen();
  11452. };
  11453. /**
  11454. * Detects whether the current browser supports typed arrays.
  11455. *
  11456. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  11457. *
  11458. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  11459. */
  11460. FeatureDetection.supportsTypedArrays = function() {
  11461. return typeof ArrayBuffer !== 'undefined';
  11462. };
  11463. /**
  11464. * Detects whether the current browser supports Web Workers.
  11465. *
  11466. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  11467. *
  11468. * @see {@link http://www.w3.org/TR/workers/}
  11469. */
  11470. FeatureDetection.supportsWebWorkers = function() {
  11471. return typeof Worker !== 'undefined';
  11472. };
  11473. return FeatureDetection;
  11474. });
  11475. /*global define*/
  11476. define('Core/WebGLConstants',[
  11477. './freezeObject'
  11478. ], function(
  11479. freezeObject) {
  11480. 'use strict';
  11481. /**
  11482. * Enum containing WebGL Constant values by name.
  11483. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  11484. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  11485. *
  11486. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  11487. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  11488. * specifications.
  11489. *
  11490. * @exports WebGLConstants
  11491. */
  11492. var WebGLConstants = {
  11493. DEPTH_BUFFER_BIT : 0x00000100,
  11494. STENCIL_BUFFER_BIT : 0x00000400,
  11495. COLOR_BUFFER_BIT : 0x00004000,
  11496. POINTS : 0x0000,
  11497. LINES : 0x0001,
  11498. LINE_LOOP : 0x0002,
  11499. LINE_STRIP : 0x0003,
  11500. TRIANGLES : 0x0004,
  11501. TRIANGLE_STRIP : 0x0005,
  11502. TRIANGLE_FAN : 0x0006,
  11503. ZERO : 0,
  11504. ONE : 1,
  11505. SRC_COLOR : 0x0300,
  11506. ONE_MINUS_SRC_COLOR : 0x0301,
  11507. SRC_ALPHA : 0x0302,
  11508. ONE_MINUS_SRC_ALPHA : 0x0303,
  11509. DST_ALPHA : 0x0304,
  11510. ONE_MINUS_DST_ALPHA : 0x0305,
  11511. DST_COLOR : 0x0306,
  11512. ONE_MINUS_DST_COLOR : 0x0307,
  11513. SRC_ALPHA_SATURATE : 0x0308,
  11514. FUNC_ADD : 0x8006,
  11515. BLEND_EQUATION : 0x8009,
  11516. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  11517. BLEND_EQUATION_ALPHA : 0x883D,
  11518. FUNC_SUBTRACT : 0x800A,
  11519. FUNC_REVERSE_SUBTRACT : 0x800B,
  11520. BLEND_DST_RGB : 0x80C8,
  11521. BLEND_SRC_RGB : 0x80C9,
  11522. BLEND_DST_ALPHA : 0x80CA,
  11523. BLEND_SRC_ALPHA : 0x80CB,
  11524. CONSTANT_COLOR : 0x8001,
  11525. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  11526. CONSTANT_ALPHA : 0x8003,
  11527. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  11528. BLEND_COLOR : 0x8005,
  11529. ARRAY_BUFFER : 0x8892,
  11530. ELEMENT_ARRAY_BUFFER : 0x8893,
  11531. ARRAY_BUFFER_BINDING : 0x8894,
  11532. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  11533. STREAM_DRAW : 0x88E0,
  11534. STATIC_DRAW : 0x88E4,
  11535. DYNAMIC_DRAW : 0x88E8,
  11536. BUFFER_SIZE : 0x8764,
  11537. BUFFER_USAGE : 0x8765,
  11538. CURRENT_VERTEX_ATTRIB : 0x8626,
  11539. FRONT : 0x0404,
  11540. BACK : 0x0405,
  11541. FRONT_AND_BACK : 0x0408,
  11542. CULL_FACE : 0x0B44,
  11543. BLEND : 0x0BE2,
  11544. DITHER : 0x0BD0,
  11545. STENCIL_TEST : 0x0B90,
  11546. DEPTH_TEST : 0x0B71,
  11547. SCISSOR_TEST : 0x0C11,
  11548. POLYGON_OFFSET_FILL : 0x8037,
  11549. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  11550. SAMPLE_COVERAGE : 0x80A0,
  11551. NO_ERROR : 0,
  11552. INVALID_ENUM : 0x0500,
  11553. INVALID_VALUE : 0x0501,
  11554. INVALID_OPERATION : 0x0502,
  11555. OUT_OF_MEMORY : 0x0505,
  11556. CW : 0x0900,
  11557. CCW : 0x0901,
  11558. LINE_WIDTH : 0x0B21,
  11559. ALIASED_POINT_SIZE_RANGE : 0x846D,
  11560. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  11561. CULL_FACE_MODE : 0x0B45,
  11562. FRONT_FACE : 0x0B46,
  11563. DEPTH_RANGE : 0x0B70,
  11564. DEPTH_WRITEMASK : 0x0B72,
  11565. DEPTH_CLEAR_VALUE : 0x0B73,
  11566. DEPTH_FUNC : 0x0B74,
  11567. STENCIL_CLEAR_VALUE : 0x0B91,
  11568. STENCIL_FUNC : 0x0B92,
  11569. STENCIL_FAIL : 0x0B94,
  11570. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  11571. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  11572. STENCIL_REF : 0x0B97,
  11573. STENCIL_VALUE_MASK : 0x0B93,
  11574. STENCIL_WRITEMASK : 0x0B98,
  11575. STENCIL_BACK_FUNC : 0x8800,
  11576. STENCIL_BACK_FAIL : 0x8801,
  11577. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  11578. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  11579. STENCIL_BACK_REF : 0x8CA3,
  11580. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  11581. STENCIL_BACK_WRITEMASK : 0x8CA5,
  11582. VIEWPORT : 0x0BA2,
  11583. SCISSOR_BOX : 0x0C10,
  11584. COLOR_CLEAR_VALUE : 0x0C22,
  11585. COLOR_WRITEMASK : 0x0C23,
  11586. UNPACK_ALIGNMENT : 0x0CF5,
  11587. PACK_ALIGNMENT : 0x0D05,
  11588. MAX_TEXTURE_SIZE : 0x0D33,
  11589. MAX_VIEWPORT_DIMS : 0x0D3A,
  11590. SUBPIXEL_BITS : 0x0D50,
  11591. RED_BITS : 0x0D52,
  11592. GREEN_BITS : 0x0D53,
  11593. BLUE_BITS : 0x0D54,
  11594. ALPHA_BITS : 0x0D55,
  11595. DEPTH_BITS : 0x0D56,
  11596. STENCIL_BITS : 0x0D57,
  11597. POLYGON_OFFSET_UNITS : 0x2A00,
  11598. POLYGON_OFFSET_FACTOR : 0x8038,
  11599. TEXTURE_BINDING_2D : 0x8069,
  11600. SAMPLE_BUFFERS : 0x80A8,
  11601. SAMPLES : 0x80A9,
  11602. SAMPLE_COVERAGE_VALUE : 0x80AA,
  11603. SAMPLE_COVERAGE_INVERT : 0x80AB,
  11604. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  11605. DONT_CARE : 0x1100,
  11606. FASTEST : 0x1101,
  11607. NICEST : 0x1102,
  11608. GENERATE_MIPMAP_HINT : 0x8192,
  11609. BYTE : 0x1400,
  11610. UNSIGNED_BYTE : 0x1401,
  11611. SHORT : 0x1402,
  11612. UNSIGNED_SHORT : 0x1403,
  11613. INT : 0x1404,
  11614. UNSIGNED_INT : 0x1405,
  11615. FLOAT : 0x1406,
  11616. DEPTH_COMPONENT : 0x1902,
  11617. ALPHA : 0x1906,
  11618. RGB : 0x1907,
  11619. RGBA : 0x1908,
  11620. LUMINANCE : 0x1909,
  11621. LUMINANCE_ALPHA : 0x190A,
  11622. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  11623. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  11624. UNSIGNED_SHORT_5_6_5 : 0x8363,
  11625. FRAGMENT_SHADER : 0x8B30,
  11626. VERTEX_SHADER : 0x8B31,
  11627. MAX_VERTEX_ATTRIBS : 0x8869,
  11628. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  11629. MAX_VARYING_VECTORS : 0x8DFC,
  11630. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  11631. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  11632. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  11633. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  11634. SHADER_TYPE : 0x8B4F,
  11635. DELETE_STATUS : 0x8B80,
  11636. LINK_STATUS : 0x8B82,
  11637. VALIDATE_STATUS : 0x8B83,
  11638. ATTACHED_SHADERS : 0x8B85,
  11639. ACTIVE_UNIFORMS : 0x8B86,
  11640. ACTIVE_ATTRIBUTES : 0x8B89,
  11641. SHADING_LANGUAGE_VERSION : 0x8B8C,
  11642. CURRENT_PROGRAM : 0x8B8D,
  11643. NEVER : 0x0200,
  11644. LESS : 0x0201,
  11645. EQUAL : 0x0202,
  11646. LEQUAL : 0x0203,
  11647. GREATER : 0x0204,
  11648. NOTEQUAL : 0x0205,
  11649. GEQUAL : 0x0206,
  11650. ALWAYS : 0x0207,
  11651. KEEP : 0x1E00,
  11652. REPLACE : 0x1E01,
  11653. INCR : 0x1E02,
  11654. DECR : 0x1E03,
  11655. INVERT : 0x150A,
  11656. INCR_WRAP : 0x8507,
  11657. DECR_WRAP : 0x8508,
  11658. VENDOR : 0x1F00,
  11659. RENDERER : 0x1F01,
  11660. VERSION : 0x1F02,
  11661. NEAREST : 0x2600,
  11662. LINEAR : 0x2601,
  11663. NEAREST_MIPMAP_NEAREST : 0x2700,
  11664. LINEAR_MIPMAP_NEAREST : 0x2701,
  11665. NEAREST_MIPMAP_LINEAR : 0x2702,
  11666. LINEAR_MIPMAP_LINEAR : 0x2703,
  11667. TEXTURE_MAG_FILTER : 0x2800,
  11668. TEXTURE_MIN_FILTER : 0x2801,
  11669. TEXTURE_WRAP_S : 0x2802,
  11670. TEXTURE_WRAP_T : 0x2803,
  11671. TEXTURE_2D : 0x0DE1,
  11672. TEXTURE : 0x1702,
  11673. TEXTURE_CUBE_MAP : 0x8513,
  11674. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  11675. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  11676. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  11677. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  11678. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  11679. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  11680. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  11681. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  11682. TEXTURE0 : 0x84C0,
  11683. TEXTURE1 : 0x84C1,
  11684. TEXTURE2 : 0x84C2,
  11685. TEXTURE3 : 0x84C3,
  11686. TEXTURE4 : 0x84C4,
  11687. TEXTURE5 : 0x84C5,
  11688. TEXTURE6 : 0x84C6,
  11689. TEXTURE7 : 0x84C7,
  11690. TEXTURE8 : 0x84C8,
  11691. TEXTURE9 : 0x84C9,
  11692. TEXTURE10 : 0x84CA,
  11693. TEXTURE11 : 0x84CB,
  11694. TEXTURE12 : 0x84CC,
  11695. TEXTURE13 : 0x84CD,
  11696. TEXTURE14 : 0x84CE,
  11697. TEXTURE15 : 0x84CF,
  11698. TEXTURE16 : 0x84D0,
  11699. TEXTURE17 : 0x84D1,
  11700. TEXTURE18 : 0x84D2,
  11701. TEXTURE19 : 0x84D3,
  11702. TEXTURE20 : 0x84D4,
  11703. TEXTURE21 : 0x84D5,
  11704. TEXTURE22 : 0x84D6,
  11705. TEXTURE23 : 0x84D7,
  11706. TEXTURE24 : 0x84D8,
  11707. TEXTURE25 : 0x84D9,
  11708. TEXTURE26 : 0x84DA,
  11709. TEXTURE27 : 0x84DB,
  11710. TEXTURE28 : 0x84DC,
  11711. TEXTURE29 : 0x84DD,
  11712. TEXTURE30 : 0x84DE,
  11713. TEXTURE31 : 0x84DF,
  11714. ACTIVE_TEXTURE : 0x84E0,
  11715. REPEAT : 0x2901,
  11716. CLAMP_TO_EDGE : 0x812F,
  11717. MIRRORED_REPEAT : 0x8370,
  11718. FLOAT_VEC2 : 0x8B50,
  11719. FLOAT_VEC3 : 0x8B51,
  11720. FLOAT_VEC4 : 0x8B52,
  11721. INT_VEC2 : 0x8B53,
  11722. INT_VEC3 : 0x8B54,
  11723. INT_VEC4 : 0x8B55,
  11724. BOOL : 0x8B56,
  11725. BOOL_VEC2 : 0x8B57,
  11726. BOOL_VEC3 : 0x8B58,
  11727. BOOL_VEC4 : 0x8B59,
  11728. FLOAT_MAT2 : 0x8B5A,
  11729. FLOAT_MAT3 : 0x8B5B,
  11730. FLOAT_MAT4 : 0x8B5C,
  11731. SAMPLER_2D : 0x8B5E,
  11732. SAMPLER_CUBE : 0x8B60,
  11733. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  11734. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  11735. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  11736. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  11737. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  11738. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  11739. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  11740. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  11741. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  11742. COMPILE_STATUS : 0x8B81,
  11743. LOW_FLOAT : 0x8DF0,
  11744. MEDIUM_FLOAT : 0x8DF1,
  11745. HIGH_FLOAT : 0x8DF2,
  11746. LOW_INT : 0x8DF3,
  11747. MEDIUM_INT : 0x8DF4,
  11748. HIGH_INT : 0x8DF5,
  11749. FRAMEBUFFER : 0x8D40,
  11750. RENDERBUFFER : 0x8D41,
  11751. RGBA4 : 0x8056,
  11752. RGB5_A1 : 0x8057,
  11753. RGB565 : 0x8D62,
  11754. DEPTH_COMPONENT16 : 0x81A5,
  11755. STENCIL_INDEX : 0x1901,
  11756. STENCIL_INDEX8 : 0x8D48,
  11757. DEPTH_STENCIL : 0x84F9,
  11758. RENDERBUFFER_WIDTH : 0x8D42,
  11759. RENDERBUFFER_HEIGHT : 0x8D43,
  11760. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  11761. RENDERBUFFER_RED_SIZE : 0x8D50,
  11762. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  11763. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  11764. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  11765. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  11766. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  11767. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  11768. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  11769. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  11770. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  11771. COLOR_ATTACHMENT0 : 0x8CE0,
  11772. DEPTH_ATTACHMENT : 0x8D00,
  11773. STENCIL_ATTACHMENT : 0x8D20,
  11774. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  11775. NONE : 0,
  11776. FRAMEBUFFER_COMPLETE : 0x8CD5,
  11777. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  11778. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  11779. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  11780. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  11781. FRAMEBUFFER_BINDING : 0x8CA6,
  11782. RENDERBUFFER_BINDING : 0x8CA7,
  11783. MAX_RENDERBUFFER_SIZE : 0x84E8,
  11784. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  11785. UNPACK_FLIP_Y_WEBGL : 0x9240,
  11786. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  11787. CONTEXT_LOST_WEBGL : 0x9242,
  11788. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  11789. BROWSER_DEFAULT_WEBGL : 0x9244,
  11790. // Desktop OpenGL
  11791. DOUBLE : 0x140A,
  11792. // WebGL 2
  11793. READ_BUFFER : 0x0C02,
  11794. UNPACK_ROW_LENGTH : 0x0CF2,
  11795. UNPACK_SKIP_ROWS : 0x0CF3,
  11796. UNPACK_SKIP_PIXELS : 0x0CF4,
  11797. PACK_ROW_LENGTH : 0x0D02,
  11798. PACK_SKIP_ROWS : 0x0D03,
  11799. PACK_SKIP_PIXELS : 0x0D04,
  11800. COLOR : 0x1800,
  11801. DEPTH : 0x1801,
  11802. STENCIL : 0x1802,
  11803. RED : 0x1903,
  11804. RGB8 : 0x8051,
  11805. RGBA8 : 0x8058,
  11806. RGB10_A2 : 0x8059,
  11807. TEXTURE_BINDING_3D : 0x806A,
  11808. UNPACK_SKIP_IMAGES : 0x806D,
  11809. UNPACK_IMAGE_HEIGHT : 0x806E,
  11810. TEXTURE_3D : 0x806F,
  11811. TEXTURE_WRAP_R : 0x8072,
  11812. MAX_3D_TEXTURE_SIZE : 0x8073,
  11813. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  11814. MAX_ELEMENTS_VERTICES : 0x80E8,
  11815. MAX_ELEMENTS_INDICES : 0x80E9,
  11816. TEXTURE_MIN_LOD : 0x813A,
  11817. TEXTURE_MAX_LOD : 0x813B,
  11818. TEXTURE_BASE_LEVEL : 0x813C,
  11819. TEXTURE_MAX_LEVEL : 0x813D,
  11820. MIN : 0x8007,
  11821. MAX : 0x8008,
  11822. DEPTH_COMPONENT24 : 0x81A6,
  11823. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  11824. TEXTURE_COMPARE_MODE : 0x884C,
  11825. TEXTURE_COMPARE_FUNC : 0x884D,
  11826. CURRENT_QUERY : 0x8865,
  11827. QUERY_RESULT : 0x8866,
  11828. QUERY_RESULT_AVAILABLE : 0x8867,
  11829. STREAM_READ : 0x88E1,
  11830. STREAM_COPY : 0x88E2,
  11831. STATIC_READ : 0x88E5,
  11832. STATIC_COPY : 0x88E6,
  11833. DYNAMIC_READ : 0x88E9,
  11834. DYNAMIC_COPY : 0x88EA,
  11835. MAX_DRAW_BUFFERS : 0x8824,
  11836. DRAW_BUFFER0 : 0x8825,
  11837. DRAW_BUFFER1 : 0x8826,
  11838. DRAW_BUFFER2 : 0x8827,
  11839. DRAW_BUFFER3 : 0x8828,
  11840. DRAW_BUFFER4 : 0x8829,
  11841. DRAW_BUFFER5 : 0x882A,
  11842. DRAW_BUFFER6 : 0x882B,
  11843. DRAW_BUFFER7 : 0x882C,
  11844. DRAW_BUFFER8 : 0x882D,
  11845. DRAW_BUFFER9 : 0x882E,
  11846. DRAW_BUFFER10 : 0x882F,
  11847. DRAW_BUFFER11 : 0x8830,
  11848. DRAW_BUFFER12 : 0x8831,
  11849. DRAW_BUFFER13 : 0x8832,
  11850. DRAW_BUFFER14 : 0x8833,
  11851. DRAW_BUFFER15 : 0x8834,
  11852. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  11853. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  11854. SAMPLER_3D : 0x8B5F,
  11855. SAMPLER_2D_SHADOW : 0x8B62,
  11856. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  11857. PIXEL_PACK_BUFFER : 0x88EB,
  11858. PIXEL_UNPACK_BUFFER : 0x88EC,
  11859. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  11860. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  11861. FLOAT_MAT2x3 : 0x8B65,
  11862. FLOAT_MAT2x4 : 0x8B66,
  11863. FLOAT_MAT3x2 : 0x8B67,
  11864. FLOAT_MAT3x4 : 0x8B68,
  11865. FLOAT_MAT4x2 : 0x8B69,
  11866. FLOAT_MAT4x3 : 0x8B6A,
  11867. SRGB : 0x8C40,
  11868. SRGB8 : 0x8C41,
  11869. SRGB8_ALPHA8 : 0x8C43,
  11870. COMPARE_REF_TO_TEXTURE : 0x884E,
  11871. RGBA32F : 0x8814,
  11872. RGB32F : 0x8815,
  11873. RGBA16F : 0x881A,
  11874. RGB16F : 0x881B,
  11875. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  11876. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  11877. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  11878. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  11879. MAX_VARYING_COMPONENTS : 0x8B4B,
  11880. TEXTURE_2D_ARRAY : 0x8C1A,
  11881. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  11882. R11F_G11F_B10F : 0x8C3A,
  11883. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  11884. RGB9_E5 : 0x8C3D,
  11885. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  11886. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  11887. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  11888. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  11889. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  11890. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  11891. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  11892. RASTERIZER_DISCARD : 0x8C89,
  11893. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  11894. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  11895. INTERLEAVED_ATTRIBS : 0x8C8C,
  11896. SEPARATE_ATTRIBS : 0x8C8D,
  11897. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  11898. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  11899. RGBA32UI : 0x8D70,
  11900. RGB32UI : 0x8D71,
  11901. RGBA16UI : 0x8D76,
  11902. RGB16UI : 0x8D77,
  11903. RGBA8UI : 0x8D7C,
  11904. RGB8UI : 0x8D7D,
  11905. RGBA32I : 0x8D82,
  11906. RGB32I : 0x8D83,
  11907. RGBA16I : 0x8D88,
  11908. RGB16I : 0x8D89,
  11909. RGBA8I : 0x8D8E,
  11910. RGB8I : 0x8D8F,
  11911. RED_INTEGER : 0x8D94,
  11912. RGB_INTEGER : 0x8D98,
  11913. RGBA_INTEGER : 0x8D99,
  11914. SAMPLER_2D_ARRAY : 0x8DC1,
  11915. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  11916. SAMPLER_CUBE_SHADOW : 0x8DC5,
  11917. UNSIGNED_INT_VEC2 : 0x8DC6,
  11918. UNSIGNED_INT_VEC3 : 0x8DC7,
  11919. UNSIGNED_INT_VEC4 : 0x8DC8,
  11920. INT_SAMPLER_2D : 0x8DCA,
  11921. INT_SAMPLER_3D : 0x8DCB,
  11922. INT_SAMPLER_CUBE : 0x8DCC,
  11923. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  11924. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  11925. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  11926. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  11927. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  11928. DEPTH_COMPONENT32F : 0x8CAC,
  11929. DEPTH32F_STENCIL8 : 0x8CAD,
  11930. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  11931. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  11932. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  11933. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  11934. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  11935. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  11936. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  11937. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  11938. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  11939. FRAMEBUFFER_DEFAULT : 0x8218,
  11940. UNSIGNED_INT_24_8 : 0x84FA,
  11941. DEPTH24_STENCIL8 : 0x88F0,
  11942. UNSIGNED_NORMALIZED : 0x8C17,
  11943. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  11944. READ_FRAMEBUFFER : 0x8CA8,
  11945. DRAW_FRAMEBUFFER : 0x8CA9,
  11946. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  11947. RENDERBUFFER_SAMPLES : 0x8CAB,
  11948. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  11949. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  11950. COLOR_ATTACHMENT1 : 0x8CE1,
  11951. COLOR_ATTACHMENT2 : 0x8CE2,
  11952. COLOR_ATTACHMENT3 : 0x8CE3,
  11953. COLOR_ATTACHMENT4 : 0x8CE4,
  11954. COLOR_ATTACHMENT5 : 0x8CE5,
  11955. COLOR_ATTACHMENT6 : 0x8CE6,
  11956. COLOR_ATTACHMENT7 : 0x8CE7,
  11957. COLOR_ATTACHMENT8 : 0x8CE8,
  11958. COLOR_ATTACHMENT9 : 0x8CE9,
  11959. COLOR_ATTACHMENT10 : 0x8CEA,
  11960. COLOR_ATTACHMENT11 : 0x8CEB,
  11961. COLOR_ATTACHMENT12 : 0x8CEC,
  11962. COLOR_ATTACHMENT13 : 0x8CED,
  11963. COLOR_ATTACHMENT14 : 0x8CEE,
  11964. COLOR_ATTACHMENT15 : 0x8CEF,
  11965. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  11966. MAX_SAMPLES : 0x8D57,
  11967. HALF_FLOAT : 0x140B,
  11968. RG : 0x8227,
  11969. RG_INTEGER : 0x8228,
  11970. R8 : 0x8229,
  11971. RG8 : 0x822B,
  11972. R16F : 0x822D,
  11973. R32F : 0x822E,
  11974. RG16F : 0x822F,
  11975. RG32F : 0x8230,
  11976. R8I : 0x8231,
  11977. R8UI : 0x8232,
  11978. R16I : 0x8233,
  11979. R16UI : 0x8234,
  11980. R32I : 0x8235,
  11981. R32UI : 0x8236,
  11982. RG8I : 0x8237,
  11983. RG8UI : 0x8238,
  11984. RG16I : 0x8239,
  11985. RG16UI : 0x823A,
  11986. RG32I : 0x823B,
  11987. RG32UI : 0x823C,
  11988. VERTEX_ARRAY_BINDING : 0x85B5,
  11989. R8_SNORM : 0x8F94,
  11990. RG8_SNORM : 0x8F95,
  11991. RGB8_SNORM : 0x8F96,
  11992. RGBA8_SNORM : 0x8F97,
  11993. SIGNED_NORMALIZED : 0x8F9C,
  11994. COPY_READ_BUFFER : 0x8F36,
  11995. COPY_WRITE_BUFFER : 0x8F37,
  11996. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  11997. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  11998. UNIFORM_BUFFER : 0x8A11,
  11999. UNIFORM_BUFFER_BINDING : 0x8A28,
  12000. UNIFORM_BUFFER_START : 0x8A29,
  12001. UNIFORM_BUFFER_SIZE : 0x8A2A,
  12002. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  12003. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  12004. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  12005. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  12006. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  12007. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  12008. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  12009. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  12010. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  12011. UNIFORM_TYPE : 0x8A37,
  12012. UNIFORM_SIZE : 0x8A38,
  12013. UNIFORM_BLOCK_INDEX : 0x8A3A,
  12014. UNIFORM_OFFSET : 0x8A3B,
  12015. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  12016. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  12017. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  12018. UNIFORM_BLOCK_BINDING : 0x8A3F,
  12019. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  12020. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  12021. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  12022. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  12023. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  12024. INVALID_INDEX : 0xFFFFFFFF,
  12025. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  12026. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  12027. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  12028. OBJECT_TYPE : 0x9112,
  12029. SYNC_CONDITION : 0x9113,
  12030. SYNC_STATUS : 0x9114,
  12031. SYNC_FLAGS : 0x9115,
  12032. SYNC_FENCE : 0x9116,
  12033. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  12034. UNSIGNALED : 0x9118,
  12035. SIGNALED : 0x9119,
  12036. ALREADY_SIGNALED : 0x911A,
  12037. TIMEOUT_EXPIRED : 0x911B,
  12038. CONDITION_SATISFIED : 0x911C,
  12039. WAIT_FAILED : 0x911D,
  12040. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  12041. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  12042. ANY_SAMPLES_PASSED : 0x8C2F,
  12043. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  12044. SAMPLER_BINDING : 0x8919,
  12045. RGB10_A2UI : 0x906F,
  12046. INT_2_10_10_10_REV : 0x8D9F,
  12047. TRANSFORM_FEEDBACK : 0x8E22,
  12048. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  12049. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  12050. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  12051. COMPRESSED_R11_EAC : 0x9270,
  12052. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  12053. COMPRESSED_RG11_EAC : 0x9272,
  12054. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  12055. COMPRESSED_RGB8_ETC2 : 0x9274,
  12056. COMPRESSED_SRGB8_ETC2 : 0x9275,
  12057. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  12058. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  12059. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  12060. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  12061. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  12062. MAX_ELEMENT_INDEX : 0x8D6B,
  12063. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  12064. };
  12065. return freezeObject(WebGLConstants);
  12066. });
  12067. /*global define*/
  12068. define('Core/ComponentDatatype',[
  12069. './defaultValue',
  12070. './defined',
  12071. './DeveloperError',
  12072. './FeatureDetection',
  12073. './freezeObject',
  12074. './WebGLConstants'
  12075. ], function(
  12076. defaultValue,
  12077. defined,
  12078. DeveloperError,
  12079. FeatureDetection,
  12080. freezeObject,
  12081. WebGLConstants) {
  12082. 'use strict';
  12083. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  12084. // from failing, since we won't be able to create a WebGL context anyway.
  12085. if (!FeatureDetection.supportsTypedArrays()) {
  12086. return {};
  12087. }
  12088. /**
  12089. * WebGL component datatypes. Components are intrinsics,
  12090. * which form attributes, which form vertices.
  12091. *
  12092. * @exports ComponentDatatype
  12093. */
  12094. var ComponentDatatype = {
  12095. /**
  12096. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  12097. * of an element in <code>Int8Array</code>.
  12098. *
  12099. * @type {Number}
  12100. * @constant
  12101. */
  12102. BYTE : WebGLConstants.BYTE,
  12103. /**
  12104. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  12105. * of an element in <code>Uint8Array</code>.
  12106. *
  12107. * @type {Number}
  12108. * @constant
  12109. */
  12110. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  12111. /**
  12112. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  12113. * of an element in <code>Int16Array</code>.
  12114. *
  12115. * @type {Number}
  12116. * @constant
  12117. */
  12118. SHORT : WebGLConstants.SHORT,
  12119. /**
  12120. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  12121. * of an element in <code>Uint16Array</code>.
  12122. *
  12123. * @type {Number}
  12124. * @constant
  12125. */
  12126. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  12127. /**
  12128. * 32-bit signed int corresponding to <code>INT</code> and the type
  12129. * of an element in <code>Int32Array</code>.
  12130. *
  12131. * @memberOf ComponentDatatype
  12132. *
  12133. * @type {Number}
  12134. * @constant
  12135. */
  12136. INT : WebGLConstants.INT,
  12137. /**
  12138. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  12139. * of an element in <code>Uint32Array</code>.
  12140. *
  12141. * @memberOf ComponentDatatype
  12142. *
  12143. * @type {Number}
  12144. * @constant
  12145. */
  12146. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  12147. /**
  12148. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  12149. * of an element in <code>Float32Array</code>.
  12150. *
  12151. * @type {Number}
  12152. * @constant
  12153. */
  12154. FLOAT : WebGLConstants.FLOAT,
  12155. /**
  12156. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  12157. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  12158. * and the type of an element in <code>Float64Array</code>.
  12159. *
  12160. * @memberOf ComponentDatatype
  12161. *
  12162. * @type {Number}
  12163. * @constant
  12164. * @default 0x140A
  12165. */
  12166. DOUBLE : WebGLConstants.DOUBLE
  12167. };
  12168. /**
  12169. * Returns the size, in bytes, of the corresponding datatype.
  12170. *
  12171. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  12172. * @returns {Number} The size in bytes.
  12173. *
  12174. * @exception {DeveloperError} componentDatatype is not a valid value.
  12175. *
  12176. * @example
  12177. * // Returns Int8Array.BYTES_PER_ELEMENT
  12178. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  12179. */
  12180. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  12181. if (!defined(componentDatatype)) {
  12182. throw new DeveloperError('value is required.');
  12183. }
  12184. switch (componentDatatype) {
  12185. case ComponentDatatype.BYTE:
  12186. return Int8Array.BYTES_PER_ELEMENT;
  12187. case ComponentDatatype.UNSIGNED_BYTE:
  12188. return Uint8Array.BYTES_PER_ELEMENT;
  12189. case ComponentDatatype.SHORT:
  12190. return Int16Array.BYTES_PER_ELEMENT;
  12191. case ComponentDatatype.UNSIGNED_SHORT:
  12192. return Uint16Array.BYTES_PER_ELEMENT;
  12193. case ComponentDatatype.INT:
  12194. return Int32Array.BYTES_PER_ELEMENT;
  12195. case ComponentDatatype.UNSIGNED_INT:
  12196. return Uint32Array.BYTES_PER_ELEMENT;
  12197. case ComponentDatatype.FLOAT:
  12198. return Float32Array.BYTES_PER_ELEMENT;
  12199. case ComponentDatatype.DOUBLE:
  12200. return Float64Array.BYTES_PER_ELEMENT;
  12201. default:
  12202. throw new DeveloperError('componentDatatype is not a valid value.');
  12203. }
  12204. };
  12205. /**
  12206. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  12207. *
  12208. * @param {TypedArray} array The typed array.
  12209. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  12210. */
  12211. ComponentDatatype.fromTypedArray = function(array) {
  12212. if (array instanceof Int8Array) {
  12213. return ComponentDatatype.BYTE;
  12214. }
  12215. if (array instanceof Uint8Array) {
  12216. return ComponentDatatype.UNSIGNED_BYTE;
  12217. }
  12218. if (array instanceof Int16Array) {
  12219. return ComponentDatatype.SHORT;
  12220. }
  12221. if (array instanceof Uint16Array) {
  12222. return ComponentDatatype.UNSIGNED_SHORT;
  12223. }
  12224. if (array instanceof Int32Array) {
  12225. return ComponentDatatype.INT;
  12226. }
  12227. if (array instanceof Uint32Array) {
  12228. return ComponentDatatype.UNSIGNED_INT;
  12229. }
  12230. if (array instanceof Float32Array) {
  12231. return ComponentDatatype.FLOAT;
  12232. }
  12233. if (array instanceof Float64Array) {
  12234. return ComponentDatatype.DOUBLE;
  12235. }
  12236. };
  12237. /**
  12238. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  12239. *
  12240. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  12241. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  12242. *
  12243. * @example
  12244. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  12245. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  12246. * }
  12247. */
  12248. ComponentDatatype.validate = function(componentDatatype) {
  12249. return defined(componentDatatype) &&
  12250. (componentDatatype === ComponentDatatype.BYTE ||
  12251. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  12252. componentDatatype === ComponentDatatype.SHORT ||
  12253. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  12254. componentDatatype === ComponentDatatype.INT ||
  12255. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  12256. componentDatatype === ComponentDatatype.FLOAT ||
  12257. componentDatatype === ComponentDatatype.DOUBLE);
  12258. };
  12259. /**
  12260. * Creates a typed array corresponding to component data type.
  12261. *
  12262. * @param {ComponentDatatype} componentDatatype The component data type.
  12263. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  12264. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  12265. *
  12266. * @exception {DeveloperError} componentDatatype is not a valid value.
  12267. *
  12268. * @example
  12269. * // creates a Float32Array with length of 100
  12270. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  12271. */
  12272. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  12273. if (!defined(componentDatatype)) {
  12274. throw new DeveloperError('componentDatatype is required.');
  12275. }
  12276. if (!defined(valuesOrLength)) {
  12277. throw new DeveloperError('valuesOrLength is required.');
  12278. }
  12279. switch (componentDatatype) {
  12280. case ComponentDatatype.BYTE:
  12281. return new Int8Array(valuesOrLength);
  12282. case ComponentDatatype.UNSIGNED_BYTE:
  12283. return new Uint8Array(valuesOrLength);
  12284. case ComponentDatatype.SHORT:
  12285. return new Int16Array(valuesOrLength);
  12286. case ComponentDatatype.UNSIGNED_SHORT:
  12287. return new Uint16Array(valuesOrLength);
  12288. case ComponentDatatype.INT:
  12289. return new Int32Array(valuesOrLength);
  12290. case ComponentDatatype.UNSIGNED_INT:
  12291. return new Uint32Array(valuesOrLength);
  12292. case ComponentDatatype.FLOAT:
  12293. return new Float32Array(valuesOrLength);
  12294. case ComponentDatatype.DOUBLE:
  12295. return new Float64Array(valuesOrLength);
  12296. default:
  12297. throw new DeveloperError('componentDatatype is not a valid value.');
  12298. }
  12299. };
  12300. /**
  12301. * Creates a typed view of an array of bytes.
  12302. *
  12303. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  12304. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  12305. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  12306. * @param {Number} [length] The number of elements in the view.
  12307. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  12308. *
  12309. * @exception {DeveloperError} componentDatatype is not a valid value.
  12310. */
  12311. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  12312. if (!defined(componentDatatype)) {
  12313. throw new DeveloperError('componentDatatype is required.');
  12314. }
  12315. if (!defined(buffer)) {
  12316. throw new DeveloperError('buffer is required.');
  12317. }
  12318. byteOffset = defaultValue(byteOffset, 0);
  12319. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  12320. switch (componentDatatype) {
  12321. case ComponentDatatype.BYTE:
  12322. return new Int8Array(buffer, byteOffset, length);
  12323. case ComponentDatatype.UNSIGNED_BYTE:
  12324. return new Uint8Array(buffer, byteOffset, length);
  12325. case ComponentDatatype.SHORT:
  12326. return new Int16Array(buffer, byteOffset, length);
  12327. case ComponentDatatype.UNSIGNED_SHORT:
  12328. return new Uint16Array(buffer, byteOffset, length);
  12329. case ComponentDatatype.INT:
  12330. return new Int32Array(buffer, byteOffset, length);
  12331. case ComponentDatatype.UNSIGNED_INT:
  12332. return new Uint32Array(buffer, byteOffset, length);
  12333. case ComponentDatatype.FLOAT:
  12334. return new Float32Array(buffer, byteOffset, length);
  12335. case ComponentDatatype.DOUBLE:
  12336. return new Float64Array(buffer, byteOffset, length);
  12337. default:
  12338. throw new DeveloperError('componentDatatype is not a valid value.');
  12339. }
  12340. };
  12341. /**
  12342. * Get the ComponentDatatype from its name.
  12343. *
  12344. * @param {String} name The name of the ComponentDatatype.
  12345. * @returns {ComponentDatatype} The ComponentDatatype.
  12346. *
  12347. * @exception {DeveloperError} name is not a valid value.
  12348. */
  12349. ComponentDatatype.fromName = function(name) {
  12350. switch (name) {
  12351. case 'BYTE':
  12352. return ComponentDatatype.BYTE;
  12353. case 'UNSIGNED_BYTE':
  12354. return ComponentDatatype.UNSIGNED_BYTE;
  12355. case 'SHORT':
  12356. return ComponentDatatype.SHORT;
  12357. case 'UNSIGNED_SHORT':
  12358. return ComponentDatatype.UNSIGNED_SHORT;
  12359. case 'INT':
  12360. return ComponentDatatype.INT;
  12361. case 'UNSIGNED_INT':
  12362. return ComponentDatatype.UNSIGNED_INT;
  12363. case 'FLOAT':
  12364. return ComponentDatatype.FLOAT;
  12365. case 'DOUBLE':
  12366. return ComponentDatatype.DOUBLE;
  12367. default:
  12368. throw new DeveloperError('name is not a valid value.');
  12369. }
  12370. };
  12371. return freezeObject(ComponentDatatype);
  12372. });
  12373. /*global define*/
  12374. define('Core/CornerType',[
  12375. './freezeObject'
  12376. ], function(
  12377. freezeObject) {
  12378. 'use strict';
  12379. /**
  12380. * Style options for corners.
  12381. *
  12382. * @demo The {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Corridor.html&label=Geometries|Corridor Demo}
  12383. * demonstrates the three corner types, as used by {@link CorridorGraphics}.
  12384. *
  12385. * @exports CornerType
  12386. */
  12387. var CornerType = {
  12388. /**
  12389. * <img src="images/CornerTypeRounded.png" style="vertical-align: middle;" width="186" height="189" />
  12390. *
  12391. * Corner has a smooth edge.
  12392. * @type {Number}
  12393. * @constant
  12394. */
  12395. ROUNDED : 0,
  12396. /**
  12397. * <img src="images/CornerTypeMitered.png" style="vertical-align: middle;" width="186" height="189" />
  12398. *
  12399. * Corner point is the intersection of adjacent edges.
  12400. * @type {Number}
  12401. * @constant
  12402. */
  12403. MITERED : 1,
  12404. /**
  12405. * <img src="images/CornerTypeBeveled.png" style="vertical-align: middle;" width="186" height="189" />
  12406. *
  12407. * Corner is clipped.
  12408. * @type {Number}
  12409. * @constant
  12410. */
  12411. BEVELED : 2
  12412. };
  12413. return freezeObject(CornerType);
  12414. });
  12415. /*global define*/
  12416. define('Core/GeometryType',[
  12417. './freezeObject'
  12418. ], function(
  12419. freezeObject) {
  12420. 'use strict';
  12421. /**
  12422. * @private
  12423. */
  12424. var GeometryType = {
  12425. NONE : 0,
  12426. TRIANGLES : 1,
  12427. LINES : 2,
  12428. POLYLINES : 3
  12429. };
  12430. return freezeObject(GeometryType);
  12431. });
  12432. /*global define*/
  12433. define('Core/PrimitiveType',[
  12434. './freezeObject',
  12435. './WebGLConstants'
  12436. ], function(
  12437. freezeObject,
  12438. WebGLConstants) {
  12439. 'use strict';
  12440. /**
  12441. * The type of a geometric primitive, i.e., points, lines, and triangles.
  12442. *
  12443. * @exports PrimitiveType
  12444. */
  12445. var PrimitiveType = {
  12446. /**
  12447. * Points primitive where each vertex (or index) is a separate point.
  12448. *
  12449. * @type {Number}
  12450. * @constant
  12451. */
  12452. POINTS : WebGLConstants.POINTS,
  12453. /**
  12454. * Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
  12455. *
  12456. * @type {Number}
  12457. * @constant
  12458. */
  12459. LINES : WebGLConstants.LINES,
  12460. /**
  12461. * Line loop primitive where each vertex (or index) after the first connects a line to
  12462. * the previous vertex, and the last vertex implicitly connects to the first.
  12463. *
  12464. * @type {Number}
  12465. * @constant
  12466. */
  12467. LINE_LOOP : WebGLConstants.LINE_LOOP,
  12468. /**
  12469. * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
  12470. *
  12471. * @type {Number}
  12472. * @constant
  12473. */
  12474. LINE_STRIP : WebGLConstants.LINE_STRIP,
  12475. /**
  12476. * Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
  12477. *
  12478. * @type {Number}
  12479. * @constant
  12480. */
  12481. TRIANGLES : WebGLConstants.TRIANGLES,
  12482. /**
  12483. * Triangle strip primitive where each vertex (or index) after the first two connect to
  12484. * the previous two vertices forming a triangle. For example, this can be used to model a wall.
  12485. *
  12486. * @type {Number}
  12487. * @constant
  12488. */
  12489. TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
  12490. /**
  12491. * Triangle fan primitive where each vertex (or index) after the first two connect to
  12492. * the previous vertex and the first vertex forming a triangle. For example, this can be used
  12493. * to model a cone or circle.
  12494. *
  12495. * @type {Number}
  12496. * @constant
  12497. */
  12498. TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
  12499. /**
  12500. * @private
  12501. */
  12502. validate : function(primitiveType) {
  12503. return primitiveType === PrimitiveType.POINTS ||
  12504. primitiveType === PrimitiveType.LINES ||
  12505. primitiveType === PrimitiveType.LINE_LOOP ||
  12506. primitiveType === PrimitiveType.LINE_STRIP ||
  12507. primitiveType === PrimitiveType.TRIANGLES ||
  12508. primitiveType === PrimitiveType.TRIANGLE_STRIP ||
  12509. primitiveType === PrimitiveType.TRIANGLE_FAN;
  12510. }
  12511. };
  12512. return freezeObject(PrimitiveType);
  12513. });
  12514. /*global define*/
  12515. define('Core/Geometry',[
  12516. './defaultValue',
  12517. './defined',
  12518. './DeveloperError',
  12519. './GeometryType',
  12520. './PrimitiveType'
  12521. ], function(
  12522. defaultValue,
  12523. defined,
  12524. DeveloperError,
  12525. GeometryType,
  12526. PrimitiveType) {
  12527. 'use strict';
  12528. /**
  12529. * A geometry representation with attributes forming vertices and optional index data
  12530. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  12531. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  12532. * be created from many heterogeneous - in many cases - geometries for performance.
  12533. * <p>
  12534. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  12535. * </p>
  12536. *
  12537. * @alias Geometry
  12538. * @constructor
  12539. *
  12540. * @param {Object} options Object with the following properties:
  12541. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  12542. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  12543. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  12544. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  12545. *
  12546. * @see PolygonGeometry
  12547. * @see RectangleGeometry
  12548. * @see EllipseGeometry
  12549. * @see CircleGeometry
  12550. * @see WallGeometry
  12551. * @see SimplePolylineGeometry
  12552. * @see BoxGeometry
  12553. * @see EllipsoidGeometry
  12554. *
  12555. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  12556. *
  12557. * @example
  12558. * // Create geometry with a position attribute and indexed lines.
  12559. * var positions = new Float64Array([
  12560. * 0.0, 0.0, 0.0,
  12561. * 7500000.0, 0.0, 0.0,
  12562. * 0.0, 7500000.0, 0.0
  12563. * ]);
  12564. *
  12565. * var geometry = new Cesium.Geometry({
  12566. * attributes : {
  12567. * position : new Cesium.GeometryAttribute({
  12568. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  12569. * componentsPerAttribute : 3,
  12570. * values : positions
  12571. * })
  12572. * },
  12573. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  12574. * primitiveType : Cesium.PrimitiveType.LINES,
  12575. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  12576. * });
  12577. */
  12578. function Geometry(options) {
  12579. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12580. if (!defined(options.attributes)) {
  12581. throw new DeveloperError('options.attributes is required.');
  12582. }
  12583. /**
  12584. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  12585. * {@link GeometryAttribute} containing the attribute's data.
  12586. * <p>
  12587. * Attributes are always stored non-interleaved in a Geometry.
  12588. * </p>
  12589. * <p>
  12590. * There are reserved attribute names with well-known semantics. The following attributes
  12591. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  12592. * <ul>
  12593. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  12594. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  12595. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  12596. * <li><code>binormal</code> - Binormal (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#binormal}.</li>
  12597. * <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
  12598. * </ul>
  12599. * </p>
  12600. * <p>
  12601. * The following attribute names are generally not created by a Geometry, but are added
  12602. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  12603. * the geometry for rendering.
  12604. * <ul>
  12605. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  12606. * <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  12607. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  12608. * <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  12609. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  12610. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  12611. * </ul>
  12612. * </p>
  12613. *
  12614. * @type GeometryAttributes
  12615. *
  12616. * @default undefined
  12617. *
  12618. *
  12619. * @example
  12620. * geometry.attributes.position = new Cesium.GeometryAttribute({
  12621. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  12622. * componentsPerAttribute : 3,
  12623. * values : new Float32Array(0)
  12624. * });
  12625. *
  12626. * @see GeometryAttribute
  12627. * @see VertexFormat
  12628. */
  12629. this.attributes = options.attributes;
  12630. /**
  12631. * Optional index data that - along with {@link Geometry#primitiveType} -
  12632. * determines the primitives in the geometry.
  12633. *
  12634. * @type Array
  12635. *
  12636. * @default undefined
  12637. */
  12638. this.indices = options.indices;
  12639. /**
  12640. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  12641. * but can varying based on the specific geometry.
  12642. *
  12643. * @type PrimitiveType
  12644. *
  12645. * @default undefined
  12646. */
  12647. this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
  12648. /**
  12649. * An optional bounding sphere that fully encloses the geometry. This is
  12650. * commonly used for culling.
  12651. *
  12652. * @type BoundingSphere
  12653. *
  12654. * @default undefined
  12655. */
  12656. this.boundingSphere = options.boundingSphere;
  12657. /**
  12658. * @private
  12659. */
  12660. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  12661. /**
  12662. * @private
  12663. */
  12664. this.boundingSphereCV = options.boundingSphereCV;
  12665. }
  12666. /**
  12667. * Computes the number of vertices in a geometry. The runtime is linear with
  12668. * respect to the number of attributes in a vertex, not the number of vertices.
  12669. *
  12670. * @param {Geometry} geometry The geometry.
  12671. * @returns {Number} The number of vertices in the geometry.
  12672. *
  12673. * @example
  12674. * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  12675. */
  12676. Geometry.computeNumberOfVertices = function(geometry) {
  12677. if (!defined(geometry)) {
  12678. throw new DeveloperError('geometry is required.');
  12679. }
  12680. var numberOfVertices = -1;
  12681. for ( var property in geometry.attributes) {
  12682. if (geometry.attributes.hasOwnProperty(property) &&
  12683. defined(geometry.attributes[property]) &&
  12684. defined(geometry.attributes[property].values)) {
  12685. var attribute = geometry.attributes[property];
  12686. var num = attribute.values.length / attribute.componentsPerAttribute;
  12687. if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
  12688. throw new DeveloperError('All attribute lists must have the same number of attributes.');
  12689. }
  12690. numberOfVertices = num;
  12691. }
  12692. }
  12693. return numberOfVertices;
  12694. };
  12695. return Geometry;
  12696. });
  12697. /*global define*/
  12698. define('Core/GeometryAttribute',[
  12699. './defaultValue',
  12700. './defined',
  12701. './DeveloperError'
  12702. ], function(
  12703. defaultValue,
  12704. defined,
  12705. DeveloperError) {
  12706. 'use strict';
  12707. /**
  12708. * Values and type information for geometry attributes. A {@link Geometry}
  12709. * generally contains one or more attributes. All attributes together form
  12710. * the geometry's vertices.
  12711. *
  12712. * @alias GeometryAttribute
  12713. * @constructor
  12714. *
  12715. * @param {Object} [options] Object with the following properties:
  12716. * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
  12717. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
  12718. * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  12719. * @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
  12720. *
  12721. * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
  12722. *
  12723. *
  12724. * @example
  12725. * var geometry = new Cesium.Geometry({
  12726. * attributes : {
  12727. * position : new Cesium.GeometryAttribute({
  12728. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  12729. * componentsPerAttribute : 3,
  12730. * values : new Float32Array([
  12731. * 0.0, 0.0, 0.0,
  12732. * 7500000.0, 0.0, 0.0,
  12733. * 0.0, 7500000.0, 0.0
  12734. * ])
  12735. * })
  12736. * },
  12737. * primitiveType : Cesium.PrimitiveType.LINE_LOOP
  12738. * });
  12739. *
  12740. * @see Geometry
  12741. */
  12742. function GeometryAttribute(options) {
  12743. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12744. if (!defined(options.componentDatatype)) {
  12745. throw new DeveloperError('options.componentDatatype is required.');
  12746. }
  12747. if (!defined(options.componentsPerAttribute)) {
  12748. throw new DeveloperError('options.componentsPerAttribute is required.');
  12749. }
  12750. if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
  12751. throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
  12752. }
  12753. if (!defined(options.values)) {
  12754. throw new DeveloperError('options.values is required.');
  12755. }
  12756. /**
  12757. * The datatype of each component in the attribute, e.g., individual elements in
  12758. * {@link GeometryAttribute#values}.
  12759. *
  12760. * @type ComponentDatatype
  12761. *
  12762. * @default undefined
  12763. */
  12764. this.componentDatatype = options.componentDatatype;
  12765. /**
  12766. * A number between 1 and 4 that defines the number of components in an attributes.
  12767. * For example, a position attribute with x, y, and z components would have 3 as
  12768. * shown in the code example.
  12769. *
  12770. * @type Number
  12771. *
  12772. * @default undefined
  12773. *
  12774. * @example
  12775. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  12776. * attribute.componentsPerAttribute = 3;
  12777. * attribute.values = new Float32Array([
  12778. * 0.0, 0.0, 0.0,
  12779. * 7500000.0, 0.0, 0.0,
  12780. * 0.0, 7500000.0, 0.0
  12781. * ]);
  12782. */
  12783. this.componentsPerAttribute = options.componentsPerAttribute;
  12784. /**
  12785. * When <code>true</code> and <code>componentDatatype</code> is an integer format,
  12786. * indicate that the components should be mapped to the range [0, 1] (unsigned)
  12787. * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  12788. * <p>
  12789. * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
  12790. * </p>
  12791. *
  12792. * @type Boolean
  12793. *
  12794. * @default false
  12795. *
  12796. * @example
  12797. * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  12798. * attribute.componentsPerAttribute = 4;
  12799. * attribute.normalize = true;
  12800. * attribute.values = new Uint8Array([
  12801. * Cesium.Color.floatToByte(color.red),
  12802. * Cesium.Color.floatToByte(color.green),
  12803. * Cesium.Color.floatToByte(color.blue),
  12804. * Cesium.Color.floatToByte(color.alpha)
  12805. * ]);
  12806. */
  12807. this.normalize = defaultValue(options.normalize, false);
  12808. /**
  12809. * The values for the attributes stored in a typed array. In the code example,
  12810. * every three elements in <code>values</code> defines one attributes since
  12811. * <code>componentsPerAttribute</code> is 3.
  12812. *
  12813. * @type TypedArray
  12814. *
  12815. * @default undefined
  12816. *
  12817. * @example
  12818. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  12819. * attribute.componentsPerAttribute = 3;
  12820. * attribute.values = new Float32Array([
  12821. * 0.0, 0.0, 0.0,
  12822. * 7500000.0, 0.0, 0.0,
  12823. * 0.0, 7500000.0, 0.0
  12824. * ]);
  12825. */
  12826. this.values = options.values;
  12827. }
  12828. return GeometryAttribute;
  12829. });
  12830. /*global define*/
  12831. define('Core/GeometryAttributes',[
  12832. './defaultValue'
  12833. ], function(
  12834. defaultValue) {
  12835. 'use strict';
  12836. /**
  12837. * Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
  12838. * {@link GeometryAttribute} containing the attribute's data.
  12839. * <p>
  12840. * Attributes are always stored non-interleaved in a Geometry.
  12841. * </p>
  12842. *
  12843. * @alias GeometryAttributes
  12844. * @constructor
  12845. */
  12846. function GeometryAttributes(options) {
  12847. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12848. /**
  12849. * The 3D position attribute.
  12850. * <p>
  12851. * 64-bit floating-point (for precision). 3 components per attribute.
  12852. * </p>
  12853. *
  12854. * @type GeometryAttribute
  12855. *
  12856. * @default undefined
  12857. */
  12858. this.position = options.position;
  12859. /**
  12860. * The normal attribute (normalized), which is commonly used for lighting.
  12861. * <p>
  12862. * 32-bit floating-point. 3 components per attribute.
  12863. * </p>
  12864. *
  12865. * @type GeometryAttribute
  12866. *
  12867. * @default undefined
  12868. */
  12869. this.normal = options.normal;
  12870. /**
  12871. * The 2D texture coordinate attribute.
  12872. * <p>
  12873. * 32-bit floating-point. 2 components per attribute
  12874. * </p>
  12875. *
  12876. * @type GeometryAttribute
  12877. *
  12878. * @default undefined
  12879. */
  12880. this.st = options.st;
  12881. /**
  12882. * The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  12883. * <p>
  12884. * 32-bit floating-point. 3 components per attribute.
  12885. * </p>
  12886. *
  12887. * @type GeometryAttribute
  12888. *
  12889. * @default undefined
  12890. */
  12891. this.binormal = options.binormal;
  12892. /**
  12893. * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  12894. * <p>
  12895. * 32-bit floating-point. 3 components per attribute.
  12896. * </p>
  12897. *
  12898. * @type GeometryAttribute
  12899. *
  12900. * @default undefined
  12901. */
  12902. this.tangent = options.tangent;
  12903. /**
  12904. * The color attribute.
  12905. * <p>
  12906. * 8-bit unsigned integer. 4 components per attribute.
  12907. * </p>
  12908. *
  12909. * @type GeometryAttribute
  12910. *
  12911. * @default undefined
  12912. */
  12913. this.color = options.color;
  12914. }
  12915. return GeometryAttributes;
  12916. });
  12917. /*global define*/
  12918. define('Core/IndexDatatype',[
  12919. './defined',
  12920. './DeveloperError',
  12921. './freezeObject',
  12922. './Math',
  12923. './WebGLConstants'
  12924. ], function(
  12925. defined,
  12926. DeveloperError,
  12927. freezeObject,
  12928. CesiumMath,
  12929. WebGLConstants) {
  12930. 'use strict';
  12931. /**
  12932. * Constants for WebGL index datatypes. These corresponds to the
  12933. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  12934. *
  12935. * @exports IndexDatatype
  12936. */
  12937. var IndexDatatype = {
  12938. /**
  12939. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  12940. * of an element in <code>Uint8Array</code>.
  12941. *
  12942. * @type {Number}
  12943. * @constant
  12944. */
  12945. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  12946. /**
  12947. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  12948. * of an element in <code>Uint16Array</code>.
  12949. *
  12950. * @type {Number}
  12951. * @constant
  12952. */
  12953. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  12954. /**
  12955. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  12956. * of an element in <code>Uint32Array</code>.
  12957. *
  12958. * @type {Number}
  12959. * @constant
  12960. */
  12961. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  12962. };
  12963. /**
  12964. * Returns the size, in bytes, of the corresponding datatype.
  12965. *
  12966. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  12967. * @returns {Number} The size in bytes.
  12968. *
  12969. * @example
  12970. * // Returns 2
  12971. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  12972. */
  12973. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  12974. switch(indexDatatype) {
  12975. case IndexDatatype.UNSIGNED_BYTE:
  12976. return Uint8Array.BYTES_PER_ELEMENT;
  12977. case IndexDatatype.UNSIGNED_SHORT:
  12978. return Uint16Array.BYTES_PER_ELEMENT;
  12979. case IndexDatatype.UNSIGNED_INT:
  12980. return Uint32Array.BYTES_PER_ELEMENT;
  12981. }
  12982. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  12983. };
  12984. /**
  12985. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  12986. *
  12987. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  12988. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  12989. *
  12990. * @example
  12991. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  12992. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  12993. * }
  12994. */
  12995. IndexDatatype.validate = function(indexDatatype) {
  12996. return defined(indexDatatype) &&
  12997. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  12998. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  12999. indexDatatype === IndexDatatype.UNSIGNED_INT);
  13000. };
  13001. /**
  13002. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  13003. * or <code>Uint32Array</code> depending on the number of vertices.
  13004. *
  13005. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  13006. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  13007. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  13008. *
  13009. * @example
  13010. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  13011. */
  13012. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  13013. if (!defined(numberOfVertices)) {
  13014. throw new DeveloperError('numberOfVertices is required.');
  13015. }
  13016. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  13017. return new Uint32Array(indicesLengthOrArray);
  13018. }
  13019. return new Uint16Array(indicesLengthOrArray);
  13020. };
  13021. /**
  13022. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  13023. * or <code>Uint32Array</code> depending on the number of vertices.
  13024. *
  13025. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  13026. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  13027. * @param {Number} byteOffset Passed through to the typed array constructor.
  13028. * @param {Number} length Passed through to the typed array constructor.
  13029. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  13030. *
  13031. */
  13032. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  13033. if (!defined(numberOfVertices)) {
  13034. throw new DeveloperError('numberOfVertices is required.');
  13035. }
  13036. if (!defined(sourceArray)) {
  13037. throw new DeveloperError('sourceArray is required.');
  13038. }
  13039. if (!defined(byteOffset)) {
  13040. throw new DeveloperError('byteOffset is required.');
  13041. }
  13042. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  13043. return new Uint32Array(sourceArray, byteOffset, length);
  13044. }
  13045. return new Uint16Array(sourceArray, byteOffset, length);
  13046. };
  13047. return freezeObject(IndexDatatype);
  13048. });
  13049. /*global define*/
  13050. define('ThirdParty/earcut-2.1.1',[], function() {
  13051. 'use strict';
  13052. function earcut(data, holeIndices, dim) {
  13053. dim = dim || 2;
  13054. var hasHoles = holeIndices && holeIndices.length,
  13055. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  13056. outerNode = linkedList(data, 0, outerLen, dim, true),
  13057. triangles = [];
  13058. if (!outerNode) return triangles;
  13059. var minX, minY, maxX, maxY, x, y, size;
  13060. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  13061. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  13062. if (data.length > 80 * dim) {
  13063. minX = maxX = data[0];
  13064. minY = maxY = data[1];
  13065. for (var i = dim; i < outerLen; i += dim) {
  13066. x = data[i];
  13067. y = data[i + 1];
  13068. if (x < minX) minX = x;
  13069. if (y < minY) minY = y;
  13070. if (x > maxX) maxX = x;
  13071. if (y > maxY) maxY = y;
  13072. }
  13073. // minX, minY and size are later used to transform coords into integers for z-order calculation
  13074. size = Math.max(maxX - minX, maxY - minY);
  13075. }
  13076. earcutLinked(outerNode, triangles, dim, minX, minY, size);
  13077. return triangles;
  13078. }
  13079. // create a circular doubly linked list from polygon points in the specified winding order
  13080. function linkedList(data, start, end, dim, clockwise) {
  13081. var i, last;
  13082. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  13083. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  13084. } else {
  13085. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  13086. }
  13087. if (last && equals(last, last.next)) {
  13088. removeNode(last);
  13089. last = last.next;
  13090. }
  13091. return last;
  13092. }
  13093. // eliminate colinear or duplicate points
  13094. function filterPoints(start, end) {
  13095. if (!start) return start;
  13096. if (!end) end = start;
  13097. var p = start,
  13098. again;
  13099. do {
  13100. again = false;
  13101. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  13102. removeNode(p);
  13103. p = end = p.prev;
  13104. if (p === p.next) return null;
  13105. again = true;
  13106. } else {
  13107. p = p.next;
  13108. }
  13109. } while (again || p !== end);
  13110. return end;
  13111. }
  13112. // main ear slicing loop which triangulates a polygon (given as a linked list)
  13113. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  13114. if (!ear) return;
  13115. // interlink polygon nodes in z-order
  13116. if (!pass && size) indexCurve(ear, minX, minY, size);
  13117. var stop = ear,
  13118. prev, next;
  13119. // iterate through ears, slicing them one by one
  13120. while (ear.prev !== ear.next) {
  13121. prev = ear.prev;
  13122. next = ear.next;
  13123. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  13124. // cut off the triangle
  13125. triangles.push(prev.i / dim);
  13126. triangles.push(ear.i / dim);
  13127. triangles.push(next.i / dim);
  13128. removeNode(ear);
  13129. // skipping the next vertice leads to less sliver triangles
  13130. ear = next.next;
  13131. stop = next.next;
  13132. continue;
  13133. }
  13134. ear = next;
  13135. // if we looped through the whole remaining polygon and can't find any more ears
  13136. if (ear === stop) {
  13137. // try filtering points and slicing again
  13138. if (!pass) {
  13139. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
  13140. // if this didn't work, try curing all small self-intersections locally
  13141. } else if (pass === 1) {
  13142. ear = cureLocalIntersections(ear, triangles, dim);
  13143. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  13144. // as a last resort, try splitting the remaining polygon into two
  13145. } else if (pass === 2) {
  13146. splitEarcut(ear, triangles, dim, minX, minY, size);
  13147. }
  13148. break;
  13149. }
  13150. }
  13151. }
  13152. // check whether a polygon node forms a valid ear with adjacent nodes
  13153. function isEar(ear) {
  13154. var a = ear.prev,
  13155. b = ear,
  13156. c = ear.next;
  13157. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  13158. // now make sure we don't have other points inside the potential ear
  13159. var p = ear.next.next;
  13160. while (p !== ear.prev) {
  13161. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  13162. area(p.prev, p, p.next) >= 0) return false;
  13163. p = p.next;
  13164. }
  13165. return true;
  13166. }
  13167. function isEarHashed(ear, minX, minY, size) {
  13168. var a = ear.prev,
  13169. b = ear,
  13170. c = ear.next;
  13171. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  13172. // triangle bbox; min & max are calculated like this for speed
  13173. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  13174. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  13175. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  13176. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  13177. // z-order range for the current triangle bbox;
  13178. var minZ = zOrder(minTX, minTY, minX, minY, size),
  13179. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  13180. // first look for points inside the triangle in increasing z-order
  13181. var p = ear.nextZ;
  13182. while (p && p.z <= maxZ) {
  13183. if (p !== ear.prev && p !== ear.next &&
  13184. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  13185. area(p.prev, p, p.next) >= 0) return false;
  13186. p = p.nextZ;
  13187. }
  13188. // then look for points in decreasing z-order
  13189. p = ear.prevZ;
  13190. while (p && p.z >= minZ) {
  13191. if (p !== ear.prev && p !== ear.next &&
  13192. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  13193. area(p.prev, p, p.next) >= 0) return false;
  13194. p = p.prevZ;
  13195. }
  13196. return true;
  13197. }
  13198. // go through all polygon nodes and cure small local self-intersections
  13199. function cureLocalIntersections(start, triangles, dim) {
  13200. var p = start;
  13201. do {
  13202. var a = p.prev,
  13203. b = p.next.next;
  13204. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  13205. triangles.push(a.i / dim);
  13206. triangles.push(p.i / dim);
  13207. triangles.push(b.i / dim);
  13208. // remove two nodes involved
  13209. removeNode(p);
  13210. removeNode(p.next);
  13211. p = start = b;
  13212. }
  13213. p = p.next;
  13214. } while (p !== start);
  13215. return p;
  13216. }
  13217. // try splitting polygon into two and triangulate them independently
  13218. function splitEarcut(start, triangles, dim, minX, minY, size) {
  13219. // look for a valid diagonal that divides the polygon into two
  13220. var a = start;
  13221. do {
  13222. var b = a.next.next;
  13223. while (b !== a.prev) {
  13224. if (a.i !== b.i && isValidDiagonal(a, b)) {
  13225. // split the polygon in two by the diagonal
  13226. var c = splitPolygon(a, b);
  13227. // filter colinear points around the cuts
  13228. a = filterPoints(a, a.next);
  13229. c = filterPoints(c, c.next);
  13230. // run earcut on each half
  13231. earcutLinked(a, triangles, dim, minX, minY, size);
  13232. earcutLinked(c, triangles, dim, minX, minY, size);
  13233. return;
  13234. }
  13235. b = b.next;
  13236. }
  13237. a = a.next;
  13238. } while (a !== start);
  13239. }
  13240. // link every hole into the outer loop, producing a single-ring polygon without holes
  13241. function eliminateHoles(data, holeIndices, outerNode, dim) {
  13242. var queue = [],
  13243. i, len, start, end, list;
  13244. for (i = 0, len = holeIndices.length; i < len; i++) {
  13245. start = holeIndices[i] * dim;
  13246. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  13247. list = linkedList(data, start, end, dim, false);
  13248. if (list === list.next) list.steiner = true;
  13249. queue.push(getLeftmost(list));
  13250. }
  13251. queue.sort(compareX);
  13252. // process holes from left to right
  13253. for (i = 0; i < queue.length; i++) {
  13254. eliminateHole(queue[i], outerNode);
  13255. outerNode = filterPoints(outerNode, outerNode.next);
  13256. }
  13257. return outerNode;
  13258. }
  13259. function compareX(a, b) {
  13260. return a.x - b.x;
  13261. }
  13262. // find a bridge between vertices that connects hole with an outer ring and and link it
  13263. function eliminateHole(hole, outerNode) {
  13264. outerNode = findHoleBridge(hole, outerNode);
  13265. if (outerNode) {
  13266. var b = splitPolygon(outerNode, hole);
  13267. filterPoints(b, b.next);
  13268. }
  13269. }
  13270. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  13271. function findHoleBridge(hole, outerNode) {
  13272. var p = outerNode,
  13273. hx = hole.x,
  13274. hy = hole.y,
  13275. qx = -Infinity,
  13276. m;
  13277. // find a segment intersected by a ray from the hole's leftmost point to the left;
  13278. // segment's endpoint with lesser x will be potential connection point
  13279. do {
  13280. if (hy <= p.y && hy >= p.next.y) {
  13281. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  13282. if (x <= hx && x > qx) {
  13283. qx = x;
  13284. if (x === hx) {
  13285. if (hy === p.y) return p;
  13286. if (hy === p.next.y) return p.next;
  13287. }
  13288. m = p.x < p.next.x ? p : p.next;
  13289. }
  13290. }
  13291. p = p.next;
  13292. } while (p !== outerNode);
  13293. if (!m) return null;
  13294. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  13295. // look for points inside the triangle of hole point, segment intersection and endpoint;
  13296. // if there are no points found, we have a valid connection;
  13297. // otherwise choose the point of the minimum angle with the ray as connection point
  13298. var stop = m,
  13299. mx = m.x,
  13300. my = m.y,
  13301. tanMin = Infinity,
  13302. tan;
  13303. p = m.next;
  13304. while (p !== stop) {
  13305. if (hx >= p.x && p.x >= mx &&
  13306. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  13307. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  13308. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  13309. m = p;
  13310. tanMin = tan;
  13311. }
  13312. }
  13313. p = p.next;
  13314. }
  13315. return m;
  13316. }
  13317. // interlink polygon nodes in z-order
  13318. function indexCurve(start, minX, minY, size) {
  13319. var p = start;
  13320. do {
  13321. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  13322. p.prevZ = p.prev;
  13323. p.nextZ = p.next;
  13324. p = p.next;
  13325. } while (p !== start);
  13326. p.prevZ.nextZ = null;
  13327. p.prevZ = null;
  13328. sortLinked(p);
  13329. }
  13330. // Simon Tatham's linked list merge sort algorithm
  13331. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  13332. function sortLinked(list) {
  13333. var i, p, q, e, tail, numMerges, pSize, qSize,
  13334. inSize = 1;
  13335. do {
  13336. p = list;
  13337. list = null;
  13338. tail = null;
  13339. numMerges = 0;
  13340. while (p) {
  13341. numMerges++;
  13342. q = p;
  13343. pSize = 0;
  13344. for (i = 0; i < inSize; i++) {
  13345. pSize++;
  13346. q = q.nextZ;
  13347. if (!q) break;
  13348. }
  13349. qSize = inSize;
  13350. while (pSize > 0 || (qSize > 0 && q)) {
  13351. if (pSize === 0) {
  13352. e = q;
  13353. q = q.nextZ;
  13354. qSize--;
  13355. } else if (qSize === 0 || !q) {
  13356. e = p;
  13357. p = p.nextZ;
  13358. pSize--;
  13359. } else if (p.z <= q.z) {
  13360. e = p;
  13361. p = p.nextZ;
  13362. pSize--;
  13363. } else {
  13364. e = q;
  13365. q = q.nextZ;
  13366. qSize--;
  13367. }
  13368. if (tail) tail.nextZ = e;
  13369. else list = e;
  13370. e.prevZ = tail;
  13371. tail = e;
  13372. }
  13373. p = q;
  13374. }
  13375. tail.nextZ = null;
  13376. inSize *= 2;
  13377. } while (numMerges > 1);
  13378. return list;
  13379. }
  13380. // z-order of a point given coords and size of the data bounding box
  13381. function zOrder(x, y, minX, minY, size) {
  13382. // coords are transformed into non-negative 15-bit integer range
  13383. x = 32767 * (x - minX) / size;
  13384. y = 32767 * (y - minY) / size;
  13385. x = (x | (x << 8)) & 0x00FF00FF;
  13386. x = (x | (x << 4)) & 0x0F0F0F0F;
  13387. x = (x | (x << 2)) & 0x33333333;
  13388. x = (x | (x << 1)) & 0x55555555;
  13389. y = (y | (y << 8)) & 0x00FF00FF;
  13390. y = (y | (y << 4)) & 0x0F0F0F0F;
  13391. y = (y | (y << 2)) & 0x33333333;
  13392. y = (y | (y << 1)) & 0x55555555;
  13393. return x | (y << 1);
  13394. }
  13395. // find the leftmost node of a polygon ring
  13396. function getLeftmost(start) {
  13397. var p = start,
  13398. leftmost = start;
  13399. do {
  13400. if (p.x < leftmost.x) leftmost = p;
  13401. p = p.next;
  13402. } while (p !== start);
  13403. return leftmost;
  13404. }
  13405. // check if a point lies within a convex triangle
  13406. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  13407. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  13408. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  13409. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  13410. }
  13411. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  13412. function isValidDiagonal(a, b) {
  13413. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  13414. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  13415. }
  13416. // signed area of a triangle
  13417. function area(p, q, r) {
  13418. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  13419. }
  13420. // check if two points are equal
  13421. function equals(p1, p2) {
  13422. return p1.x === p2.x && p1.y === p2.y;
  13423. }
  13424. // check if two segments intersect
  13425. function intersects(p1, q1, p2, q2) {
  13426. if ((equals(p1, q1) && equals(p2, q2)) ||
  13427. (equals(p1, q2) && equals(p2, q1))) return true;
  13428. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  13429. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  13430. }
  13431. // check if a polygon diagonal intersects any polygon segments
  13432. function intersectsPolygon(a, b) {
  13433. var p = a;
  13434. do {
  13435. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  13436. intersects(p, p.next, a, b)) return true;
  13437. p = p.next;
  13438. } while (p !== a);
  13439. return false;
  13440. }
  13441. // check if a polygon diagonal is locally inside the polygon
  13442. function locallyInside(a, b) {
  13443. return area(a.prev, a, a.next) < 0 ?
  13444. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  13445. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  13446. }
  13447. // check if the middle point of a polygon diagonal is inside the polygon
  13448. function middleInside(a, b) {
  13449. var p = a,
  13450. inside = false,
  13451. px = (a.x + b.x) / 2,
  13452. py = (a.y + b.y) / 2;
  13453. do {
  13454. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  13455. inside = !inside;
  13456. p = p.next;
  13457. } while (p !== a);
  13458. return inside;
  13459. }
  13460. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  13461. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  13462. function splitPolygon(a, b) {
  13463. var a2 = new Node(a.i, a.x, a.y),
  13464. b2 = new Node(b.i, b.x, b.y),
  13465. an = a.next,
  13466. bp = b.prev;
  13467. a.next = b;
  13468. b.prev = a;
  13469. a2.next = an;
  13470. an.prev = a2;
  13471. b2.next = a2;
  13472. a2.prev = b2;
  13473. bp.next = b2;
  13474. b2.prev = bp;
  13475. return b2;
  13476. }
  13477. // create a node and optionally link it with previous one (in a circular doubly linked list)
  13478. function insertNode(i, x, y, last) {
  13479. var p = new Node(i, x, y);
  13480. if (!last) {
  13481. p.prev = p;
  13482. p.next = p;
  13483. } else {
  13484. p.next = last.next;
  13485. p.prev = last;
  13486. last.next.prev = p;
  13487. last.next = p;
  13488. }
  13489. return p;
  13490. }
  13491. function removeNode(p) {
  13492. p.next.prev = p.prev;
  13493. p.prev.next = p.next;
  13494. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  13495. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  13496. }
  13497. function Node(i, x, y) {
  13498. // vertice index in coordinates array
  13499. this.i = i;
  13500. // vertex coordinates
  13501. this.x = x;
  13502. this.y = y;
  13503. // previous and next vertice nodes in a polygon ring
  13504. this.prev = null;
  13505. this.next = null;
  13506. // z-order curve value
  13507. this.z = null;
  13508. // previous and next nodes in z-order
  13509. this.prevZ = null;
  13510. this.nextZ = null;
  13511. // indicates whether this is a steiner point
  13512. this.steiner = false;
  13513. }
  13514. // return a percentage difference between the polygon area and its triangulation area;
  13515. // used to verify correctness of triangulation
  13516. earcut.deviation = function (data, holeIndices, dim, triangles) {
  13517. var hasHoles = holeIndices && holeIndices.length;
  13518. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  13519. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  13520. if (hasHoles) {
  13521. for (var i = 0, len = holeIndices.length; i < len; i++) {
  13522. var start = holeIndices[i] * dim;
  13523. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  13524. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  13525. }
  13526. }
  13527. var trianglesArea = 0;
  13528. for (i = 0; i < triangles.length; i += 3) {
  13529. var a = triangles[i] * dim;
  13530. var b = triangles[i + 1] * dim;
  13531. var c = triangles[i + 2] * dim;
  13532. trianglesArea += Math.abs(
  13533. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  13534. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  13535. }
  13536. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  13537. Math.abs((trianglesArea - polygonArea) / polygonArea);
  13538. };
  13539. function signedArea(data, start, end, dim) {
  13540. var sum = 0;
  13541. for (var i = start, j = end - dim; i < end; i += dim) {
  13542. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  13543. j = i;
  13544. }
  13545. return sum;
  13546. }
  13547. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  13548. earcut.flatten = function (data) {
  13549. var dim = data[0][0].length,
  13550. result = {vertices: [], holes: [], dimensions: dim},
  13551. holeIndex = 0;
  13552. for (var i = 0; i < data.length; i++) {
  13553. for (var j = 0; j < data[i].length; j++) {
  13554. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  13555. }
  13556. if (i > 0) {
  13557. holeIndex += data[i - 1].length;
  13558. result.holes.push(holeIndex);
  13559. }
  13560. }
  13561. return result;
  13562. };
  13563. return earcut;
  13564. });
  13565. /*global define*/
  13566. define('Core/WindingOrder',[
  13567. './freezeObject',
  13568. './WebGLConstants'
  13569. ], function(
  13570. freezeObject,
  13571. WebGLConstants) {
  13572. 'use strict';
  13573. /**
  13574. * Winding order defines the order of vertices for a triangle to be considered front-facing.
  13575. *
  13576. * @exports WindingOrder
  13577. */
  13578. var WindingOrder = {
  13579. /**
  13580. * Vertices are in clockwise order.
  13581. *
  13582. * @type {Number}
  13583. * @constant
  13584. */
  13585. CLOCKWISE : WebGLConstants.CW,
  13586. /**
  13587. * Vertices are in counter-clockwise order.
  13588. *
  13589. * @type {Number}
  13590. * @constant
  13591. */
  13592. COUNTER_CLOCKWISE : WebGLConstants.CCW,
  13593. /**
  13594. * @private
  13595. */
  13596. validate : function(windingOrder) {
  13597. return windingOrder === WindingOrder.CLOCKWISE ||
  13598. windingOrder === WindingOrder.COUNTER_CLOCKWISE;
  13599. }
  13600. };
  13601. return freezeObject(WindingOrder);
  13602. });
  13603. /*global define*/
  13604. define('Core/PolygonPipeline',[
  13605. '../ThirdParty/earcut-2.1.1',
  13606. './Cartesian2',
  13607. './Cartesian3',
  13608. './ComponentDatatype',
  13609. './defaultValue',
  13610. './defined',
  13611. './DeveloperError',
  13612. './Ellipsoid',
  13613. './Geometry',
  13614. './GeometryAttribute',
  13615. './Math',
  13616. './PrimitiveType',
  13617. './WindingOrder'
  13618. ], function(
  13619. earcut,
  13620. Cartesian2,
  13621. Cartesian3,
  13622. ComponentDatatype,
  13623. defaultValue,
  13624. defined,
  13625. DeveloperError,
  13626. Ellipsoid,
  13627. Geometry,
  13628. GeometryAttribute,
  13629. CesiumMath,
  13630. PrimitiveType,
  13631. WindingOrder) {
  13632. 'use strict';
  13633. var scaleToGeodeticHeightN = new Cartesian3();
  13634. var scaleToGeodeticHeightP = new Cartesian3();
  13635. /**
  13636. * @private
  13637. */
  13638. var PolygonPipeline = {};
  13639. /**
  13640. * @exception {DeveloperError} At least three positions are required.
  13641. */
  13642. PolygonPipeline.computeArea2D = function(positions) {
  13643. if (!defined(positions)) {
  13644. throw new DeveloperError('positions is required.');
  13645. }
  13646. if (positions.length < 3) {
  13647. throw new DeveloperError('At least three positions are required.');
  13648. }
  13649. var length = positions.length;
  13650. var area = 0.0;
  13651. for ( var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  13652. var v0 = positions[i0];
  13653. var v1 = positions[i1];
  13654. area += (v0.x * v1.y) - (v1.x * v0.y);
  13655. }
  13656. return area * 0.5;
  13657. };
  13658. /**
  13659. * @returns {WindingOrder} The winding order.
  13660. *
  13661. * @exception {DeveloperError} At least three positions are required.
  13662. */
  13663. PolygonPipeline.computeWindingOrder2D = function(positions) {
  13664. var area = PolygonPipeline.computeArea2D(positions);
  13665. return (area > 0.0) ? WindingOrder.COUNTER_CLOCKWISE : WindingOrder.CLOCKWISE;
  13666. };
  13667. /**
  13668. * Triangulate a polygon.
  13669. *
  13670. * @param {Cartesian2[]} positions Cartesian2 array containing the vertices of the polygon
  13671. * @param {Number[]} [holes] An array of the staring indices of the holes.
  13672. * @returns {Number[]} Index array representing triangles that fill the polygon
  13673. */
  13674. PolygonPipeline.triangulate = function(positions, holes) {
  13675. if (!defined(positions)) {
  13676. throw new DeveloperError('positions is required.');
  13677. }
  13678. var flattenedPositions = Cartesian2.packArray(positions);
  13679. return earcut(flattenedPositions, holes, 2);
  13680. };
  13681. var subdivisionV0Scratch = new Cartesian3();
  13682. var subdivisionV1Scratch = new Cartesian3();
  13683. var subdivisionV2Scratch = new Cartesian3();
  13684. var subdivisionS0Scratch = new Cartesian3();
  13685. var subdivisionS1Scratch = new Cartesian3();
  13686. var subdivisionS2Scratch = new Cartesian3();
  13687. var subdivisionMidScratch = new Cartesian3();
  13688. /**
  13689. * Subdivides positions and raises points to the surface of the ellipsoid.
  13690. *
  13691. * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
  13692. * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
  13693. * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
  13694. * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  13695. *
  13696. * @exception {DeveloperError} At least three indices are required.
  13697. * @exception {DeveloperError} The number of indices must be divisable by three.
  13698. * @exception {DeveloperError} Granularity must be greater than zero.
  13699. */
  13700. PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices, granularity) {
  13701. granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);
  13702. if (!defined(ellipsoid)) {
  13703. throw new DeveloperError('ellipsoid is required.');
  13704. }
  13705. if (!defined(positions)) {
  13706. throw new DeveloperError('positions is required.');
  13707. }
  13708. if (!defined(indices)) {
  13709. throw new DeveloperError('indices is required.');
  13710. }
  13711. if (indices.length < 3) {
  13712. throw new DeveloperError('At least three indices are required.');
  13713. }
  13714. if (indices.length % 3 !== 0) {
  13715. throw new DeveloperError('The number of indices must be divisable by three.');
  13716. }
  13717. if (granularity <= 0.0) {
  13718. throw new DeveloperError('granularity must be greater than zero.');
  13719. }
  13720. // triangles that need (or might need) to be subdivided.
  13721. var triangles = indices.slice(0);
  13722. // New positions due to edge splits are appended to the positions list.
  13723. var i;
  13724. var length = positions.length;
  13725. var subdividedPositions = new Array(length * 3);
  13726. var q = 0;
  13727. for (i = 0; i < length; i++) {
  13728. var item = positions[i];
  13729. subdividedPositions[q++] = item.x;
  13730. subdividedPositions[q++] = item.y;
  13731. subdividedPositions[q++] = item.z;
  13732. }
  13733. var subdividedIndices = [];
  13734. // Used to make sure shared edges are not split more than once.
  13735. var edges = {};
  13736. var radius = ellipsoid.maximumRadius;
  13737. var minDistance = CesiumMath.chordLength(granularity, radius);
  13738. var minDistanceSqrd = minDistance * minDistance;
  13739. while (triangles.length > 0) {
  13740. var i2 = triangles.pop();
  13741. var i1 = triangles.pop();
  13742. var i0 = triangles.pop();
  13743. var v0 = Cartesian3.fromArray(subdividedPositions, i0 * 3, subdivisionV0Scratch);
  13744. var v1 = Cartesian3.fromArray(subdividedPositions, i1 * 3, subdivisionV1Scratch);
  13745. var v2 = Cartesian3.fromArray(subdividedPositions, i2 * 3, subdivisionV2Scratch);
  13746. var s0 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v0, subdivisionS0Scratch), radius, subdivisionS0Scratch);
  13747. var s1 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v1, subdivisionS1Scratch), radius, subdivisionS1Scratch);
  13748. var s2 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v2, subdivisionS2Scratch), radius, subdivisionS2Scratch);
  13749. var g0 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s0, s1, subdivisionMidScratch));
  13750. var g1 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s1, s2, subdivisionMidScratch));
  13751. var g2 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s2, s0, subdivisionMidScratch));
  13752. var max = Math.max(g0, g1, g2);
  13753. var edge;
  13754. var mid;
  13755. // if the max length squared of a triangle edge is greater than the chord length of squared
  13756. // of the granularity, subdivide the triangle
  13757. if (max > minDistanceSqrd) {
  13758. if (g0 === max) {
  13759. edge = Math.min(i0, i1) + ' ' + Math.max(i0, i1);
  13760. i = edges[edge];
  13761. if (!defined(i)) {
  13762. mid = Cartesian3.add(v0, v1, subdivisionMidScratch);
  13763. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  13764. subdividedPositions.push(mid.x, mid.y, mid.z);
  13765. i = subdividedPositions.length / 3 - 1;
  13766. edges[edge] = i;
  13767. }
  13768. triangles.push(i0, i, i2);
  13769. triangles.push(i, i1, i2);
  13770. } else if (g1 === max) {
  13771. edge = Math.min(i1, i2) + ' ' + Math.max(i1, i2);
  13772. i = edges[edge];
  13773. if (!defined(i)) {
  13774. mid = Cartesian3.add(v1, v2, subdivisionMidScratch);
  13775. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  13776. subdividedPositions.push(mid.x, mid.y, mid.z);
  13777. i = subdividedPositions.length / 3 - 1;
  13778. edges[edge] = i;
  13779. }
  13780. triangles.push(i1, i, i0);
  13781. triangles.push(i, i2, i0);
  13782. } else if (g2 === max) {
  13783. edge = Math.min(i2, i0) + ' ' + Math.max(i2, i0);
  13784. i = edges[edge];
  13785. if (!defined(i)) {
  13786. mid = Cartesian3.add(v2, v0, subdivisionMidScratch);
  13787. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  13788. subdividedPositions.push(mid.x, mid.y, mid.z);
  13789. i = subdividedPositions.length / 3 - 1;
  13790. edges[edge] = i;
  13791. }
  13792. triangles.push(i2, i, i1);
  13793. triangles.push(i, i0, i1);
  13794. }
  13795. } else {
  13796. subdividedIndices.push(i0);
  13797. subdividedIndices.push(i1);
  13798. subdividedIndices.push(i2);
  13799. }
  13800. }
  13801. return new Geometry({
  13802. attributes : {
  13803. position : new GeometryAttribute({
  13804. componentDatatype : ComponentDatatype.DOUBLE,
  13805. componentsPerAttribute : 3,
  13806. values : subdividedPositions
  13807. })
  13808. },
  13809. indices : subdividedIndices,
  13810. primitiveType : PrimitiveType.TRIANGLES
  13811. });
  13812. };
  13813. /**
  13814. * Scales each position of a geometry's position attribute to a height, in place.
  13815. *
  13816. * @param {Number[]} positions The array of numbers representing the positions to be scaled
  13817. * @param {Number} [height=0.0] The desired height to add to the positions
  13818. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  13819. * @param {Boolean} [scaleToSurface=true] <code>true</code> if the positions need to be scaled to the surface before the height is added.
  13820. * @returns {Number[]} The input array of positions, scaled to height
  13821. */
  13822. PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface) {
  13823. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  13824. var n = scaleToGeodeticHeightN;
  13825. var p = scaleToGeodeticHeightP;
  13826. height = defaultValue(height, 0.0);
  13827. scaleToSurface = defaultValue(scaleToSurface, true);
  13828. if (defined(positions)) {
  13829. var length = positions.length;
  13830. for ( var i = 0; i < length; i += 3) {
  13831. Cartesian3.fromArray(positions, i, p);
  13832. if (scaleToSurface) {
  13833. p = ellipsoid.scaleToGeodeticSurface(p, p);
  13834. }
  13835. if (height !== 0) {
  13836. n = ellipsoid.geodeticSurfaceNormal(p, n);
  13837. Cartesian3.multiplyByScalar(n, height, n);
  13838. Cartesian3.add(p, n, p);
  13839. }
  13840. positions[i] = p.x;
  13841. positions[i + 1] = p.y;
  13842. positions[i + 2] = p.z;
  13843. }
  13844. }
  13845. return positions;
  13846. };
  13847. return PolygonPipeline;
  13848. });
  13849. /*global define*/
  13850. define('Core/AxisAlignedBoundingBox',[
  13851. './Cartesian3',
  13852. './defaultValue',
  13853. './defined',
  13854. './DeveloperError',
  13855. './Intersect'
  13856. ], function(
  13857. Cartesian3,
  13858. defaultValue,
  13859. defined,
  13860. DeveloperError,
  13861. Intersect) {
  13862. 'use strict';
  13863. /**
  13864. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  13865. * @alias AxisAlignedBoundingBox
  13866. * @constructor
  13867. *
  13868. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  13869. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  13870. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  13871. *
  13872. * @see BoundingSphere
  13873. * @see BoundingRectangle
  13874. */
  13875. function AxisAlignedBoundingBox(minimum, maximum, center) {
  13876. /**
  13877. * The minimum point defining the bounding box.
  13878. * @type {Cartesian3}
  13879. * @default {@link Cartesian3.ZERO}
  13880. */
  13881. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  13882. /**
  13883. * The maximum point defining the bounding box.
  13884. * @type {Cartesian3}
  13885. * @default {@link Cartesian3.ZERO}
  13886. */
  13887. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  13888. //If center was not defined, compute it.
  13889. if (!defined(center)) {
  13890. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  13891. Cartesian3.multiplyByScalar(center, 0.5, center);
  13892. } else {
  13893. center = Cartesian3.clone(center);
  13894. }
  13895. /**
  13896. * The center point of the bounding box.
  13897. * @type {Cartesian3}
  13898. */
  13899. this.center = center;
  13900. }
  13901. /**
  13902. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  13903. * finding the points spaced the farthest apart on the x, y, and z axes.
  13904. *
  13905. * @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.
  13906. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  13907. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  13908. *
  13909. * @example
  13910. * // Compute an axis aligned bounding box enclosing two points.
  13911. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  13912. */
  13913. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  13914. if (!defined(result)) {
  13915. result = new AxisAlignedBoundingBox();
  13916. }
  13917. if (!defined(positions) || positions.length === 0) {
  13918. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  13919. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  13920. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  13921. return result;
  13922. }
  13923. var minimumX = positions[0].x;
  13924. var minimumY = positions[0].y;
  13925. var minimumZ = positions[0].z;
  13926. var maximumX = positions[0].x;
  13927. var maximumY = positions[0].y;
  13928. var maximumZ = positions[0].z;
  13929. var length = positions.length;
  13930. for ( var i = 1; i < length; i++) {
  13931. var p = positions[i];
  13932. var x = p.x;
  13933. var y = p.y;
  13934. var z = p.z;
  13935. minimumX = Math.min(x, minimumX);
  13936. maximumX = Math.max(x, maximumX);
  13937. minimumY = Math.min(y, minimumY);
  13938. maximumY = Math.max(y, maximumY);
  13939. minimumZ = Math.min(z, minimumZ);
  13940. maximumZ = Math.max(z, maximumZ);
  13941. }
  13942. var minimum = result.minimum;
  13943. minimum.x = minimumX;
  13944. minimum.y = minimumY;
  13945. minimum.z = minimumZ;
  13946. var maximum = result.maximum;
  13947. maximum.x = maximumX;
  13948. maximum.y = maximumY;
  13949. maximum.z = maximumZ;
  13950. var center = Cartesian3.add(minimum, maximum, result.center);
  13951. Cartesian3.multiplyByScalar(center, 0.5, center);
  13952. return result;
  13953. };
  13954. /**
  13955. * Duplicates a AxisAlignedBoundingBox instance.
  13956. *
  13957. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  13958. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  13959. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  13960. */
  13961. AxisAlignedBoundingBox.clone = function(box, result) {
  13962. if (!defined(box)) {
  13963. return undefined;
  13964. }
  13965. if (!defined(result)) {
  13966. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  13967. }
  13968. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  13969. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  13970. result.center = Cartesian3.clone(box.center, result.center);
  13971. return result;
  13972. };
  13973. /**
  13974. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  13975. * <code>true</code> if they are equal, <code>false</code> otherwise.
  13976. *
  13977. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  13978. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  13979. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  13980. */
  13981. AxisAlignedBoundingBox.equals = function(left, right) {
  13982. return (left === right) ||
  13983. ((defined(left)) &&
  13984. (defined(right)) &&
  13985. Cartesian3.equals(left.center, right.center) &&
  13986. Cartesian3.equals(left.minimum, right.minimum) &&
  13987. Cartesian3.equals(left.maximum, right.maximum));
  13988. };
  13989. var intersectScratch = new Cartesian3();
  13990. /**
  13991. * Determines which side of a plane a box is located.
  13992. *
  13993. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  13994. * @param {Plane} plane The plane to test against.
  13995. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  13996. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  13997. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  13998. * intersects the plane.
  13999. */
  14000. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  14001. if (!defined(box)) {
  14002. throw new DeveloperError('box is required.');
  14003. }
  14004. if (!defined(plane)) {
  14005. throw new DeveloperError('plane is required.');
  14006. }
  14007. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  14008. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  14009. var normal = plane.normal;
  14010. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  14011. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  14012. if (s - e > 0) {
  14013. return Intersect.INSIDE;
  14014. }
  14015. if (s + e < 0) {
  14016. //Not in front because normals point inward
  14017. return Intersect.OUTSIDE;
  14018. }
  14019. return Intersect.INTERSECTING;
  14020. };
  14021. /**
  14022. * Duplicates this AxisAlignedBoundingBox instance.
  14023. *
  14024. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  14025. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  14026. */
  14027. AxisAlignedBoundingBox.prototype.clone = function(result) {
  14028. return AxisAlignedBoundingBox.clone(this, result);
  14029. };
  14030. /**
  14031. * Determines which side of a plane this box is located.
  14032. *
  14033. * @param {Plane} plane The plane to test against.
  14034. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  14035. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  14036. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  14037. * intersects the plane.
  14038. */
  14039. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  14040. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  14041. };
  14042. /**
  14043. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  14044. * <code>true</code> if they are equal, <code>false</code> otherwise.
  14045. *
  14046. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  14047. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  14048. */
  14049. AxisAlignedBoundingBox.prototype.equals = function(right) {
  14050. return AxisAlignedBoundingBox.equals(this, right);
  14051. };
  14052. return AxisAlignedBoundingBox;
  14053. });
  14054. /*global define*/
  14055. define('Core/QuadraticRealPolynomial',[
  14056. './DeveloperError',
  14057. './Math'
  14058. ], function(
  14059. DeveloperError,
  14060. CesiumMath) {
  14061. 'use strict';
  14062. /**
  14063. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  14064. *
  14065. * @exports QuadraticRealPolynomial
  14066. */
  14067. var QuadraticRealPolynomial = {};
  14068. /**
  14069. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  14070. *
  14071. * @param {Number} a The coefficient of the 2nd order monomial.
  14072. * @param {Number} b The coefficient of the 1st order monomial.
  14073. * @param {Number} c The coefficient of the 0th order monomial.
  14074. * @returns {Number} The value of the discriminant.
  14075. */
  14076. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  14077. if (typeof a !== 'number') {
  14078. throw new DeveloperError('a is a required number.');
  14079. }
  14080. if (typeof b !== 'number') {
  14081. throw new DeveloperError('b is a required number.');
  14082. }
  14083. if (typeof c !== 'number') {
  14084. throw new DeveloperError('c is a required number.');
  14085. }
  14086. var discriminant = b * b - 4.0 * a * c;
  14087. return discriminant;
  14088. };
  14089. function addWithCancellationCheck(left, right, tolerance) {
  14090. var difference = left + right;
  14091. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  14092. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  14093. return 0.0;
  14094. }
  14095. return difference;
  14096. }
  14097. /**
  14098. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  14099. *
  14100. * @param {Number} a The coefficient of the 2nd order monomial.
  14101. * @param {Number} b The coefficient of the 1st order monomial.
  14102. * @param {Number} c The coefficient of the 0th order monomial.
  14103. * @returns {Number[]} The real valued roots.
  14104. */
  14105. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  14106. if (typeof a !== 'number') {
  14107. throw new DeveloperError('a is a required number.');
  14108. }
  14109. if (typeof b !== 'number') {
  14110. throw new DeveloperError('b is a required number.');
  14111. }
  14112. if (typeof c !== 'number') {
  14113. throw new DeveloperError('c is a required number.');
  14114. }
  14115. var ratio;
  14116. if (a === 0.0) {
  14117. if (b === 0.0) {
  14118. // Constant function: c = 0.
  14119. return [];
  14120. }
  14121. // Linear function: b * x + c = 0.
  14122. return [-c / b];
  14123. } else if (b === 0.0) {
  14124. if (c === 0.0) {
  14125. // 2nd order monomial: a * x^2 = 0.
  14126. return [0.0, 0.0];
  14127. }
  14128. var cMagnitude = Math.abs(c);
  14129. var aMagnitude = Math.abs(a);
  14130. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  14131. // 2nd order monomial: a * x^2 = 0.
  14132. return [0.0, 0.0];
  14133. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  14134. // Constant function: c = 0.
  14135. return [];
  14136. }
  14137. // a * x^2 + c = 0
  14138. ratio = -c / a;
  14139. if (ratio < 0.0) {
  14140. // Both roots are complex.
  14141. return [];
  14142. }
  14143. // Both roots are real.
  14144. var root = Math.sqrt(ratio);
  14145. return [-root, root];
  14146. } else if (c === 0.0) {
  14147. // a * x^2 + b * x = 0
  14148. ratio = -b / a;
  14149. if (ratio < 0.0) {
  14150. return [ratio, 0.0];
  14151. }
  14152. return [0.0, ratio];
  14153. }
  14154. // a * x^2 + b * x + c = 0
  14155. var b2 = b * b;
  14156. var four_ac = 4.0 * a * c;
  14157. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  14158. if (radicand < 0.0) {
  14159. // Both roots are complex.
  14160. return [];
  14161. }
  14162. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  14163. if (b > 0.0) {
  14164. return [q / a, c / q];
  14165. }
  14166. return [c / q, q / a];
  14167. };
  14168. return QuadraticRealPolynomial;
  14169. });
  14170. /*global define*/
  14171. define('Core/CubicRealPolynomial',[
  14172. './DeveloperError',
  14173. './QuadraticRealPolynomial'
  14174. ], function(
  14175. DeveloperError,
  14176. QuadraticRealPolynomial) {
  14177. 'use strict';
  14178. /**
  14179. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  14180. *
  14181. * @exports CubicRealPolynomial
  14182. */
  14183. var CubicRealPolynomial = {};
  14184. /**
  14185. * Provides the discriminant of the cubic equation from the supplied coefficients.
  14186. *
  14187. * @param {Number} a The coefficient of the 3rd order monomial.
  14188. * @param {Number} b The coefficient of the 2nd order monomial.
  14189. * @param {Number} c The coefficient of the 1st order monomial.
  14190. * @param {Number} d The coefficient of the 0th order monomial.
  14191. * @returns {Number} The value of the discriminant.
  14192. */
  14193. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  14194. if (typeof a !== 'number') {
  14195. throw new DeveloperError('a is a required number.');
  14196. }
  14197. if (typeof b !== 'number') {
  14198. throw new DeveloperError('b is a required number.');
  14199. }
  14200. if (typeof c !== 'number') {
  14201. throw new DeveloperError('c is a required number.');
  14202. }
  14203. if (typeof d !== 'number') {
  14204. throw new DeveloperError('d is a required number.');
  14205. }
  14206. var a2 = a * a;
  14207. var b2 = b * b;
  14208. var c2 = c * c;
  14209. var d2 = d * d;
  14210. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  14211. return discriminant;
  14212. };
  14213. function computeRealRoots(a, b, c, d) {
  14214. var A = a;
  14215. var B = b / 3.0;
  14216. var C = c / 3.0;
  14217. var D = d;
  14218. var AC = A * C;
  14219. var BD = B * D;
  14220. var B2 = B * B;
  14221. var C2 = C * C;
  14222. var delta1 = A * C - B2;
  14223. var delta2 = A * D - B * C;
  14224. var delta3 = B * D - C2;
  14225. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  14226. var temp;
  14227. var temp1;
  14228. if (discriminant < 0.0) {
  14229. var ABar;
  14230. var CBar;
  14231. var DBar;
  14232. if (B2 * BD >= AC * C2) {
  14233. ABar = A;
  14234. CBar = delta1;
  14235. DBar = -2.0 * B * delta1 + A * delta2;
  14236. } else {
  14237. ABar = D;
  14238. CBar = delta3;
  14239. DBar = -D * delta2 + 2.0 * C * delta3;
  14240. }
  14241. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  14242. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  14243. temp1 = -DBar + temp0;
  14244. var x = temp1 / 2.0;
  14245. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  14246. var q = (temp1 === temp0) ? -p : -CBar / p;
  14247. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  14248. if (B2 * BD >= AC * C2) {
  14249. return [(temp - B) / A];
  14250. }
  14251. return [-D / (temp + C)];
  14252. }
  14253. var CBarA = delta1;
  14254. var DBarA = -2.0 * B * delta1 + A * delta2;
  14255. var CBarD = delta3;
  14256. var DBarD = -D * delta2 + 2.0 * C * delta3;
  14257. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  14258. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  14259. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  14260. temp = 2.0 * Math.sqrt(-CBarA);
  14261. var cosine = Math.cos(theta);
  14262. temp1 = temp * cosine;
  14263. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  14264. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  14265. var denominatorLarge = A;
  14266. var root1 = numeratorLarge / denominatorLarge;
  14267. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  14268. temp = 2.0 * Math.sqrt(-CBarD);
  14269. cosine = Math.cos(theta);
  14270. temp1 = temp * cosine;
  14271. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  14272. var numeratorSmall = -D;
  14273. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  14274. var root3 = numeratorSmall / denominatorSmall;
  14275. var E = denominatorLarge * denominatorSmall;
  14276. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  14277. var G = numeratorLarge * numeratorSmall;
  14278. var root2 = (C * F - B * G) / (-B * F + C * E);
  14279. if (root1 <= root2) {
  14280. if (root1 <= root3) {
  14281. if (root2 <= root3) {
  14282. return [root1, root2, root3];
  14283. }
  14284. return [root1, root3, root2];
  14285. }
  14286. return [root3, root1, root2];
  14287. }
  14288. if (root1 <= root3) {
  14289. return [root2, root1, root3];
  14290. }
  14291. if (root2 <= root3) {
  14292. return [root2, root3, root1];
  14293. }
  14294. return [root3, root2, root1];
  14295. }
  14296. /**
  14297. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  14298. *
  14299. * @param {Number} a The coefficient of the 3rd order monomial.
  14300. * @param {Number} b The coefficient of the 2nd order monomial.
  14301. * @param {Number} c The coefficient of the 1st order monomial.
  14302. * @param {Number} d The coefficient of the 0th order monomial.
  14303. * @returns {Number[]} The real valued roots.
  14304. */
  14305. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  14306. if (typeof a !== 'number') {
  14307. throw new DeveloperError('a is a required number.');
  14308. }
  14309. if (typeof b !== 'number') {
  14310. throw new DeveloperError('b is a required number.');
  14311. }
  14312. if (typeof c !== 'number') {
  14313. throw new DeveloperError('c is a required number.');
  14314. }
  14315. if (typeof d !== 'number') {
  14316. throw new DeveloperError('d is a required number.');
  14317. }
  14318. var roots;
  14319. var ratio;
  14320. if (a === 0.0) {
  14321. // Quadratic function: b * x^2 + c * x + d = 0.
  14322. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  14323. } else if (b === 0.0) {
  14324. if (c === 0.0) {
  14325. if (d === 0.0) {
  14326. // 3rd order monomial: a * x^3 = 0.
  14327. return [0.0, 0.0, 0.0];
  14328. }
  14329. // a * x^3 + d = 0
  14330. ratio = -d / a;
  14331. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  14332. return [root, root, root];
  14333. } else if (d === 0.0) {
  14334. // x * (a * x^2 + c) = 0.
  14335. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  14336. // Return the roots in ascending order.
  14337. if (roots.Length === 0) {
  14338. return [0.0];
  14339. }
  14340. return [roots[0], 0.0, roots[1]];
  14341. }
  14342. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  14343. return computeRealRoots(a, 0, c, d);
  14344. } else if (c === 0.0) {
  14345. if (d === 0.0) {
  14346. // x^2 * (a * x + b) = 0.
  14347. ratio = -b / a;
  14348. if (ratio < 0.0) {
  14349. return [ratio, 0.0, 0.0];
  14350. }
  14351. return [0.0, 0.0, ratio];
  14352. }
  14353. // a * x^3 + b * x^2 + d = 0.
  14354. return computeRealRoots(a, b, 0, d);
  14355. } else if (d === 0.0) {
  14356. // x * (a * x^2 + b * x + c) = 0
  14357. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  14358. // Return the roots in ascending order.
  14359. if (roots.length === 0) {
  14360. return [0.0];
  14361. } else if (roots[1] <= 0.0) {
  14362. return [roots[0], roots[1], 0.0];
  14363. } else if (roots[0] >= 0.0) {
  14364. return [0.0, roots[0], roots[1]];
  14365. }
  14366. return [roots[0], 0.0, roots[1]];
  14367. }
  14368. return computeRealRoots(a, b, c, d);
  14369. };
  14370. return CubicRealPolynomial;
  14371. });
  14372. /*global define*/
  14373. define('Core/QuarticRealPolynomial',[
  14374. './CubicRealPolynomial',
  14375. './DeveloperError',
  14376. './Math',
  14377. './QuadraticRealPolynomial'
  14378. ], function(
  14379. CubicRealPolynomial,
  14380. DeveloperError,
  14381. CesiumMath,
  14382. QuadraticRealPolynomial) {
  14383. 'use strict';
  14384. /**
  14385. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  14386. *
  14387. * @exports QuarticRealPolynomial
  14388. */
  14389. var QuarticRealPolynomial = {};
  14390. /**
  14391. * Provides the discriminant of the quartic equation from the supplied coefficients.
  14392. *
  14393. * @param {Number} a The coefficient of the 4th order monomial.
  14394. * @param {Number} b The coefficient of the 3rd order monomial.
  14395. * @param {Number} c The coefficient of the 2nd order monomial.
  14396. * @param {Number} d The coefficient of the 1st order monomial.
  14397. * @param {Number} e The coefficient of the 0th order monomial.
  14398. * @returns {Number} The value of the discriminant.
  14399. */
  14400. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  14401. if (typeof a !== 'number') {
  14402. throw new DeveloperError('a is a required number.');
  14403. }
  14404. if (typeof b !== 'number') {
  14405. throw new DeveloperError('b is a required number.');
  14406. }
  14407. if (typeof c !== 'number') {
  14408. throw new DeveloperError('c is a required number.');
  14409. }
  14410. if (typeof d !== 'number') {
  14411. throw new DeveloperError('d is a required number.');
  14412. }
  14413. if (typeof e !== 'number') {
  14414. throw new DeveloperError('e is a required number.');
  14415. }
  14416. var a2 = a * a;
  14417. var a3 = a2 * a;
  14418. var b2 = b * b;
  14419. var b3 = b2 * b;
  14420. var c2 = c * c;
  14421. var c3 = c2 * c;
  14422. var d2 = d * d;
  14423. var d3 = d2 * d;
  14424. var e2 = e * e;
  14425. var e3 = e2 * e;
  14426. 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) +
  14427. 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) +
  14428. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  14429. return discriminant;
  14430. };
  14431. function original(a3, a2, a1, a0) {
  14432. var a3Squared = a3 * a3;
  14433. var p = a2 - 3.0 * a3Squared / 8.0;
  14434. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  14435. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  14436. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  14437. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  14438. if (cubicRoots.length > 0) {
  14439. var temp = -a3 / 4.0;
  14440. // Use the largest positive root.
  14441. var hSquared = cubicRoots[cubicRoots.length - 1];
  14442. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  14443. // y^4 + p y^2 + r = 0.
  14444. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  14445. if (roots.length === 2) {
  14446. var root0 = roots[0];
  14447. var root1 = roots[1];
  14448. var y;
  14449. if (root0 >= 0.0 && root1 >= 0.0) {
  14450. var y0 = Math.sqrt(root0);
  14451. var y1 = Math.sqrt(root1);
  14452. return [temp - y1, temp - y0, temp + y0, temp + y1];
  14453. } else if (root0 >= 0.0 && root1 < 0.0) {
  14454. y = Math.sqrt(root0);
  14455. return [temp - y, temp + y];
  14456. } else if (root0 < 0.0 && root1 >= 0.0) {
  14457. y = Math.sqrt(root1);
  14458. return [temp - y, temp + y];
  14459. }
  14460. }
  14461. return [];
  14462. } else if (hSquared > 0.0) {
  14463. var h = Math.sqrt(hSquared);
  14464. var m = (p + hSquared - q / h) / 2.0;
  14465. var n = (p + hSquared + q / h) / 2.0;
  14466. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  14467. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  14468. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  14469. if (roots1.length !== 0) {
  14470. roots1[0] += temp;
  14471. roots1[1] += temp;
  14472. if (roots2.length !== 0) {
  14473. roots2[0] += temp;
  14474. roots2[1] += temp;
  14475. if (roots1[1] <= roots2[0]) {
  14476. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  14477. } else if (roots2[1] <= roots1[0]) {
  14478. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  14479. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  14480. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  14481. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  14482. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  14483. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  14484. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  14485. }
  14486. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  14487. }
  14488. return roots1;
  14489. }
  14490. if (roots2.length !== 0) {
  14491. roots2[0] += temp;
  14492. roots2[1] += temp;
  14493. return roots2;
  14494. }
  14495. return [];
  14496. }
  14497. }
  14498. return [];
  14499. }
  14500. function neumark(a3, a2, a1, a0) {
  14501. var a1Squared = a1 * a1;
  14502. var a2Squared = a2 * a2;
  14503. var a3Squared = a3 * a3;
  14504. var p = -2.0 * a2;
  14505. var q = a1 * a3 + a2Squared - 4.0 * a0;
  14506. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  14507. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  14508. if (cubicRoots.length > 0) {
  14509. // Use the most positive root
  14510. var y = cubicRoots[0];
  14511. var temp = (a2 - y);
  14512. var tempSquared = temp * temp;
  14513. var g1 = a3 / 2.0;
  14514. var h1 = temp / 2.0;
  14515. var m = tempSquared - 4.0 * a0;
  14516. var mError = tempSquared + 4.0 * Math.abs(a0);
  14517. var n = a3Squared - 4.0 * y;
  14518. var nError = a3Squared + 4.0 * Math.abs(y);
  14519. var g2;
  14520. var h2;
  14521. if (y < 0.0 || (m * nError < n * mError)) {
  14522. var squareRootOfN = Math.sqrt(n);
  14523. g2 = squareRootOfN / 2.0;
  14524. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  14525. } else {
  14526. var squareRootOfM = Math.sqrt(m);
  14527. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  14528. h2 = squareRootOfM / 2.0;
  14529. }
  14530. var G;
  14531. var g;
  14532. if (g1 === 0.0 && g2 === 0.0) {
  14533. G = 0.0;
  14534. g = 0.0;
  14535. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  14536. G = g1 + g2;
  14537. g = y / G;
  14538. } else {
  14539. g = g1 - g2;
  14540. G = y / g;
  14541. }
  14542. var H;
  14543. var h;
  14544. if (h1 === 0.0 && h2 === 0.0) {
  14545. H = 0.0;
  14546. h = 0.0;
  14547. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  14548. H = h1 + h2;
  14549. h = a0 / H;
  14550. } else {
  14551. h = h1 - h2;
  14552. H = a0 / h;
  14553. }
  14554. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  14555. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  14556. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  14557. if (roots1.length !== 0) {
  14558. if (roots2.length !== 0) {
  14559. if (roots1[1] <= roots2[0]) {
  14560. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  14561. } else if (roots2[1] <= roots1[0]) {
  14562. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  14563. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  14564. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  14565. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  14566. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  14567. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  14568. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  14569. } else {
  14570. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  14571. }
  14572. }
  14573. return roots1;
  14574. }
  14575. if (roots2.length !== 0) {
  14576. return roots2;
  14577. }
  14578. }
  14579. return [];
  14580. }
  14581. /**
  14582. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  14583. *
  14584. * @param {Number} a The coefficient of the 4th order monomial.
  14585. * @param {Number} b The coefficient of the 3rd order monomial.
  14586. * @param {Number} c The coefficient of the 2nd order monomial.
  14587. * @param {Number} d The coefficient of the 1st order monomial.
  14588. * @param {Number} e The coefficient of the 0th order monomial.
  14589. * @returns {Number[]} The real valued roots.
  14590. */
  14591. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  14592. if (typeof a !== 'number') {
  14593. throw new DeveloperError('a is a required number.');
  14594. }
  14595. if (typeof b !== 'number') {
  14596. throw new DeveloperError('b is a required number.');
  14597. }
  14598. if (typeof c !== 'number') {
  14599. throw new DeveloperError('c is a required number.');
  14600. }
  14601. if (typeof d !== 'number') {
  14602. throw new DeveloperError('d is a required number.');
  14603. }
  14604. if (typeof e !== 'number') {
  14605. throw new DeveloperError('e is a required number.');
  14606. }
  14607. if (Math.abs(a) < CesiumMath.EPSILON15) {
  14608. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  14609. }
  14610. var a3 = b / a;
  14611. var a2 = c / a;
  14612. var a1 = d / a;
  14613. var a0 = e / a;
  14614. var k = (a3 < 0.0) ? 1 : 0;
  14615. k += (a2 < 0.0) ? k + 1 : k;
  14616. k += (a1 < 0.0) ? k + 1 : k;
  14617. k += (a0 < 0.0) ? k + 1 : k;
  14618. switch (k) {
  14619. case 0:
  14620. return original(a3, a2, a1, a0);
  14621. case 1:
  14622. return neumark(a3, a2, a1, a0);
  14623. case 2:
  14624. return neumark(a3, a2, a1, a0);
  14625. case 3:
  14626. return original(a3, a2, a1, a0);
  14627. case 4:
  14628. return original(a3, a2, a1, a0);
  14629. case 5:
  14630. return neumark(a3, a2, a1, a0);
  14631. case 6:
  14632. return original(a3, a2, a1, a0);
  14633. case 7:
  14634. return original(a3, a2, a1, a0);
  14635. case 8:
  14636. return neumark(a3, a2, a1, a0);
  14637. case 9:
  14638. return original(a3, a2, a1, a0);
  14639. case 10:
  14640. return original(a3, a2, a1, a0);
  14641. case 11:
  14642. return neumark(a3, a2, a1, a0);
  14643. case 12:
  14644. return original(a3, a2, a1, a0);
  14645. case 13:
  14646. return original(a3, a2, a1, a0);
  14647. case 14:
  14648. return original(a3, a2, a1, a0);
  14649. case 15:
  14650. return original(a3, a2, a1, a0);
  14651. default:
  14652. return undefined;
  14653. }
  14654. };
  14655. return QuarticRealPolynomial;
  14656. });
  14657. /*global define*/
  14658. define('Core/Ray',[
  14659. './Cartesian3',
  14660. './defaultValue',
  14661. './defined',
  14662. './DeveloperError'
  14663. ], function(
  14664. Cartesian3,
  14665. defaultValue,
  14666. defined,
  14667. DeveloperError) {
  14668. 'use strict';
  14669. /**
  14670. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  14671. * @alias Ray
  14672. * @constructor
  14673. *
  14674. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  14675. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  14676. */
  14677. function Ray(origin, direction) {
  14678. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  14679. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  14680. Cartesian3.normalize(direction, direction);
  14681. }
  14682. /**
  14683. * The origin of the ray.
  14684. * @type {Cartesian3}
  14685. * @default {@link Cartesian3.ZERO}
  14686. */
  14687. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  14688. /**
  14689. * The direction of the ray.
  14690. * @type {Cartesian3}
  14691. */
  14692. this.direction = direction;
  14693. }
  14694. /**
  14695. * Computes the point along the ray given by r(t) = o + t*d,
  14696. * where o is the origin of the ray and d is the direction.
  14697. *
  14698. * @param {Ray} ray The ray.
  14699. * @param {Number} t A scalar value.
  14700. * @param {Cartesian3} [result] The object in which the result will be stored.
  14701. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  14702. *
  14703. * @example
  14704. * //Get the first intersection point of a ray and an ellipsoid.
  14705. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  14706. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  14707. */
  14708. Ray.getPoint = function(ray, t, result) {
  14709. if (!defined(ray)){
  14710. throw new DeveloperError('ray is requred');
  14711. }
  14712. if (typeof t !== 'number') {
  14713. throw new DeveloperError('t is a required number');
  14714. }
  14715. if (!defined(result)) {
  14716. result = new Cartesian3();
  14717. }
  14718. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  14719. return Cartesian3.add(ray.origin, result, result);
  14720. };
  14721. return Ray;
  14722. });
  14723. /*global define*/
  14724. define('Core/IntersectionTests',[
  14725. './Cartesian3',
  14726. './Cartographic',
  14727. './defaultValue',
  14728. './defined',
  14729. './DeveloperError',
  14730. './Math',
  14731. './Matrix3',
  14732. './QuadraticRealPolynomial',
  14733. './QuarticRealPolynomial',
  14734. './Ray'
  14735. ], function(
  14736. Cartesian3,
  14737. Cartographic,
  14738. defaultValue,
  14739. defined,
  14740. DeveloperError,
  14741. CesiumMath,
  14742. Matrix3,
  14743. QuadraticRealPolynomial,
  14744. QuarticRealPolynomial,
  14745. Ray) {
  14746. 'use strict';
  14747. /**
  14748. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  14749. *
  14750. * @exports IntersectionTests
  14751. */
  14752. var IntersectionTests = {};
  14753. /**
  14754. * Computes the intersection of a ray and a plane.
  14755. *
  14756. * @param {Ray} ray The ray.
  14757. * @param {Plane} plane The plane.
  14758. * @param {Cartesian3} [result] The object onto which to store the result.
  14759. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14760. */
  14761. IntersectionTests.rayPlane = function(ray, plane, result) {
  14762. if (!defined(ray)) {
  14763. throw new DeveloperError('ray is required.');
  14764. }
  14765. if (!defined(plane)) {
  14766. throw new DeveloperError('plane is required.');
  14767. }
  14768. if (!defined(result)) {
  14769. result = new Cartesian3();
  14770. }
  14771. var origin = ray.origin;
  14772. var direction = ray.direction;
  14773. var normal = plane.normal;
  14774. var denominator = Cartesian3.dot(normal, direction);
  14775. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  14776. // Ray is parallel to plane. The ray may be in the polygon's plane.
  14777. return undefined;
  14778. }
  14779. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  14780. if (t < 0) {
  14781. return undefined;
  14782. }
  14783. result = Cartesian3.multiplyByScalar(direction, t, result);
  14784. return Cartesian3.add(origin, result, result);
  14785. };
  14786. var scratchEdge0 = new Cartesian3();
  14787. var scratchEdge1 = new Cartesian3();
  14788. var scratchPVec = new Cartesian3();
  14789. var scratchTVec = new Cartesian3();
  14790. var scratchQVec = new Cartesian3();
  14791. /**
  14792. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  14793. *
  14794. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  14795. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  14796. *
  14797. * @memberof IntersectionTests
  14798. *
  14799. * @param {Ray} ray The ray.
  14800. * @param {Cartesian3} p0 The first vertex of the triangle.
  14801. * @param {Cartesian3} p1 The second vertex of the triangle.
  14802. * @param {Cartesian3} p2 The third vertex of the triangle.
  14803. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14804. * and return undefined for intersections with the back face.
  14805. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  14806. */
  14807. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  14808. if (!defined(ray)) {
  14809. throw new DeveloperError('ray is required.');
  14810. }
  14811. if (!defined(p0)) {
  14812. throw new DeveloperError('p0 is required.');
  14813. }
  14814. if (!defined(p1)) {
  14815. throw new DeveloperError('p1 is required.');
  14816. }
  14817. if (!defined(p2)) {
  14818. throw new DeveloperError('p2 is required.');
  14819. }
  14820. cullBackFaces = defaultValue(cullBackFaces, false);
  14821. var origin = ray.origin;
  14822. var direction = ray.direction;
  14823. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  14824. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  14825. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  14826. var det = Cartesian3.dot(edge0, p);
  14827. var tvec;
  14828. var q;
  14829. var u;
  14830. var v;
  14831. var t;
  14832. if (cullBackFaces) {
  14833. if (det < CesiumMath.EPSILON6) {
  14834. return undefined;
  14835. }
  14836. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  14837. u = Cartesian3.dot(tvec, p);
  14838. if (u < 0.0 || u > det) {
  14839. return undefined;
  14840. }
  14841. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  14842. v = Cartesian3.dot(direction, q);
  14843. if (v < 0.0 || u + v > det) {
  14844. return undefined;
  14845. }
  14846. t = Cartesian3.dot(edge1, q) / det;
  14847. } else {
  14848. if (Math.abs(det) < CesiumMath.EPSILON6) {
  14849. return undefined;
  14850. }
  14851. var invDet = 1.0 / det;
  14852. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  14853. u = Cartesian3.dot(tvec, p) * invDet;
  14854. if (u < 0.0 || u > 1.0) {
  14855. return undefined;
  14856. }
  14857. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  14858. v = Cartesian3.dot(direction, q) * invDet;
  14859. if (v < 0.0 || u + v > 1.0) {
  14860. return undefined;
  14861. }
  14862. t = Cartesian3.dot(edge1, q) * invDet;
  14863. }
  14864. return t;
  14865. };
  14866. /**
  14867. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  14868. *
  14869. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  14870. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  14871. *
  14872. * @memberof IntersectionTests
  14873. *
  14874. * @param {Ray} ray The ray.
  14875. * @param {Cartesian3} p0 The first vertex of the triangle.
  14876. * @param {Cartesian3} p1 The second vertex of the triangle.
  14877. * @param {Cartesian3} p2 The third vertex of the triangle.
  14878. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14879. * and return undefined for intersections with the back face.
  14880. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  14881. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14882. */
  14883. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  14884. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  14885. if (!defined(t) || t < 0.0) {
  14886. return undefined;
  14887. }
  14888. if (!defined(result)) {
  14889. result = new Cartesian3();
  14890. }
  14891. Cartesian3.multiplyByScalar(ray.direction, t, result);
  14892. return Cartesian3.add(ray.origin, result, result);
  14893. };
  14894. var scratchLineSegmentTriangleRay = new Ray();
  14895. /**
  14896. * Computes the intersection of a line segment and a triangle.
  14897. * @memberof IntersectionTests
  14898. *
  14899. * @param {Cartesian3} v0 The an end point of the line segment.
  14900. * @param {Cartesian3} v1 The other end point of the line segment.
  14901. * @param {Cartesian3} p0 The first vertex of the triangle.
  14902. * @param {Cartesian3} p1 The second vertex of the triangle.
  14903. * @param {Cartesian3} p2 The third vertex of the triangle.
  14904. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14905. * and return undefined for intersections with the back face.
  14906. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  14907. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14908. */
  14909. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  14910. if (!defined(v0)) {
  14911. throw new DeveloperError('v0 is required.');
  14912. }
  14913. if (!defined(v1)) {
  14914. throw new DeveloperError('v1 is required.');
  14915. }
  14916. if (!defined(p0)) {
  14917. throw new DeveloperError('p0 is required.');
  14918. }
  14919. if (!defined(p1)) {
  14920. throw new DeveloperError('p1 is required.');
  14921. }
  14922. if (!defined(p2)) {
  14923. throw new DeveloperError('p2 is required.');
  14924. }
  14925. var ray = scratchLineSegmentTriangleRay;
  14926. Cartesian3.clone(v0, ray.origin);
  14927. Cartesian3.subtract(v1, v0, ray.direction);
  14928. Cartesian3.normalize(ray.direction, ray.direction);
  14929. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  14930. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  14931. return undefined;
  14932. }
  14933. if (!defined(result)) {
  14934. result = new Cartesian3();
  14935. }
  14936. Cartesian3.multiplyByScalar(ray.direction, t, result);
  14937. return Cartesian3.add(ray.origin, result, result);
  14938. };
  14939. function solveQuadratic(a, b, c, result) {
  14940. var det = b * b - 4.0 * a * c;
  14941. if (det < 0.0) {
  14942. return undefined;
  14943. } else if (det > 0.0) {
  14944. var denom = 1.0 / (2.0 * a);
  14945. var disc = Math.sqrt(det);
  14946. var root0 = (-b + disc) * denom;
  14947. var root1 = (-b - disc) * denom;
  14948. if (root0 < root1) {
  14949. result.root0 = root0;
  14950. result.root1 = root1;
  14951. } else {
  14952. result.root0 = root1;
  14953. result.root1 = root0;
  14954. }
  14955. return result;
  14956. }
  14957. var root = -b / (2.0 * a);
  14958. if (root === 0.0) {
  14959. return undefined;
  14960. }
  14961. result.root0 = result.root1 = root;
  14962. return result;
  14963. }
  14964. var raySphereRoots = {
  14965. root0 : 0.0,
  14966. root1 : 0.0
  14967. };
  14968. function raySphere(ray, sphere, result) {
  14969. if (!defined(result)) {
  14970. result = {};
  14971. }
  14972. var origin = ray.origin;
  14973. var direction = ray.direction;
  14974. var center = sphere.center;
  14975. var radiusSquared = sphere.radius * sphere.radius;
  14976. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  14977. var a = Cartesian3.dot(direction, direction);
  14978. var b = 2.0 * Cartesian3.dot(direction, diff);
  14979. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  14980. var roots = solveQuadratic(a, b, c, raySphereRoots);
  14981. if (!defined(roots)) {
  14982. return undefined;
  14983. }
  14984. result.start = roots.root0;
  14985. result.stop = roots.root1;
  14986. return result;
  14987. }
  14988. /**
  14989. * Computes the intersection points of a ray with a sphere.
  14990. * @memberof IntersectionTests
  14991. *
  14992. * @param {Ray} ray The ray.
  14993. * @param {BoundingSphere} sphere The sphere.
  14994. * @param {Object} [result] The result onto which to store the result.
  14995. * @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.
  14996. */
  14997. IntersectionTests.raySphere = function(ray, sphere, result) {
  14998. if (!defined(ray)) {
  14999. throw new DeveloperError('ray is required.');
  15000. }
  15001. if (!defined(sphere)) {
  15002. throw new DeveloperError('sphere is required.');
  15003. }
  15004. result = raySphere(ray, sphere, result);
  15005. if (!defined(result) || result.stop < 0.0) {
  15006. return undefined;
  15007. }
  15008. result.start = Math.max(result.start, 0.0);
  15009. return result;
  15010. };
  15011. var scratchLineSegmentRay = new Ray();
  15012. /**
  15013. * Computes the intersection points of a line segment with a sphere.
  15014. * @memberof IntersectionTests
  15015. *
  15016. * @param {Cartesian3} p0 An end point of the line segment.
  15017. * @param {Cartesian3} p1 The other end point of the line segment.
  15018. * @param {BoundingSphere} sphere The sphere.
  15019. * @param {Object} [result] The result onto which to store the result.
  15020. * @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.
  15021. */
  15022. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  15023. if (!defined(p0)) {
  15024. throw new DeveloperError('p0 is required.');
  15025. }
  15026. if (!defined(p1)) {
  15027. throw new DeveloperError('p1 is required.');
  15028. }
  15029. if (!defined(sphere)) {
  15030. throw new DeveloperError('sphere is required.');
  15031. }
  15032. var ray = scratchLineSegmentRay;
  15033. Cartesian3.clone(p0, ray.origin);
  15034. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  15035. var maxT = Cartesian3.magnitude(direction);
  15036. Cartesian3.normalize(direction, direction);
  15037. result = raySphere(ray, sphere, result);
  15038. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  15039. return undefined;
  15040. }
  15041. result.start = Math.max(result.start, 0.0);
  15042. result.stop = Math.min(result.stop, maxT);
  15043. return result;
  15044. };
  15045. var scratchQ = new Cartesian3();
  15046. var scratchW = new Cartesian3();
  15047. /**
  15048. * Computes the intersection points of a ray with an ellipsoid.
  15049. *
  15050. * @param {Ray} ray The ray.
  15051. * @param {Ellipsoid} ellipsoid The ellipsoid.
  15052. * @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.
  15053. */
  15054. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  15055. if (!defined(ray)) {
  15056. throw new DeveloperError('ray is required.');
  15057. }
  15058. if (!defined(ellipsoid)) {
  15059. throw new DeveloperError('ellipsoid is required.');
  15060. }
  15061. var inverseRadii = ellipsoid.oneOverRadii;
  15062. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  15063. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  15064. var q2 = Cartesian3.magnitudeSquared(q);
  15065. var qw = Cartesian3.dot(q, w);
  15066. var difference, w2, product, discriminant, temp;
  15067. if (q2 > 1.0) {
  15068. // Outside ellipsoid.
  15069. if (qw >= 0.0) {
  15070. // Looking outward or tangent (0 intersections).
  15071. return undefined;
  15072. }
  15073. // qw < 0.0.
  15074. var qw2 = qw * qw;
  15075. difference = q2 - 1.0; // Positively valued.
  15076. w2 = Cartesian3.magnitudeSquared(w);
  15077. product = w2 * difference;
  15078. if (qw2 < product) {
  15079. // Imaginary roots (0 intersections).
  15080. return undefined;
  15081. } else if (qw2 > product) {
  15082. // Distinct roots (2 intersections).
  15083. discriminant = qw * qw - product;
  15084. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  15085. var root0 = temp / w2;
  15086. var root1 = difference / temp;
  15087. if (root0 < root1) {
  15088. return {
  15089. start : root0,
  15090. stop : root1
  15091. };
  15092. }
  15093. return {
  15094. start : root1,
  15095. stop : root0
  15096. };
  15097. } else {
  15098. // qw2 == product. Repeated roots (2 intersections).
  15099. var root = Math.sqrt(difference / w2);
  15100. return {
  15101. start : root,
  15102. stop : root
  15103. };
  15104. }
  15105. } else if (q2 < 1.0) {
  15106. // Inside ellipsoid (2 intersections).
  15107. difference = q2 - 1.0; // Negatively valued.
  15108. w2 = Cartesian3.magnitudeSquared(w);
  15109. product = w2 * difference; // Negatively valued.
  15110. discriminant = qw * qw - product;
  15111. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  15112. return {
  15113. start : 0.0,
  15114. stop : temp / w2
  15115. };
  15116. } else {
  15117. // q2 == 1.0. On ellipsoid.
  15118. if (qw < 0.0) {
  15119. // Looking inward.
  15120. w2 = Cartesian3.magnitudeSquared(w);
  15121. return {
  15122. start : 0.0,
  15123. stop : -qw / w2
  15124. };
  15125. }
  15126. // qw >= 0.0. Looking outward or tangent.
  15127. return undefined;
  15128. }
  15129. };
  15130. function addWithCancellationCheck(left, right, tolerance) {
  15131. var difference = left + right;
  15132. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  15133. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  15134. return 0.0;
  15135. }
  15136. return difference;
  15137. }
  15138. function quadraticVectorExpression(A, b, c, x, w) {
  15139. var xSquared = x * x;
  15140. var wSquared = w * w;
  15141. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  15142. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  15143. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  15144. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  15145. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  15146. var cosines;
  15147. var solutions = [];
  15148. if (r0 === 0.0 && r1 === 0.0) {
  15149. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  15150. if (cosines.length === 0) {
  15151. return solutions;
  15152. }
  15153. var cosine0 = cosines[0];
  15154. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  15155. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  15156. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  15157. if (cosines.length === 2) {
  15158. var cosine1 = cosines[1];
  15159. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  15160. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  15161. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  15162. }
  15163. return solutions;
  15164. }
  15165. var r0Squared = r0 * r0;
  15166. var r1Squared = r1 * r1;
  15167. var l2Squared = l2 * l2;
  15168. var r0r1 = r0 * r1;
  15169. var c4 = l2Squared + r1Squared;
  15170. var c3 = 2.0 * (l1 * l2 + r0r1);
  15171. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  15172. var c1 = 2.0 * (l0 * l1 - r0r1);
  15173. var c0 = l0 * l0 - r0Squared;
  15174. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  15175. return solutions;
  15176. }
  15177. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  15178. var length = cosines.length;
  15179. if (length === 0) {
  15180. return solutions;
  15181. }
  15182. for ( var i = 0; i < length; ++i) {
  15183. var cosine = cosines[i];
  15184. var cosineSquared = cosine * cosine;
  15185. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  15186. var sine = Math.sqrt(sineSquared);
  15187. //var left = l2 * cosineSquared + l1 * cosine + l0;
  15188. var left;
  15189. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  15190. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  15191. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  15192. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  15193. } else {
  15194. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  15195. }
  15196. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  15197. var product = left * right;
  15198. if (product < 0.0) {
  15199. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15200. } else if (product > 0.0) {
  15201. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  15202. } else if (sine !== 0.0) {
  15203. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  15204. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15205. ++i;
  15206. } else {
  15207. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15208. }
  15209. }
  15210. return solutions;
  15211. }
  15212. var firstAxisScratch = new Cartesian3();
  15213. var secondAxisScratch = new Cartesian3();
  15214. var thirdAxisScratch = new Cartesian3();
  15215. var referenceScratch = new Cartesian3();
  15216. var bCart = new Cartesian3();
  15217. var bScratch = new Matrix3();
  15218. var btScratch = new Matrix3();
  15219. var diScratch = new Matrix3();
  15220. var dScratch = new Matrix3();
  15221. var cScratch = new Matrix3();
  15222. var tempMatrix = new Matrix3();
  15223. var aScratch = new Matrix3();
  15224. var sScratch = new Cartesian3();
  15225. var closestScratch = new Cartesian3();
  15226. var surfPointScratch = new Cartographic();
  15227. /**
  15228. * Provides the point along the ray which is nearest to the ellipsoid.
  15229. *
  15230. * @param {Ray} ray The ray.
  15231. * @param {Ellipsoid} ellipsoid The ellipsoid.
  15232. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  15233. */
  15234. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  15235. if (!defined(ray)) {
  15236. throw new DeveloperError('ray is required.');
  15237. }
  15238. if (!defined(ellipsoid)) {
  15239. throw new DeveloperError('ellipsoid is required.');
  15240. }
  15241. var position = ray.origin;
  15242. var direction = ray.direction;
  15243. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  15244. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  15245. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  15246. return position;
  15247. }
  15248. }
  15249. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  15250. // Compute the scaled direction vector.
  15251. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  15252. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  15253. var firstAxis = Cartesian3.normalize(f, f);
  15254. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  15255. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  15256. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  15257. var B = bScratch;
  15258. B[0] = firstAxis.x;
  15259. B[1] = firstAxis.y;
  15260. B[2] = firstAxis.z;
  15261. B[3] = secondAxis.x;
  15262. B[4] = secondAxis.y;
  15263. B[5] = secondAxis.z;
  15264. B[6] = thirdAxis.x;
  15265. B[7] = thirdAxis.y;
  15266. B[8] = thirdAxis.z;
  15267. var B_T = Matrix3.transpose(B, btScratch);
  15268. // Get the scaling matrix and its inverse.
  15269. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  15270. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  15271. var C = cScratch;
  15272. C[0] = 0.0;
  15273. C[1] = -direction.z;
  15274. C[2] = direction.y;
  15275. C[3] = direction.z;
  15276. C[4] = 0.0;
  15277. C[5] = -direction.x;
  15278. C[6] = -direction.y;
  15279. C[7] = direction.x;
  15280. C[8] = 0.0;
  15281. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  15282. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  15283. var b = Matrix3.multiplyByVector(temp, position, bCart);
  15284. // Solve for the solutions to the expression in standard form:
  15285. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  15286. var s;
  15287. var altitude;
  15288. var length = solutions.length;
  15289. if (length > 0) {
  15290. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  15291. var maximumValue = Number.NEGATIVE_INFINITY;
  15292. for ( var i = 0; i < length; ++i) {
  15293. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  15294. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  15295. var dotProduct = Cartesian3.dot(v, direction);
  15296. if (dotProduct > maximumValue) {
  15297. maximumValue = dotProduct;
  15298. closest = Cartesian3.clone(s, closest);
  15299. }
  15300. }
  15301. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  15302. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  15303. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  15304. altitude = intersects ? -altitude : altitude;
  15305. surfacePoint.height = altitude;
  15306. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  15307. }
  15308. return undefined;
  15309. };
  15310. var lineSegmentPlaneDifference = new Cartesian3();
  15311. /**
  15312. * Computes the intersection of a line segment and a plane.
  15313. *
  15314. * @param {Cartesian3} endPoint0 An end point of the line segment.
  15315. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  15316. * @param {Plane} plane The plane.
  15317. * @param {Cartesian3} [result] The object onto which to store the result.
  15318. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  15319. *
  15320. * @example
  15321. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  15322. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  15323. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  15324. *
  15325. * var p0 = new Cesium.Cartesian3(...);
  15326. * var p1 = new Cesium.Cartesian3(...);
  15327. *
  15328. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  15329. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  15330. */
  15331. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  15332. if (!defined(endPoint0)) {
  15333. throw new DeveloperError('endPoint0 is required.');
  15334. }
  15335. if (!defined(endPoint1)) {
  15336. throw new DeveloperError('endPoint1 is required.');
  15337. }
  15338. if (!defined(plane)) {
  15339. throw new DeveloperError('plane is required.');
  15340. }
  15341. if (!defined(result)) {
  15342. result = new Cartesian3();
  15343. }
  15344. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  15345. var normal = plane.normal;
  15346. var nDotDiff = Cartesian3.dot(normal, difference);
  15347. // check if the segment and plane are parallel
  15348. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  15349. return undefined;
  15350. }
  15351. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  15352. var t = -(plane.distance + nDotP0) / nDotDiff;
  15353. // intersection only if t is in [0, 1]
  15354. if (t < 0.0 || t > 1.0) {
  15355. return undefined;
  15356. }
  15357. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  15358. Cartesian3.multiplyByScalar(difference, t, result);
  15359. Cartesian3.add(endPoint0, result, result);
  15360. return result;
  15361. };
  15362. /**
  15363. * Computes the intersection of a triangle and a plane
  15364. *
  15365. * @param {Cartesian3} p0 First point of the triangle
  15366. * @param {Cartesian3} p1 Second point of the triangle
  15367. * @param {Cartesian3} p2 Third point of the triangle
  15368. * @param {Plane} plane Intersection plane
  15369. * @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)
  15370. *
  15371. * @example
  15372. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  15373. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  15374. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  15375. *
  15376. * var p0 = new Cesium.Cartesian3(...);
  15377. * var p1 = new Cesium.Cartesian3(...);
  15378. * var p2 = new Cesium.Cartesian3(...);
  15379. *
  15380. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  15381. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  15382. */
  15383. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  15384. if ((!defined(p0)) ||
  15385. (!defined(p1)) ||
  15386. (!defined(p2)) ||
  15387. (!defined(plane))) {
  15388. throw new DeveloperError('p0, p1, p2, and plane are required.');
  15389. }
  15390. var planeNormal = plane.normal;
  15391. var planeD = plane.distance;
  15392. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  15393. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  15394. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  15395. // Given these dots products, the calls to lineSegmentPlaneIntersection
  15396. // always have defined results.
  15397. var numBehind = 0;
  15398. numBehind += p0Behind ? 1 : 0;
  15399. numBehind += p1Behind ? 1 : 0;
  15400. numBehind += p2Behind ? 1 : 0;
  15401. var u1, u2;
  15402. if (numBehind === 1 || numBehind === 2) {
  15403. u1 = new Cartesian3();
  15404. u2 = new Cartesian3();
  15405. }
  15406. if (numBehind === 1) {
  15407. if (p0Behind) {
  15408. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  15409. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  15410. return {
  15411. positions : [p0, p1, p2, u1, u2 ],
  15412. indices : [
  15413. // Behind
  15414. 0, 3, 4,
  15415. // In front
  15416. 1, 2, 4,
  15417. 1, 4, 3
  15418. ]
  15419. };
  15420. } else if (p1Behind) {
  15421. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  15422. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  15423. return {
  15424. positions : [p0, p1, p2, u1, u2 ],
  15425. indices : [
  15426. // Behind
  15427. 1, 3, 4,
  15428. // In front
  15429. 2, 0, 4,
  15430. 2, 4, 3
  15431. ]
  15432. };
  15433. } else if (p2Behind) {
  15434. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  15435. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  15436. return {
  15437. positions : [p0, p1, p2, u1, u2 ],
  15438. indices : [
  15439. // Behind
  15440. 2, 3, 4,
  15441. // In front
  15442. 0, 1, 4,
  15443. 0, 4, 3
  15444. ]
  15445. };
  15446. }
  15447. } else if (numBehind === 2) {
  15448. if (!p0Behind) {
  15449. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  15450. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  15451. return {
  15452. positions : [p0, p1, p2, u1, u2 ],
  15453. indices : [
  15454. // Behind
  15455. 1, 2, 4,
  15456. 1, 4, 3,
  15457. // In front
  15458. 0, 3, 4
  15459. ]
  15460. };
  15461. } else if (!p1Behind) {
  15462. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  15463. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  15464. return {
  15465. positions : [p0, p1, p2, u1, u2 ],
  15466. indices : [
  15467. // Behind
  15468. 2, 0, 4,
  15469. 2, 4, 3,
  15470. // In front
  15471. 1, 3, 4
  15472. ]
  15473. };
  15474. } else if (!p2Behind) {
  15475. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  15476. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  15477. return {
  15478. positions : [p0, p1, p2, u1, u2 ],
  15479. indices : [
  15480. // Behind
  15481. 0, 1, 4,
  15482. 0, 4, 3,
  15483. // In front
  15484. 2, 3, 4
  15485. ]
  15486. };
  15487. }
  15488. }
  15489. // if numBehind is 3, the triangle is completely behind the plane;
  15490. // otherwise, it is completely in front (numBehind is 0).
  15491. return undefined;
  15492. };
  15493. return IntersectionTests;
  15494. });
  15495. /*global define*/
  15496. define('Core/Plane',[
  15497. './Cartesian3',
  15498. './defined',
  15499. './DeveloperError',
  15500. './freezeObject'
  15501. ], function(
  15502. Cartesian3,
  15503. defined,
  15504. DeveloperError,
  15505. freezeObject) {
  15506. 'use strict';
  15507. /**
  15508. * A plane in Hessian Normal Form defined by
  15509. * <pre>
  15510. * ax + by + cz + d = 0
  15511. * </pre>
  15512. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  15513. * <code>distance</code> to the plane, and (x, y, z) is any point on
  15514. * the plane.
  15515. *
  15516. * @alias Plane
  15517. * @constructor
  15518. *
  15519. * @param {Cartesian3} normal The plane's normal (normalized).
  15520. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  15521. * <code>distance</code> determines which side of the plane the origin
  15522. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15523. * in the direction of the normal; if negative, the origin is in the half-space
  15524. * opposite to the normal; if zero, the plane passes through the origin.
  15525. *
  15526. * @example
  15527. * // The plane x=0
  15528. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  15529. */
  15530. function Plane(normal, distance) {
  15531. if (!defined(normal)) {
  15532. throw new DeveloperError('normal is required.');
  15533. }
  15534. if (!defined(distance)) {
  15535. throw new DeveloperError('distance is required.');
  15536. }
  15537. /**
  15538. * The plane's normal.
  15539. *
  15540. * @type {Cartesian3}
  15541. */
  15542. this.normal = Cartesian3.clone(normal);
  15543. /**
  15544. * The shortest distance from the origin to the plane. The sign of
  15545. * <code>distance</code> determines which side of the plane the origin
  15546. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15547. * in the direction of the normal; if negative, the origin is in the half-space
  15548. * opposite to the normal; if zero, the plane passes through the origin.
  15549. *
  15550. * @type {Number}
  15551. */
  15552. this.distance = distance;
  15553. }
  15554. /**
  15555. * Creates a plane from a normal and a point on the plane.
  15556. *
  15557. * @param {Cartesian3} point The point on the plane.
  15558. * @param {Cartesian3} normal The plane's normal (normalized).
  15559. * @param {Plane} [result] The object onto which to store the result.
  15560. * @returns {Plane} A new plane instance or the modified result parameter.
  15561. *
  15562. * @example
  15563. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  15564. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  15565. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  15566. */
  15567. Plane.fromPointNormal = function(point, normal, result) {
  15568. if (!defined(point)) {
  15569. throw new DeveloperError('point is required.');
  15570. }
  15571. if (!defined(normal)) {
  15572. throw new DeveloperError('normal is required.');
  15573. }
  15574. var distance = -Cartesian3.dot(normal, point);
  15575. if (!defined(result)) {
  15576. return new Plane(normal, distance);
  15577. }
  15578. Cartesian3.clone(normal, result.normal);
  15579. result.distance = distance;
  15580. return result;
  15581. };
  15582. var scratchNormal = new Cartesian3();
  15583. /**
  15584. * Creates a plane from the general equation
  15585. *
  15586. * @param {Cartesian4} coefficients The plane's normal (normalized).
  15587. * @param {Plane} [result] The object onto which to store the result.
  15588. * @returns {Plane} A new plane instance or the modified result parameter.
  15589. */
  15590. Plane.fromCartesian4 = function(coefficients, result) {
  15591. if (!defined(coefficients)) {
  15592. throw new DeveloperError('coefficients is required.');
  15593. }
  15594. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  15595. var distance = coefficients.w;
  15596. if (!defined(result)) {
  15597. return new Plane(normal, distance);
  15598. } else {
  15599. Cartesian3.clone(normal, result.normal);
  15600. result.distance = distance;
  15601. return result;
  15602. }
  15603. };
  15604. /**
  15605. * Computes the signed shortest distance of a point to a plane.
  15606. * The sign of the distance determines which side of the plane the point
  15607. * is on. If the distance is positive, the point is in the half-space
  15608. * in the direction of the normal; if negative, the point is in the half-space
  15609. * opposite to the normal; if zero, the plane passes through the point.
  15610. *
  15611. * @param {Plane} plane The plane.
  15612. * @param {Cartesian3} point The point.
  15613. * @returns {Number} The signed shortest distance of the point to the plane.
  15614. */
  15615. Plane.getPointDistance = function(plane, point) {
  15616. if (!defined(plane)) {
  15617. throw new DeveloperError('plane is required.');
  15618. }
  15619. if (!defined(point)) {
  15620. throw new DeveloperError('point is required.');
  15621. }
  15622. return Cartesian3.dot(plane.normal, point) + plane.distance;
  15623. };
  15624. /**
  15625. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  15626. *
  15627. * @type {Plane}
  15628. * @constant
  15629. */
  15630. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  15631. /**
  15632. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  15633. *
  15634. * @type {Plane}
  15635. * @constant
  15636. */
  15637. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  15638. /**
  15639. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  15640. *
  15641. * @type {Plane}
  15642. * @constant
  15643. */
  15644. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  15645. return Plane;
  15646. });
  15647. /**
  15648. @license
  15649. when.js - https://github.com/cujojs/when
  15650. MIT License (c) copyright B Cavalier & J Hann
  15651. * A lightweight CommonJS Promises/A and when() implementation
  15652. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  15653. *
  15654. * Licensed under the MIT License at:
  15655. * http://www.opensource.org/licenses/mit-license.php
  15656. *
  15657. * @version 1.7.1
  15658. */
  15659. (function(define) { 'use strict';
  15660. define('ThirdParty/when',[],function () {
  15661. var reduceArray, slice, undef;
  15662. //
  15663. // Public API
  15664. //
  15665. when.defer = defer; // Create a deferred
  15666. when.resolve = resolve; // Create a resolved promise
  15667. when.reject = reject; // Create a rejected promise
  15668. when.join = join; // Join 2 or more promises
  15669. when.all = all; // Resolve a list of promises
  15670. when.map = map; // Array.map() for promises
  15671. when.reduce = reduce; // Array.reduce() for promises
  15672. when.any = any; // One-winner race
  15673. when.some = some; // Multi-winner race
  15674. when.chain = chain; // Make a promise trigger another resolver
  15675. when.isPromise = isPromise; // Determine if a thing is a promise
  15676. /**
  15677. * Register an observer for a promise or immediate value.
  15678. *
  15679. * @param {*} promiseOrValue
  15680. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  15681. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  15682. * will be invoked immediately.
  15683. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  15684. * rejected.
  15685. * @param {function?} [onProgress] callback to be called when progress updates
  15686. * are issued for promiseOrValue.
  15687. * @returns {Promise} a new {@link Promise} that will complete with the return
  15688. * value of callback or errback or the completion value of promiseOrValue if
  15689. * callback and/or errback is not supplied.
  15690. */
  15691. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  15692. // Get a trusted promise for the input promiseOrValue, and then
  15693. // register promise handlers
  15694. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  15695. }
  15696. /**
  15697. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  15698. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  15699. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  15700. *
  15701. * @param {*} promiseOrValue
  15702. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  15703. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  15704. * whose resolution value is:
  15705. * * the resolution value of promiseOrValue if it's a foreign promise, or
  15706. * * promiseOrValue if it's a value
  15707. */
  15708. function resolve(promiseOrValue) {
  15709. var promise, deferred;
  15710. if(promiseOrValue instanceof Promise) {
  15711. // It's a when.js promise, so we trust it
  15712. promise = promiseOrValue;
  15713. } else {
  15714. // It's not a when.js promise. See if it's a foreign promise or a value.
  15715. if(isPromise(promiseOrValue)) {
  15716. // It's a thenable, but we don't know where it came from, so don't trust
  15717. // its implementation entirely. Introduce a trusted middleman when.js promise
  15718. deferred = defer();
  15719. // IMPORTANT: This is the only place when.js should ever call .then() on an
  15720. // untrusted promise. Don't expose the return value to the untrusted promise
  15721. promiseOrValue.then(
  15722. function(value) { deferred.resolve(value); },
  15723. function(reason) { deferred.reject(reason); },
  15724. function(update) { deferred.progress(update); }
  15725. );
  15726. promise = deferred.promise;
  15727. } else {
  15728. // It's a value, not a promise. Create a resolved promise for it.
  15729. promise = fulfilled(promiseOrValue);
  15730. }
  15731. }
  15732. return promise;
  15733. }
  15734. /**
  15735. * Returns a rejected promise for the supplied promiseOrValue. The returned
  15736. * promise will be rejected with:
  15737. * - promiseOrValue, if it is a value, or
  15738. * - if promiseOrValue is a promise
  15739. * - promiseOrValue's value after it is fulfilled
  15740. * - promiseOrValue's reason after it is rejected
  15741. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  15742. * @returns {Promise} rejected {@link Promise}
  15743. */
  15744. function reject(promiseOrValue) {
  15745. return when(promiseOrValue, rejected);
  15746. }
  15747. /**
  15748. * Trusted Promise constructor. A Promise created from this constructor is
  15749. * a trusted when.js promise. Any other duck-typed promise is considered
  15750. * untrusted.
  15751. * @constructor
  15752. * @name Promise
  15753. */
  15754. function Promise(then) {
  15755. this.then = then;
  15756. }
  15757. Promise.prototype = {
  15758. /**
  15759. * Register a callback that will be called when a promise is
  15760. * fulfilled or rejected. Optionally also register a progress handler.
  15761. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  15762. * @param {function?} [onFulfilledOrRejected]
  15763. * @param {function?} [onProgress]
  15764. * @returns {Promise}
  15765. */
  15766. always: function(onFulfilledOrRejected, onProgress) {
  15767. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  15768. },
  15769. /**
  15770. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  15771. * @param {function?} onRejected
  15772. * @returns {Promise}
  15773. */
  15774. otherwise: function(onRejected) {
  15775. return this.then(undef, onRejected);
  15776. },
  15777. /**
  15778. * Shortcut for .then(function() { return value; })
  15779. * @param {*} value
  15780. * @returns {Promise} a promise that:
  15781. * - is fulfilled if value is not a promise, or
  15782. * - if value is a promise, will fulfill with its value, or reject
  15783. * with its reason.
  15784. */
  15785. yield: function(value) {
  15786. return this.then(function() {
  15787. return value;
  15788. });
  15789. },
  15790. /**
  15791. * Assumes that this promise will fulfill with an array, and arranges
  15792. * for the onFulfilled to be called with the array as its argument list
  15793. * i.e. onFulfilled.spread(undefined, array).
  15794. * @param {function} onFulfilled function to receive spread arguments
  15795. * @returns {Promise}
  15796. */
  15797. spread: function(onFulfilled) {
  15798. return this.then(function(array) {
  15799. // array may contain promises, so resolve its contents.
  15800. return all(array, function(array) {
  15801. return onFulfilled.apply(undef, array);
  15802. });
  15803. });
  15804. }
  15805. };
  15806. /**
  15807. * Create an already-resolved promise for the supplied value
  15808. * @private
  15809. *
  15810. * @param {*} value
  15811. * @returns {Promise} fulfilled promise
  15812. */
  15813. function fulfilled(value) {
  15814. var p = new Promise(function(onFulfilled) {
  15815. // TODO: Promises/A+ check typeof onFulfilled
  15816. try {
  15817. return resolve(onFulfilled ? onFulfilled(value) : value);
  15818. } catch(e) {
  15819. return rejected(e);
  15820. }
  15821. });
  15822. return p;
  15823. }
  15824. /**
  15825. * Create an already-rejected {@link Promise} with the supplied
  15826. * rejection reason.
  15827. * @private
  15828. *
  15829. * @param {*} reason
  15830. * @returns {Promise} rejected promise
  15831. */
  15832. function rejected(reason) {
  15833. var p = new Promise(function(_, onRejected) {
  15834. // TODO: Promises/A+ check typeof onRejected
  15835. try {
  15836. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  15837. } catch(e) {
  15838. return rejected(e);
  15839. }
  15840. });
  15841. return p;
  15842. }
  15843. /**
  15844. * Creates a new, Deferred with fully isolated resolver and promise parts,
  15845. * either or both of which may be given out safely to consumers.
  15846. * The Deferred itself has the full API: resolve, reject, progress, and
  15847. * then. The resolver has resolve, reject, and progress. The promise
  15848. * only has then.
  15849. *
  15850. * @returns {Deferred}
  15851. */
  15852. function defer() {
  15853. var deferred, promise, handlers, progressHandlers,
  15854. _then, _progress, _resolve;
  15855. /**
  15856. * The promise for the new deferred
  15857. * @type {Promise}
  15858. */
  15859. promise = new Promise(then);
  15860. /**
  15861. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  15862. * @class Deferred
  15863. * @name Deferred
  15864. */
  15865. deferred = {
  15866. then: then, // DEPRECATED: use deferred.promise.then
  15867. resolve: promiseResolve,
  15868. reject: promiseReject,
  15869. // TODO: Consider renaming progress() to notify()
  15870. progress: promiseProgress,
  15871. promise: promise,
  15872. resolver: {
  15873. resolve: promiseResolve,
  15874. reject: promiseReject,
  15875. progress: promiseProgress
  15876. }
  15877. };
  15878. handlers = [];
  15879. progressHandlers = [];
  15880. /**
  15881. * Pre-resolution then() that adds the supplied callback, errback, and progback
  15882. * functions to the registered listeners
  15883. * @private
  15884. *
  15885. * @param {function?} [onFulfilled] resolution handler
  15886. * @param {function?} [onRejected] rejection handler
  15887. * @param {function?} [onProgress] progress handler
  15888. */
  15889. _then = function(onFulfilled, onRejected, onProgress) {
  15890. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  15891. var deferred, progressHandler;
  15892. deferred = defer();
  15893. progressHandler = typeof onProgress === 'function'
  15894. ? function(update) {
  15895. try {
  15896. // Allow progress handler to transform progress event
  15897. deferred.progress(onProgress(update));
  15898. } catch(e) {
  15899. // Use caught value as progress
  15900. deferred.progress(e);
  15901. }
  15902. }
  15903. : function(update) { deferred.progress(update); };
  15904. handlers.push(function(promise) {
  15905. promise.then(onFulfilled, onRejected)
  15906. .then(deferred.resolve, deferred.reject, progressHandler);
  15907. });
  15908. progressHandlers.push(progressHandler);
  15909. return deferred.promise;
  15910. };
  15911. /**
  15912. * Issue a progress event, notifying all progress listeners
  15913. * @private
  15914. * @param {*} update progress event payload to pass to all listeners
  15915. */
  15916. _progress = function(update) {
  15917. processQueue(progressHandlers, update);
  15918. return update;
  15919. };
  15920. /**
  15921. * Transition from pre-resolution state to post-resolution state, notifying
  15922. * all listeners of the resolution or rejection
  15923. * @private
  15924. * @param {*} value the value of this deferred
  15925. */
  15926. _resolve = function(value) {
  15927. value = resolve(value);
  15928. // Replace _then with one that directly notifies with the result.
  15929. _then = value.then;
  15930. // Replace _resolve so that this Deferred can only be resolved once
  15931. _resolve = resolve;
  15932. // Make _progress a noop, to disallow progress for the resolved promise.
  15933. _progress = noop;
  15934. // Notify handlers
  15935. processQueue(handlers, value);
  15936. // Free progressHandlers array since we'll never issue progress events
  15937. progressHandlers = handlers = undef;
  15938. return value;
  15939. };
  15940. return deferred;
  15941. /**
  15942. * Wrapper to allow _then to be replaced safely
  15943. * @param {function?} [onFulfilled] resolution handler
  15944. * @param {function?} [onRejected] rejection handler
  15945. * @param {function?} [onProgress] progress handler
  15946. * @returns {Promise} new promise
  15947. */
  15948. function then(onFulfilled, onRejected, onProgress) {
  15949. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  15950. return _then(onFulfilled, onRejected, onProgress);
  15951. }
  15952. /**
  15953. * Wrapper to allow _resolve to be replaced
  15954. */
  15955. function promiseResolve(val) {
  15956. return _resolve(val);
  15957. }
  15958. /**
  15959. * Wrapper to allow _reject to be replaced
  15960. */
  15961. function promiseReject(err) {
  15962. return _resolve(rejected(err));
  15963. }
  15964. /**
  15965. * Wrapper to allow _progress to be replaced
  15966. */
  15967. function promiseProgress(update) {
  15968. return _progress(update);
  15969. }
  15970. }
  15971. /**
  15972. * Determines if promiseOrValue is a promise or not. Uses the feature
  15973. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  15974. * promiseOrValue is a promise.
  15975. *
  15976. * @param {*} promiseOrValue anything
  15977. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  15978. */
  15979. function isPromise(promiseOrValue) {
  15980. return promiseOrValue && typeof promiseOrValue.then === 'function';
  15981. }
  15982. /**
  15983. * Initiates a competitive race, returning a promise that will resolve when
  15984. * howMany of the supplied promisesOrValues have resolved, or will reject when
  15985. * it becomes impossible for howMany to resolve, for example, when
  15986. * (promisesOrValues.length - howMany) + 1 input promises reject.
  15987. *
  15988. * @param {Array} promisesOrValues array of anything, may contain a mix
  15989. * of promises and values
  15990. * @param howMany {number} number of promisesOrValues to resolve
  15991. * @param {function?} [onFulfilled] resolution handler
  15992. * @param {function?} [onRejected] rejection handler
  15993. * @param {function?} [onProgress] progress handler
  15994. * @returns {Promise} promise that will resolve to an array of howMany values that
  15995. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  15996. * rejection reasons.
  15997. */
  15998. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  15999. checkCallbacks(2, arguments);
  16000. return when(promisesOrValues, function(promisesOrValues) {
  16001. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  16002. len = promisesOrValues.length >>> 0;
  16003. toResolve = Math.max(0, Math.min(howMany, len));
  16004. values = [];
  16005. toReject = (len - toResolve) + 1;
  16006. reasons = [];
  16007. deferred = defer();
  16008. // No items in the input, resolve immediately
  16009. if (!toResolve) {
  16010. deferred.resolve(values);
  16011. } else {
  16012. progress = deferred.progress;
  16013. rejectOne = function(reason) {
  16014. reasons.push(reason);
  16015. if(!--toReject) {
  16016. fulfillOne = rejectOne = noop;
  16017. deferred.reject(reasons);
  16018. }
  16019. };
  16020. fulfillOne = function(val) {
  16021. // This orders the values based on promise resolution order
  16022. // Another strategy would be to use the original position of
  16023. // the corresponding promise.
  16024. values.push(val);
  16025. if (!--toResolve) {
  16026. fulfillOne = rejectOne = noop;
  16027. deferred.resolve(values);
  16028. }
  16029. };
  16030. for(i = 0; i < len; ++i) {
  16031. if(i in promisesOrValues) {
  16032. when(promisesOrValues[i], fulfiller, rejecter, progress);
  16033. }
  16034. }
  16035. }
  16036. return deferred.then(onFulfilled, onRejected, onProgress);
  16037. function rejecter(reason) {
  16038. rejectOne(reason);
  16039. }
  16040. function fulfiller(val) {
  16041. fulfillOne(val);
  16042. }
  16043. });
  16044. }
  16045. /**
  16046. * Initiates a competitive race, returning a promise that will resolve when
  16047. * any one of the supplied promisesOrValues has resolved or will reject when
  16048. * *all* promisesOrValues have rejected.
  16049. *
  16050. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  16051. * of {@link Promise}s and values
  16052. * @param {function?} [onFulfilled] resolution handler
  16053. * @param {function?} [onRejected] rejection handler
  16054. * @param {function?} [onProgress] progress handler
  16055. * @returns {Promise} promise that will resolve to the value that resolved first, or
  16056. * will reject with an array of all rejected inputs.
  16057. */
  16058. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  16059. function unwrapSingleResult(val) {
  16060. return onFulfilled ? onFulfilled(val[0]) : val[0];
  16061. }
  16062. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  16063. }
  16064. /**
  16065. * Return a promise that will resolve only once all the supplied promisesOrValues
  16066. * have resolved. The resolution value of the returned promise will be an array
  16067. * containing the resolution values of each of the promisesOrValues.
  16068. * @memberOf when
  16069. *
  16070. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  16071. * of {@link Promise}s and values
  16072. * @param {function?} [onFulfilled] resolution handler
  16073. * @param {function?} [onRejected] rejection handler
  16074. * @param {function?} [onProgress] progress handler
  16075. * @returns {Promise}
  16076. */
  16077. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  16078. checkCallbacks(1, arguments);
  16079. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  16080. }
  16081. /**
  16082. * Joins multiple promises into a single returned promise.
  16083. * @returns {Promise} a promise that will fulfill when *all* the input promises
  16084. * have fulfilled, or will reject when *any one* of the input promises rejects.
  16085. */
  16086. function join(/* ...promises */) {
  16087. return map(arguments, identity);
  16088. }
  16089. /**
  16090. * Traditional map function, similar to `Array.prototype.map()`, but allows
  16091. * input to contain {@link Promise}s and/or values, and mapFunc may return
  16092. * either a value or a {@link Promise}
  16093. *
  16094. * @param {Array|Promise} promise array of anything, may contain a mix
  16095. * of {@link Promise}s and values
  16096. * @param {function} mapFunc mapping function mapFunc(value) which may return
  16097. * either a {@link Promise} or value
  16098. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  16099. * the mapped output values.
  16100. */
  16101. function map(promise, mapFunc) {
  16102. return when(promise, function(array) {
  16103. var results, len, toResolve, resolve, i, d;
  16104. // Since we know the resulting length, we can preallocate the results
  16105. // array to avoid array expansions.
  16106. toResolve = len = array.length >>> 0;
  16107. results = [];
  16108. d = defer();
  16109. if(!toResolve) {
  16110. d.resolve(results);
  16111. } else {
  16112. resolve = function resolveOne(item, i) {
  16113. when(item, mapFunc).then(function(mapped) {
  16114. results[i] = mapped;
  16115. if(!--toResolve) {
  16116. d.resolve(results);
  16117. }
  16118. }, d.reject);
  16119. };
  16120. // Since mapFunc may be async, get all invocations of it into flight
  16121. for(i = 0; i < len; i++) {
  16122. if(i in array) {
  16123. resolve(array[i], i);
  16124. } else {
  16125. --toResolve;
  16126. }
  16127. }
  16128. }
  16129. return d.promise;
  16130. });
  16131. }
  16132. /**
  16133. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  16134. * input may contain promises and/or values, and reduceFunc
  16135. * may return either a value or a promise, *and* initialValue may
  16136. * be a promise for the starting value.
  16137. *
  16138. * @param {Array|Promise} promise array or promise for an array of anything,
  16139. * may contain a mix of promises and values.
  16140. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  16141. * where total is the total number of items being reduced, and will be the same
  16142. * in each call to reduceFunc.
  16143. * @returns {Promise} that will resolve to the final reduced value
  16144. */
  16145. function reduce(promise, reduceFunc /*, initialValue */) {
  16146. var args = slice.call(arguments, 1);
  16147. return when(promise, function(array) {
  16148. var total;
  16149. total = array.length;
  16150. // Wrap the supplied reduceFunc with one that handles promises and then
  16151. // delegates to the supplied.
  16152. args[0] = function (current, val, i) {
  16153. return when(current, function (c) {
  16154. return when(val, function (value) {
  16155. return reduceFunc(c, value, i, total);
  16156. });
  16157. });
  16158. };
  16159. return reduceArray.apply(array, args);
  16160. });
  16161. }
  16162. /**
  16163. * Ensure that resolution of promiseOrValue will trigger resolver with the
  16164. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  16165. *
  16166. * @param promiseOrValue
  16167. * @param {Object} resolver
  16168. * @param {function} resolver.resolve
  16169. * @param {function} resolver.reject
  16170. * @param {*} [resolveValue]
  16171. * @returns {Promise}
  16172. */
  16173. function chain(promiseOrValue, resolver, resolveValue) {
  16174. var useResolveValue = arguments.length > 2;
  16175. return when(promiseOrValue,
  16176. function(val) {
  16177. val = useResolveValue ? resolveValue : val;
  16178. resolver.resolve(val);
  16179. return val;
  16180. },
  16181. function(reason) {
  16182. resolver.reject(reason);
  16183. return rejected(reason);
  16184. },
  16185. resolver.progress
  16186. );
  16187. }
  16188. //
  16189. // Utility functions
  16190. //
  16191. /**
  16192. * Apply all functions in queue to value
  16193. * @param {Array} queue array of functions to execute
  16194. * @param {*} value argument passed to each function
  16195. */
  16196. function processQueue(queue, value) {
  16197. var handler, i = 0;
  16198. while (handler = queue[i++]) {
  16199. handler(value);
  16200. }
  16201. }
  16202. /**
  16203. * Helper that checks arrayOfCallbacks to ensure that each element is either
  16204. * a function, or null or undefined.
  16205. * @private
  16206. * @param {number} start index at which to start checking items in arrayOfCallbacks
  16207. * @param {Array} arrayOfCallbacks array to check
  16208. * @throws {Error} if any element of arrayOfCallbacks is something other than
  16209. * a functions, null, or undefined.
  16210. */
  16211. function checkCallbacks(start, arrayOfCallbacks) {
  16212. // TODO: Promises/A+ update type checking and docs
  16213. var arg, i = arrayOfCallbacks.length;
  16214. while(i > start) {
  16215. arg = arrayOfCallbacks[--i];
  16216. if (arg != null && typeof arg != 'function') {
  16217. throw new Error('arg '+i+' must be a function');
  16218. }
  16219. }
  16220. }
  16221. /**
  16222. * No-Op function used in method replacement
  16223. * @private
  16224. */
  16225. function noop() {}
  16226. slice = [].slice;
  16227. // ES5 reduce implementation if native not available
  16228. // See: http://es5.github.com/#x15.4.4.21 as there are many
  16229. // specifics and edge cases.
  16230. reduceArray = [].reduce ||
  16231. function(reduceFunc /*, initialValue */) {
  16232. /*jshint maxcomplexity: 7*/
  16233. // ES5 dictates that reduce.length === 1
  16234. // This implementation deviates from ES5 spec in the following ways:
  16235. // 1. It does not check if reduceFunc is a Callable
  16236. var arr, args, reduced, len, i;
  16237. i = 0;
  16238. // This generates a jshint warning, despite being valid
  16239. // "Missing 'new' prefix when invoking a constructor."
  16240. // See https://github.com/jshint/jshint/issues/392
  16241. arr = Object(this);
  16242. len = arr.length >>> 0;
  16243. args = arguments;
  16244. // If no initialValue, use first item of array (we know length !== 0 here)
  16245. // and adjust i to start at second item
  16246. if(args.length <= 1) {
  16247. // Skip to the first real element in the array
  16248. for(;;) {
  16249. if(i in arr) {
  16250. reduced = arr[i++];
  16251. break;
  16252. }
  16253. // If we reached the end of the array without finding any real
  16254. // elements, it's a TypeError
  16255. if(++i >= len) {
  16256. throw new TypeError();
  16257. }
  16258. }
  16259. } else {
  16260. // If initialValue provided, use it
  16261. reduced = args[1];
  16262. }
  16263. // Do the actual reduce
  16264. for(;i < len; ++i) {
  16265. // Skip holes
  16266. if(i in arr) {
  16267. reduced = reduceFunc(reduced, arr[i], i, arr);
  16268. }
  16269. }
  16270. return reduced;
  16271. };
  16272. function identity(x) {
  16273. return x;
  16274. }
  16275. return when;
  16276. });
  16277. })(typeof define == 'function' && define.amd
  16278. ? define
  16279. : function (factory) { typeof exports === 'object'
  16280. ? (module.exports = factory())
  16281. : (this.when = factory());
  16282. }
  16283. // Boilerplate for AMD, Node, and browser global
  16284. );
  16285. /*global define*/
  16286. define('Core/oneTimeWarning',[
  16287. './defaultValue',
  16288. './defined',
  16289. './DeveloperError'
  16290. ], function(
  16291. defaultValue,
  16292. defined,
  16293. DeveloperError) {
  16294. "use strict";
  16295. var warnings = {};
  16296. /**
  16297. * Logs a one time message to the console. Use this function instead of
  16298. * <code>console.log</code> directly since this does not log duplicate messages
  16299. * unless it is called from multiple workers.
  16300. *
  16301. * @exports oneTimeWarning
  16302. *
  16303. * @param {String} identifier The unique identifier for this warning.
  16304. * @param {String} [message=identifier] The message to log to the console.
  16305. *
  16306. * @example
  16307. * for(var i=0;i<foo.length;++i) {
  16308. * if (!defined(foo[i].bar)) {
  16309. * // Something that can be recovered from but may happen a lot
  16310. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  16311. * foo[i].bar = 0;
  16312. * // ...
  16313. * }
  16314. * }
  16315. *
  16316. * @private
  16317. */
  16318. function oneTimeWarning(identifier, message) {
  16319. if (!defined(identifier)) {
  16320. throw new DeveloperError('identifier is required.');
  16321. }
  16322. if (!defined(warnings[identifier])) {
  16323. warnings[identifier] = true;
  16324. console.log(defaultValue(message, identifier));
  16325. }
  16326. }
  16327. 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.';
  16328. return oneTimeWarning;
  16329. });
  16330. /*global define*/
  16331. define('Core/deprecationWarning',[
  16332. './defined',
  16333. './DeveloperError',
  16334. './oneTimeWarning'
  16335. ], function(
  16336. defined,
  16337. DeveloperError,
  16338. oneTimeWarning) {
  16339. 'use strict';
  16340. /**
  16341. * Logs a deprecation message to the console. Use this function instead of
  16342. * <code>console.log</code> directly since this does not log duplicate messages
  16343. * unless it is called from multiple workers.
  16344. *
  16345. * @exports deprecationWarning
  16346. *
  16347. * @param {String} identifier The unique identifier for this deprecated API.
  16348. * @param {String} message The message to log to the console.
  16349. *
  16350. * @example
  16351. * // Deprecated function or class
  16352. * function Foo() {
  16353. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  16354. * // ...
  16355. * }
  16356. *
  16357. * // Deprecated function
  16358. * Bar.prototype.func = function() {
  16359. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  16360. * // ...
  16361. * };
  16362. *
  16363. * // Deprecated property
  16364. * defineProperties(Bar.prototype, {
  16365. * prop : {
  16366. * get : function() {
  16367. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  16368. * // ...
  16369. * },
  16370. * set : function(value) {
  16371. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  16372. * // ...
  16373. * }
  16374. * }
  16375. * });
  16376. *
  16377. * @private
  16378. */
  16379. function deprecationWarning(identifier, message) {
  16380. if (!defined(identifier) || !defined(message)) {
  16381. throw new DeveloperError('identifier and message are required.');
  16382. }
  16383. oneTimeWarning(identifier, message);
  16384. }
  16385. return deprecationWarning;
  16386. });
  16387. /*global define*/
  16388. define('Core/binarySearch',[
  16389. './defined',
  16390. './DeveloperError'
  16391. ], function(
  16392. defined,
  16393. DeveloperError) {
  16394. 'use strict';
  16395. /**
  16396. * Finds an item in a sorted array.
  16397. *
  16398. * @exports binarySearch
  16399. *
  16400. * @param {Array} array The sorted array to search.
  16401. * @param {Object} itemToFind The item to find in the array.
  16402. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  16403. * elements in the array.
  16404. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  16405. * does not exist, the return value is a negative number which is the bitwise complement (~)
  16406. * of the index before which the itemToFind should be inserted in order to maintain the
  16407. * sorted order of the array.
  16408. *
  16409. * @example
  16410. * // Create a comparator function to search through an array of numbers.
  16411. * function comparator(a, b) {
  16412. * return a - b;
  16413. * };
  16414. * var numbers = [0, 2, 4, 6, 8];
  16415. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  16416. */
  16417. function binarySearch(array, itemToFind, comparator) {
  16418. if (!defined(array)) {
  16419. throw new DeveloperError('array is required.');
  16420. }
  16421. if (!defined(itemToFind)) {
  16422. throw new DeveloperError('itemToFind is required.');
  16423. }
  16424. if (!defined(comparator)) {
  16425. throw new DeveloperError('comparator is required.');
  16426. }
  16427. var low = 0;
  16428. var high = array.length - 1;
  16429. var i;
  16430. var comparison;
  16431. while (low <= high) {
  16432. i = ~~((low + high) / 2);
  16433. comparison = comparator(array[i], itemToFind);
  16434. if (comparison < 0) {
  16435. low = i + 1;
  16436. continue;
  16437. }
  16438. if (comparison > 0) {
  16439. high = i - 1;
  16440. continue;
  16441. }
  16442. return i;
  16443. }
  16444. return ~(high + 1);
  16445. }
  16446. /**
  16447. * A function used to compare two items while performing a binary search.
  16448. * @callback binarySearch~Comparator
  16449. *
  16450. * @param {Object} a An item in the array.
  16451. * @param {Object} b The item being searched for.
  16452. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  16453. * a positive value if <code>a</code> is greater than <code>b</code>, or
  16454. * 0 if <code>a</code> is equal to <code>b</code>.
  16455. *
  16456. * @example
  16457. * function compareNumbers(a, b) {
  16458. * return a - b;
  16459. * }
  16460. */
  16461. return binarySearch;
  16462. });
  16463. /*global define*/
  16464. define('Core/EarthOrientationParametersSample',[],function() {
  16465. 'use strict';
  16466. /**
  16467. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  16468. *
  16469. * @alias EarthOrientationParametersSample
  16470. * @constructor
  16471. *
  16472. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  16473. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  16474. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  16475. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  16476. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  16477. *
  16478. * @private
  16479. */
  16480. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  16481. /**
  16482. * The pole wander about the X axis, in radians.
  16483. * @type {Number}
  16484. */
  16485. this.xPoleWander = xPoleWander;
  16486. /**
  16487. * The pole wander about the Y axis, in radians.
  16488. * @type {Number}
  16489. */
  16490. this.yPoleWander = yPoleWander;
  16491. /**
  16492. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  16493. * @type {Number}
  16494. */
  16495. this.xPoleOffset = xPoleOffset;
  16496. /**
  16497. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  16498. * @type {Number}
  16499. */
  16500. this.yPoleOffset = yPoleOffset;
  16501. /**
  16502. * The difference in time standards, UT1 - UTC, in seconds.
  16503. * @type {Number}
  16504. */
  16505. this.ut1MinusUtc = ut1MinusUtc;
  16506. }
  16507. return EarthOrientationParametersSample;
  16508. });
  16509. /**
  16510. @license
  16511. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  16512. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  16513. php.js is copyright 2012 Kevin van Zonneveld.
  16514. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  16515. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  16516. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  16517. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  16518. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  16519. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  16520. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  16521. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  16522. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  16523. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  16524. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  16525. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  16526. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  16527. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  16528. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  16529. (http://geekfg.blogspot.com), Andrea Giammarchi
  16530. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  16531. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  16532. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  16533. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  16534. Marc Palau, Martin
  16535. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  16536. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  16537. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  16538. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  16539. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  16540. Ariede (http://caioariede.com), Robin, Kankrelune
  16541. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  16542. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  16543. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  16544. David, Aman Gupta, Michael White, Public Domain
  16545. (http://www.json.org/json2.js), Steven Levithan
  16546. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  16547. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  16548. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  16549. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  16550. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  16551. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  16552. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  16553. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  16554. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  16555. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  16556. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  16557. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  16558. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  16559. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  16560. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  16561. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  16562. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  16563. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  16564. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  16565. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  16566. (http://yass.meetcweb.com), Peter-Paul Koch
  16567. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  16568. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  16569. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  16570. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  16571. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  16572. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  16573. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  16574. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  16575. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  16576. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  16577. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  16578. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  16579. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  16580. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  16581. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  16582. (http://www.premasolutions.com/), Philippe Jausions
  16583. (http://pear.php.net/user/jausions), Aidan Lister
  16584. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  16585. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  16586. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  16587. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  16588. (http://www.pedrotainha.com), James, Arnout Kazemier
  16589. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  16590. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  16591. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  16592. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  16593. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  16594. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  16595. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  16596. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  16597. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  16598. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  16599. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  16600. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  16601. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  16602. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  16603. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  16604. (http://benblume.co.uk/), DtTvB
  16605. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  16606. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  16607. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  16608. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  16609. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  16610. Bryan
  16611. Licensed under the MIT (MIT-LICENSE.txt) license.
  16612. Permission is hereby granted, free of charge, to any person obtaining a
  16613. copy of this software and associated documentation files (the
  16614. "Software"), to deal in the Software without restriction, including
  16615. without limitation the rights to use, copy, modify, merge, publish,
  16616. distribute, sublicense, and/or sell copies of the Software, and to
  16617. permit persons to whom the Software is furnished to do so, subject to
  16618. the following conditions:
  16619. The above copyright notice and this permission notice shall be included
  16620. in all copies or substantial portions of the Software.
  16621. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16622. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16623. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16624. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  16625. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  16626. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  16627. OTHER DEALINGS IN THE SOFTWARE.
  16628. */
  16629. /*global define*/
  16630. define('ThirdParty/sprintf',[],function() {
  16631. function sprintf () {
  16632. // http://kevin.vanzonneveld.net
  16633. // + original by: Ash Searle (http://hexmen.com/blog/)
  16634. // + namespaced by: Michael White (http://getsprink.com)
  16635. // + tweaked by: Jack
  16636. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  16637. // + input by: Paulo Freitas
  16638. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  16639. // + input by: Brett Zamir (http://brett-zamir.me)
  16640. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  16641. // + improved by: Dj
  16642. // + improved by: Allidylls
  16643. // * example 1: sprintf("%01.2f", 123.1);
  16644. // * returns 1: 123.10
  16645. // * example 2: sprintf("[%10s]", 'monkey');
  16646. // * returns 2: '[ monkey]'
  16647. // * example 3: sprintf("[%'#10s]", 'monkey');
  16648. // * returns 3: '[####monkey]'
  16649. // * example 4: sprintf("%d", 123456789012345);
  16650. // * returns 4: '123456789012345'
  16651. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  16652. var a = arguments,
  16653. i = 0,
  16654. format = a[i++];
  16655. // pad()
  16656. var pad = function (str, len, chr, leftJustify) {
  16657. if (!chr) {
  16658. chr = ' ';
  16659. }
  16660. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  16661. return leftJustify ? str + padding : padding + str;
  16662. };
  16663. // justify()
  16664. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  16665. var diff = minWidth - value.length;
  16666. if (diff > 0) {
  16667. if (leftJustify || !zeroPad) {
  16668. value = pad(value, minWidth, customPadChar, leftJustify);
  16669. } else {
  16670. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  16671. }
  16672. }
  16673. return value;
  16674. };
  16675. // formatBaseX()
  16676. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  16677. // Note: casts negative numbers to positive ones
  16678. var number = value >>> 0;
  16679. prefix = prefix && number && {
  16680. '2': '0b',
  16681. '8': '0',
  16682. '16': '0x'
  16683. }[base] || '';
  16684. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  16685. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  16686. };
  16687. // formatString()
  16688. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  16689. if (precision != null) {
  16690. value = value.slice(0, precision);
  16691. }
  16692. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  16693. };
  16694. // doFormat()
  16695. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  16696. var number;
  16697. var prefix;
  16698. var method;
  16699. var textTransform;
  16700. var value;
  16701. if (substring == '%%') {
  16702. return '%';
  16703. }
  16704. // parse flags
  16705. var leftJustify = false,
  16706. positivePrefix = '',
  16707. zeroPad = false,
  16708. prefixBaseX = false,
  16709. customPadChar = ' ';
  16710. var flagsl = flags.length;
  16711. for (var j = 0; flags && j < flagsl; j++) {
  16712. switch (flags.charAt(j)) {
  16713. case ' ':
  16714. positivePrefix = ' ';
  16715. break;
  16716. case '+':
  16717. positivePrefix = '+';
  16718. break;
  16719. case '-':
  16720. leftJustify = true;
  16721. break;
  16722. case "'":
  16723. customPadChar = flags.charAt(j + 1);
  16724. break;
  16725. case '0':
  16726. zeroPad = true;
  16727. break;
  16728. case '#':
  16729. prefixBaseX = true;
  16730. break;
  16731. }
  16732. }
  16733. // parameters may be null, undefined, empty-string or real valued
  16734. // we want to ignore null, undefined and empty-string values
  16735. if (!minWidth) {
  16736. minWidth = 0;
  16737. } else if (minWidth == '*') {
  16738. minWidth = +a[i++];
  16739. } else if (minWidth.charAt(0) == '*') {
  16740. minWidth = +a[minWidth.slice(1, -1)];
  16741. } else {
  16742. minWidth = +minWidth;
  16743. }
  16744. // Note: undocumented perl feature:
  16745. if (minWidth < 0) {
  16746. minWidth = -minWidth;
  16747. leftJustify = true;
  16748. }
  16749. if (!isFinite(minWidth)) {
  16750. throw new Error('sprintf: (minimum-)width must be finite');
  16751. }
  16752. if (!precision) {
  16753. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  16754. } else if (precision == '*') {
  16755. precision = +a[i++];
  16756. } else if (precision.charAt(0) == '*') {
  16757. precision = +a[precision.slice(1, -1)];
  16758. } else {
  16759. precision = +precision;
  16760. }
  16761. // grab value using valueIndex if required?
  16762. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  16763. switch (type) {
  16764. case 's':
  16765. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  16766. case 'c':
  16767. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  16768. case 'b':
  16769. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  16770. case 'o':
  16771. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  16772. case 'x':
  16773. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  16774. case 'X':
  16775. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  16776. case 'u':
  16777. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  16778. case 'i':
  16779. case 'd':
  16780. number = +value || 0;
  16781. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  16782. prefix = number < 0 ? '-' : positivePrefix;
  16783. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  16784. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  16785. case 'e':
  16786. case 'E':
  16787. case 'f': // Should handle locales (as per setlocale)
  16788. case 'F':
  16789. case 'g':
  16790. case 'G':
  16791. number = +value;
  16792. prefix = number < 0 ? '-' : positivePrefix;
  16793. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  16794. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  16795. value = prefix + Math.abs(number)[method](precision);
  16796. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  16797. default:
  16798. return substring;
  16799. }
  16800. };
  16801. return format.replace(regex, doFormat);
  16802. }
  16803. return sprintf;
  16804. });
  16805. /*global define*/
  16806. define('Core/GregorianDate',[],function() {
  16807. 'use strict';
  16808. /**
  16809. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  16810. * In addition to submillisecond precision, this object can also represent leap seconds.
  16811. * @alias GregorianDate
  16812. * @constructor
  16813. *
  16814. * @see JulianDate#toGregorianDate
  16815. */
  16816. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  16817. /**
  16818. * Gets or sets the year as a whole number.
  16819. * @type {Number}
  16820. */
  16821. this.year = year;
  16822. /**
  16823. * Gets or sets the month as a whole number with range [1, 12].
  16824. * @type {Number}
  16825. */
  16826. this.month = month;
  16827. /**
  16828. * Gets or sets the day of the month as a whole number starting at 1.
  16829. * @type {Number}
  16830. */
  16831. this.day = day;
  16832. /**
  16833. * Gets or sets the hour as a whole number with range [0, 23].
  16834. * @type {Number}
  16835. */
  16836. this.hour = hour;
  16837. /**
  16838. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  16839. * @type {Number}
  16840. */
  16841. this.minute = minute;
  16842. /**
  16843. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  16844. * @type {Number}
  16845. */
  16846. this.second = second;
  16847. /**
  16848. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  16849. * @type {Number}
  16850. */
  16851. this.millisecond = millisecond;
  16852. /**
  16853. * Gets or sets whether this time is during a leap second.
  16854. * @type {Boolean}
  16855. */
  16856. this.isLeapSecond = isLeapSecond;
  16857. }
  16858. return GregorianDate;
  16859. });
  16860. /*global define*/
  16861. define('Core/isLeapYear',[
  16862. './DeveloperError'
  16863. ], function(
  16864. DeveloperError) {
  16865. 'use strict';
  16866. /**
  16867. * Determines if a given date is a leap year.
  16868. *
  16869. * @exports isLeapYear
  16870. *
  16871. * @param {Number} year The year to be tested.
  16872. * @returns {Boolean} True if <code>year</code> is a leap year.
  16873. *
  16874. * @example
  16875. * var leapYear = Cesium.isLeapYear(2000); // true
  16876. */
  16877. function isLeapYear(year) {
  16878. if (year === null || isNaN(year)) {
  16879. throw new DeveloperError('year is required and must be a number.');
  16880. }
  16881. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  16882. }
  16883. return isLeapYear;
  16884. });
  16885. /*global define*/
  16886. define('Core/LeapSecond',[],function() {
  16887. 'use strict';
  16888. /**
  16889. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  16890. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  16891. * @alias LeapSecond
  16892. * @constructor
  16893. *
  16894. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  16895. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  16896. */
  16897. function LeapSecond(date, offset) {
  16898. /**
  16899. * Gets or sets the date at which this leap second occurs.
  16900. * @type {JulianDate}
  16901. */
  16902. this.julianDate = date;
  16903. /**
  16904. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  16905. * of this leap second.
  16906. * @type {Number}
  16907. */
  16908. this.offset = offset;
  16909. }
  16910. return LeapSecond;
  16911. });
  16912. /*global define*/
  16913. define('Core/TimeConstants',[
  16914. './freezeObject'
  16915. ], function(
  16916. freezeObject) {
  16917. 'use strict';
  16918. /**
  16919. * Constants for time conversions like those done by {@link JulianDate}.
  16920. *
  16921. * @exports TimeConstants
  16922. *
  16923. * @see JulianDate
  16924. *
  16925. * @private
  16926. */
  16927. var TimeConstants = {
  16928. /**
  16929. * The number of seconds in one millisecond: <code>0.001</code>
  16930. * @type {Number}
  16931. * @constant
  16932. */
  16933. SECONDS_PER_MILLISECOND : 0.001,
  16934. /**
  16935. * The number of seconds in one minute: <code>60</code>.
  16936. * @type {Number}
  16937. * @constant
  16938. */
  16939. SECONDS_PER_MINUTE : 60.0,
  16940. /**
  16941. * The number of minutes in one hour: <code>60</code>.
  16942. * @type {Number}
  16943. * @constant
  16944. */
  16945. MINUTES_PER_HOUR : 60.0,
  16946. /**
  16947. * The number of hours in one day: <code>24</code>.
  16948. * @type {Number}
  16949. * @constant
  16950. */
  16951. HOURS_PER_DAY : 24.0,
  16952. /**
  16953. * The number of seconds in one hour: <code>3600</code>.
  16954. * @type {Number}
  16955. * @constant
  16956. */
  16957. SECONDS_PER_HOUR : 3600.0,
  16958. /**
  16959. * The number of minutes in one day: <code>1440</code>.
  16960. * @type {Number}
  16961. * @constant
  16962. */
  16963. MINUTES_PER_DAY : 1440.0,
  16964. /**
  16965. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  16966. * @type {Number}
  16967. * @constant
  16968. */
  16969. SECONDS_PER_DAY : 86400.0,
  16970. /**
  16971. * The number of days in one Julian century: <code>36525</code>.
  16972. * @type {Number}
  16973. * @constant
  16974. */
  16975. DAYS_PER_JULIAN_CENTURY : 36525.0,
  16976. /**
  16977. * One trillionth of a second.
  16978. * @type {Number}
  16979. * @constant
  16980. */
  16981. PICOSECOND : 0.000000001,
  16982. /**
  16983. * The number of days to subtract from a Julian date to determine the
  16984. * modified Julian date, which gives the number of days since midnight
  16985. * on November 17, 1858.
  16986. * @type {Number}
  16987. * @constant
  16988. */
  16989. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  16990. };
  16991. return freezeObject(TimeConstants);
  16992. });
  16993. /*global define*/
  16994. define('Core/TimeStandard',[
  16995. './freezeObject'
  16996. ], function(
  16997. freezeObject) {
  16998. 'use strict';
  16999. /**
  17000. * Provides the type of time standards which JulianDate can take as input.
  17001. *
  17002. * @exports TimeStandard
  17003. *
  17004. * @see JulianDate
  17005. */
  17006. var TimeStandard = {
  17007. /**
  17008. * Represents the coordinated Universal Time (UTC) time standard.
  17009. *
  17010. * UTC is related to TAI according to the relationship
  17011. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  17012. * seconds which have been introduced as of the time in TAI.
  17013. *
  17014. */
  17015. UTC : 0,
  17016. /**
  17017. * Represents the International Atomic Time (TAI) time standard.
  17018. * TAI is the principal time standard to which the other time standards are related.
  17019. */
  17020. TAI : 1
  17021. };
  17022. return freezeObject(TimeStandard);
  17023. });
  17024. /*global define*/
  17025. define('Core/JulianDate',[
  17026. '../ThirdParty/sprintf',
  17027. './binarySearch',
  17028. './defaultValue',
  17029. './defined',
  17030. './DeveloperError',
  17031. './GregorianDate',
  17032. './isLeapYear',
  17033. './LeapSecond',
  17034. './TimeConstants',
  17035. './TimeStandard'
  17036. ], function(
  17037. sprintf,
  17038. binarySearch,
  17039. defaultValue,
  17040. defined,
  17041. DeveloperError,
  17042. GregorianDate,
  17043. isLeapYear,
  17044. LeapSecond,
  17045. TimeConstants,
  17046. TimeStandard) {
  17047. 'use strict';
  17048. var gregorianDateScratch = new GregorianDate();
  17049. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  17050. var daysInLeapFeburary = 29;
  17051. function compareLeapSecondDates(leapSecond, dateToFind) {
  17052. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  17053. }
  17054. // we don't really need a leap second instance, anything with a julianDate property will do
  17055. var binarySearchScratchLeapSecond = new LeapSecond();
  17056. function convertUtcToTai(julianDate) {
  17057. //Even though julianDate is in UTC, we'll treat it as TAI and
  17058. //search the leap second table for it.
  17059. binarySearchScratchLeapSecond.julianDate = julianDate;
  17060. var leapSeconds = JulianDate.leapSeconds;
  17061. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  17062. if (index < 0) {
  17063. index = ~index;
  17064. }
  17065. if (index >= leapSeconds.length) {
  17066. index = leapSeconds.length - 1;
  17067. }
  17068. var offset = leapSeconds[index].offset;
  17069. if (index > 0) {
  17070. //Now we have the index of the closest leap second that comes on or after our UTC time.
  17071. //However, if the difference between the UTC date being converted and the TAI
  17072. //defined leap second is greater than the offset, we are off by one and need to use
  17073. //the previous leap second.
  17074. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  17075. if (difference > offset) {
  17076. index--;
  17077. offset = leapSeconds[index].offset;
  17078. }
  17079. }
  17080. JulianDate.addSeconds(julianDate, offset, julianDate);
  17081. }
  17082. function convertTaiToUtc(julianDate, result) {
  17083. binarySearchScratchLeapSecond.julianDate = julianDate;
  17084. var leapSeconds = JulianDate.leapSeconds;
  17085. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  17086. if (index < 0) {
  17087. index = ~index;
  17088. }
  17089. //All times before our first leap second get the first offset.
  17090. if (index === 0) {
  17091. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  17092. }
  17093. //All times after our leap second get the last offset.
  17094. if (index >= leapSeconds.length) {
  17095. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  17096. }
  17097. //Compute the difference between the found leap second and the time we are converting.
  17098. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  17099. if (difference === 0) {
  17100. //The date is in our leap second table.
  17101. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  17102. }
  17103. if (difference <= 1.0) {
  17104. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  17105. return undefined;
  17106. }
  17107. //The time is in between two leap seconds, index is the leap second after the date
  17108. //we're converting, so we subtract one to get the correct LeapSecond instance.
  17109. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  17110. }
  17111. function setComponents(wholeDays, secondsOfDay, julianDate) {
  17112. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  17113. wholeDays += extraDays;
  17114. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  17115. if (secondsOfDay < 0) {
  17116. wholeDays--;
  17117. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  17118. }
  17119. julianDate.dayNumber = wholeDays;
  17120. julianDate.secondsOfDay = secondsOfDay;
  17121. return julianDate;
  17122. }
  17123. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  17124. // Algorithm from page 604 of the Explanatory Supplement to the
  17125. // Astronomical Almanac (Seidelmann 1992).
  17126. var a = ((month - 14) / 12) | 0;
  17127. var b = year + 4800 + a;
  17128. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  17129. // JulianDates are noon-based
  17130. hour = hour - 12;
  17131. if (hour < 0) {
  17132. hour += 24;
  17133. }
  17134. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  17135. if (secondsOfDay >= 43200.0) {
  17136. dayNumber -= 1;
  17137. }
  17138. return [dayNumber, secondsOfDay];
  17139. }
  17140. //Regular expressions used for ISO8601 date parsing.
  17141. //YYYY
  17142. var matchCalendarYear = /^(\d{4})$/;
  17143. //YYYY-MM (YYYYMM is invalid)
  17144. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  17145. //YYYY-DDD or YYYYDDD
  17146. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  17147. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  17148. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  17149. //YYYY-MM-DD or YYYYMMDD
  17150. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  17151. // Match utc offset
  17152. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  17153. // Match hours HH or HH.xxxxx
  17154. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  17155. // Match hours/minutes HH:MM HHMM.xxxxx
  17156. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  17157. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  17158. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  17159. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  17160. /**
  17161. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  17162. * For increased precision, this class stores the whole number part of the date and the seconds
  17163. * part of the date in separate components. In order to be safe for arithmetic and represent
  17164. * leap seconds, the date is always stored in the International Atomic Time standard
  17165. * {@link TimeStandard.TAI}.
  17166. * @alias JulianDate
  17167. * @constructor
  17168. *
  17169. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  17170. * @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.
  17171. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  17172. */
  17173. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  17174. /**
  17175. * Gets or sets the number of whole days.
  17176. * @type {Number}
  17177. */
  17178. this.dayNumber = undefined;
  17179. /**
  17180. * Gets or sets the number of seconds into the current day.
  17181. * @type {Number}
  17182. */
  17183. this.secondsOfDay = undefined;
  17184. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  17185. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  17186. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  17187. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  17188. var wholeDays = julianDayNumber | 0;
  17189. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  17190. setComponents(wholeDays, secondsOfDay, this);
  17191. if (timeStandard === TimeStandard.UTC) {
  17192. convertUtcToTai(this);
  17193. }
  17194. }
  17195. /**
  17196. * Creates a new instance from a JavaScript Date.
  17197. *
  17198. * @param {Date} date A JavaScript Date.
  17199. * @param {JulianDate} [result] An existing instance to use for the result.
  17200. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  17201. *
  17202. * @exception {DeveloperError} date must be a valid JavaScript Date.
  17203. */
  17204. JulianDate.fromDate = function(date, result) {
  17205. if (!(date instanceof Date) || isNaN(date.getTime())) {
  17206. throw new DeveloperError('date must be a valid JavaScript Date.');
  17207. }
  17208. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  17209. if (!defined(result)) {
  17210. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  17211. }
  17212. setComponents(components[0], components[1], result);
  17213. convertUtcToTai(result);
  17214. return result;
  17215. };
  17216. /**
  17217. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  17218. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  17219. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  17220. *
  17221. * @param {String} iso8601String An ISO 8601 date.
  17222. * @param {JulianDate} [result] An existing instance to use for the result.
  17223. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  17224. *
  17225. * @exception {DeveloperError} Invalid ISO 8601 date.
  17226. */
  17227. JulianDate.fromIso8601 = function(iso8601String, result) {
  17228. if (typeof iso8601String !== 'string') {
  17229. throw new DeveloperError(iso8601ErrorMessage);
  17230. }
  17231. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  17232. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  17233. iso8601String = iso8601String.replace(',', '.');
  17234. //Split the string into its date and time components, denoted by a mandatory T
  17235. var tokens = iso8601String.split('T');
  17236. var year;
  17237. var month = 1;
  17238. var day = 1;
  17239. var hour = 0;
  17240. var minute = 0;
  17241. var second = 0;
  17242. var millisecond = 0;
  17243. //Lacking a time is okay, but a missing date is illegal.
  17244. var date = tokens[0];
  17245. var time = tokens[1];
  17246. var tmp;
  17247. var inLeapYear;
  17248. if (!defined(date)) {
  17249. throw new DeveloperError(iso8601ErrorMessage);
  17250. }
  17251. var dashCount;
  17252. //First match the date against possible regular expressions.
  17253. tokens = date.match(matchCalendarDate);
  17254. if (tokens !== null) {
  17255. dashCount = date.split('-').length - 1;
  17256. if (dashCount > 0 && dashCount !== 2) {
  17257. throw new DeveloperError(iso8601ErrorMessage);
  17258. }
  17259. year = +tokens[1];
  17260. month = +tokens[2];
  17261. day = +tokens[3];
  17262. } else {
  17263. tokens = date.match(matchCalendarMonth);
  17264. if (tokens !== null) {
  17265. year = +tokens[1];
  17266. month = +tokens[2];
  17267. } else {
  17268. tokens = date.match(matchCalendarYear);
  17269. if (tokens !== null) {
  17270. year = +tokens[1];
  17271. } else {
  17272. //Not a year/month/day so it must be an ordinal date.
  17273. var dayOfYear;
  17274. tokens = date.match(matchOrdinalDate);
  17275. if (tokens !== null) {
  17276. year = +tokens[1];
  17277. dayOfYear = +tokens[2];
  17278. inLeapYear = isLeapYear(year);
  17279. //This validation is only applicable for this format.
  17280. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  17281. throw new DeveloperError(iso8601ErrorMessage);
  17282. }
  17283. } else {
  17284. tokens = date.match(matchWeekDate);
  17285. if (tokens !== null) {
  17286. //ISO week date to ordinal date from
  17287. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  17288. year = +tokens[1];
  17289. var weekNumber = +tokens[2];
  17290. var dayOfWeek = +tokens[3] || 0;
  17291. dashCount = date.split('-').length - 1;
  17292. if (dashCount > 0 &&
  17293. ((!defined(tokens[3]) && dashCount !== 1) ||
  17294. (defined(tokens[3]) && dashCount !== 2))) {
  17295. throw new DeveloperError(iso8601ErrorMessage);
  17296. }
  17297. var january4 = new Date(Date.UTC(year, 0, 4));
  17298. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  17299. } else {
  17300. //None of our regular expressions succeeded in parsing the date properly.
  17301. throw new DeveloperError(iso8601ErrorMessage);
  17302. }
  17303. }
  17304. //Split an ordinal date into month/day.
  17305. tmp = new Date(Date.UTC(year, 0, 1));
  17306. tmp.setUTCDate(dayOfYear);
  17307. month = tmp.getUTCMonth() + 1;
  17308. day = tmp.getUTCDate();
  17309. }
  17310. }
  17311. }
  17312. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  17313. inLeapYear = isLeapYear(year);
  17314. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  17315. throw new DeveloperError(iso8601ErrorMessage);
  17316. }
  17317. //Not move onto the time string, which is much simpler.
  17318. var offsetIndex;
  17319. if (defined(time)) {
  17320. tokens = time.match(matchHoursMinutesSeconds);
  17321. if (tokens !== null) {
  17322. dashCount = time.split(':').length - 1;
  17323. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  17324. throw new DeveloperError(iso8601ErrorMessage);
  17325. }
  17326. hour = +tokens[1];
  17327. minute = +tokens[2];
  17328. second = +tokens[3];
  17329. millisecond = +(tokens[4] || 0) * 1000.0;
  17330. offsetIndex = 5;
  17331. } else {
  17332. tokens = time.match(matchHoursMinutes);
  17333. if (tokens !== null) {
  17334. dashCount = time.split(':').length - 1;
  17335. if (dashCount > 2) {
  17336. throw new DeveloperError(iso8601ErrorMessage);
  17337. }
  17338. hour = +tokens[1];
  17339. minute = +tokens[2];
  17340. second = +(tokens[3] || 0) * 60.0;
  17341. offsetIndex = 4;
  17342. } else {
  17343. tokens = time.match(matchHours);
  17344. if (tokens !== null) {
  17345. hour = +tokens[1];
  17346. minute = +(tokens[2] || 0) * 60.0;
  17347. offsetIndex = 3;
  17348. } else {
  17349. throw new DeveloperError(iso8601ErrorMessage);
  17350. }
  17351. }
  17352. }
  17353. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  17354. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  17355. throw new DeveloperError(iso8601ErrorMessage);
  17356. }
  17357. //Check the UTC offset value, if no value exists, use local time
  17358. //a Z indicates UTC, + or - are offsets.
  17359. var offset = tokens[offsetIndex];
  17360. var offsetHours = +(tokens[offsetIndex + 1]);
  17361. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  17362. switch (offset) {
  17363. case '+':
  17364. hour = hour - offsetHours;
  17365. minute = minute - offsetMinutes;
  17366. break;
  17367. case '-':
  17368. hour = hour + offsetHours;
  17369. minute = minute + offsetMinutes;
  17370. break;
  17371. case 'Z':
  17372. break;
  17373. default:
  17374. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  17375. break;
  17376. }
  17377. } else {
  17378. //If no time is specified, it is considered the beginning of the day, local time.
  17379. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  17380. }
  17381. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  17382. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  17383. //Then we add it back in after converting to TAI.
  17384. var isLeapSecond = second === 60;
  17385. if (isLeapSecond) {
  17386. second--;
  17387. }
  17388. //Even if we successfully parsed the string into its components, after applying UTC offset or
  17389. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  17390. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  17391. while (minute >= 60) {
  17392. minute -= 60;
  17393. hour++;
  17394. }
  17395. while (hour >= 24) {
  17396. hour -= 24;
  17397. day++;
  17398. }
  17399. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  17400. while (day > tmp) {
  17401. day -= tmp;
  17402. month++;
  17403. if (month > 12) {
  17404. month -= 12;
  17405. year++;
  17406. }
  17407. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  17408. }
  17409. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  17410. while (minute < 0) {
  17411. minute += 60;
  17412. hour--;
  17413. }
  17414. while (hour < 0) {
  17415. hour += 24;
  17416. day--;
  17417. }
  17418. while (day < 1) {
  17419. month--;
  17420. if (month < 1) {
  17421. month += 12;
  17422. year--;
  17423. }
  17424. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  17425. day += tmp;
  17426. }
  17427. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  17428. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  17429. if (!defined(result)) {
  17430. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  17431. } else {
  17432. setComponents(components[0], components[1], result);
  17433. convertUtcToTai(result);
  17434. }
  17435. //If we were on a leap second, add it back.
  17436. if (isLeapSecond) {
  17437. JulianDate.addSeconds(result, 1, result);
  17438. }
  17439. return result;
  17440. };
  17441. /**
  17442. * Creates a new instance that represents the current system time.
  17443. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  17444. *
  17445. * @param {JulianDate} [result] An existing instance to use for the result.
  17446. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  17447. */
  17448. JulianDate.now = function(result) {
  17449. return JulianDate.fromDate(new Date(), result);
  17450. };
  17451. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  17452. /**
  17453. * Creates a {@link GregorianDate} from the provided instance.
  17454. *
  17455. * @param {JulianDate} julianDate The date to be converted.
  17456. * @param {GregorianDate} [result] An existing instance to use for the result.
  17457. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  17458. */
  17459. JulianDate.toGregorianDate = function(julianDate, result) {
  17460. if (!defined(julianDate)) {
  17461. throw new DeveloperError('julianDate is required.');
  17462. }
  17463. var isLeapSecond = false;
  17464. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  17465. if (!defined(thisUtc)) {
  17466. //Conversion to UTC will fail if we are during a leap second.
  17467. //If that's the case, subtract a second and convert again.
  17468. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  17469. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  17470. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  17471. isLeapSecond = true;
  17472. }
  17473. var julianDayNumber = thisUtc.dayNumber;
  17474. var secondsOfDay = thisUtc.secondsOfDay;
  17475. if (secondsOfDay >= 43200.0) {
  17476. julianDayNumber += 1;
  17477. }
  17478. // Algorithm from page 604 of the Explanatory Supplement to the
  17479. // Astronomical Almanac (Seidelmann 1992).
  17480. var L = (julianDayNumber + 68569) | 0;
  17481. var N = (4 * L / 146097) | 0;
  17482. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  17483. var I = ((4000 * (L + 1)) / 1461001) | 0;
  17484. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  17485. var J = ((80 * L) / 2447) | 0;
  17486. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  17487. L = (J / 11) | 0;
  17488. var month = (J + 2 - 12 * L) | 0;
  17489. var year = (100 * (N - 49) + I + L) | 0;
  17490. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  17491. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  17492. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  17493. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  17494. var second = remainingSeconds | 0;
  17495. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  17496. // JulianDates are noon-based
  17497. hour += 12;
  17498. if (hour > 23) {
  17499. hour -= 24;
  17500. }
  17501. //If we were on a leap second, add it back.
  17502. if (isLeapSecond) {
  17503. second += 1;
  17504. }
  17505. if (!defined(result)) {
  17506. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  17507. }
  17508. result.year = year;
  17509. result.month = month;
  17510. result.day = day;
  17511. result.hour = hour;
  17512. result.minute = minute;
  17513. result.second = second;
  17514. result.millisecond = millisecond;
  17515. result.isLeapSecond = isLeapSecond;
  17516. return result;
  17517. };
  17518. /**
  17519. * Creates a JavaScript Date from the provided instance.
  17520. * Since JavaScript dates are only accurate to the nearest millisecond and
  17521. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  17522. * If the provided JulianDate is during a leap second, the previous second is used.
  17523. *
  17524. * @param {JulianDate} julianDate The date to be converted.
  17525. * @returns {Date} A new instance representing the provided date.
  17526. */
  17527. JulianDate.toDate = function(julianDate) {
  17528. if (!defined(julianDate)) {
  17529. throw new DeveloperError('julianDate is required.');
  17530. }
  17531. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  17532. var second = gDate.second;
  17533. if (gDate.isLeapSecond) {
  17534. second -= 1;
  17535. }
  17536. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  17537. };
  17538. /**
  17539. * Creates an ISO8601 representation of the provided date.
  17540. *
  17541. * @param {JulianDate} julianDate The date to be converted.
  17542. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  17543. * @returns {String} The ISO8601 representation of the provided date.
  17544. */
  17545. JulianDate.toIso8601 = function(julianDate, precision) {
  17546. if (!defined(julianDate)) {
  17547. throw new DeveloperError('julianDate is required.');
  17548. }
  17549. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  17550. var millisecondStr;
  17551. if (!defined(precision) && gDate.millisecond !== 0) {
  17552. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  17553. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  17554. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  17555. }
  17556. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  17557. if (!defined(precision) || precision === 0) {
  17558. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  17559. }
  17560. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  17561. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  17562. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  17563. };
  17564. /**
  17565. * Duplicates a JulianDate instance.
  17566. *
  17567. * @param {JulianDate} julianDate The date to duplicate.
  17568. * @param {JulianDate} [result] An existing instance to use for the result.
  17569. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  17570. */
  17571. JulianDate.clone = function(julianDate, result) {
  17572. if (!defined(julianDate)) {
  17573. return undefined;
  17574. }
  17575. if (!defined(result)) {
  17576. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  17577. }
  17578. result.dayNumber = julianDate.dayNumber;
  17579. result.secondsOfDay = julianDate.secondsOfDay;
  17580. return result;
  17581. };
  17582. /**
  17583. * Compares two instances.
  17584. *
  17585. * @param {JulianDate} left The first instance.
  17586. * @param {JulianDate} right The second instance.
  17587. * @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.
  17588. */
  17589. JulianDate.compare = function(left, right) {
  17590. if (!defined(left)) {
  17591. throw new DeveloperError('left is required.');
  17592. }
  17593. if (!defined(right)) {
  17594. throw new DeveloperError('right is required.');
  17595. }
  17596. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  17597. if (julianDayNumberDifference !== 0) {
  17598. return julianDayNumberDifference;
  17599. }
  17600. return left.secondsOfDay - right.secondsOfDay;
  17601. };
  17602. /**
  17603. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  17604. *
  17605. * @param {JulianDate} [left] The first instance.
  17606. * @param {JulianDate} [right] The second instance.
  17607. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  17608. */
  17609. JulianDate.equals = function(left, right) {
  17610. return (left === right) ||
  17611. (defined(left) &&
  17612. defined(right) &&
  17613. left.dayNumber === right.dayNumber &&
  17614. left.secondsOfDay === right.secondsOfDay);
  17615. };
  17616. /**
  17617. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  17618. * each other. That is, in order for the dates to be considered equal (and for
  17619. * this function to return <code>true</code>), the absolute value of the difference between them, in
  17620. * seconds, must be less than <code>epsilon</code>.
  17621. *
  17622. * @param {JulianDate} [left] The first instance.
  17623. * @param {JulianDate} [right] The second instance.
  17624. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  17625. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  17626. */
  17627. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  17628. if (!defined(epsilon)) {
  17629. throw new DeveloperError('epsilon is required.');
  17630. }
  17631. return (left === right) ||
  17632. (defined(left) &&
  17633. defined(right) &&
  17634. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  17635. };
  17636. /**
  17637. * Computes the total number of whole and fractional days represented by the provided instance.
  17638. *
  17639. * @param {JulianDate} julianDate The date.
  17640. * @returns {Number} The Julian date as single floating point number.
  17641. */
  17642. JulianDate.totalDays = function(julianDate) {
  17643. if (!defined(julianDate)) {
  17644. throw new DeveloperError('julianDate is required.');
  17645. }
  17646. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  17647. };
  17648. /**
  17649. * Computes the difference in seconds between the provided instance.
  17650. *
  17651. * @param {JulianDate} left The first instance.
  17652. * @param {JulianDate} right The second instance.
  17653. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  17654. */
  17655. JulianDate.secondsDifference = function(left, right) {
  17656. if (!defined(left)) {
  17657. throw new DeveloperError('left is required.');
  17658. }
  17659. if (!defined(right)) {
  17660. throw new DeveloperError('right is required.');
  17661. }
  17662. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  17663. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  17664. };
  17665. /**
  17666. * Computes the difference in days between the provided instance.
  17667. *
  17668. * @param {JulianDate} left The first instance.
  17669. * @param {JulianDate} right The second instance.
  17670. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  17671. */
  17672. JulianDate.daysDifference = function(left, right) {
  17673. if (!defined(left)) {
  17674. throw new DeveloperError('left is required.');
  17675. }
  17676. if (!defined(right)) {
  17677. throw new DeveloperError('right is required.');
  17678. }
  17679. var dayDifference = (left.dayNumber - right.dayNumber);
  17680. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  17681. return dayDifference + secondDifference;
  17682. };
  17683. /**
  17684. * Computes the number of seconds the provided instance is ahead of UTC.
  17685. *
  17686. * @param {JulianDate} julianDate The date.
  17687. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  17688. */
  17689. JulianDate.computeTaiMinusUtc = function(julianDate) {
  17690. binarySearchScratchLeapSecond.julianDate = julianDate;
  17691. var leapSeconds = JulianDate.leapSeconds;
  17692. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  17693. if (index < 0) {
  17694. index = ~index;
  17695. --index;
  17696. if (index < 0) {
  17697. index = 0;
  17698. }
  17699. }
  17700. return leapSeconds[index].offset;
  17701. };
  17702. /**
  17703. * Adds the provided number of seconds to the provided date instance.
  17704. *
  17705. * @param {JulianDate} julianDate The date.
  17706. * @param {Number} seconds The number of seconds to add or subtract.
  17707. * @param {JulianDate} result An existing instance to use for the result.
  17708. * @returns {JulianDate} The modified result parameter.
  17709. */
  17710. JulianDate.addSeconds = function(julianDate, seconds, result) {
  17711. if (!defined(julianDate)) {
  17712. throw new DeveloperError('julianDate is required.');
  17713. }
  17714. if (!defined(seconds)) {
  17715. throw new DeveloperError('seconds is required.');
  17716. }
  17717. if (!defined(result)) {
  17718. throw new DeveloperError('result is required.');
  17719. }
  17720. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  17721. };
  17722. /**
  17723. * Adds the provided number of minutes to the provided date instance.
  17724. *
  17725. * @param {JulianDate} julianDate The date.
  17726. * @param {Number} minutes The number of minutes to add or subtract.
  17727. * @param {JulianDate} result An existing instance to use for the result.
  17728. * @returns {JulianDate} The modified result parameter.
  17729. */
  17730. JulianDate.addMinutes = function(julianDate, minutes, result) {
  17731. if (!defined(julianDate)) {
  17732. throw new DeveloperError('julianDate is required.');
  17733. }
  17734. if (!defined(minutes)) {
  17735. throw new DeveloperError('minutes is required.');
  17736. }
  17737. if (!defined(result)) {
  17738. throw new DeveloperError('result is required.');
  17739. }
  17740. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  17741. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  17742. };
  17743. /**
  17744. * Adds the provided number of hours to the provided date instance.
  17745. *
  17746. * @param {JulianDate} julianDate The date.
  17747. * @param {Number} hours The number of hours to add or subtract.
  17748. * @param {JulianDate} result An existing instance to use for the result.
  17749. * @returns {JulianDate} The modified result parameter.
  17750. */
  17751. JulianDate.addHours = function(julianDate, hours, result) {
  17752. if (!defined(julianDate)) {
  17753. throw new DeveloperError('julianDate is required.');
  17754. }
  17755. if (!defined(hours)) {
  17756. throw new DeveloperError('hours is required.');
  17757. }
  17758. if (!defined(result)) {
  17759. throw new DeveloperError('result is required.');
  17760. }
  17761. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  17762. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  17763. };
  17764. /**
  17765. * Adds the provided number of days to the provided date instance.
  17766. *
  17767. * @param {JulianDate} julianDate The date.
  17768. * @param {Number} days The number of days to add or subtract.
  17769. * @param {JulianDate} result An existing instance to use for the result.
  17770. * @returns {JulianDate} The modified result parameter.
  17771. */
  17772. JulianDate.addDays = function(julianDate, days, result) {
  17773. if (!defined(julianDate)) {
  17774. throw new DeveloperError('julianDate is required.');
  17775. }
  17776. if (!defined(days)) {
  17777. throw new DeveloperError('days is required.');
  17778. }
  17779. if (!defined(result)) {
  17780. throw new DeveloperError('result is required.');
  17781. }
  17782. var newJulianDayNumber = julianDate.dayNumber + days;
  17783. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  17784. };
  17785. /**
  17786. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  17787. *
  17788. * @param {JulianDate} left The first instance.
  17789. * @param {JulianDate} right The second instance.
  17790. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  17791. */
  17792. JulianDate.lessThan = function(left, right) {
  17793. return JulianDate.compare(left, right) < 0;
  17794. };
  17795. /**
  17796. * 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.
  17797. *
  17798. * @param {JulianDate} left The first instance.
  17799. * @param {JulianDate} right The second instance.
  17800. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  17801. */
  17802. JulianDate.lessThanOrEquals = function(left, right) {
  17803. return JulianDate.compare(left, right) <= 0;
  17804. };
  17805. /**
  17806. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  17807. *
  17808. * @param {JulianDate} left The first instance.
  17809. * @param {JulianDate} right The second instance.
  17810. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  17811. */
  17812. JulianDate.greaterThan = function(left, right) {
  17813. return JulianDate.compare(left, right) > 0;
  17814. };
  17815. /**
  17816. * 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.
  17817. *
  17818. * @param {JulianDate} left The first instance.
  17819. * @param {JulianDate} right The second instance.
  17820. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  17821. */
  17822. JulianDate.greaterThanOrEquals = function(left, right) {
  17823. return JulianDate.compare(left, right) >= 0;
  17824. };
  17825. /**
  17826. * Duplicates this instance.
  17827. *
  17828. * @param {JulianDate} [result] An existing instance to use for the result.
  17829. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  17830. */
  17831. JulianDate.prototype.clone = function(result) {
  17832. return JulianDate.clone(this, result);
  17833. };
  17834. /**
  17835. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  17836. *
  17837. * @param {JulianDate} [right] The second instance.
  17838. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  17839. */
  17840. JulianDate.prototype.equals = function(right) {
  17841. return JulianDate.equals(this, right);
  17842. };
  17843. /**
  17844. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  17845. * each other. That is, in order for the dates to be considered equal (and for
  17846. * this function to return <code>true</code>), the absolute value of the difference between them, in
  17847. * seconds, must be less than <code>epsilon</code>.
  17848. *
  17849. * @param {JulianDate} [right] The second instance.
  17850. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  17851. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  17852. */
  17853. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  17854. return JulianDate.equalsEpsilon(this, right, epsilon);
  17855. };
  17856. /**
  17857. * Creates a string representing this date in ISO8601 format.
  17858. *
  17859. * @returns {String} A string representing this date in ISO8601 format.
  17860. */
  17861. JulianDate.prototype.toString = function() {
  17862. return JulianDate.toIso8601(this);
  17863. };
  17864. /**
  17865. * Gets or sets the list of leap seconds used throughout Cesium.
  17866. * @memberof JulianDate
  17867. * @type {LeapSecond[]}
  17868. */
  17869. JulianDate.leapSeconds = [
  17870. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  17871. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  17872. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  17873. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  17874. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  17875. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  17876. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  17877. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  17878. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  17879. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  17880. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  17881. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  17882. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  17883. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  17884. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  17885. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  17886. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  17887. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  17888. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  17889. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  17890. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  17891. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  17892. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  17893. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  17894. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  17895. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  17896. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  17897. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  17898. ];
  17899. return JulianDate;
  17900. });
  17901. /*global define*/
  17902. define('Core/clone',[
  17903. './defaultValue'
  17904. ], function(
  17905. defaultValue) {
  17906. 'use strict';
  17907. /**
  17908. * Clones an object, returning a new object containing the same properties.
  17909. *
  17910. * @exports clone
  17911. *
  17912. * @param {Object} object The object to clone.
  17913. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  17914. * @returns {Object} The cloned object.
  17915. */
  17916. function clone(object, deep) {
  17917. if (object === null || typeof object !== 'object') {
  17918. return object;
  17919. }
  17920. deep = defaultValue(deep, false);
  17921. var result = new object.constructor();
  17922. for ( var propertyName in object) {
  17923. if (object.hasOwnProperty(propertyName)) {
  17924. var value = object[propertyName];
  17925. if (deep) {
  17926. value = clone(value, deep);
  17927. }
  17928. result[propertyName] = value;
  17929. }
  17930. }
  17931. return result;
  17932. }
  17933. return clone;
  17934. });
  17935. /*global define*/
  17936. define('Core/parseResponseHeaders',[], function() {
  17937. 'use strict';
  17938. /**
  17939. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  17940. * a dictionary.
  17941. *
  17942. * @exports parseResponseHeaders
  17943. *
  17944. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  17945. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  17946. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  17947. * is that header's value.
  17948. *
  17949. * @private
  17950. */
  17951. function parseResponseHeaders(headerString) {
  17952. var headers = {};
  17953. if (!headerString) {
  17954. return headers;
  17955. }
  17956. var headerPairs = headerString.split('\u000d\u000a');
  17957. for (var i = 0; i < headerPairs.length; ++i) {
  17958. var headerPair = headerPairs[i];
  17959. // Can't use split() here because it does the wrong thing
  17960. // if the header value has the string ": " in it.
  17961. var index = headerPair.indexOf('\u003a\u0020');
  17962. if (index > 0) {
  17963. var key = headerPair.substring(0, index);
  17964. var val = headerPair.substring(index + 2);
  17965. headers[key] = val;
  17966. }
  17967. }
  17968. return headers;
  17969. }
  17970. return parseResponseHeaders;
  17971. });
  17972. /*global define*/
  17973. define('Core/RequestErrorEvent',[
  17974. './defined',
  17975. './parseResponseHeaders'
  17976. ], function(
  17977. defined,
  17978. parseResponseHeaders) {
  17979. 'use strict';
  17980. /**
  17981. * An event that is raised when a request encounters an error.
  17982. *
  17983. * @constructor
  17984. * @alias RequestErrorEvent
  17985. *
  17986. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  17987. * @param {Object} [response] The response included along with the error.
  17988. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  17989. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  17990. */
  17991. function RequestErrorEvent(statusCode, response, responseHeaders) {
  17992. /**
  17993. * The HTTP error status code, such as 404. If the error does not have a particular
  17994. * HTTP code, this property will be undefined.
  17995. *
  17996. * @type {Number}
  17997. */
  17998. this.statusCode = statusCode;
  17999. /**
  18000. * The response included along with the error. If the error does not include a response,
  18001. * this property will be undefined.
  18002. *
  18003. * @type {Object}
  18004. */
  18005. this.response = response;
  18006. /**
  18007. * The headers included in the response, represented as an object literal of key/value pairs.
  18008. * If the error does not include any headers, this property will be undefined.
  18009. *
  18010. * @type {Object}
  18011. */
  18012. this.responseHeaders = responseHeaders;
  18013. if (typeof this.responseHeaders === 'string') {
  18014. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  18015. }
  18016. }
  18017. /**
  18018. * Creates a string representing this RequestErrorEvent.
  18019. * @memberof RequestErrorEvent
  18020. *
  18021. * @returns {String} A string representing the provided RequestErrorEvent.
  18022. */
  18023. RequestErrorEvent.prototype.toString = function() {
  18024. var str = 'Request has failed.';
  18025. if (defined(this.statusCode)) {
  18026. str += ' Status Code: ' + this.statusCode;
  18027. }
  18028. return str;
  18029. };
  18030. return RequestErrorEvent;
  18031. });
  18032. /**
  18033. * @license
  18034. *
  18035. * Grauw URI utilities
  18036. *
  18037. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  18038. *
  18039. * @author Laurens Holst (http://www.grauw.nl/)
  18040. *
  18041. * Copyright 2012 Laurens Holst
  18042. *
  18043. * Licensed under the Apache License, Version 2.0 (the "License");
  18044. * you may not use this file except in compliance with the License.
  18045. * You may obtain a copy of the License at
  18046. *
  18047. * http://www.apache.org/licenses/LICENSE-2.0
  18048. *
  18049. * Unless required by applicable law or agreed to in writing, software
  18050. * distributed under the License is distributed on an "AS IS" BASIS,
  18051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18052. * See the License for the specific language governing permissions and
  18053. * limitations under the License.
  18054. *
  18055. */
  18056. /*global define*/
  18057. define('ThirdParty/Uri',[],function() {
  18058. /**
  18059. * Constructs a URI object.
  18060. * @constructor
  18061. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  18062. * @param {string|URI} uri A string or URI object to create the object from.
  18063. */
  18064. function URI(uri) {
  18065. if (uri instanceof URI) { // copy constructor
  18066. this.scheme = uri.scheme;
  18067. this.authority = uri.authority;
  18068. this.path = uri.path;
  18069. this.query = uri.query;
  18070. this.fragment = uri.fragment;
  18071. } else if (uri) { // uri is URI string or cast to string
  18072. var c = parseRegex.exec(uri);
  18073. this.scheme = c[1];
  18074. this.authority = c[2];
  18075. this.path = c[3];
  18076. this.query = c[4];
  18077. this.fragment = c[5];
  18078. }
  18079. }
  18080. // Initial values on the prototype
  18081. URI.prototype.scheme = null;
  18082. URI.prototype.authority = null;
  18083. URI.prototype.path = '';
  18084. URI.prototype.query = null;
  18085. URI.prototype.fragment = null;
  18086. // Regular expression from RFC 3986 appendix B
  18087. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  18088. /**
  18089. * Returns the scheme part of the URI.
  18090. * In "http://example.com:80/a/b?x#y" this is "http".
  18091. */
  18092. URI.prototype.getScheme = function() {
  18093. return this.scheme;
  18094. };
  18095. /**
  18096. * Returns the authority part of the URI.
  18097. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  18098. */
  18099. URI.prototype.getAuthority = function() {
  18100. return this.authority;
  18101. };
  18102. /**
  18103. * Returns the path part of the URI.
  18104. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  18105. * In "mailto:mike@example.com" this is "mike@example.com".
  18106. */
  18107. URI.prototype.getPath = function() {
  18108. return this.path;
  18109. };
  18110. /**
  18111. * Returns the query part of the URI.
  18112. * In "http://example.com:80/a/b?x#y" this is "x".
  18113. */
  18114. URI.prototype.getQuery = function() {
  18115. return this.query;
  18116. };
  18117. /**
  18118. * Returns the fragment part of the URI.
  18119. * In "http://example.com:80/a/b?x#y" this is "y".
  18120. */
  18121. URI.prototype.getFragment = function() {
  18122. return this.fragment;
  18123. };
  18124. /**
  18125. * Tests whether the URI is an absolute URI.
  18126. * See RFC 3986 section 4.3.
  18127. */
  18128. URI.prototype.isAbsolute = function() {
  18129. return !!this.scheme && !this.fragment;
  18130. };
  18131. ///**
  18132. //* Extensive validation of the URI against the ABNF in RFC 3986
  18133. //*/
  18134. //URI.prototype.validate
  18135. /**
  18136. * Tests whether the URI is a same-document reference.
  18137. * See RFC 3986 section 4.4.
  18138. *
  18139. * To perform more thorough comparison, you can normalise the URI objects.
  18140. */
  18141. URI.prototype.isSameDocumentAs = function(uri) {
  18142. return uri.scheme == this.scheme &&
  18143. uri.authority == this.authority &&
  18144. uri.path == this.path &&
  18145. uri.query == this.query;
  18146. };
  18147. /**
  18148. * Simple String Comparison of two URIs.
  18149. * See RFC 3986 section 6.2.1.
  18150. *
  18151. * To perform more thorough comparison, you can normalise the URI objects.
  18152. */
  18153. URI.prototype.equals = function(uri) {
  18154. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  18155. };
  18156. /**
  18157. * Normalizes the URI using syntax-based normalization.
  18158. * This includes case normalization, percent-encoding normalization and path segment normalization.
  18159. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  18160. * (Although that would not be a valid URI in the first place. See validate().)
  18161. * See RFC 3986 section 6.2.2.
  18162. */
  18163. URI.prototype.normalize = function() {
  18164. this.removeDotSegments();
  18165. if (this.scheme)
  18166. this.scheme = this.scheme.toLowerCase();
  18167. if (this.authority)
  18168. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  18169. replace(caseRegex, replaceCase);
  18170. if (this.path)
  18171. this.path = this.path.replace(caseRegex, replaceCase);
  18172. if (this.query)
  18173. this.query = this.query.replace(caseRegex, replaceCase);
  18174. if (this.fragment)
  18175. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  18176. };
  18177. var caseRegex = /%[0-9a-z]{2}/gi;
  18178. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  18179. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  18180. function replaceCase(str) {
  18181. var dec = unescape(str);
  18182. return percentRegex.test(dec) ? dec : str.toUpperCase();
  18183. }
  18184. function replaceAuthority(str, p1, p2, p3) {
  18185. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  18186. }
  18187. /**
  18188. * Resolve a relative URI (this) against a base URI.
  18189. * The base URI must be an absolute URI.
  18190. * See RFC 3986 section 5.2
  18191. */
  18192. URI.prototype.resolve = function(baseURI) {
  18193. var uri = new URI();
  18194. if (this.scheme) {
  18195. uri.scheme = this.scheme;
  18196. uri.authority = this.authority;
  18197. uri.path = this.path;
  18198. uri.query = this.query;
  18199. } else {
  18200. uri.scheme = baseURI.scheme;
  18201. if (this.authority) {
  18202. uri.authority = this.authority;
  18203. uri.path = this.path;
  18204. uri.query = this.query;
  18205. } else {
  18206. uri.authority = baseURI.authority;
  18207. if (this.path == '') {
  18208. uri.path = baseURI.path;
  18209. uri.query = this.query || baseURI.query;
  18210. } else {
  18211. if (this.path.charAt(0) == '/') {
  18212. uri.path = this.path;
  18213. uri.removeDotSegments();
  18214. } else {
  18215. if (baseURI.authority && baseURI.path == '') {
  18216. uri.path = '/' + this.path;
  18217. } else {
  18218. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  18219. }
  18220. uri.removeDotSegments();
  18221. }
  18222. uri.query = this.query;
  18223. }
  18224. }
  18225. }
  18226. uri.fragment = this.fragment;
  18227. return uri;
  18228. };
  18229. /**
  18230. * Remove dot segments from path.
  18231. * See RFC 3986 section 5.2.4
  18232. * @private
  18233. */
  18234. URI.prototype.removeDotSegments = function() {
  18235. var input = this.path.split('/'),
  18236. output = [],
  18237. segment,
  18238. absPath = input[0] == '';
  18239. if (absPath)
  18240. input.shift();
  18241. var sFirst = input[0] == '' ? input.shift() : null;
  18242. while (input.length) {
  18243. segment = input.shift();
  18244. if (segment == '..') {
  18245. output.pop();
  18246. } else if (segment != '.') {
  18247. output.push(segment);
  18248. }
  18249. }
  18250. if (segment == '.' || segment == '..')
  18251. output.push('');
  18252. if (absPath)
  18253. output.unshift('');
  18254. this.path = output.join('/');
  18255. };
  18256. // We don't like this function because it builds up a cache that is never cleared.
  18257. // /**
  18258. // * Resolves a relative URI against an absolute base URI.
  18259. // * Convenience method.
  18260. // * @param {String} uri the relative URI to resolve
  18261. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  18262. // */
  18263. // URI.resolve = function(sURI, sBaseURI) {
  18264. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  18265. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  18266. // return uri.resolve(baseURI).toString();
  18267. // };
  18268. // var cache = {};
  18269. /**
  18270. * Serialises the URI to a string.
  18271. */
  18272. URI.prototype.toString = function() {
  18273. var result = '';
  18274. if (this.scheme)
  18275. result += this.scheme + ':';
  18276. if (this.authority)
  18277. result += '//' + this.authority;
  18278. result += this.path;
  18279. if (this.query)
  18280. result += '?' + this.query;
  18281. if (this.fragment)
  18282. result += '#' + this.fragment;
  18283. return result;
  18284. };
  18285. return URI;
  18286. });
  18287. /*global define*/
  18288. define('Core/TrustedServers',[
  18289. '../ThirdParty/Uri',
  18290. './defined',
  18291. './DeveloperError'
  18292. ], function(
  18293. Uri,
  18294. defined,
  18295. DeveloperError) {
  18296. 'use strict';
  18297. /**
  18298. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  18299. * any requests to these servers.
  18300. *
  18301. * @exports TrustedServers
  18302. *
  18303. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  18304. */
  18305. var TrustedServers = {};
  18306. var _servers = {};
  18307. /**
  18308. * Adds a trusted server to the registry
  18309. *
  18310. * @param {String} host The host to be added.
  18311. * @param {Number} port The port used to access the host.
  18312. *
  18313. * @example
  18314. * // Add a trusted server
  18315. * TrustedServers.add('my.server.com', 80);
  18316. */
  18317. TrustedServers.add = function(host, port) {
  18318. if (!defined(host)) {
  18319. throw new DeveloperError('host is required.');
  18320. }
  18321. if (!defined(port) || port <= 0) {
  18322. throw new DeveloperError('port is required to be greater than 0.');
  18323. }
  18324. var authority = host.toLowerCase() + ':' + port;
  18325. if (!defined(_servers[authority])) {
  18326. _servers[authority] = true;
  18327. }
  18328. };
  18329. /**
  18330. * Removes a trusted server from the registry
  18331. *
  18332. * @param {String} host The host to be removed.
  18333. * @param {Number} port The port used to access the host.
  18334. *
  18335. * @example
  18336. * // Remove a trusted server
  18337. * TrustedServers.remove('my.server.com', 80);
  18338. */
  18339. TrustedServers.remove = function(host, port) {
  18340. if (!defined(host)) {
  18341. throw new DeveloperError('host is required.');
  18342. }
  18343. if (!defined(port) || port <= 0) {
  18344. throw new DeveloperError('port is required to be greater than 0.');
  18345. }
  18346. var authority = host.toLowerCase() + ':' + port;
  18347. if (defined(_servers[authority])) {
  18348. delete _servers[authority];
  18349. }
  18350. };
  18351. function getAuthority(url) {
  18352. var uri = new Uri(url);
  18353. uri.normalize();
  18354. // Removes username:password@ so we just have host[:port]
  18355. var authority = uri.getAuthority();
  18356. if (!defined(authority)) {
  18357. return undefined; // Relative URL
  18358. }
  18359. if (authority.indexOf('@') !== -1) {
  18360. var parts = authority.split('@');
  18361. authority = parts[1];
  18362. }
  18363. // If the port is missing add one based on the scheme
  18364. if (authority.indexOf(':') === -1) {
  18365. var scheme = uri.getScheme();
  18366. if (!defined(scheme)) {
  18367. scheme = window.location.protocol;
  18368. scheme = scheme.substring(0, scheme.length-1);
  18369. }
  18370. if (scheme === 'http') {
  18371. authority += ':80';
  18372. } else if (scheme === 'https') {
  18373. authority += ':443';
  18374. } else {
  18375. return undefined;
  18376. }
  18377. }
  18378. return authority;
  18379. }
  18380. /**
  18381. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  18382. *
  18383. * @param {String} url The url to be tested against the trusted list
  18384. *
  18385. * @returns {boolean} Returns true if url is trusted, false otherwise.
  18386. *
  18387. * @example
  18388. * // Add server
  18389. * TrustedServers.add('my.server.com', 81);
  18390. *
  18391. * // Check if server is trusted
  18392. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  18393. * // my.server.com:81 is trusted
  18394. * }
  18395. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  18396. * // my.server.com isn't trusted
  18397. * }
  18398. */
  18399. TrustedServers.contains = function(url) {
  18400. if (!defined(url)) {
  18401. throw new DeveloperError('url is required.');
  18402. }
  18403. var authority = getAuthority(url);
  18404. if (defined(authority) && defined(_servers[authority])) {
  18405. return true;
  18406. }
  18407. return false;
  18408. };
  18409. /**
  18410. * Clears the registry
  18411. *
  18412. * @example
  18413. * // Remove a trusted server
  18414. * TrustedServers.clear();
  18415. */
  18416. TrustedServers.clear = function() {
  18417. _servers = {};
  18418. };
  18419. return TrustedServers;
  18420. });
  18421. /*global define*/
  18422. define('Core/loadWithXhr',[
  18423. '../ThirdParty/when',
  18424. './defaultValue',
  18425. './defined',
  18426. './DeveloperError',
  18427. './RequestErrorEvent',
  18428. './RuntimeError',
  18429. './TrustedServers'
  18430. ], function(
  18431. when,
  18432. defaultValue,
  18433. defined,
  18434. DeveloperError,
  18435. RequestErrorEvent,
  18436. RuntimeError,
  18437. TrustedServers) {
  18438. 'use strict';
  18439. /**
  18440. * Asynchronously loads the given URL. Returns a promise that will resolve to
  18441. * the result once loaded, or reject if the URL failed to load. The data is loaded
  18442. * using XMLHttpRequest, which means that in order to make requests to another origin,
  18443. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  18444. *
  18445. * @exports loadWithXhr
  18446. *
  18447. * @param {Object} options Object with the following properties:
  18448. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  18449. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  18450. * @param {String} [options.method='GET'] The HTTP method to use.
  18451. * @param {String} [options.data] The data to send with the request, if any.
  18452. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  18453. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  18454. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  18455. *
  18456. *
  18457. * @example
  18458. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  18459. * Cesium.loadWithXhr({
  18460. * url : 'some/url',
  18461. * responseType : 'blob'
  18462. * }).then(function(blob) {
  18463. * // use the data
  18464. * }).otherwise(function(error) {
  18465. * // an error occurred
  18466. * });
  18467. *
  18468. * @see loadArrayBuffer
  18469. * @see loadBlob
  18470. * @see loadJson
  18471. * @see loadText
  18472. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  18473. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  18474. */
  18475. function loadWithXhr(options) {
  18476. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  18477. if (!defined(options.url)) {
  18478. throw new DeveloperError('options.url is required.');
  18479. }
  18480. var responseType = options.responseType;
  18481. var method = defaultValue(options.method, 'GET');
  18482. var data = options.data;
  18483. var headers = options.headers;
  18484. var overrideMimeType = options.overrideMimeType;
  18485. return when(options.url, function(url) {
  18486. var deferred = when.defer();
  18487. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  18488. return deferred.promise;
  18489. });
  18490. }
  18491. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  18492. function decodeDataUriText(isBase64, data) {
  18493. var result = decodeURIComponent(data);
  18494. if (isBase64) {
  18495. return atob(result);
  18496. }
  18497. return result;
  18498. }
  18499. function decodeDataUriArrayBuffer(isBase64, data) {
  18500. var byteString = decodeDataUriText(isBase64, data);
  18501. var buffer = new ArrayBuffer(byteString.length);
  18502. var view = new Uint8Array(buffer);
  18503. for (var i = 0; i < byteString.length; i++) {
  18504. view[i] = byteString.charCodeAt(i);
  18505. }
  18506. return buffer;
  18507. }
  18508. function decodeDataUri(dataUriRegexResult, responseType) {
  18509. responseType = defaultValue(responseType, '');
  18510. var mimeType = dataUriRegexResult[1];
  18511. var isBase64 = !!dataUriRegexResult[2];
  18512. var data = dataUriRegexResult[3];
  18513. switch (responseType) {
  18514. case '':
  18515. case 'text':
  18516. return decodeDataUriText(isBase64, data);
  18517. case 'arraybuffer':
  18518. return decodeDataUriArrayBuffer(isBase64, data);
  18519. case 'blob':
  18520. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  18521. return new Blob([buffer], {
  18522. type : mimeType
  18523. });
  18524. case 'document':
  18525. var parser = new DOMParser();
  18526. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  18527. case 'json':
  18528. return JSON.parse(decodeDataUriText(isBase64, data));
  18529. default:
  18530. throw new DeveloperError('Unhandled responseType: ' + responseType);
  18531. }
  18532. }
  18533. // This is broken out into a separate function so that it can be mocked for testing purposes.
  18534. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  18535. var dataUriRegexResult = dataUriRegex.exec(url);
  18536. if (dataUriRegexResult !== null) {
  18537. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  18538. return;
  18539. }
  18540. var xhr = new XMLHttpRequest();
  18541. if (TrustedServers.contains(url)) {
  18542. xhr.withCredentials = true;
  18543. }
  18544. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  18545. xhr.overrideMimeType(overrideMimeType);
  18546. }
  18547. xhr.open(method, url, true);
  18548. if (defined(headers)) {
  18549. for (var key in headers) {
  18550. if (headers.hasOwnProperty(key)) {
  18551. xhr.setRequestHeader(key, headers[key]);
  18552. }
  18553. }
  18554. }
  18555. if (defined(responseType)) {
  18556. xhr.responseType = responseType;
  18557. }
  18558. xhr.onload = function() {
  18559. if (xhr.status < 200 || xhr.status >= 300) {
  18560. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  18561. return;
  18562. }
  18563. var response = xhr.response;
  18564. var browserResponseType = xhr.responseType;
  18565. //All modern browsers will go into either the first if block or last else block.
  18566. //Other code paths support older browsers that either do not support the supplied responseType
  18567. //or do not support the xhr.response property.
  18568. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  18569. deferred.resolve(response);
  18570. } else if ((responseType === 'json') && typeof response === 'string') {
  18571. try {
  18572. deferred.resolve(JSON.parse(response));
  18573. } catch (e) {
  18574. deferred.reject(e);
  18575. }
  18576. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  18577. deferred.resolve(xhr.responseXML);
  18578. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  18579. deferred.resolve(xhr.responseText);
  18580. } else {
  18581. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  18582. }
  18583. };
  18584. xhr.onerror = function(e) {
  18585. deferred.reject(new RequestErrorEvent());
  18586. };
  18587. xhr.send(data);
  18588. };
  18589. loadWithXhr.defaultLoad = loadWithXhr.load;
  18590. return loadWithXhr;
  18591. });
  18592. /*global define*/
  18593. define('Core/loadText',[
  18594. './loadWithXhr'
  18595. ], function(
  18596. loadWithXhr) {
  18597. 'use strict';
  18598. /**
  18599. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  18600. * a String once loaded, or reject if the URL failed to load. The data is loaded
  18601. * using XMLHttpRequest, which means that in order to make requests to another origin,
  18602. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  18603. *
  18604. * @exports loadText
  18605. *
  18606. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  18607. * @param {Object} [headers] HTTP headers to send with the request.
  18608. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  18609. *
  18610. *
  18611. * @example
  18612. * // load text from a URL, setting a custom header
  18613. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  18614. * 'X-Custom-Header' : 'some value'
  18615. * }).then(function(text) {
  18616. * // Do something with the text
  18617. * }).otherwise(function(error) {
  18618. * // an error occurred
  18619. * });
  18620. *
  18621. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  18622. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  18623. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  18624. */
  18625. function loadText(url, headers) {
  18626. return loadWithXhr({
  18627. url : url,
  18628. headers : headers
  18629. });
  18630. }
  18631. return loadText;
  18632. });
  18633. /*global define*/
  18634. define('Core/loadJson',[
  18635. './clone',
  18636. './defined',
  18637. './DeveloperError',
  18638. './loadText'
  18639. ], function(
  18640. clone,
  18641. defined,
  18642. DeveloperError,
  18643. loadText) {
  18644. 'use strict';
  18645. var defaultHeaders = {
  18646. Accept : 'application/json,*/*;q=0.01'
  18647. };
  18648. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  18649. /**
  18650. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  18651. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  18652. * using XMLHttpRequest, which means that in order to make requests to another origin,
  18653. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  18654. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  18655. * already specified.
  18656. *
  18657. * @exports loadJson
  18658. *
  18659. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  18660. * @param {Object} [headers] HTTP headers to send with the request.
  18661. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  18662. * if not specified.
  18663. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  18664. *
  18665. *
  18666. * @example
  18667. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  18668. * // Do something with the JSON object
  18669. * }).otherwise(function(error) {
  18670. * // an error occurred
  18671. * });
  18672. *
  18673. * @see loadText
  18674. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  18675. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  18676. */
  18677. function loadJson(url, headers) {
  18678. if (!defined(url)) {
  18679. throw new DeveloperError('url is required.');
  18680. }
  18681. if (!defined(headers)) {
  18682. headers = defaultHeaders;
  18683. } else if (!defined(headers.Accept)) {
  18684. // clone before adding the Accept header
  18685. headers = clone(headers);
  18686. headers.Accept = defaultHeaders.Accept;
  18687. }
  18688. return loadText(url, headers).then(function(value) {
  18689. return JSON.parse(value);
  18690. });
  18691. }
  18692. return loadJson;
  18693. });
  18694. /*global define*/
  18695. define('Core/EarthOrientationParameters',[
  18696. '../ThirdParty/when',
  18697. './binarySearch',
  18698. './defaultValue',
  18699. './defined',
  18700. './EarthOrientationParametersSample',
  18701. './freezeObject',
  18702. './JulianDate',
  18703. './LeapSecond',
  18704. './loadJson',
  18705. './RuntimeError',
  18706. './TimeConstants',
  18707. './TimeStandard'
  18708. ], function(
  18709. when,
  18710. binarySearch,
  18711. defaultValue,
  18712. defined,
  18713. EarthOrientationParametersSample,
  18714. freezeObject,
  18715. JulianDate,
  18716. LeapSecond,
  18717. loadJson,
  18718. RuntimeError,
  18719. TimeConstants,
  18720. TimeStandard) {
  18721. 'use strict';
  18722. /**
  18723. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  18724. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  18725. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  18726. * Reference Frame (ITRF).
  18727. *
  18728. * @alias EarthOrientationParameters
  18729. * @constructor
  18730. *
  18731. * @param {Object} [options] Object with the following properties:
  18732. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  18733. * parameter nor options.data is specified, all EOP values are assumed
  18734. * to be 0.0. If options.data is specified, this parameter is
  18735. * ignored.
  18736. * @param {Object} [options.data] The actual EOP data. If neither this
  18737. * parameter nor options.data is specified, all EOP values are assumed
  18738. * to be 0.0.
  18739. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  18740. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  18741. * should be added to {@link JulianDate.leapSeconds}. False if
  18742. * new leap seconds should be handled correctly in the context
  18743. * of the EOP data but otherwise ignored.
  18744. *
  18745. * @example
  18746. * // An example EOP data file, EOP.json:
  18747. * {
  18748. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  18749. * "samples" : [
  18750. * "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,
  18751. * "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,
  18752. * "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
  18753. * ]
  18754. * }
  18755. *
  18756. * @example
  18757. * // Loading the EOP data
  18758. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  18759. * Cesium.Transforms.earthOrientationParameters = eop;
  18760. *
  18761. * @private
  18762. */
  18763. function EarthOrientationParameters(options) {
  18764. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  18765. this._dates = undefined;
  18766. this._samples = undefined;
  18767. this._dateColumn = -1;
  18768. this._xPoleWanderRadiansColumn = -1;
  18769. this._yPoleWanderRadiansColumn = -1;
  18770. this._ut1MinusUtcSecondsColumn = -1;
  18771. this._xCelestialPoleOffsetRadiansColumn = -1;
  18772. this._yCelestialPoleOffsetRadiansColumn = -1;
  18773. this._taiMinusUtcSecondsColumn = -1;
  18774. this._columnCount = 0;
  18775. this._lastIndex = -1;
  18776. this._downloadPromise = undefined;
  18777. this._dataError = undefined;
  18778. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  18779. if (defined(options.data)) {
  18780. // Use supplied EOP data.
  18781. onDataReady(this, options.data);
  18782. } else if (defined(options.url)) {
  18783. // Download EOP data.
  18784. var that = this;
  18785. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  18786. onDataReady(that, eopData);
  18787. }, function() {
  18788. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  18789. });
  18790. } else {
  18791. // Use all zeros for EOP data.
  18792. onDataReady(this, {
  18793. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  18794. 'samples' : []
  18795. });
  18796. }
  18797. }
  18798. /**
  18799. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  18800. */
  18801. EarthOrientationParameters.NONE = freezeObject({
  18802. getPromiseToLoad : function() {
  18803. return when();
  18804. },
  18805. compute : function(date, result) {
  18806. if (!defined(result)) {
  18807. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  18808. } else {
  18809. result.xPoleWander = 0.0;
  18810. result.yPoleWander = 0.0;
  18811. result.xPoleOffset = 0.0;
  18812. result.yPoleOffset = 0.0;
  18813. result.ut1MinusUtc = 0.0;
  18814. }
  18815. return result;
  18816. }
  18817. });
  18818. /**
  18819. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  18820. * ready to use.
  18821. *
  18822. * @returns {Promise.<undefined>} The promise.
  18823. *
  18824. * @see when
  18825. */
  18826. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  18827. return when(this._downloadPromise);
  18828. };
  18829. /**
  18830. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  18831. * If the EOP data has not yet been download, this method returns undefined.
  18832. *
  18833. * @param {JulianDate} date The date for each to evaluate the EOP.
  18834. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  18835. * If this parameter is undefined, a new instance is created and returned.
  18836. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  18837. * undefined if the data necessary to evaluate EOP at the date has not yet been
  18838. * downloaded.
  18839. *
  18840. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  18841. *
  18842. * @see EarthOrientationParameters#getPromiseToLoad
  18843. */
  18844. EarthOrientationParameters.prototype.compute = function(date, result) {
  18845. // We cannot compute until the samples are available.
  18846. if (!defined(this._samples)) {
  18847. if (defined(this._dataError)) {
  18848. throw new RuntimeError(this._dataError);
  18849. }
  18850. return undefined;
  18851. }
  18852. if (!defined(result)) {
  18853. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  18854. }
  18855. if (this._samples.length === 0) {
  18856. result.xPoleWander = 0.0;
  18857. result.yPoleWander = 0.0;
  18858. result.xPoleOffset = 0.0;
  18859. result.yPoleOffset = 0.0;
  18860. result.ut1MinusUtc = 0.0;
  18861. return result;
  18862. }
  18863. var dates = this._dates;
  18864. var lastIndex = this._lastIndex;
  18865. var before = 0;
  18866. var after = 0;
  18867. if (defined(lastIndex)) {
  18868. var previousIndexDate = dates[lastIndex];
  18869. var nextIndexDate = dates[lastIndex + 1];
  18870. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  18871. var isAfterLastSample = !defined(nextIndexDate);
  18872. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  18873. if (isAfterPrevious && isBeforeNext) {
  18874. before = lastIndex;
  18875. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  18876. ++before;
  18877. }
  18878. after = before + 1;
  18879. interpolate(this, dates, this._samples, date, before, after, result);
  18880. return result;
  18881. }
  18882. }
  18883. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  18884. if (index >= 0) {
  18885. // If the next entry is the same date, use the later entry. This way, if two entries
  18886. // describe the same moment, one before a leap second and the other after, then we will use
  18887. // the post-leap second data.
  18888. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  18889. ++index;
  18890. }
  18891. before = index;
  18892. after = index;
  18893. } else {
  18894. after = ~index;
  18895. before = after - 1;
  18896. // Use the first entry if the date requested is before the beginning of the data.
  18897. if (before < 0) {
  18898. before = 0;
  18899. }
  18900. }
  18901. this._lastIndex = before;
  18902. interpolate(this, dates, this._samples, date, before, after, result);
  18903. return result;
  18904. };
  18905. function compareLeapSecondDates(leapSecond, dateToFind) {
  18906. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  18907. }
  18908. function onDataReady(eop, eopData) {
  18909. if (!defined(eopData.columnNames)) {
  18910. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  18911. return;
  18912. }
  18913. if (!defined(eopData.samples)) {
  18914. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  18915. return;
  18916. }
  18917. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  18918. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  18919. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  18920. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  18921. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  18922. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  18923. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  18924. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  18925. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  18926. return;
  18927. }
  18928. var samples = eop._samples = eopData.samples;
  18929. var dates = eop._dates = [];
  18930. eop._dateColumn = dateColumn;
  18931. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  18932. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  18933. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  18934. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  18935. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  18936. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  18937. eop._columnCount = eopData.columnNames.length;
  18938. eop._lastIndex = undefined;
  18939. var lastTaiMinusUtc;
  18940. var addNewLeapSeconds = eop._addNewLeapSeconds;
  18941. // Convert the ISO8601 dates to JulianDates.
  18942. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  18943. var mjd = samples[i + dateColumn];
  18944. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  18945. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  18946. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  18947. dates.push(date);
  18948. if (addNewLeapSeconds) {
  18949. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  18950. // We crossed a leap second boundary, so add the leap second
  18951. // if it does not already exist.
  18952. var leapSeconds = JulianDate.leapSeconds;
  18953. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  18954. if (leapSecondIndex < 0) {
  18955. var leapSecond = new LeapSecond(date, taiMinusUtc);
  18956. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  18957. }
  18958. }
  18959. lastTaiMinusUtc = taiMinusUtc;
  18960. }
  18961. }
  18962. }
  18963. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  18964. var start = index * columnCount;
  18965. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  18966. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  18967. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  18968. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  18969. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  18970. }
  18971. function linearInterp(dx, y1, y2) {
  18972. return y1 + dx * (y2 - y1);
  18973. }
  18974. function interpolate(eop, dates, samples, date, before, after, result) {
  18975. var columnCount = eop._columnCount;
  18976. // First check the bounds on the EOP data
  18977. // If we are after the bounds of the data, return zeros.
  18978. // The 'before' index should never be less than zero.
  18979. if (after > dates.length - 1) {
  18980. result.xPoleWander = 0;
  18981. result.yPoleWander = 0;
  18982. result.xPoleOffset = 0;
  18983. result.yPoleOffset = 0;
  18984. result.ut1MinusUtc = 0;
  18985. return result;
  18986. }
  18987. var beforeDate = dates[before];
  18988. var afterDate = dates[after];
  18989. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  18990. fillResultFromIndex(eop, samples, before, columnCount, result);
  18991. return result;
  18992. } else if (date.equals(afterDate)) {
  18993. fillResultFromIndex(eop, samples, after, columnCount, result);
  18994. return result;
  18995. }
  18996. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  18997. var startBefore = before * columnCount;
  18998. var startAfter = after * columnCount;
  18999. // Handle UT1 leap second edge case
  19000. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  19001. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  19002. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  19003. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  19004. // The absolute difference between the values is more than 0.5, so we may have
  19005. // crossed a leap second. Check if this is the case and, if so, adjust the
  19006. // afterValue to account for the leap second. This way, our interpolation will
  19007. // produce reasonable results.
  19008. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  19009. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  19010. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  19011. if (afterDate.equals(date)) {
  19012. // If we are at the end of the leap second interval, take the second value
  19013. // Otherwise, the interpolation below will yield the wrong side of the
  19014. // discontinuity
  19015. // At the end of the leap second, we need to start accounting for the jump
  19016. beforeUt1MinusUtc = afterUt1MinusUtc;
  19017. } else {
  19018. // Otherwise, remove the leap second so that the interpolation is correct
  19019. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  19020. }
  19021. }
  19022. }
  19023. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  19024. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  19025. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  19026. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  19027. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  19028. return result;
  19029. }
  19030. return EarthOrientationParameters;
  19031. });
  19032. /*global define*/
  19033. define('Core/HeadingPitchRoll',[
  19034. './defaultValue',
  19035. './defined',
  19036. './DeveloperError',
  19037. './Math'
  19038. ], function(
  19039. defaultValue,
  19040. defined,
  19041. DeveloperError,
  19042. CesiumMath) {
  19043. "use strict";
  19044. /**
  19045. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  19046. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  19047. * the positive x axis.
  19048. * @alias HeadingPitchRoll
  19049. * @constructor
  19050. *
  19051. * @param {Number} [heading=0.0] The heading component in radians.
  19052. * @param {Number} [pitch=0.0] The pitch component in radians.
  19053. * @param {Number} [roll=0.0] The roll component in radians.
  19054. */
  19055. function HeadingPitchRoll(heading, pitch, roll) {
  19056. this.heading = defaultValue(heading, 0.0);
  19057. this.pitch = defaultValue(pitch, 0.0);
  19058. this.roll = defaultValue(roll, 0.0);
  19059. }
  19060. /**
  19061. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  19062. *
  19063. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  19064. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  19065. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  19066. */
  19067. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  19068. if (!defined(quaternion)) {
  19069. throw new DeveloperError('quaternion is required');
  19070. }
  19071. if (!defined(result)) {
  19072. result = new HeadingPitchRoll();
  19073. }
  19074. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  19075. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  19076. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  19077. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  19078. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  19079. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  19080. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  19081. result.pitch = -Math.asin(test);
  19082. return result;
  19083. };
  19084. /**
  19085. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  19086. *
  19087. * @param {Number} heading the heading in degrees
  19088. * @param {Number} pitch the pitch in degrees
  19089. * @param {Number} roll the heading in degrees
  19090. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  19091. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  19092. */
  19093. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  19094. if (!defined(heading)) {
  19095. throw new DeveloperError('heading is required');
  19096. }
  19097. if (!defined(pitch)) {
  19098. throw new DeveloperError('pitch is required');
  19099. }
  19100. if (!defined(roll)) {
  19101. throw new DeveloperError('roll is required');
  19102. }
  19103. if (!defined(result)) {
  19104. result = new HeadingPitchRoll();
  19105. }
  19106. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  19107. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  19108. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  19109. return result;
  19110. };
  19111. /**
  19112. * Duplicates a HeadingPitchRoll instance.
  19113. *
  19114. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  19115. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  19116. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  19117. */
  19118. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  19119. if (!defined(headingPitchRoll)) {
  19120. return undefined;
  19121. }
  19122. if (!defined(result)) {
  19123. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  19124. }
  19125. result.heading = headingPitchRoll.heading;
  19126. result.pitch = headingPitchRoll.pitch;
  19127. result.roll = headingPitchRoll.roll;
  19128. return result;
  19129. };
  19130. /**
  19131. * Compares the provided HeadingPitchRolls componentwise and returns
  19132. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19133. *
  19134. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  19135. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  19136. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  19137. */
  19138. HeadingPitchRoll.equals = function(left, right) {
  19139. return (left === right) ||
  19140. ((defined(left)) &&
  19141. (defined(right)) &&
  19142. (left.heading === right.heading) &&
  19143. (left.pitch === right.pitch) &&
  19144. (left.roll === right.roll));
  19145. };
  19146. /**
  19147. * Compares the provided HeadingPitchRolls componentwise and returns
  19148. * <code>true</code> if they pass an absolute or relative tolerance test,
  19149. * <code>false</code> otherwise.
  19150. *
  19151. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  19152. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  19153. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  19154. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  19155. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  19156. */
  19157. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  19158. return (left === right) ||
  19159. (defined(left) &&
  19160. defined(right) &&
  19161. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  19162. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  19163. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  19164. };
  19165. /**
  19166. * Duplicates this HeadingPitchRoll instance.
  19167. *
  19168. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  19169. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  19170. */
  19171. HeadingPitchRoll.prototype.clone = function(result) {
  19172. return HeadingPitchRoll.clone(this, result);
  19173. };
  19174. /**
  19175. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  19176. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19177. *
  19178. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  19179. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  19180. */
  19181. HeadingPitchRoll.prototype.equals = function(right) {
  19182. return HeadingPitchRoll.equals(this, right);
  19183. };
  19184. /**
  19185. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  19186. * <code>true</code> if they pass an absolute or relative tolerance test,
  19187. * <code>false</code> otherwise.
  19188. *
  19189. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  19190. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  19191. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  19192. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  19193. */
  19194. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  19195. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  19196. };
  19197. /**
  19198. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  19199. *
  19200. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  19201. */
  19202. HeadingPitchRoll.prototype.toString = function() {
  19203. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  19204. };
  19205. return HeadingPitchRoll;
  19206. });
  19207. /*global define*/
  19208. define('Core/getAbsoluteUri',[
  19209. '../ThirdParty/Uri',
  19210. './defaultValue',
  19211. './defined',
  19212. './DeveloperError'
  19213. ], function(
  19214. Uri,
  19215. defaultValue,
  19216. defined,
  19217. DeveloperError) {
  19218. 'use strict';
  19219. /**
  19220. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  19221. * @exports getAbsoluteUri
  19222. *
  19223. * @param {String} relative The relative Uri.
  19224. * @param {String} [base] The base Uri.
  19225. * @returns {String} The absolute Uri of the given relative Uri.
  19226. *
  19227. * @example
  19228. * //absolute Uri will be "https://test.com/awesome.png";
  19229. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  19230. */
  19231. function getAbsoluteUri(relative, base) {
  19232. if (!defined(relative)) {
  19233. throw new DeveloperError('relative uri is required.');
  19234. }
  19235. base = defaultValue(base, document.location.href);
  19236. var baseUri = new Uri(base);
  19237. var relativeUri = new Uri(relative);
  19238. return relativeUri.resolve(baseUri).toString();
  19239. }
  19240. return getAbsoluteUri;
  19241. });
  19242. /*global define*/
  19243. define('Core/joinUrls',[
  19244. '../ThirdParty/Uri',
  19245. './defaultValue',
  19246. './defined',
  19247. './DeveloperError'
  19248. ], function(
  19249. Uri,
  19250. defaultValue,
  19251. defined,
  19252. DeveloperError) {
  19253. 'use strict';
  19254. /**
  19255. * Function for joining URLs in a manner that is aware of query strings and fragments.
  19256. * This is useful when the base URL has a query string that needs to be maintained
  19257. * (e.g. a presigned base URL).
  19258. * @param {String|Uri} first The base URL.
  19259. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  19260. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  19261. * @private
  19262. */
  19263. function joinUrls(first, second, appendSlash) {
  19264. if (!defined(first)) {
  19265. throw new DeveloperError('first is required');
  19266. }
  19267. if (!defined(second)) {
  19268. throw new DeveloperError('second is required');
  19269. }
  19270. appendSlash = defaultValue(appendSlash, true);
  19271. if (!(first instanceof Uri)) {
  19272. first = new Uri(first);
  19273. }
  19274. if (!(second instanceof Uri)) {
  19275. second = new Uri(second);
  19276. }
  19277. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  19278. // not a scheme, add a scheme matching the page's scheme.
  19279. if (defined(second.authority) && !defined(second.scheme)) {
  19280. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  19281. second.scheme = new Uri(document.location.href).scheme;
  19282. } else {
  19283. // Not in a browser? Use the first URL's scheme instead.
  19284. second.scheme = first.scheme;
  19285. }
  19286. }
  19287. // If the second URL is absolute, use it for the scheme, authority, and path.
  19288. var baseUri = first;
  19289. if (second.isAbsolute()) {
  19290. baseUri = second;
  19291. }
  19292. var url = '';
  19293. if (defined(baseUri.scheme)) {
  19294. url += baseUri.scheme + ':';
  19295. }
  19296. if (defined(baseUri.authority)) {
  19297. url += '//' + baseUri.authority;
  19298. if (baseUri.path !== '' && baseUri.path !== '/') {
  19299. url = url.replace(/\/?$/, '/');
  19300. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  19301. }
  19302. }
  19303. // Combine the paths (only if second is relative).
  19304. if (baseUri === first) {
  19305. if (appendSlash) {
  19306. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  19307. } else {
  19308. url += first.path + second.path;
  19309. }
  19310. } else {
  19311. url += second.path;
  19312. }
  19313. // Combine the queries and fragments.
  19314. var hasFirstQuery = defined(first.query);
  19315. var hasSecondQuery = defined(second.query);
  19316. if (hasFirstQuery && hasSecondQuery) {
  19317. url += '?' + first.query + '&' + second.query;
  19318. } else if (hasFirstQuery && !hasSecondQuery) {
  19319. url += '?' + first.query;
  19320. } else if (!hasFirstQuery && hasSecondQuery) {
  19321. url += '?' + second.query;
  19322. }
  19323. var hasSecondFragment = defined(second.fragment);
  19324. if (defined(first.fragment) && !hasSecondFragment) {
  19325. url += '#' + first.fragment;
  19326. } else if (hasSecondFragment) {
  19327. url += '#' + second.fragment;
  19328. }
  19329. return url;
  19330. }
  19331. return joinUrls;
  19332. });
  19333. /*global define*/
  19334. define('Core/buildModuleUrl',[
  19335. '../ThirdParty/Uri',
  19336. './defined',
  19337. './DeveloperError',
  19338. './getAbsoluteUri',
  19339. './joinUrls',
  19340. 'require'
  19341. ], function(
  19342. Uri,
  19343. defined,
  19344. DeveloperError,
  19345. getAbsoluteUri,
  19346. joinUrls,
  19347. require) {
  19348. 'use strict';
  19349. /*global CESIUM_BASE_URL*/
  19350. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  19351. function getBaseUrlFromCesiumScript() {
  19352. var scripts = document.getElementsByTagName('script');
  19353. for ( var i = 0, len = scripts.length; i < len; ++i) {
  19354. var src = scripts[i].getAttribute('src');
  19355. var result = cesiumScriptRegex.exec(src);
  19356. if (result !== null) {
  19357. return result[1];
  19358. }
  19359. }
  19360. return undefined;
  19361. }
  19362. var baseUrl;
  19363. function getCesiumBaseUrl() {
  19364. if (defined(baseUrl)) {
  19365. return baseUrl;
  19366. }
  19367. var baseUrlString;
  19368. if (typeof CESIUM_BASE_URL !== 'undefined') {
  19369. baseUrlString = CESIUM_BASE_URL;
  19370. } else {
  19371. baseUrlString = getBaseUrlFromCesiumScript();
  19372. }
  19373. if (!defined(baseUrlString)) {
  19374. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  19375. }
  19376. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  19377. return baseUrl;
  19378. }
  19379. function buildModuleUrlFromRequireToUrl(moduleID) {
  19380. //moduleID will be non-relative, so require it relative to this module, in Core.
  19381. return require.toUrl('../' + moduleID);
  19382. }
  19383. function buildModuleUrlFromBaseUrl(moduleID) {
  19384. return joinUrls(getCesiumBaseUrl(), moduleID);
  19385. }
  19386. var implementation;
  19387. var a;
  19388. /**
  19389. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  19390. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  19391. * the base URL of the Cesium.js script.
  19392. *
  19393. * @private
  19394. */
  19395. function buildModuleUrl(moduleID) {
  19396. if (!defined(implementation)) {
  19397. //select implementation
  19398. if (defined(require.toUrl)) {
  19399. implementation = buildModuleUrlFromRequireToUrl;
  19400. } else {
  19401. implementation = buildModuleUrlFromBaseUrl;
  19402. }
  19403. }
  19404. if (!defined(a)) {
  19405. a = document.createElement('a');
  19406. }
  19407. var url = implementation(moduleID);
  19408. a.href = url;
  19409. a.href = a.href; // IE only absolutizes href on get, not set
  19410. return a.href;
  19411. }
  19412. // exposed for testing
  19413. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  19414. /**
  19415. * Sets the base URL for resolving modules.
  19416. * @param {String} value The new base URL.
  19417. */
  19418. buildModuleUrl.setBaseUrl = function(value) {
  19419. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  19420. };
  19421. return buildModuleUrl;
  19422. });
  19423. /*global define*/
  19424. define('Core/Iau2006XysSample',[],function() {
  19425. 'use strict';
  19426. /**
  19427. * An IAU 2006 XYS value sampled at a particular time.
  19428. *
  19429. * @alias Iau2006XysSample
  19430. * @constructor
  19431. *
  19432. * @param {Number} x The X value.
  19433. * @param {Number} y The Y value.
  19434. * @param {Number} s The S value.
  19435. *
  19436. * @private
  19437. */
  19438. function Iau2006XysSample(x, y, s) {
  19439. /**
  19440. * The X value.
  19441. * @type {Number}
  19442. */
  19443. this.x = x;
  19444. /**
  19445. * The Y value.
  19446. * @type {Number}
  19447. */
  19448. this.y = y;
  19449. /**
  19450. * The S value.
  19451. * @type {Number}
  19452. */
  19453. this.s = s;
  19454. }
  19455. return Iau2006XysSample;
  19456. });
  19457. /*global define*/
  19458. define('Core/Iau2006XysData',[
  19459. '../ThirdParty/when',
  19460. './buildModuleUrl',
  19461. './defaultValue',
  19462. './defined',
  19463. './Iau2006XysSample',
  19464. './JulianDate',
  19465. './loadJson',
  19466. './TimeStandard'
  19467. ], function(
  19468. when,
  19469. buildModuleUrl,
  19470. defaultValue,
  19471. defined,
  19472. Iau2006XysSample,
  19473. JulianDate,
  19474. loadJson,
  19475. TimeStandard) {
  19476. 'use strict';
  19477. /**
  19478. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  19479. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  19480. *
  19481. * @alias Iau2006XysData
  19482. * @constructor
  19483. *
  19484. * @param {Object} [options] Object with the following properties:
  19485. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  19486. * `{0}` will be replaced with the file index.
  19487. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  19488. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  19489. * first XYS sample.
  19490. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  19491. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  19492. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  19493. *
  19494. * @private
  19495. */
  19496. function Iau2006XysData(options) {
  19497. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  19498. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  19499. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  19500. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  19501. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  19502. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  19503. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  19504. this._totalSamples = defaultValue(options.totalSamples, 27426);
  19505. this._samples = new Array(this._totalSamples * 3);
  19506. this._chunkDownloadsInProgress = [];
  19507. var order = this._interpolationOrder;
  19508. // Compute denominators and X values for interpolation.
  19509. var denom = this._denominators = new Array(order + 1);
  19510. var xTable = this._xTable = new Array(order + 1);
  19511. var stepN = Math.pow(this._stepSizeDays, order);
  19512. for ( var i = 0; i <= order; ++i) {
  19513. denom[i] = stepN;
  19514. xTable[i] = i * this._stepSizeDays;
  19515. for ( var j = 0; j <= order; ++j) {
  19516. if (j !== i) {
  19517. denom[i] *= (i - j);
  19518. }
  19519. }
  19520. denom[i] = 1.0 / denom[i];
  19521. }
  19522. // Allocate scratch arrays for interpolation.
  19523. this._work = new Array(order + 1);
  19524. this._coef = new Array(order + 1);
  19525. }
  19526. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  19527. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  19528. var dateTT = julianDateScratch;
  19529. dateTT.dayNumber = dayTT;
  19530. dateTT.secondsOfDay = secondTT;
  19531. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  19532. }
  19533. /**
  19534. * Preloads XYS data for a specified date range.
  19535. *
  19536. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  19537. * the Terrestrial Time (TT) time standard.
  19538. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  19539. * the Terrestrial Time (TT) time standard.
  19540. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  19541. * the Terrestrial Time (TT) time standard.
  19542. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  19543. * the Terrestrial Time (TT) time standard.
  19544. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  19545. * preloaded.
  19546. */
  19547. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  19548. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  19549. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  19550. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  19551. if (startIndex < 0) {
  19552. startIndex = 0;
  19553. }
  19554. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  19555. if (stopIndex >= this._totalSamples) {
  19556. stopIndex = this._totalSamples - 1;
  19557. }
  19558. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  19559. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  19560. var promises = [];
  19561. for ( var i = startChunk; i <= stopChunk; ++i) {
  19562. promises.push(requestXysChunk(this, i));
  19563. }
  19564. return when.all(promises);
  19565. };
  19566. /**
  19567. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  19568. * this method will return undefined.
  19569. *
  19570. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  19571. * the Terrestrial Time (TT) time standard.
  19572. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  19573. * the Terrestrial Time (TT) time standard.
  19574. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  19575. * is undefined, a new instance is allocated and returned.
  19576. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  19577. * computation has not yet been downloaded.
  19578. *
  19579. * @see Iau2006XysData#preload
  19580. */
  19581. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  19582. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  19583. if (daysSinceEpoch < 0.0) {
  19584. // Can't evaluate prior to the epoch of the data.
  19585. return undefined;
  19586. }
  19587. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  19588. if (centerIndex >= this._totalSamples) {
  19589. // Can't evaluate after the last sample in the data.
  19590. return undefined;
  19591. }
  19592. var degree = this._interpolationOrder;
  19593. var firstIndex = centerIndex - ((degree / 2) | 0);
  19594. if (firstIndex < 0) {
  19595. firstIndex = 0;
  19596. }
  19597. var lastIndex = firstIndex + degree;
  19598. if (lastIndex >= this._totalSamples) {
  19599. lastIndex = this._totalSamples - 1;
  19600. firstIndex = lastIndex - degree;
  19601. if (firstIndex < 0) {
  19602. firstIndex = 0;
  19603. }
  19604. }
  19605. // Are all the samples we need present?
  19606. // We can assume so if the first and last are present
  19607. var isDataMissing = false;
  19608. var samples = this._samples;
  19609. if (!defined(samples[firstIndex * 3])) {
  19610. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  19611. isDataMissing = true;
  19612. }
  19613. if (!defined(samples[lastIndex * 3])) {
  19614. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  19615. isDataMissing = true;
  19616. }
  19617. if (isDataMissing) {
  19618. return undefined;
  19619. }
  19620. if (!defined(result)) {
  19621. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  19622. } else {
  19623. result.x = 0.0;
  19624. result.y = 0.0;
  19625. result.s = 0.0;
  19626. }
  19627. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  19628. var work = this._work;
  19629. var denom = this._denominators;
  19630. var coef = this._coef;
  19631. var xTable = this._xTable;
  19632. var i, j;
  19633. for (i = 0; i <= degree; ++i) {
  19634. work[i] = x - xTable[i];
  19635. }
  19636. for (i = 0; i <= degree; ++i) {
  19637. coef[i] = 1.0;
  19638. for (j = 0; j <= degree; ++j) {
  19639. if (j !== i) {
  19640. coef[i] *= work[j];
  19641. }
  19642. }
  19643. coef[i] *= denom[i];
  19644. var sampleIndex = (firstIndex + i) * 3;
  19645. result.x += coef[i] * samples[sampleIndex++];
  19646. result.y += coef[i] * samples[sampleIndex++];
  19647. result.s += coef[i] * samples[sampleIndex];
  19648. }
  19649. return result;
  19650. };
  19651. function requestXysChunk(xysData, chunkIndex) {
  19652. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  19653. // Chunk has already been requested.
  19654. return xysData._chunkDownloadsInProgress[chunkIndex];
  19655. }
  19656. var deferred = when.defer();
  19657. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  19658. var chunkUrl;
  19659. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  19660. if (defined(xysFileUrlTemplate)) {
  19661. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  19662. } else {
  19663. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  19664. }
  19665. when(loadJson(chunkUrl), function(chunk) {
  19666. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  19667. var samples = xysData._samples;
  19668. var newSamples = chunk.samples;
  19669. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  19670. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  19671. samples[startIndex + i] = newSamples[i];
  19672. }
  19673. deferred.resolve();
  19674. });
  19675. return deferred.promise;
  19676. }
  19677. return Iau2006XysData;
  19678. });
  19679. /*global define*/
  19680. define('Core/Quaternion',[
  19681. './Cartesian3',
  19682. './defaultValue',
  19683. './defined',
  19684. './DeveloperError',
  19685. './FeatureDetection',
  19686. './freezeObject',
  19687. './Math',
  19688. './Matrix3'
  19689. ], function(
  19690. Cartesian3,
  19691. defaultValue,
  19692. defined,
  19693. DeveloperError,
  19694. FeatureDetection,
  19695. freezeObject,
  19696. CesiumMath,
  19697. Matrix3) {
  19698. 'use strict';
  19699. /**
  19700. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  19701. * @alias Quaternion
  19702. * @constructor
  19703. *
  19704. * @param {Number} [x=0.0] The X component.
  19705. * @param {Number} [y=0.0] The Y component.
  19706. * @param {Number} [z=0.0] The Z component.
  19707. * @param {Number} [w=0.0] The W component.
  19708. *
  19709. * @see PackableForInterpolation
  19710. */
  19711. function Quaternion(x, y, z, w) {
  19712. /**
  19713. * The X component.
  19714. * @type {Number}
  19715. * @default 0.0
  19716. */
  19717. this.x = defaultValue(x, 0.0);
  19718. /**
  19719. * The Y component.
  19720. * @type {Number}
  19721. * @default 0.0
  19722. */
  19723. this.y = defaultValue(y, 0.0);
  19724. /**
  19725. * The Z component.
  19726. * @type {Number}
  19727. * @default 0.0
  19728. */
  19729. this.z = defaultValue(z, 0.0);
  19730. /**
  19731. * The W component.
  19732. * @type {Number}
  19733. * @default 0.0
  19734. */
  19735. this.w = defaultValue(w, 0.0);
  19736. }
  19737. var fromAxisAngleScratch = new Cartesian3();
  19738. /**
  19739. * Computes a quaternion representing a rotation around an axis.
  19740. *
  19741. * @param {Cartesian3} axis The axis of rotation.
  19742. * @param {Number} angle The angle in radians to rotate around the axis.
  19743. * @param {Quaternion} [result] The object onto which to store the result.
  19744. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  19745. */
  19746. Quaternion.fromAxisAngle = function(axis, angle, result) {
  19747. if (!defined(axis)) {
  19748. throw new DeveloperError('axis is required.');
  19749. }
  19750. if (typeof angle !== 'number') {
  19751. throw new DeveloperError('angle is required and must be a number.');
  19752. }
  19753. var halfAngle = angle / 2.0;
  19754. var s = Math.sin(halfAngle);
  19755. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  19756. var x = fromAxisAngleScratch.x * s;
  19757. var y = fromAxisAngleScratch.y * s;
  19758. var z = fromAxisAngleScratch.z * s;
  19759. var w = Math.cos(halfAngle);
  19760. if (!defined(result)) {
  19761. return new Quaternion(x, y, z, w);
  19762. }
  19763. result.x = x;
  19764. result.y = y;
  19765. result.z = z;
  19766. result.w = w;
  19767. return result;
  19768. };
  19769. var fromRotationMatrixNext = [1, 2, 0];
  19770. var fromRotationMatrixQuat = new Array(3);
  19771. /**
  19772. * Computes a Quaternion from the provided Matrix3 instance.
  19773. *
  19774. * @param {Matrix3} matrix The rotation matrix.
  19775. * @param {Quaternion} [result] The object onto which to store the result.
  19776. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  19777. *
  19778. * @see Matrix3.fromQuaternion
  19779. */
  19780. Quaternion.fromRotationMatrix = function(matrix, result) {
  19781. if (!defined(matrix)) {
  19782. throw new DeveloperError('matrix is required.');
  19783. }
  19784. var root;
  19785. var x;
  19786. var y;
  19787. var z;
  19788. var w;
  19789. var m00 = matrix[Matrix3.COLUMN0ROW0];
  19790. var m11 = matrix[Matrix3.COLUMN1ROW1];
  19791. var m22 = matrix[Matrix3.COLUMN2ROW2];
  19792. var trace = m00 + m11 + m22;
  19793. if (trace > 0.0) {
  19794. // |w| > 1/2, may as well choose w > 1/2
  19795. root = Math.sqrt(trace + 1.0); // 2w
  19796. w = 0.5 * root;
  19797. root = 0.5 / root; // 1/(4w)
  19798. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  19799. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  19800. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  19801. } else {
  19802. // |w| <= 1/2
  19803. var next = fromRotationMatrixNext;
  19804. var i = 0;
  19805. if (m11 > m00) {
  19806. i = 1;
  19807. }
  19808. if (m22 > m00 && m22 > m11) {
  19809. i = 2;
  19810. }
  19811. var j = next[i];
  19812. var k = next[j];
  19813. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  19814. var quat = fromRotationMatrixQuat;
  19815. quat[i] = 0.5 * root;
  19816. root = 0.5 / root;
  19817. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  19818. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  19819. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  19820. x = -quat[0];
  19821. y = -quat[1];
  19822. z = -quat[2];
  19823. }
  19824. if (!defined(result)) {
  19825. return new Quaternion(x, y, z, w);
  19826. }
  19827. result.x = x;
  19828. result.y = y;
  19829. result.z = z;
  19830. result.w = w;
  19831. return result;
  19832. };
  19833. var scratchHPRQuaternion = new Quaternion();
  19834. /**
  19835. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  19836. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  19837. * the positive x axis.
  19838. *
  19839. * @param {Number} heading The heading angle in radians.
  19840. * @param {Number} pitch The pitch angle in radians.
  19841. * @param {Number} roll The roll angle in radians.
  19842. * @param {Quaternion} [result] The object onto which to store the result.
  19843. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  19844. */
  19845. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  19846. if (!defined(heading)) {
  19847. throw new DeveloperError('heading is required.');
  19848. }
  19849. if (!defined(pitch)) {
  19850. throw new DeveloperError('pitch is required.');
  19851. }
  19852. if (!defined(roll)) {
  19853. throw new DeveloperError('roll is required.');
  19854. }
  19855. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  19856. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  19857. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  19858. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  19859. return Quaternion.multiply(headingQuaternion, result, result);
  19860. };
  19861. var sampledQuaternionAxis = new Cartesian3();
  19862. var sampledQuaternionRotation = new Cartesian3();
  19863. var sampledQuaternionTempQuaternion = new Quaternion();
  19864. var sampledQuaternionQuaternion0 = new Quaternion();
  19865. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  19866. /**
  19867. * The number of elements used to pack the object into an array.
  19868. * @type {Number}
  19869. */
  19870. Quaternion.packedLength = 4;
  19871. /**
  19872. * Stores the provided instance into the provided array.
  19873. *
  19874. * @param {Quaternion} value The value to pack.
  19875. * @param {Number[]} array The array to pack into.
  19876. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  19877. *
  19878. * @returns {Number[]} The array that was packed into
  19879. */
  19880. Quaternion.pack = function(value, array, startingIndex) {
  19881. if (!defined(value)) {
  19882. throw new DeveloperError('value is required');
  19883. }
  19884. if (!defined(array)) {
  19885. throw new DeveloperError('array is required');
  19886. }
  19887. startingIndex = defaultValue(startingIndex, 0);
  19888. array[startingIndex++] = value.x;
  19889. array[startingIndex++] = value.y;
  19890. array[startingIndex++] = value.z;
  19891. array[startingIndex] = value.w;
  19892. return array;
  19893. };
  19894. /**
  19895. * Retrieves an instance from a packed array.
  19896. *
  19897. * @param {Number[]} array The packed array.
  19898. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  19899. * @param {Quaternion} [result] The object into which to store the result.
  19900. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  19901. */
  19902. Quaternion.unpack = function(array, startingIndex, result) {
  19903. if (!defined(array)) {
  19904. throw new DeveloperError('array is required');
  19905. }
  19906. startingIndex = defaultValue(startingIndex, 0);
  19907. if (!defined(result)) {
  19908. result = new Quaternion();
  19909. }
  19910. result.x = array[startingIndex];
  19911. result.y = array[startingIndex + 1];
  19912. result.z = array[startingIndex + 2];
  19913. result.w = array[startingIndex + 3];
  19914. return result;
  19915. };
  19916. /**
  19917. * The number of elements used to store the object into an array in its interpolatable form.
  19918. * @type {Number}
  19919. */
  19920. Quaternion.packedInterpolationLength = 3;
  19921. /**
  19922. * Converts a packed array into a form suitable for interpolation.
  19923. *
  19924. * @param {Number[]} packedArray The packed array.
  19925. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  19926. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  19927. * @param {Number[]} result The object into which to store the result.
  19928. */
  19929. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  19930. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  19931. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  19932. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  19933. var offset = i * 3;
  19934. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  19935. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  19936. if (sampledQuaternionTempQuaternion.w < 0) {
  19937. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  19938. }
  19939. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  19940. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  19941. result[offset] = sampledQuaternionAxis.x * angle;
  19942. result[offset + 1] = sampledQuaternionAxis.y * angle;
  19943. result[offset + 2] = sampledQuaternionAxis.z * angle;
  19944. }
  19945. };
  19946. /**
  19947. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  19948. *
  19949. * @param {Number[]} array The array previously packed for interpolation.
  19950. * @param {Number[]} sourceArray The original packed array.
  19951. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  19952. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  19953. * @param {Quaternion} [result] The object into which to store the result.
  19954. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  19955. */
  19956. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  19957. if (!defined(result)) {
  19958. result = new Quaternion();
  19959. }
  19960. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  19961. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  19962. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  19963. if (magnitude === 0) {
  19964. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  19965. } else {
  19966. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  19967. }
  19968. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  19969. };
  19970. /**
  19971. * Duplicates a Quaternion instance.
  19972. *
  19973. * @param {Quaternion} quaternion The quaternion to duplicate.
  19974. * @param {Quaternion} [result] The object onto which to store the result.
  19975. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  19976. */
  19977. Quaternion.clone = function(quaternion, result) {
  19978. if (!defined(quaternion)) {
  19979. return undefined;
  19980. }
  19981. if (!defined(result)) {
  19982. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  19983. }
  19984. result.x = quaternion.x;
  19985. result.y = quaternion.y;
  19986. result.z = quaternion.z;
  19987. result.w = quaternion.w;
  19988. return result;
  19989. };
  19990. /**
  19991. * Computes the conjugate of the provided quaternion.
  19992. *
  19993. * @param {Quaternion} quaternion The quaternion to conjugate.
  19994. * @param {Quaternion} result The object onto which to store the result.
  19995. * @returns {Quaternion} The modified result parameter.
  19996. */
  19997. Quaternion.conjugate = function(quaternion, result) {
  19998. if (!defined(quaternion)) {
  19999. throw new DeveloperError('quaternion is required');
  20000. }
  20001. if (!defined(result)) {
  20002. throw new DeveloperError('result is required');
  20003. }
  20004. result.x = -quaternion.x;
  20005. result.y = -quaternion.y;
  20006. result.z = -quaternion.z;
  20007. result.w = quaternion.w;
  20008. return result;
  20009. };
  20010. /**
  20011. * Computes magnitude squared for the provided quaternion.
  20012. *
  20013. * @param {Quaternion} quaternion The quaternion to conjugate.
  20014. * @returns {Number} The magnitude squared.
  20015. */
  20016. Quaternion.magnitudeSquared = function(quaternion) {
  20017. if (!defined(quaternion)) {
  20018. throw new DeveloperError('quaternion is required');
  20019. }
  20020. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  20021. };
  20022. /**
  20023. * Computes magnitude for the provided quaternion.
  20024. *
  20025. * @param {Quaternion} quaternion The quaternion to conjugate.
  20026. * @returns {Number} The magnitude.
  20027. */
  20028. Quaternion.magnitude = function(quaternion) {
  20029. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  20030. };
  20031. /**
  20032. * Computes the normalized form of the provided quaternion.
  20033. *
  20034. * @param {Quaternion} quaternion The quaternion to normalize.
  20035. * @param {Quaternion} result The object onto which to store the result.
  20036. * @returns {Quaternion} The modified result parameter.
  20037. */
  20038. Quaternion.normalize = function(quaternion, result) {
  20039. if (!defined(result)) {
  20040. throw new DeveloperError('result is required');
  20041. }
  20042. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  20043. var x = quaternion.x * inverseMagnitude;
  20044. var y = quaternion.y * inverseMagnitude;
  20045. var z = quaternion.z * inverseMagnitude;
  20046. var w = quaternion.w * inverseMagnitude;
  20047. result.x = x;
  20048. result.y = y;
  20049. result.z = z;
  20050. result.w = w;
  20051. return result;
  20052. };
  20053. /**
  20054. * Computes the inverse of the provided quaternion.
  20055. *
  20056. * @param {Quaternion} quaternion The quaternion to normalize.
  20057. * @param {Quaternion} result The object onto which to store the result.
  20058. * @returns {Quaternion} The modified result parameter.
  20059. */
  20060. Quaternion.inverse = function(quaternion, result) {
  20061. if (!defined(result)) {
  20062. throw new DeveloperError('result is required');
  20063. }
  20064. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  20065. result = Quaternion.conjugate(quaternion, result);
  20066. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  20067. };
  20068. /**
  20069. * Computes the componentwise sum of two quaternions.
  20070. *
  20071. * @param {Quaternion} left The first quaternion.
  20072. * @param {Quaternion} right The second quaternion.
  20073. * @param {Quaternion} result The object onto which to store the result.
  20074. * @returns {Quaternion} The modified result parameter.
  20075. */
  20076. Quaternion.add = function(left, right, result) {
  20077. if (!defined(left)) {
  20078. throw new DeveloperError('left is required');
  20079. }
  20080. if (!defined(right)) {
  20081. throw new DeveloperError('right is required');
  20082. }
  20083. if (!defined(result)) {
  20084. throw new DeveloperError('result is required');
  20085. }
  20086. result.x = left.x + right.x;
  20087. result.y = left.y + right.y;
  20088. result.z = left.z + right.z;
  20089. result.w = left.w + right.w;
  20090. return result;
  20091. };
  20092. /**
  20093. * Computes the componentwise difference of two quaternions.
  20094. *
  20095. * @param {Quaternion} left The first quaternion.
  20096. * @param {Quaternion} right The second quaternion.
  20097. * @param {Quaternion} result The object onto which to store the result.
  20098. * @returns {Quaternion} The modified result parameter.
  20099. */
  20100. Quaternion.subtract = function(left, right, result) {
  20101. if (!defined(left)) {
  20102. throw new DeveloperError('left is required');
  20103. }
  20104. if (!defined(right)) {
  20105. throw new DeveloperError('right is required');
  20106. }
  20107. if (!defined(result)) {
  20108. throw new DeveloperError('result is required');
  20109. }
  20110. result.x = left.x - right.x;
  20111. result.y = left.y - right.y;
  20112. result.z = left.z - right.z;
  20113. result.w = left.w - right.w;
  20114. return result;
  20115. };
  20116. /**
  20117. * Negates the provided quaternion.
  20118. *
  20119. * @param {Quaternion} quaternion The quaternion to be negated.
  20120. * @param {Quaternion} result The object onto which to store the result.
  20121. * @returns {Quaternion} The modified result parameter.
  20122. */
  20123. Quaternion.negate = function(quaternion, result) {
  20124. if (!defined(quaternion)) {
  20125. throw new DeveloperError('quaternion is required');
  20126. }
  20127. if (!defined(result)) {
  20128. throw new DeveloperError('result is required');
  20129. }
  20130. result.x = -quaternion.x;
  20131. result.y = -quaternion.y;
  20132. result.z = -quaternion.z;
  20133. result.w = -quaternion.w;
  20134. return result;
  20135. };
  20136. /**
  20137. * Computes the dot (scalar) product of two quaternions.
  20138. *
  20139. * @param {Quaternion} left The first quaternion.
  20140. * @param {Quaternion} right The second quaternion.
  20141. * @returns {Number} The dot product.
  20142. */
  20143. Quaternion.dot = function(left, right) {
  20144. if (!defined(left)) {
  20145. throw new DeveloperError('left is required');
  20146. }
  20147. if (!defined(right)) {
  20148. throw new DeveloperError('right is required');
  20149. }
  20150. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  20151. };
  20152. /**
  20153. * Computes the product of two quaternions.
  20154. *
  20155. * @param {Quaternion} left The first quaternion.
  20156. * @param {Quaternion} right The second quaternion.
  20157. * @param {Quaternion} result The object onto which to store the result.
  20158. * @returns {Quaternion} The modified result parameter.
  20159. */
  20160. Quaternion.multiply = function(left, right, result) {
  20161. if (!defined(left)) {
  20162. throw new DeveloperError('left is required');
  20163. }
  20164. if (!defined(right)) {
  20165. throw new DeveloperError('right is required');
  20166. }
  20167. if (!defined(result)) {
  20168. throw new DeveloperError('result is required');
  20169. }
  20170. var leftX = left.x;
  20171. var leftY = left.y;
  20172. var leftZ = left.z;
  20173. var leftW = left.w;
  20174. var rightX = right.x;
  20175. var rightY = right.y;
  20176. var rightZ = right.z;
  20177. var rightW = right.w;
  20178. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  20179. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  20180. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  20181. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  20182. result.x = x;
  20183. result.y = y;
  20184. result.z = z;
  20185. result.w = w;
  20186. return result;
  20187. };
  20188. /**
  20189. * Multiplies the provided quaternion componentwise by the provided scalar.
  20190. *
  20191. * @param {Quaternion} quaternion The quaternion to be scaled.
  20192. * @param {Number} scalar The scalar to multiply with.
  20193. * @param {Quaternion} result The object onto which to store the result.
  20194. * @returns {Quaternion} The modified result parameter.
  20195. */
  20196. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  20197. if (!defined(quaternion)) {
  20198. throw new DeveloperError('quaternion is required');
  20199. }
  20200. if (typeof scalar !== 'number') {
  20201. throw new DeveloperError('scalar is required and must be a number.');
  20202. }
  20203. if (!defined(result)) {
  20204. throw new DeveloperError('result is required');
  20205. }
  20206. result.x = quaternion.x * scalar;
  20207. result.y = quaternion.y * scalar;
  20208. result.z = quaternion.z * scalar;
  20209. result.w = quaternion.w * scalar;
  20210. return result;
  20211. };
  20212. /**
  20213. * Divides the provided quaternion componentwise by the provided scalar.
  20214. *
  20215. * @param {Quaternion} quaternion The quaternion to be divided.
  20216. * @param {Number} scalar The scalar to divide by.
  20217. * @param {Quaternion} result The object onto which to store the result.
  20218. * @returns {Quaternion} The modified result parameter.
  20219. */
  20220. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  20221. if (!defined(quaternion)) {
  20222. throw new DeveloperError('quaternion is required');
  20223. }
  20224. if (typeof scalar !== 'number') {
  20225. throw new DeveloperError('scalar is required and must be a number.');
  20226. }
  20227. if (!defined(result)) {
  20228. throw new DeveloperError('result is required');
  20229. }
  20230. result.x = quaternion.x / scalar;
  20231. result.y = quaternion.y / scalar;
  20232. result.z = quaternion.z / scalar;
  20233. result.w = quaternion.w / scalar;
  20234. return result;
  20235. };
  20236. /**
  20237. * Computes the axis of rotation of the provided quaternion.
  20238. *
  20239. * @param {Quaternion} quaternion The quaternion to use.
  20240. * @param {Cartesian3} result The object onto which to store the result.
  20241. * @returns {Cartesian3} The modified result parameter.
  20242. */
  20243. Quaternion.computeAxis = function(quaternion, result) {
  20244. if (!defined(quaternion)) {
  20245. throw new DeveloperError('quaternion is required');
  20246. }
  20247. if (!defined(result)) {
  20248. throw new DeveloperError('result is required');
  20249. }
  20250. var w = quaternion.w;
  20251. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  20252. result.x = result.y = result.z = 0;
  20253. return result;
  20254. }
  20255. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  20256. result.x = quaternion.x * scalar;
  20257. result.y = quaternion.y * scalar;
  20258. result.z = quaternion.z * scalar;
  20259. return result;
  20260. };
  20261. /**
  20262. * Computes the angle of rotation of the provided quaternion.
  20263. *
  20264. * @param {Quaternion} quaternion The quaternion to use.
  20265. * @returns {Number} The angle of rotation.
  20266. */
  20267. Quaternion.computeAngle = function(quaternion) {
  20268. if (!defined(quaternion)) {
  20269. throw new DeveloperError('quaternion is required');
  20270. }
  20271. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  20272. return 0.0;
  20273. }
  20274. return 2.0 * Math.acos(quaternion.w);
  20275. };
  20276. var lerpScratch = new Quaternion();
  20277. /**
  20278. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  20279. *
  20280. * @param {Quaternion} start The value corresponding to t at 0.0.
  20281. * @param {Quaternion} end The value corresponding to t at 1.0.
  20282. * @param {Number} t The point along t at which to interpolate.
  20283. * @param {Quaternion} result The object onto which to store the result.
  20284. * @returns {Quaternion} The modified result parameter.
  20285. */
  20286. Quaternion.lerp = function(start, end, t, result) {
  20287. if (!defined(start)) {
  20288. throw new DeveloperError('start is required.');
  20289. }
  20290. if (!defined(end)) {
  20291. throw new DeveloperError('end is required.');
  20292. }
  20293. if (typeof t !== 'number') {
  20294. throw new DeveloperError('t is required and must be a number.');
  20295. }
  20296. if (!defined(result)) {
  20297. throw new DeveloperError('result is required');
  20298. }
  20299. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  20300. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  20301. return Quaternion.add(lerpScratch, result, result);
  20302. };
  20303. var slerpEndNegated = new Quaternion();
  20304. var slerpScaledP = new Quaternion();
  20305. var slerpScaledR = new Quaternion();
  20306. /**
  20307. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  20308. *
  20309. * @param {Quaternion} start The value corresponding to t at 0.0.
  20310. * @param {Quaternion} end The value corresponding to t at 1.0.
  20311. * @param {Number} t The point along t at which to interpolate.
  20312. * @param {Quaternion} result The object onto which to store the result.
  20313. * @returns {Quaternion} The modified result parameter.
  20314. *
  20315. * @see Quaternion#fastSlerp
  20316. */
  20317. Quaternion.slerp = function(start, end, t, result) {
  20318. if (!defined(start)) {
  20319. throw new DeveloperError('start is required.');
  20320. }
  20321. if (!defined(end)) {
  20322. throw new DeveloperError('end is required.');
  20323. }
  20324. if (typeof t !== 'number') {
  20325. throw new DeveloperError('t is required and must be a number.');
  20326. }
  20327. if (!defined(result)) {
  20328. throw new DeveloperError('result is required');
  20329. }
  20330. var dot = Quaternion.dot(start, end);
  20331. // The angle between start must be acute. Since q and -q represent
  20332. // the same rotation, negate q to get the acute angle.
  20333. var r = end;
  20334. if (dot < 0.0) {
  20335. dot = -dot;
  20336. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  20337. }
  20338. // dot > 0, as the dot product approaches 1, the angle between the
  20339. // quaternions vanishes. use linear interpolation.
  20340. if (1.0 - dot < CesiumMath.EPSILON6) {
  20341. return Quaternion.lerp(start, r, t, result);
  20342. }
  20343. var theta = Math.acos(dot);
  20344. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  20345. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  20346. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  20347. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  20348. };
  20349. /**
  20350. * The logarithmic quaternion function.
  20351. *
  20352. * @param {Quaternion} quaternion The unit quaternion.
  20353. * @param {Cartesian3} result The object onto which to store the result.
  20354. * @returns {Cartesian3} The modified result parameter.
  20355. */
  20356. Quaternion.log = function(quaternion, result) {
  20357. if (!defined(quaternion)) {
  20358. throw new DeveloperError('quaternion is required.');
  20359. }
  20360. if (!defined(result)) {
  20361. throw new DeveloperError('result is required');
  20362. }
  20363. var theta = CesiumMath.acosClamped(quaternion.w);
  20364. var thetaOverSinTheta = 0.0;
  20365. if (theta !== 0.0) {
  20366. thetaOverSinTheta = theta / Math.sin(theta);
  20367. }
  20368. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  20369. };
  20370. /**
  20371. * The exponential quaternion function.
  20372. *
  20373. * @param {Cartesian3} cartesian The cartesian.
  20374. * @param {Quaternion} result The object onto which to store the result.
  20375. * @returns {Quaternion} The modified result parameter.
  20376. */
  20377. Quaternion.exp = function(cartesian, result) {
  20378. if (!defined(cartesian)) {
  20379. throw new DeveloperError('cartesian is required.');
  20380. }
  20381. if (!defined(result)) {
  20382. throw new DeveloperError('result is required');
  20383. }
  20384. var theta = Cartesian3.magnitude(cartesian);
  20385. var sinThetaOverTheta = 0.0;
  20386. if (theta !== 0.0) {
  20387. sinThetaOverTheta = Math.sin(theta) / theta;
  20388. }
  20389. result.x = cartesian.x * sinThetaOverTheta;
  20390. result.y = cartesian.y * sinThetaOverTheta;
  20391. result.z = cartesian.z * sinThetaOverTheta;
  20392. result.w = Math.cos(theta);
  20393. return result;
  20394. };
  20395. var squadScratchCartesian0 = new Cartesian3();
  20396. var squadScratchCartesian1 = new Cartesian3();
  20397. var squadScratchQuaternion0 = new Quaternion();
  20398. var squadScratchQuaternion1 = new Quaternion();
  20399. /**
  20400. * Computes an inner quadrangle point.
  20401. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  20402. *
  20403. * @param {Quaternion} q0 The first quaternion.
  20404. * @param {Quaternion} q1 The second quaternion.
  20405. * @param {Quaternion} q2 The third quaternion.
  20406. * @param {Quaternion} result The object onto which to store the result.
  20407. * @returns {Quaternion} The modified result parameter.
  20408. *
  20409. * @see Quaternion#squad
  20410. */
  20411. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  20412. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  20413. throw new DeveloperError('q0, q1, and q2 are required.');
  20414. }
  20415. if (!defined(result)) {
  20416. throw new DeveloperError('result is required');
  20417. }
  20418. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  20419. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  20420. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  20421. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  20422. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  20423. Cartesian3.add(cart0, cart1, cart0);
  20424. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  20425. Cartesian3.negate(cart0, cart0);
  20426. Quaternion.exp(cart0, squadScratchQuaternion0);
  20427. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  20428. };
  20429. /**
  20430. * Computes the spherical quadrangle interpolation between quaternions.
  20431. *
  20432. * @param {Quaternion} q0 The first quaternion.
  20433. * @param {Quaternion} q1 The second quaternion.
  20434. * @param {Quaternion} s0 The first inner quadrangle.
  20435. * @param {Quaternion} s1 The second inner quadrangle.
  20436. * @param {Number} t The time in [0,1] used to interpolate.
  20437. * @param {Quaternion} result The object onto which to store the result.
  20438. * @returns {Quaternion} The modified result parameter.
  20439. *
  20440. *
  20441. * @example
  20442. * // 1. compute the squad interpolation between two quaternions on a curve
  20443. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  20444. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  20445. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  20446. *
  20447. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  20448. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  20449. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  20450. *
  20451. * @see Quaternion#computeInnerQuadrangle
  20452. */
  20453. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  20454. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  20455. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  20456. }
  20457. if (typeof t !== 'number') {
  20458. throw new DeveloperError('t is required and must be a number.');
  20459. }
  20460. if (!defined(result)) {
  20461. throw new DeveloperError('result is required');
  20462. }
  20463. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  20464. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  20465. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  20466. };
  20467. var fastSlerpScratchQuaternion = new Quaternion();
  20468. var opmu = 1.90110745351730037;
  20469. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  20470. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  20471. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  20472. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  20473. for (var i = 0; i < 7; ++i) {
  20474. var s = i + 1.0;
  20475. var t = 2.0 * s + 1.0;
  20476. u[i] = 1.0 / (s * t);
  20477. v[i] = s / t;
  20478. }
  20479. u[7] = opmu / (8.0 * 17.0);
  20480. v[7] = opmu * 8.0 / 17.0;
  20481. /**
  20482. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  20483. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  20484. *
  20485. * @param {Quaternion} start The value corresponding to t at 0.0.
  20486. * @param {Quaternion} end The value corresponding to t at 1.0.
  20487. * @param {Number} t The point along t at which to interpolate.
  20488. * @param {Quaternion} result The object onto which to store the result.
  20489. * @returns {Quaternion} The modified result parameter.
  20490. *
  20491. * @see Quaternion#slerp
  20492. */
  20493. Quaternion.fastSlerp = function(start, end, t, result) {
  20494. if (!defined(start)) {
  20495. throw new DeveloperError('start is required.');
  20496. }
  20497. if (!defined(end)) {
  20498. throw new DeveloperError('end is required.');
  20499. }
  20500. if (typeof t !== 'number') {
  20501. throw new DeveloperError('t is required and must be a number.');
  20502. }
  20503. if (!defined(result)) {
  20504. throw new DeveloperError('result is required');
  20505. }
  20506. var x = Quaternion.dot(start, end);
  20507. var sign;
  20508. if (x >= 0) {
  20509. sign = 1.0;
  20510. } else {
  20511. sign = -1.0;
  20512. x = -x;
  20513. }
  20514. var xm1 = x - 1.0;
  20515. var d = 1.0 - t;
  20516. var sqrT = t * t;
  20517. var sqrD = d * d;
  20518. for (var i = 7; i >= 0; --i) {
  20519. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  20520. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  20521. }
  20522. var cT = sign * t * (
  20523. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  20524. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  20525. var cD = d * (
  20526. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  20527. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  20528. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  20529. Quaternion.multiplyByScalar(end, cT, result);
  20530. return Quaternion.add(temp, result, result);
  20531. };
  20532. /**
  20533. * Computes the spherical quadrangle interpolation between quaternions.
  20534. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  20535. *
  20536. * @param {Quaternion} q0 The first quaternion.
  20537. * @param {Quaternion} q1 The second quaternion.
  20538. * @param {Quaternion} s0 The first inner quadrangle.
  20539. * @param {Quaternion} s1 The second inner quadrangle.
  20540. * @param {Number} t The time in [0,1] used to interpolate.
  20541. * @param {Quaternion} result The object onto which to store the result.
  20542. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  20543. *
  20544. * @see Quaternion#squad
  20545. */
  20546. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  20547. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  20548. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  20549. }
  20550. if (typeof t !== 'number') {
  20551. throw new DeveloperError('t is required and must be a number.');
  20552. }
  20553. if (!defined(result)) {
  20554. throw new DeveloperError('result is required');
  20555. }
  20556. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  20557. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  20558. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  20559. };
  20560. /**
  20561. * Compares the provided quaternions componentwise and returns
  20562. * <code>true</code> if they are equal, <code>false</code> otherwise.
  20563. *
  20564. * @param {Quaternion} [left] The first quaternion.
  20565. * @param {Quaternion} [right] The second quaternion.
  20566. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  20567. */
  20568. Quaternion.equals = function(left, right) {
  20569. return (left === right) ||
  20570. ((defined(left)) &&
  20571. (defined(right)) &&
  20572. (left.x === right.x) &&
  20573. (left.y === right.y) &&
  20574. (left.z === right.z) &&
  20575. (left.w === right.w));
  20576. };
  20577. /**
  20578. * Compares the provided quaternions componentwise and returns
  20579. * <code>true</code> if they are within the provided epsilon,
  20580. * <code>false</code> otherwise.
  20581. *
  20582. * @param {Quaternion} [left] The first quaternion.
  20583. * @param {Quaternion} [right] The second quaternion.
  20584. * @param {Number} epsilon The epsilon to use for equality testing.
  20585. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  20586. */
  20587. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  20588. if (typeof epsilon !== 'number') {
  20589. throw new DeveloperError('epsilon is required and must be a number.');
  20590. }
  20591. return (left === right) ||
  20592. ((defined(left)) &&
  20593. (defined(right)) &&
  20594. (Math.abs(left.x - right.x) <= epsilon) &&
  20595. (Math.abs(left.y - right.y) <= epsilon) &&
  20596. (Math.abs(left.z - right.z) <= epsilon) &&
  20597. (Math.abs(left.w - right.w) <= epsilon));
  20598. };
  20599. /**
  20600. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  20601. *
  20602. * @type {Quaternion}
  20603. * @constant
  20604. */
  20605. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  20606. /**
  20607. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  20608. *
  20609. * @type {Quaternion}
  20610. * @constant
  20611. */
  20612. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  20613. /**
  20614. * Duplicates this Quaternion instance.
  20615. *
  20616. * @param {Quaternion} [result] The object onto which to store the result.
  20617. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  20618. */
  20619. Quaternion.prototype.clone = function(result) {
  20620. return Quaternion.clone(this, result);
  20621. };
  20622. /**
  20623. * Compares this and the provided quaternion componentwise and returns
  20624. * <code>true</code> if they are equal, <code>false</code> otherwise.
  20625. *
  20626. * @param {Quaternion} [right] The right hand side quaternion.
  20627. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  20628. */
  20629. Quaternion.prototype.equals = function(right) {
  20630. return Quaternion.equals(this, right);
  20631. };
  20632. /**
  20633. * Compares this and the provided quaternion componentwise and returns
  20634. * <code>true</code> if they are within the provided epsilon,
  20635. * <code>false</code> otherwise.
  20636. *
  20637. * @param {Quaternion} [right] The right hand side quaternion.
  20638. * @param {Number} epsilon The epsilon to use for equality testing.
  20639. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  20640. */
  20641. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  20642. return Quaternion.equalsEpsilon(this, right, epsilon);
  20643. };
  20644. /**
  20645. * Returns a string representing this quaternion in the format (x, y, z, w).
  20646. *
  20647. * @returns {String} A string representing this Quaternion.
  20648. */
  20649. Quaternion.prototype.toString = function() {
  20650. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  20651. };
  20652. return Quaternion;
  20653. });
  20654. /*global define*/
  20655. define('Core/Transforms',[
  20656. '../ThirdParty/when',
  20657. './Cartesian2',
  20658. './Cartesian3',
  20659. './Cartesian4',
  20660. './Cartographic',
  20661. './defaultValue',
  20662. './defined',
  20663. './deprecationWarning',
  20664. './DeveloperError',
  20665. './EarthOrientationParameters',
  20666. './EarthOrientationParametersSample',
  20667. './Ellipsoid',
  20668. './HeadingPitchRoll',
  20669. './Iau2006XysData',
  20670. './Iau2006XysSample',
  20671. './JulianDate',
  20672. './Math',
  20673. './Matrix3',
  20674. './Matrix4',
  20675. './Quaternion',
  20676. './TimeConstants'
  20677. ], function(
  20678. when,
  20679. Cartesian2,
  20680. Cartesian3,
  20681. Cartesian4,
  20682. Cartographic,
  20683. defaultValue,
  20684. defined,
  20685. deprecationWarning,
  20686. DeveloperError,
  20687. EarthOrientationParameters,
  20688. EarthOrientationParametersSample,
  20689. Ellipsoid,
  20690. HeadingPitchRoll,
  20691. Iau2006XysData,
  20692. Iau2006XysSample,
  20693. JulianDate,
  20694. CesiumMath,
  20695. Matrix3,
  20696. Matrix4,
  20697. Quaternion,
  20698. TimeConstants) {
  20699. 'use strict';
  20700. /**
  20701. * Contains functions for transforming positions to various reference frames.
  20702. *
  20703. * @exports Transforms
  20704. */
  20705. var Transforms = {};
  20706. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  20707. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  20708. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  20709. /**
  20710. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  20711. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  20712. * The local axes are defined as:
  20713. * <ul>
  20714. * <li>The <code>x</code> axis points in the local east direction.</li>
  20715. * <li>The <code>y</code> axis points in the local north direction.</li>
  20716. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  20717. * </ul>
  20718. *
  20719. * @param {Cartesian3} origin The center point of the local reference frame.
  20720. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  20721. * @param {Matrix4} [result] The object onto which to store the result.
  20722. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  20723. *
  20724. * @example
  20725. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  20726. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  20727. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  20728. */
  20729. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  20730. if (!defined(origin)) {
  20731. throw new DeveloperError('origin is required.');
  20732. }
  20733. // If x and y are zero, assume origin is at a pole, which is a special case.
  20734. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  20735. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  20736. var sign = CesiumMath.sign(origin.z);
  20737. if (!defined(result)) {
  20738. return new Matrix4(
  20739. 0.0, -sign, 0.0, origin.x,
  20740. 1.0, 0.0, 0.0, origin.y,
  20741. 0.0, 0.0, sign, origin.z,
  20742. 0.0, 0.0, 0.0, 1.0);
  20743. }
  20744. result[0] = 0.0;
  20745. result[1] = 1.0;
  20746. result[2] = 0.0;
  20747. result[3] = 0.0;
  20748. result[4] = -sign;
  20749. result[5] = 0.0;
  20750. result[6] = 0.0;
  20751. result[7] = 0.0;
  20752. result[8] = 0.0;
  20753. result[9] = 0.0;
  20754. result[10] = sign;
  20755. result[11] = 0.0;
  20756. result[12] = origin.x;
  20757. result[13] = origin.y;
  20758. result[14] = origin.z;
  20759. result[15] = 1.0;
  20760. return result;
  20761. }
  20762. var normal = eastNorthUpToFixedFrameNormal;
  20763. var tangent = eastNorthUpToFixedFrameTangent;
  20764. var bitangent = eastNorthUpToFixedFrameBitangent;
  20765. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  20766. ellipsoid.geodeticSurfaceNormal(origin, normal);
  20767. tangent.x = -origin.y;
  20768. tangent.y = origin.x;
  20769. tangent.z = 0.0;
  20770. Cartesian3.normalize(tangent, tangent);
  20771. Cartesian3.cross(normal, tangent, bitangent);
  20772. if (!defined(result)) {
  20773. return new Matrix4(
  20774. tangent.x, bitangent.x, normal.x, origin.x,
  20775. tangent.y, bitangent.y, normal.y, origin.y,
  20776. tangent.z, bitangent.z, normal.z, origin.z,
  20777. 0.0, 0.0, 0.0, 1.0);
  20778. }
  20779. result[0] = tangent.x;
  20780. result[1] = tangent.y;
  20781. result[2] = tangent.z;
  20782. result[3] = 0.0;
  20783. result[4] = bitangent.x;
  20784. result[5] = bitangent.y;
  20785. result[6] = bitangent.z;
  20786. result[7] = 0.0;
  20787. result[8] = normal.x;
  20788. result[9] = normal.y;
  20789. result[10] = normal.z;
  20790. result[11] = 0.0;
  20791. result[12] = origin.x;
  20792. result[13] = origin.y;
  20793. result[14] = origin.z;
  20794. result[15] = 1.0;
  20795. return result;
  20796. };
  20797. var northEastDownToFixedFrameNormal = new Cartesian3();
  20798. var northEastDownToFixedFrameTangent = new Cartesian3();
  20799. var northEastDownToFixedFrameBitangent = new Cartesian3();
  20800. /**
  20801. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  20802. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  20803. * The local axes are defined as:
  20804. * <ul>
  20805. * <li>The <code>x</code> axis points in the local north direction.</li>
  20806. * <li>The <code>y</code> axis points in the local east direction.</li>
  20807. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  20808. * </ul>
  20809. *
  20810. * @param {Cartesian3} origin The center point of the local reference frame.
  20811. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  20812. * @param {Matrix4} [result] The object onto which to store the result.
  20813. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  20814. *
  20815. * @example
  20816. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  20817. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  20818. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  20819. */
  20820. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  20821. if (!defined(origin)) {
  20822. throw new DeveloperError('origin is required.');
  20823. }
  20824. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  20825. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  20826. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  20827. var sign = CesiumMath.sign(origin.z);
  20828. if (!defined(result)) {
  20829. return new Matrix4(
  20830. -sign, 0.0, 0.0, origin.x,
  20831. 0.0, 1.0, 0.0, origin.y,
  20832. 0.0, 0.0, -sign, origin.z,
  20833. 0.0, 0.0, 0.0, 1.0);
  20834. }
  20835. result[0] = -sign;
  20836. result[1] = 0.0;
  20837. result[2] = 0.0;
  20838. result[3] = 0.0;
  20839. result[4] = 0.0;
  20840. result[5] = 1.0;
  20841. result[6] = 0.0;
  20842. result[7] = 0.0;
  20843. result[8] = 0.0;
  20844. result[9] = 0.0;
  20845. result[10] = -sign;
  20846. result[11] = 0.0;
  20847. result[12] = origin.x;
  20848. result[13] = origin.y;
  20849. result[14] = origin.z;
  20850. result[15] = 1.0;
  20851. return result;
  20852. }
  20853. var normal = northEastDownToFixedFrameNormal;
  20854. var tangent = northEastDownToFixedFrameTangent;
  20855. var bitangent = northEastDownToFixedFrameBitangent;
  20856. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  20857. ellipsoid.geodeticSurfaceNormal(origin, normal);
  20858. tangent.x = -origin.y;
  20859. tangent.y = origin.x;
  20860. tangent.z = 0.0;
  20861. Cartesian3.normalize(tangent, tangent);
  20862. Cartesian3.cross(normal, tangent, bitangent);
  20863. if (!defined(result)) {
  20864. return new Matrix4(
  20865. bitangent.x, tangent.x, -normal.x, origin.x,
  20866. bitangent.y, tangent.y, -normal.y, origin.y,
  20867. bitangent.z, tangent.z, -normal.z, origin.z,
  20868. 0.0, 0.0, 0.0, 1.0);
  20869. }
  20870. result[0] = bitangent.x;
  20871. result[1] = bitangent.y;
  20872. result[2] = bitangent.z;
  20873. result[3] = 0.0;
  20874. result[4] = tangent.x;
  20875. result[5] = tangent.y;
  20876. result[6] = tangent.z;
  20877. result[7] = 0.0;
  20878. result[8] = -normal.x;
  20879. result[9] = -normal.y;
  20880. result[10] = -normal.z;
  20881. result[11] = 0.0;
  20882. result[12] = origin.x;
  20883. result[13] = origin.y;
  20884. result[14] = origin.z;
  20885. result[15] = 1.0;
  20886. return result;
  20887. };
  20888. /**
  20889. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  20890. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  20891. * The local axes are defined as:
  20892. * <ul>
  20893. * <li>The <code>x</code> axis points in the local north direction.</li>
  20894. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  20895. * <li>The <code>z</code> axis points in the local east direction.</li>
  20896. * </ul>
  20897. *
  20898. * @param {Cartesian3} origin The center point of the local reference frame.
  20899. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  20900. * @param {Matrix4} [result] The object onto which to store the result.
  20901. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  20902. *
  20903. * @example
  20904. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  20905. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  20906. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  20907. */
  20908. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  20909. if (!defined(origin)) {
  20910. throw new DeveloperError('origin is required.');
  20911. }
  20912. // If x and y are zero, assume origin is at a pole, which is a special case.
  20913. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  20914. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  20915. var sign = CesiumMath.sign(origin.z);
  20916. if (!defined(result)) {
  20917. return new Matrix4(
  20918. -sign, 0.0, 0.0, origin.x,
  20919. 0.0, 0.0, 1.0, origin.y,
  20920. 0.0, sign, 0.0, origin.z,
  20921. 0.0, 0.0, 0.0, 1.0);
  20922. }
  20923. result[0] = -sign;
  20924. result[1] = 0.0;
  20925. result[2] = 0.0;
  20926. result[3] = 0.0;
  20927. result[4] = 0.0;
  20928. result[5] = 0.0;
  20929. result[6] = sign;
  20930. result[7] = 0.0;
  20931. result[8] = 0.0;
  20932. result[9] = 1.0;
  20933. result[10] = 0.0;
  20934. result[11] = 0.0;
  20935. result[12] = origin.x;
  20936. result[13] = origin.y;
  20937. result[14] = origin.z;
  20938. result[15] = 1.0;
  20939. return result;
  20940. }
  20941. var normal = eastNorthUpToFixedFrameNormal;
  20942. var tangent = eastNorthUpToFixedFrameTangent;
  20943. var bitangent = eastNorthUpToFixedFrameBitangent;
  20944. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  20945. ellipsoid.geodeticSurfaceNormal(origin, normal);
  20946. tangent.x = -origin.y;
  20947. tangent.y = origin.x;
  20948. tangent.z = 0.0;
  20949. Cartesian3.normalize(tangent, tangent);
  20950. Cartesian3.cross(normal, tangent, bitangent);
  20951. if (!defined(result)) {
  20952. return new Matrix4(
  20953. bitangent.x, normal.x, tangent.x, origin.x,
  20954. bitangent.y, normal.y, tangent.y, origin.y,
  20955. bitangent.z, normal.z, tangent.z, origin.z,
  20956. 0.0, 0.0, 0.0, 1.0);
  20957. }
  20958. result[0] = bitangent.x;
  20959. result[1] = bitangent.y;
  20960. result[2] = bitangent.z;
  20961. result[3] = 0.0;
  20962. result[4] = normal.x;
  20963. result[5] = normal.y;
  20964. result[6] = normal.z;
  20965. result[7] = 0.0;
  20966. result[8] = tangent.x;
  20967. result[9] = tangent.y;
  20968. result[10] = tangent.z;
  20969. result[11] = 0.0;
  20970. result[12] = origin.x;
  20971. result[13] = origin.y;
  20972. result[14] = origin.z;
  20973. result[15] = 1.0;
  20974. return result;
  20975. };
  20976. /**
  20977. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  20978. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  20979. * The local axes are defined as:
  20980. * <ul>
  20981. * <li>The <code>x</code> axis points in the local north direction.</li>
  20982. * <li>The <code>y</code> axis points in the local west direction.</li>
  20983. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  20984. * </ul>
  20985. *
  20986. * @param {Cartesian3} origin The center point of the local reference frame.
  20987. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  20988. * @param {Matrix4} [result] The object onto which to store the result.
  20989. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  20990. *
  20991. * @example
  20992. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  20993. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  20994. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  20995. */
  20996. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  20997. if (!defined(origin)) {
  20998. throw new DeveloperError('origin is required.');
  20999. }
  21000. // If x and y are zero, assume origin is at a pole, which is a special case.
  21001. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  21002. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  21003. var sign = CesiumMath.sign(origin.z);
  21004. if (!defined(result)) {
  21005. return new Matrix4(
  21006. -sign, 0.0, 0.0, origin.x,
  21007. 0.0, -1.0, 0.0, origin.y,
  21008. 0.0, 0.0, sign, origin.z,
  21009. 0.0, 0.0, 0.0, 1.0);
  21010. }
  21011. result[0] = -sign;
  21012. result[1] = 0.0;
  21013. result[2] = 0.0;
  21014. result[3] = 0.0;
  21015. result[4] = 0.0;
  21016. result[5] = -1.0;
  21017. result[6] = 0.0;
  21018. result[7] = 0.0;
  21019. result[8] = 0.0;
  21020. result[9] = 0.0;
  21021. result[10] = sign;
  21022. result[11] = 0.0;
  21023. result[12] = origin.x;
  21024. result[13] = origin.y;
  21025. result[14] = origin.z;
  21026. result[15] = 1.0;
  21027. return result;
  21028. }
  21029. var normal = eastNorthUpToFixedFrameNormal;//Up
  21030. var tangent = eastNorthUpToFixedFrameTangent;//East
  21031. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  21032. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  21033. ellipsoid.geodeticSurfaceNormal(origin, normal);
  21034. tangent.x = -origin.y;
  21035. tangent.y = origin.x;
  21036. tangent.z = 0.0;
  21037. Cartesian3.normalize(tangent, tangent);
  21038. Cartesian3.cross(normal, tangent, bitangent);
  21039. if (!defined(result)) {
  21040. return new Matrix4(
  21041. bitangent.x, -tangent.x, normal.x, origin.x,
  21042. bitangent.y, -tangent.y, normal.y, origin.y,
  21043. bitangent.z, -tangent.z, normal.z, origin.z,
  21044. 0.0, 0.0, 0.0, 1.0);
  21045. }
  21046. result[0] = bitangent.x;
  21047. result[1] = bitangent.y;
  21048. result[2] = bitangent.z;
  21049. result[3] = 0.0;
  21050. result[4] = -tangent.x;
  21051. result[5] = -tangent.y;
  21052. result[6] = -tangent.z;
  21053. result[7] = 0.0;
  21054. result[8] = normal.x;
  21055. result[9] = normal.y;
  21056. result[10] = normal.z;
  21057. result[11] = 0.0;
  21058. result[12] = origin.x;
  21059. result[13] = origin.y;
  21060. result[14] = origin.z;
  21061. result[15] = 1.0;
  21062. return result;
  21063. };
  21064. var scratchHPRQuaternion = new Quaternion();
  21065. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  21066. var scratchHPRMatrix4 = new Matrix4();
  21067. /**
  21068. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  21069. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  21070. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  21071. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  21072. *
  21073. * @param {Cartesian3} origin The center point of the local reference frame.
  21074. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  21075. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  21076. * @param {Matrix4} [result] The object onto which to store the result.
  21077. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  21078. *
  21079. * @example
  21080. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  21081. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  21082. * var heading = -Cesium.Math.PI_OVER_TWO;
  21083. * var pitch = Cesium.Math.PI_OVER_FOUR;
  21084. * var roll = 0.0;
  21085. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  21086. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  21087. */
  21088. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  21089. var heading;
  21090. if (typeof headingPitchRoll === 'object') {
  21091. // Shift arguments using assignments to encourage JIT optimization.
  21092. ellipsoid = pitch;
  21093. result = roll;
  21094. heading = headingPitchRoll.heading;
  21095. pitch = headingPitchRoll.pitch;
  21096. roll = headingPitchRoll.roll;
  21097. } else {
  21098. 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.');
  21099. heading = headingPitchRoll;
  21100. }
  21101. // checks for required parameters happen in the called functions
  21102. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  21103. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  21104. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  21105. return Matrix4.multiply(result, hprMatrix, result);
  21106. };
  21107. var scratchHPR = new HeadingPitchRoll();
  21108. var scratchENUMatrix4 = new Matrix4();
  21109. var scratchHPRMatrix3 = new Matrix3();
  21110. /**
  21111. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  21112. * centered at the provided origin. Heading is the rotation from the local north
  21113. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  21114. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  21115. *
  21116. * @param {Cartesian3} origin The center point of the local reference frame.
  21117. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  21118. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  21119. * @param {Quaternion} [result] The object onto which to store the result.
  21120. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  21121. *
  21122. * @example
  21123. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  21124. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  21125. * var heading = -Cesium.Math.PI_OVER_TWO;
  21126. * var pitch = Cesium.Math.PI_OVER_FOUR;
  21127. * var roll = 0.0;
  21128. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  21129. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  21130. */
  21131. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  21132. var hpr;
  21133. if (typeof headingPitchRoll === 'object') {
  21134. // Shift arguments using assignment to encourage JIT optimization.
  21135. hpr = headingPitchRoll;
  21136. ellipsoid = pitch;
  21137. result = roll;
  21138. } else {
  21139. 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.');
  21140. scratchHPR.heading = headingPitchRoll;
  21141. scratchHPR.pitch = pitch;
  21142. scratchHPR.roll = roll;
  21143. hpr = scratchHPR;
  21144. }
  21145. // checks for required parameters happen in the called functions
  21146. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  21147. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  21148. return Quaternion.fromRotationMatrix(rotation, result);
  21149. };
  21150. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  21151. var gmstConstant1 = 8640184.812866;
  21152. var gmstConstant2 = 0.093104;
  21153. var gmstConstant3 = -6.2E-6;
  21154. var rateCoef = 1.1772758384668e-19;
  21155. var wgs84WRPrecessing = 7.2921158553E-5;
  21156. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  21157. var dateInUtc = new JulianDate();
  21158. /**
  21159. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  21160. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  21161. *
  21162. * @param {JulianDate} date The time at which to compute the rotation matrix.
  21163. * @param {Matrix3} [result] The object onto which to store the result.
  21164. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  21165. *
  21166. * @example
  21167. * //Set the view to in the inertial frame.
  21168. * scene.preRender.addEventListener(function(scene, time) {
  21169. * var now = Cesium.JulianDate.now();
  21170. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  21171. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  21172. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  21173. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  21174. * camera.lookAtTransform(transform, offset);
  21175. * });
  21176. */
  21177. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  21178. if (!defined(date)) {
  21179. throw new DeveloperError('date is required.');
  21180. }
  21181. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  21182. // We do not want to use the function like convertTaiToUtc in JulianDate because
  21183. // we explicitly do not want to fail when inside the leap second.
  21184. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  21185. var utcDayNumber = dateInUtc.dayNumber;
  21186. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  21187. var t;
  21188. var diffDays = utcDayNumber - 2451545;
  21189. if (utcSecondsIntoDay >= 43200.0) {
  21190. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  21191. } else {
  21192. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  21193. }
  21194. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  21195. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  21196. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  21197. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  21198. var gha = angle + (ratio * secondsSinceMidnight);
  21199. var cosGha = Math.cos(gha);
  21200. var sinGha = Math.sin(gha);
  21201. if (!defined(result)) {
  21202. return new Matrix3(cosGha, sinGha, 0.0,
  21203. -sinGha, cosGha, 0.0,
  21204. 0.0, 0.0, 1.0);
  21205. }
  21206. result[0] = cosGha;
  21207. result[1] = -sinGha;
  21208. result[2] = 0.0;
  21209. result[3] = sinGha;
  21210. result[4] = cosGha;
  21211. result[5] = 0.0;
  21212. result[6] = 0.0;
  21213. result[7] = 0.0;
  21214. result[8] = 1.0;
  21215. return result;
  21216. };
  21217. /**
  21218. * The source of IAU 2006 XYS data, used for computing the transformation between the
  21219. * Fixed and ICRF axes.
  21220. * @type {Iau2006XysData}
  21221. *
  21222. * @see Transforms.computeIcrfToFixedMatrix
  21223. * @see Transforms.computeFixedToIcrfMatrix
  21224. *
  21225. * @private
  21226. */
  21227. Transforms.iau2006XysData = new Iau2006XysData();
  21228. /**
  21229. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  21230. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  21231. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  21232. * @type {EarthOrientationParameters}
  21233. *
  21234. * @see Transforms.computeIcrfToFixedMatrix
  21235. * @see Transforms.computeFixedToIcrfMatrix
  21236. *
  21237. * @private
  21238. */
  21239. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  21240. var ttMinusTai = 32.184;
  21241. var j2000ttDays = 2451545.0;
  21242. /**
  21243. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  21244. * direction, over a given interval. This function returns a promise that, when resolved,
  21245. * indicates that the preload has completed.
  21246. *
  21247. * @param {TimeInterval} timeInterval The interval to preload.
  21248. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  21249. * and evaluation of the transformation between the fixed and ICRF axes will
  21250. * no longer return undefined for a time inside the interval.
  21251. *
  21252. *
  21253. * @example
  21254. * var interval = new Cesium.TimeInterval(...);
  21255. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  21256. * // the data is now loaded
  21257. * });
  21258. *
  21259. * @see Transforms.computeIcrfToFixedMatrix
  21260. * @see Transforms.computeFixedToIcrfMatrix
  21261. * @see when
  21262. */
  21263. Transforms.preloadIcrfFixed = function(timeInterval) {
  21264. var startDayTT = timeInterval.start.dayNumber;
  21265. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  21266. var stopDayTT = timeInterval.stop.dayNumber;
  21267. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  21268. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  21269. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  21270. return when.all([xysPromise, eopPromise]);
  21271. };
  21272. /**
  21273. * Computes a rotation matrix to transform a point or vector from the International Celestial
  21274. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  21275. * at a given time. This function may return undefined if the data necessary to
  21276. * do the transformation is not yet loaded.
  21277. *
  21278. * @param {JulianDate} date The time at which to compute the rotation matrix.
  21279. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  21280. * not specified, a new instance is created and returned.
  21281. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  21282. * transformation is not yet loaded.
  21283. *
  21284. *
  21285. * @example
  21286. * scene.preRender.addEventListener(function(scene, time) {
  21287. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  21288. * if (Cesium.defined(icrfToFixed)) {
  21289. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  21290. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  21291. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  21292. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  21293. * camera.lookAtTransform(transform, offset);
  21294. * }
  21295. * });
  21296. *
  21297. * @see Transforms.preloadIcrfFixed
  21298. */
  21299. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  21300. if (!defined(date)) {
  21301. throw new DeveloperError('date is required.');
  21302. }
  21303. if (!defined(result)) {
  21304. result = new Matrix3();
  21305. }
  21306. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  21307. if (!defined(fixedToIcrfMtx)) {
  21308. return undefined;
  21309. }
  21310. return Matrix3.transpose(fixedToIcrfMtx, result);
  21311. };
  21312. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  21313. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  21314. var rotation1Scratch = new Matrix3();
  21315. var rotation2Scratch = new Matrix3();
  21316. /**
  21317. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  21318. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  21319. * at a given time. This function may return undefined if the data necessary to
  21320. * do the transformation is not yet loaded.
  21321. *
  21322. * @param {JulianDate} date The time at which to compute the rotation matrix.
  21323. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  21324. * not specified, a new instance is created and returned.
  21325. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  21326. * transformation is not yet loaded.
  21327. *
  21328. *
  21329. * @example
  21330. * // Transform a point from the ICRF axes to the Fixed axes.
  21331. * var now = Cesium.JulianDate.now();
  21332. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  21333. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  21334. * var pointInInertial = new Cesium.Cartesian3();
  21335. * if (Cesium.defined(fixedToIcrf)) {
  21336. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  21337. * }
  21338. *
  21339. * @see Transforms.preloadIcrfFixed
  21340. */
  21341. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  21342. if (!defined(date)) {
  21343. throw new DeveloperError('date is required.');
  21344. }
  21345. if (!defined(result)) {
  21346. result = new Matrix3();
  21347. }
  21348. // Compute pole wander
  21349. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  21350. if (!defined(eop)) {
  21351. return undefined;
  21352. }
  21353. // There is no external conversion to Terrestrial Time (TT).
  21354. // So use International Atomic Time (TAI) and convert using offsets.
  21355. // Here we are assuming that dayTT and secondTT are positive
  21356. var dayTT = date.dayNumber;
  21357. // It's possible here that secondTT could roll over 86400
  21358. // This does not seem to affect the precision (unit tests check for this)
  21359. var secondTT = date.secondsOfDay + ttMinusTai;
  21360. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  21361. if (!defined(xys)) {
  21362. return undefined;
  21363. }
  21364. var x = xys.x + eop.xPoleOffset;
  21365. var y = xys.y + eop.yPoleOffset;
  21366. // Compute XYS rotation
  21367. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  21368. var rotation1 = rotation1Scratch;
  21369. rotation1[0] = 1.0 - a * x * x;
  21370. rotation1[3] = -a * x * y;
  21371. rotation1[6] = x;
  21372. rotation1[1] = -a * x * y;
  21373. rotation1[4] = 1 - a * y * y;
  21374. rotation1[7] = y;
  21375. rotation1[2] = -x;
  21376. rotation1[5] = -y;
  21377. rotation1[8] = 1 - a * (x * x + y * y);
  21378. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  21379. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  21380. // Similar to TT conversions above
  21381. // It's possible here that secondTT could roll over 86400
  21382. // This does not seem to affect the precision (unit tests check for this)
  21383. var dateUt1day = date.dayNumber;
  21384. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  21385. // Compute Earth rotation angle
  21386. // The IERS standard for era is
  21387. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  21388. // where
  21389. // Tu = JulianDateInUt1 - 2451545.0
  21390. // However, you get much more precision if you make the following simplification
  21391. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  21392. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  21393. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  21394. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  21395. var daysSinceJ2000 = dateUt1day - 2451545;
  21396. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  21397. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  21398. era = (era % 1.0) * CesiumMath.TWO_PI;
  21399. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  21400. // pseudoFixed to ICRF
  21401. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  21402. // Compute pole wander matrix
  21403. var cosxp = Math.cos(eop.xPoleWander);
  21404. var cosyp = Math.cos(eop.yPoleWander);
  21405. var sinxp = Math.sin(eop.xPoleWander);
  21406. var sinyp = Math.sin(eop.yPoleWander);
  21407. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  21408. ttt /= 36525.0;
  21409. // approximate sp value in rad
  21410. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  21411. var cossp = Math.cos(sp);
  21412. var sinsp = Math.sin(sp);
  21413. var fToPfMtx = rotation2Scratch;
  21414. fToPfMtx[0] = cosxp * cossp;
  21415. fToPfMtx[1] = cosxp * sinsp;
  21416. fToPfMtx[2] = sinxp;
  21417. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  21418. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  21419. fToPfMtx[5] = -sinyp * cosxp;
  21420. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  21421. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  21422. fToPfMtx[8] = cosyp * cosxp;
  21423. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  21424. };
  21425. var pointToWindowCoordinatesTemp = new Cartesian4();
  21426. /**
  21427. * Transform a point from model coordinates to window coordinates.
  21428. *
  21429. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  21430. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  21431. * @param {Cartesian3} point The point to transform.
  21432. * @param {Cartesian2} [result] The object onto which to store the result.
  21433. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  21434. */
  21435. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  21436. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  21437. result.y = 2.0 * viewportTransformation[5] - result.y;
  21438. return result;
  21439. };
  21440. /**
  21441. * @private
  21442. */
  21443. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  21444. if (!defined(modelViewProjectionMatrix)) {
  21445. throw new DeveloperError('modelViewProjectionMatrix is required.');
  21446. }
  21447. if (!defined(viewportTransformation)) {
  21448. throw new DeveloperError('viewportTransformation is required.');
  21449. }
  21450. if (!defined(point)) {
  21451. throw new DeveloperError('point is required.');
  21452. }
  21453. if (!defined(result)) {
  21454. result = new Cartesian2();
  21455. }
  21456. var tmp = pointToWindowCoordinatesTemp;
  21457. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  21458. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  21459. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  21460. return Cartesian2.fromCartesian4(tmp, result);
  21461. };
  21462. var normalScratch = new Cartesian3();
  21463. var rightScratch = new Cartesian3();
  21464. var upScratch = new Cartesian3();
  21465. /**
  21466. * @private
  21467. */
  21468. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  21469. if (!defined(position)) {
  21470. throw new DeveloperError('position is required.');
  21471. }
  21472. if (!defined(velocity)) {
  21473. throw new DeveloperError('velocity is required.');
  21474. }
  21475. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  21476. var right = Cartesian3.cross(velocity, normal, rightScratch);
  21477. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  21478. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  21479. }
  21480. var up = Cartesian3.cross(right, velocity, upScratch);
  21481. Cartesian3.cross(velocity, up, right);
  21482. Cartesian3.negate(right, right);
  21483. if (!defined(result)) {
  21484. result = new Matrix3();
  21485. }
  21486. result[0] = velocity.x;
  21487. result[1] = velocity.y;
  21488. result[2] = velocity.z;
  21489. result[3] = right.x;
  21490. result[4] = right.y;
  21491. result[5] = right.z;
  21492. result[6] = up.x;
  21493. result[7] = up.y;
  21494. result[8] = up.z;
  21495. return result;
  21496. };
  21497. var scratchCartographic = new Cartographic();
  21498. var scratchCartesian3Projection = new Cartesian3();
  21499. var scratchCartesian3 = new Cartesian3();
  21500. var scratchCartesian4Origin = new Cartesian4();
  21501. var scratchCartesian4NewOrigin = new Cartesian4();
  21502. var scratchCartesian4NewXAxis = new Cartesian4();
  21503. var scratchCartesian4NewYAxis = new Cartesian4();
  21504. var scratchCartesian4NewZAxis = new Cartesian4();
  21505. var scratchFromENU = new Matrix4();
  21506. var scratchToENU = new Matrix4();
  21507. /**
  21508. * @private
  21509. */
  21510. Transforms.basisTo2D = function(projection, matrix, result) {
  21511. if (!defined(projection)) {
  21512. throw new DeveloperError('projection is required.');
  21513. }
  21514. if (!defined(matrix)) {
  21515. throw new DeveloperError('matrix is required.');
  21516. }
  21517. if (!defined(result)) {
  21518. throw new DeveloperError('result is required.');
  21519. }
  21520. var ellipsoid = projection.ellipsoid;
  21521. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  21522. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  21523. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  21524. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  21525. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  21526. var newOrigin = scratchCartesian4NewOrigin;
  21527. newOrigin.x = projectedPosition.z;
  21528. newOrigin.y = projectedPosition.x;
  21529. newOrigin.z = projectedPosition.y;
  21530. newOrigin.w = 1.0;
  21531. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  21532. var xScale = Cartesian3.magnitude(xAxis);
  21533. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  21534. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  21535. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  21536. var yScale = Cartesian3.magnitude(yAxis);
  21537. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  21538. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  21539. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  21540. var zScale = Cartesian3.magnitude(zAxis);
  21541. var newZAxis = scratchCartesian4NewZAxis;
  21542. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  21543. Cartesian3.normalize(newZAxis, newZAxis);
  21544. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  21545. Cartesian3.normalize(newXAxis, newXAxis);
  21546. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  21547. Cartesian3.normalize(newYAxis, newYAxis);
  21548. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  21549. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  21550. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  21551. Matrix4.setColumn(result, 0, newXAxis, result);
  21552. Matrix4.setColumn(result, 1, newYAxis, result);
  21553. Matrix4.setColumn(result, 2, newZAxis, result);
  21554. Matrix4.setColumn(result, 3, newOrigin, result);
  21555. return result;
  21556. };
  21557. return Transforms;
  21558. });
  21559. /*global define*/
  21560. define('Core/EllipsoidTangentPlane',[
  21561. './AxisAlignedBoundingBox',
  21562. './Cartesian2',
  21563. './Cartesian3',
  21564. './Cartesian4',
  21565. './defaultValue',
  21566. './defined',
  21567. './defineProperties',
  21568. './DeveloperError',
  21569. './Ellipsoid',
  21570. './IntersectionTests',
  21571. './Matrix4',
  21572. './Plane',
  21573. './Ray',
  21574. './Transforms'
  21575. ], function(
  21576. AxisAlignedBoundingBox,
  21577. Cartesian2,
  21578. Cartesian3,
  21579. Cartesian4,
  21580. defaultValue,
  21581. defined,
  21582. defineProperties,
  21583. DeveloperError,
  21584. Ellipsoid,
  21585. IntersectionTests,
  21586. Matrix4,
  21587. Plane,
  21588. Ray,
  21589. Transforms) {
  21590. 'use strict';
  21591. var scratchCart4 = new Cartesian4();
  21592. /**
  21593. * A plane tangent to the provided ellipsoid at the provided origin.
  21594. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  21595. * If origin is at the center of the ellipsoid, an exception will be thrown.
  21596. * @alias EllipsoidTangentPlane
  21597. * @constructor
  21598. *
  21599. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  21600. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  21601. *
  21602. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  21603. */
  21604. function EllipsoidTangentPlane(origin, ellipsoid) {
  21605. if (!defined(origin)) {
  21606. throw new DeveloperError('origin is required.');
  21607. }
  21608. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  21609. origin = ellipsoid.scaleToGeodeticSurface(origin);
  21610. if (!defined(origin)) {
  21611. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  21612. }
  21613. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  21614. this._ellipsoid = ellipsoid;
  21615. this._origin = origin;
  21616. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  21617. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  21618. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  21619. this._plane = Plane.fromPointNormal(origin, normal);
  21620. }
  21621. defineProperties(EllipsoidTangentPlane.prototype, {
  21622. /**
  21623. * Gets the ellipsoid.
  21624. * @memberof EllipsoidTangentPlane.prototype
  21625. * @type {Ellipsoid}
  21626. */
  21627. ellipsoid : {
  21628. get : function() {
  21629. return this._ellipsoid;
  21630. }
  21631. },
  21632. /**
  21633. * Gets the origin.
  21634. * @memberof EllipsoidTangentPlane.prototype
  21635. * @type {Cartesian3}
  21636. */
  21637. origin : {
  21638. get : function() {
  21639. return this._origin;
  21640. }
  21641. },
  21642. /**
  21643. * Gets the plane which is tangent to the ellipsoid.
  21644. * @memberof EllipsoidTangentPlane.prototype
  21645. * @readonly
  21646. * @type {Plane}
  21647. */
  21648. plane : {
  21649. get : function() {
  21650. return this._plane;
  21651. }
  21652. },
  21653. /**
  21654. * Gets the local X-axis (east) of the tangent plane.
  21655. * @memberof EllipsoidTangentPlane.prototype
  21656. * @readonly
  21657. * @type {Cartesian3}
  21658. */
  21659. xAxis : {
  21660. get : function() {
  21661. return this._xAxis;
  21662. }
  21663. },
  21664. /**
  21665. * Gets the local Y-axis (north) of the tangent plane.
  21666. * @memberof EllipsoidTangentPlane.prototype
  21667. * @readonly
  21668. * @type {Cartesian3}
  21669. */
  21670. yAxis : {
  21671. get : function() {
  21672. return this._yAxis;
  21673. }
  21674. },
  21675. /**
  21676. * Gets the local Z-axis (up) of the tangent plane.
  21677. * @member EllipsoidTangentPlane.prototype
  21678. * @readonly
  21679. * @type {Cartesian3}
  21680. */
  21681. zAxis : {
  21682. get : function() {
  21683. return this._plane.normal;
  21684. }
  21685. }
  21686. });
  21687. var tmp = new AxisAlignedBoundingBox();
  21688. /**
  21689. * Creates a new instance from the provided ellipsoid and the center
  21690. * point of the provided Cartesians.
  21691. *
  21692. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  21693. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  21694. */
  21695. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  21696. if (!defined(cartesians)) {
  21697. throw new DeveloperError('cartesians is required.');
  21698. }
  21699. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  21700. return new EllipsoidTangentPlane(box.center, ellipsoid);
  21701. };
  21702. var scratchProjectPointOntoPlaneRay = new Ray();
  21703. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  21704. /**
  21705. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  21706. *
  21707. * @param {Cartesian3} cartesian The point to project.
  21708. * @param {Cartesian2} [result] The object onto which to store the result.
  21709. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  21710. */
  21711. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  21712. if (!defined(cartesian)) {
  21713. throw new DeveloperError('cartesian is required.');
  21714. }
  21715. var ray = scratchProjectPointOntoPlaneRay;
  21716. ray.origin = cartesian;
  21717. Cartesian3.normalize(cartesian, ray.direction);
  21718. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  21719. if (!defined(intersectionPoint)) {
  21720. Cartesian3.negate(ray.direction, ray.direction);
  21721. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  21722. }
  21723. if (defined(intersectionPoint)) {
  21724. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  21725. var x = Cartesian3.dot(this._xAxis, v);
  21726. var y = Cartesian3.dot(this._yAxis, v);
  21727. if (!defined(result)) {
  21728. return new Cartesian2(x, y);
  21729. }
  21730. result.x = x;
  21731. result.y = y;
  21732. return result;
  21733. }
  21734. return undefined;
  21735. };
  21736. /**
  21737. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  21738. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  21739. *
  21740. * @see EllipsoidTangentPlane.projectPointOntoPlane
  21741. *
  21742. * @param {Cartesian3[]} cartesians The array of points to project.
  21743. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  21744. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  21745. */
  21746. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  21747. if (!defined(cartesians)) {
  21748. throw new DeveloperError('cartesians is required.');
  21749. }
  21750. if (!defined(result)) {
  21751. result = [];
  21752. }
  21753. var count = 0;
  21754. var length = cartesians.length;
  21755. for ( var i = 0; i < length; i++) {
  21756. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  21757. if (defined(p)) {
  21758. result[count] = p;
  21759. count++;
  21760. }
  21761. }
  21762. result.length = count;
  21763. return result;
  21764. };
  21765. /**
  21766. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  21767. *
  21768. * @param {Cartesian3} cartesian The point to project.
  21769. * @param {Cartesian2} [result] The object onto which to store the result.
  21770. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  21771. */
  21772. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  21773. if (!defined(cartesian)) {
  21774. throw new DeveloperError('cartesian is required.');
  21775. }
  21776. if (!defined(result)) {
  21777. result = new Cartesian2();
  21778. }
  21779. var ray = scratchProjectPointOntoPlaneRay;
  21780. ray.origin = cartesian;
  21781. Cartesian3.clone(this._plane.normal, ray.direction);
  21782. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  21783. if (!defined(intersectionPoint)) {
  21784. Cartesian3.negate(ray.direction, ray.direction);
  21785. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  21786. }
  21787. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  21788. var x = Cartesian3.dot(this._xAxis, v);
  21789. var y = Cartesian3.dot(this._yAxis, v);
  21790. result.x = x;
  21791. result.y = y;
  21792. return result;
  21793. };
  21794. /**
  21795. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  21796. *
  21797. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  21798. *
  21799. * @param {Cartesian3[]} cartesians The array of points to project.
  21800. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  21801. * @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>.
  21802. */
  21803. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  21804. if (!defined(cartesians)) {
  21805. throw new DeveloperError('cartesians is required.');
  21806. }
  21807. if (!defined(result)) {
  21808. result = [];
  21809. }
  21810. var length = cartesians.length;
  21811. result.length = length;
  21812. for (var i = 0; i < length; i++) {
  21813. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  21814. }
  21815. return result;
  21816. };
  21817. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  21818. /**
  21819. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  21820. *
  21821. * @param {Cartesian2[]} cartesians The array of points to project.
  21822. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  21823. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  21824. */
  21825. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  21826. if (!defined(cartesians)) {
  21827. throw new DeveloperError('cartesians is required.');
  21828. }
  21829. var length = cartesians.length;
  21830. if (!defined(result)) {
  21831. result = new Array(length);
  21832. } else {
  21833. result.length = length;
  21834. }
  21835. var ellipsoid = this._ellipsoid;
  21836. var origin = this._origin;
  21837. var xAxis = this._xAxis;
  21838. var yAxis = this._yAxis;
  21839. var tmp = projectPointsOntoEllipsoidScratch;
  21840. for ( var i = 0; i < length; ++i) {
  21841. var position = cartesians[i];
  21842. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  21843. if (!defined(result[i])) {
  21844. result[i] = new Cartesian3();
  21845. }
  21846. var point = Cartesian3.add(origin, tmp, result[i]);
  21847. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  21848. Cartesian3.add(point, tmp, point);
  21849. ellipsoid.scaleToGeocentricSurface(point, point);
  21850. }
  21851. return result;
  21852. };
  21853. return EllipsoidTangentPlane;
  21854. });
  21855. /*global define*/
  21856. define('Core/EllipsoidGeodesic',[
  21857. './Cartesian3',
  21858. './Cartographic',
  21859. './defaultValue',
  21860. './defined',
  21861. './defineProperties',
  21862. './DeveloperError',
  21863. './Ellipsoid',
  21864. './Math'
  21865. ], function(
  21866. Cartesian3,
  21867. Cartographic,
  21868. defaultValue,
  21869. defined,
  21870. defineProperties,
  21871. DeveloperError,
  21872. Ellipsoid,
  21873. CesiumMath) {
  21874. 'use strict';
  21875. function setConstants(ellipsoidGeodesic) {
  21876. var uSquared = ellipsoidGeodesic._uSquared;
  21877. var a = ellipsoidGeodesic._ellipsoid.maximumRadius;
  21878. var b = ellipsoidGeodesic._ellipsoid.minimumRadius;
  21879. var f = (a - b) / a;
  21880. var cosineHeading = Math.cos(ellipsoidGeodesic._startHeading);
  21881. var sineHeading = Math.sin(ellipsoidGeodesic._startHeading);
  21882. var tanU = (1 - f) * Math.tan(ellipsoidGeodesic._start.latitude);
  21883. var cosineU = 1.0 / Math.sqrt(1.0 + tanU * tanU);
  21884. var sineU = cosineU * tanU;
  21885. var sigma = Math.atan2(tanU, cosineHeading);
  21886. var sineAlpha = cosineU * sineHeading;
  21887. var sineSquaredAlpha = sineAlpha * sineAlpha;
  21888. var cosineSquaredAlpha = 1.0 - sineSquaredAlpha;
  21889. var cosineAlpha = Math.sqrt(cosineSquaredAlpha);
  21890. var u2Over4 = uSquared / 4.0;
  21891. var u4Over16 = u2Over4 * u2Over4;
  21892. var u6Over64 = u4Over16 * u2Over4;
  21893. var u8Over256 = u4Over16 * u4Over16;
  21894. var a0 = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0);
  21895. var a1 = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0);
  21896. var a2 = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0);
  21897. var a3 = (1.0 - 5.0 * u2Over4);
  21898. var distanceRatio = a0 * sigma - a1 * Math.sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * Math.sin(4.0 * sigma) * u4Over16 / 16.0 -
  21899. a3 * Math.sin(6.0 * sigma) * u6Over64 / 48.0 - Math.sin(8.0 * sigma) * 5.0 * u8Over256 / 512;
  21900. var constants = ellipsoidGeodesic._constants;
  21901. constants.a = a;
  21902. constants.b = b;
  21903. constants.f = f;
  21904. constants.cosineHeading = cosineHeading;
  21905. constants.sineHeading = sineHeading;
  21906. constants.tanU = tanU;
  21907. constants.cosineU = cosineU;
  21908. constants.sineU = sineU;
  21909. constants.sigma = sigma;
  21910. constants.sineAlpha = sineAlpha;
  21911. constants.sineSquaredAlpha = sineSquaredAlpha;
  21912. constants.cosineSquaredAlpha = cosineSquaredAlpha;
  21913. constants.cosineAlpha = cosineAlpha;
  21914. constants.u2Over4 = u2Over4;
  21915. constants.u4Over16 = u4Over16;
  21916. constants.u6Over64 = u6Over64;
  21917. constants.u8Over256 = u8Over256;
  21918. constants.a0 = a0;
  21919. constants.a1 = a1;
  21920. constants.a2 = a2;
  21921. constants.a3 = a3;
  21922. constants.distanceRatio = distanceRatio;
  21923. }
  21924. function computeC(f, cosineSquaredAlpha) {
  21925. return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0;
  21926. }
  21927. function computeDeltaLambda(f, sineAlpha, cosineSquaredAlpha, sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint) {
  21928. var C = computeC(f, cosineSquaredAlpha);
  21929. return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint +
  21930. C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0)));
  21931. }
  21932. function vincentyInverseFormula(ellipsoidGeodesic, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
  21933. var eff = (major - minor) / major;
  21934. var l = secondLongitude - firstLongitude;
  21935. var u1 = Math.atan((1 - eff) * Math.tan(firstLatitude));
  21936. var u2 = Math.atan((1 - eff) * Math.tan(secondLatitude));
  21937. var cosineU1 = Math.cos(u1);
  21938. var sineU1 = Math.sin(u1);
  21939. var cosineU2 = Math.cos(u2);
  21940. var sineU2 = Math.sin(u2);
  21941. var cc = cosineU1 * cosineU2;
  21942. var cs = cosineU1 * sineU2;
  21943. var ss = sineU1 * sineU2;
  21944. var sc = sineU1 * cosineU2;
  21945. var lambda = l;
  21946. var lambdaDot = CesiumMath.TWO_PI;
  21947. var cosineLambda = Math.cos(lambda);
  21948. var sineLambda = Math.sin(lambda);
  21949. var sigma;
  21950. var cosineSigma;
  21951. var sineSigma;
  21952. var cosineSquaredAlpha;
  21953. var cosineTwiceSigmaMidpoint;
  21954. do {
  21955. cosineLambda = Math.cos(lambda);
  21956. sineLambda = Math.sin(lambda);
  21957. var temp = cs - sc * cosineLambda;
  21958. sineSigma = Math.sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp);
  21959. cosineSigma = ss + cc * cosineLambda;
  21960. sigma = Math.atan2(sineSigma, cosineSigma);
  21961. var sineAlpha;
  21962. if (sineSigma === 0.0) {
  21963. sineAlpha = 0.0;
  21964. cosineSquaredAlpha = 1.0;
  21965. } else {
  21966. sineAlpha = cc * sineLambda / sineSigma;
  21967. cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha;
  21968. }
  21969. lambdaDot = lambda;
  21970. cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha;
  21971. if (isNaN(cosineTwiceSigmaMidpoint)) {
  21972. cosineTwiceSigmaMidpoint = 0.0;
  21973. }
  21974. lambda = l + computeDeltaLambda(eff, sineAlpha, cosineSquaredAlpha,
  21975. sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
  21976. } while (Math.abs(lambda - lambdaDot) > CesiumMath.EPSILON12);
  21977. var uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor);
  21978. var A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0;
  21979. var B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0;
  21980. var cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
  21981. var deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma *
  21982. (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint *
  21983. (4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0);
  21984. var distance = minor * A * (sigma - deltaSigma);
  21985. var startHeading = Math.atan2(cosineU2 * sineLambda, cs - sc * cosineLambda);
  21986. var endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);
  21987. ellipsoidGeodesic._distance = distance;
  21988. ellipsoidGeodesic._startHeading = startHeading;
  21989. ellipsoidGeodesic._endHeading = endHeading;
  21990. ellipsoidGeodesic._uSquared = uSquared;
  21991. }
  21992. function computeProperties(ellipsoidGeodesic, start, end, ellipsoid) {
  21993. var firstCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(start, scratchCart2), scratchCart1);
  21994. var lastCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(end, scratchCart2), scratchCart2);
  21995. if (Math.abs(Math.abs(Cartesian3.angleBetween(firstCartesian, lastCartesian)) - Math.PI) < 0.0125) {
  21996. throw new DeveloperError('geodesic position is not unique');
  21997. }
  21998. vincentyInverseFormula(ellipsoidGeodesic, ellipsoid.maximumRadius, ellipsoid.minimumRadius,
  21999. start.longitude, start.latitude, end.longitude, end.latitude);
  22000. ellipsoidGeodesic._start = Cartographic.clone(start, ellipsoidGeodesic._start);
  22001. ellipsoidGeodesic._end = Cartographic.clone(end, ellipsoidGeodesic._end);
  22002. ellipsoidGeodesic._start.height = 0;
  22003. ellipsoidGeodesic._end.height = 0;
  22004. setConstants(ellipsoidGeodesic);
  22005. }
  22006. var scratchCart1 = new Cartesian3();
  22007. var scratchCart2 = new Cartesian3();
  22008. /**
  22009. * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points.
  22010. *
  22011. * @alias EllipsoidGeodesic
  22012. * @constructor
  22013. *
  22014. * @param {Cartographic} [start] The initial planetodetic point on the path.
  22015. * @param {Cartographic} [end] The final planetodetic point on the path.
  22016. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies.
  22017. */
  22018. function EllipsoidGeodesic(start, end, ellipsoid) {
  22019. var e = defaultValue(ellipsoid, Ellipsoid.WGS84);
  22020. this._ellipsoid = e;
  22021. this._start = new Cartographic();
  22022. this._end = new Cartographic();
  22023. this._constants = {};
  22024. this._startHeading = undefined;
  22025. this._endHeading = undefined;
  22026. this._distance = undefined;
  22027. this._uSquared = undefined;
  22028. if (defined(start) && defined(end)) {
  22029. computeProperties(this, start, end, e);
  22030. }
  22031. }
  22032. defineProperties(EllipsoidGeodesic.prototype, {
  22033. /**
  22034. * Gets the ellipsoid.
  22035. * @memberof EllipsoidGeodesic.prototype
  22036. * @type {Ellipsoid}
  22037. * @readonly
  22038. */
  22039. ellipsoid : {
  22040. get : function() {
  22041. return this._ellipsoid;
  22042. }
  22043. },
  22044. /**
  22045. * Gets the surface distance between the start and end point
  22046. * @memberof EllipsoidGeodesic.prototype
  22047. * @type {Number}
  22048. * @readonly
  22049. */
  22050. surfaceDistance : {
  22051. get : function() {
  22052. if (!defined(this._distance)) {
  22053. throw new DeveloperError('set end positions before getting surfaceDistance');
  22054. }
  22055. return this._distance;
  22056. }
  22057. },
  22058. /**
  22059. * Gets the initial planetodetic point on the path.
  22060. * @memberof EllipsoidGeodesic.prototype
  22061. * @type {Cartographic}
  22062. * @readonly
  22063. */
  22064. start : {
  22065. get : function() {
  22066. return this._start;
  22067. }
  22068. },
  22069. /**
  22070. * Gets the final planetodetic point on the path.
  22071. * @memberof EllipsoidGeodesic.prototype
  22072. * @type {Cartographic}
  22073. * @readonly
  22074. */
  22075. end : {
  22076. get : function() {
  22077. return this._end;
  22078. }
  22079. },
  22080. /**
  22081. * Gets the heading at the initial point.
  22082. * @memberof EllipsoidGeodesic.prototype
  22083. * @type {Number}
  22084. * @readonly
  22085. */
  22086. startHeading : {
  22087. get : function() {
  22088. if (!defined(this._distance)) {
  22089. throw new DeveloperError('set end positions before getting startHeading');
  22090. }
  22091. return this._startHeading;
  22092. }
  22093. },
  22094. /**
  22095. * Gets the heading at the final point.
  22096. * @memberof EllipsoidGeodesic.prototype
  22097. * @type {Number}
  22098. * @readonly
  22099. */
  22100. endHeading : {
  22101. get : function() {
  22102. if (!defined(this._distance)) {
  22103. throw new DeveloperError('set end positions before getting endHeading');
  22104. }
  22105. return this._endHeading;
  22106. }
  22107. }
  22108. });
  22109. /**
  22110. * Sets the start and end points of the geodesic
  22111. *
  22112. * @param {Cartographic} start The initial planetodetic point on the path.
  22113. * @param {Cartographic} end The final planetodetic point on the path.
  22114. */
  22115. EllipsoidGeodesic.prototype.setEndPoints = function(start, end) {
  22116. if (!defined(start)) {
  22117. throw new DeveloperError('start cartographic position is required');
  22118. }
  22119. if (!defined(end)) {
  22120. throw new DeveloperError('end cartgraphic position is required');
  22121. }
  22122. computeProperties(this, start, end, this._ellipsoid);
  22123. };
  22124. /**
  22125. * Provides the location of a point at the indicated portion along the geodesic.
  22126. *
  22127. * @param {Number} fraction The portion of the distance between the initial and final points.
  22128. * @returns {Cartographic} The location of the point along the geodesic.
  22129. */
  22130. EllipsoidGeodesic.prototype.interpolateUsingFraction = function(fraction, result) {
  22131. return this.interpolateUsingSurfaceDistance(this._distance * fraction, result);
  22132. };
  22133. /**
  22134. * Provides the location of a point at the indicated distance along the geodesic.
  22135. *
  22136. * @param {Number} distance The distance from the inital point to the point of interest along the geodesic
  22137. * @returns {Cartographic} The location of the point along the geodesic.
  22138. *
  22139. * @exception {DeveloperError} start and end must be set before calling function interpolateUsingSurfaceDistance
  22140. */
  22141. EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function(distance, result) {
  22142. if (!defined(this._distance)) {
  22143. throw new DeveloperError('start and end must be set before calling function interpolateUsingSurfaceDistance');
  22144. }
  22145. var constants = this._constants;
  22146. var s = constants.distanceRatio + distance / constants.b;
  22147. var cosine2S = Math.cos(2.0 * s);
  22148. var cosine4S = Math.cos(4.0 * s);
  22149. var cosine6S = Math.cos(6.0 * s);
  22150. var sine2S = Math.sin(2.0 * s);
  22151. var sine4S = Math.sin(4.0 * s);
  22152. var sine6S = Math.sin(6.0 * s);
  22153. var sine8S = Math.sin(8.0 * s);
  22154. var s2 = s * s;
  22155. var s3 = s * s2;
  22156. var u8Over256 = constants.u8Over256;
  22157. var u2Over4 = constants.u2Over4;
  22158. var u6Over64 = constants.u6Over64;
  22159. var u4Over16 = constants.u4Over16;
  22160. var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 +
  22161. s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 -
  22162. (u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S -
  22163. (5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S -
  22164. 29.0 * u8Over256 * cosine6S / 16.0) +
  22165. (u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S +
  22166. (5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S -
  22167. s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) +
  22168. (29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S +
  22169. 539.0 * u8Over256 * sine8S / 1536.0;
  22170. var theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
  22171. var latitude = Math.atan(constants.a / constants.b * Math.tan(theta));
  22172. // Redefine in terms of relative argument of latitude.
  22173. sigma = sigma - constants.sigma;
  22174. var cosineTwiceSigmaMidpoint = Math.cos(2.0 * constants.sigma + sigma);
  22175. var sineSigma = Math.sin(sigma);
  22176. var cosineSigma = Math.cos(sigma);
  22177. var cc = constants.cosineU * cosineSigma;
  22178. var ss = constants.sineU * sineSigma;
  22179. var lambda = Math.atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading);
  22180. var l = lambda - computeDeltaLambda(constants.f, constants.sineAlpha, constants.cosineSquaredAlpha,
  22181. sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
  22182. if (defined(result)) {
  22183. result.longitude = this._start.longitude + l;
  22184. result.latitude = latitude;
  22185. result.height = 0.0;
  22186. return result;
  22187. }
  22188. return new Cartographic(this._start.longitude + l, latitude, 0.0);
  22189. };
  22190. return EllipsoidGeodesic;
  22191. });
  22192. /*global define*/
  22193. define('Core/PolylinePipeline',[
  22194. './Cartesian3',
  22195. './Cartographic',
  22196. './defaultValue',
  22197. './defined',
  22198. './DeveloperError',
  22199. './Ellipsoid',
  22200. './EllipsoidGeodesic',
  22201. './IntersectionTests',
  22202. './isArray',
  22203. './Math',
  22204. './Matrix4',
  22205. './Plane'
  22206. ], function(
  22207. Cartesian3,
  22208. Cartographic,
  22209. defaultValue,
  22210. defined,
  22211. DeveloperError,
  22212. Ellipsoid,
  22213. EllipsoidGeodesic,
  22214. IntersectionTests,
  22215. isArray,
  22216. CesiumMath,
  22217. Matrix4,
  22218. Plane) {
  22219. 'use strict';
  22220. /**
  22221. * @private
  22222. */
  22223. var PolylinePipeline = {};
  22224. PolylinePipeline.numberOfPoints = function(p0, p1, minDistance) {
  22225. var distance = Cartesian3.distance(p0, p1);
  22226. return Math.ceil(distance / minDistance);
  22227. };
  22228. var cartoScratch = new Cartographic();
  22229. PolylinePipeline.extractHeights = function(positions, ellipsoid) {
  22230. var length = positions.length;
  22231. var heights = new Array(length);
  22232. for (var i = 0; i < length; i++) {
  22233. var p = positions[i];
  22234. heights[i] = ellipsoid.cartesianToCartographic(p, cartoScratch).height;
  22235. }
  22236. return heights;
  22237. };
  22238. var wrapLongitudeInversMatrix = new Matrix4();
  22239. var wrapLongitudeOrigin = new Cartesian3();
  22240. var wrapLongitudeXZNormal = new Cartesian3();
  22241. var wrapLongitudeXZPlane = new Plane(Cartesian3.ZERO, 0.0);
  22242. var wrapLongitudeYZNormal = new Cartesian3();
  22243. var wrapLongitudeYZPlane = new Plane(Cartesian3.ZERO, 0.0);
  22244. var wrapLongitudeIntersection = new Cartesian3();
  22245. var wrapLongitudeOffset = new Cartesian3();
  22246. var subdivideHeightsScratchArray = [];
  22247. function subdivideHeights(numPoints, h0, h1) {
  22248. var heights = subdivideHeightsScratchArray;
  22249. heights.length = numPoints;
  22250. var i;
  22251. if (h0 === h1) {
  22252. for (i = 0; i < numPoints; i++) {
  22253. heights[i] = h0;
  22254. }
  22255. return heights;
  22256. }
  22257. var dHeight = h1 - h0;
  22258. var heightPerVertex = dHeight / numPoints;
  22259. for (i = 0; i < numPoints; i++) {
  22260. var h = h0 + i*heightPerVertex;
  22261. heights[i] = h;
  22262. }
  22263. return heights;
  22264. }
  22265. var carto1 = new Cartographic();
  22266. var carto2 = new Cartographic();
  22267. var cartesian = new Cartesian3();
  22268. var scaleFirst = new Cartesian3();
  22269. var scaleLast = new Cartesian3();
  22270. var ellipsoidGeodesic = new EllipsoidGeodesic();
  22271. //Returns subdivided line scaled to ellipsoid surface starting at p1 and ending at p2.
  22272. //Result includes p1, but not include p2. This function is called for a sequence of line segments,
  22273. //and this prevents duplication of end point.
  22274. function generateCartesianArc(p0, p1, minDistance, ellipsoid, h0, h1, array, offset) {
  22275. var first = ellipsoid.scaleToGeodeticSurface(p0, scaleFirst);
  22276. var last = ellipsoid.scaleToGeodeticSurface(p1, scaleLast);
  22277. var numPoints = PolylinePipeline.numberOfPoints(p0, p1, minDistance);
  22278. var start = ellipsoid.cartesianToCartographic(first, carto1);
  22279. var end = ellipsoid.cartesianToCartographic(last, carto2);
  22280. var heights = subdivideHeights(numPoints, h0, h1);
  22281. ellipsoidGeodesic.setEndPoints(start, end);
  22282. var surfaceDistanceBetweenPoints = ellipsoidGeodesic.surfaceDistance / numPoints;
  22283. var index = offset;
  22284. start.height = h0;
  22285. var cart = ellipsoid.cartographicToCartesian(start, cartesian);
  22286. Cartesian3.pack(cart, array, index);
  22287. index += 3;
  22288. for (var i = 1; i < numPoints; i++) {
  22289. var carto = ellipsoidGeodesic.interpolateUsingSurfaceDistance(i * surfaceDistanceBetweenPoints, carto2);
  22290. carto.height = heights[i];
  22291. cart = ellipsoid.cartographicToCartesian(carto, cartesian);
  22292. Cartesian3.pack(cart, array, index);
  22293. index += 3;
  22294. }
  22295. return index;
  22296. }
  22297. /**
  22298. * Breaks a {@link Polyline} into segments such that it does not cross the &plusmn;180 degree meridian of an ellipsoid.
  22299. *
  22300. * @param {Cartesian3[]} positions The polyline's Cartesian positions.
  22301. * @param {Matrix4} [modelMatrix=Matrix4.IDENTITY] The polyline's model matrix. Assumed to be an affine
  22302. * transformation matrix, where the upper left 3x3 elements are a rotation matrix, and
  22303. * the upper three elements in the fourth column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  22304. * The matrix is not verified to be in the proper form.
  22305. * @returns {Object} An object with a <code>positions</code> property that is an array of positions and a
  22306. * <code>segments</code> property.
  22307. *
  22308. *
  22309. * @example
  22310. * var polylines = new Cesium.PolylineCollection();
  22311. * var polyline = polylines.add(...);
  22312. * var positions = polyline.positions;
  22313. * var modelMatrix = polylines.modelMatrix;
  22314. * var segments = Cesium.PolylinePipeline.wrapLongitude(positions, modelMatrix);
  22315. *
  22316. * @see PolygonPipeline.wrapLongitude
  22317. * @see Polyline
  22318. * @see PolylineCollection
  22319. */
  22320. PolylinePipeline.wrapLongitude = function(positions, modelMatrix) {
  22321. var cartesians = [];
  22322. var segments = [];
  22323. if (defined(positions) && positions.length > 0) {
  22324. modelMatrix = defaultValue(modelMatrix, Matrix4.IDENTITY);
  22325. var inverseModelMatrix = Matrix4.inverseTransformation(modelMatrix, wrapLongitudeInversMatrix);
  22326. var origin = Matrix4.multiplyByPoint(inverseModelMatrix, Cartesian3.ZERO, wrapLongitudeOrigin);
  22327. var xzNormal = Matrix4.multiplyByPointAsVector(inverseModelMatrix, Cartesian3.UNIT_Y, wrapLongitudeXZNormal);
  22328. var xzPlane = Plane.fromPointNormal(origin, xzNormal, wrapLongitudeXZPlane);
  22329. var yzNormal = Matrix4.multiplyByPointAsVector(inverseModelMatrix, Cartesian3.UNIT_X, wrapLongitudeYZNormal);
  22330. var yzPlane = Plane.fromPointNormal(origin, yzNormal, wrapLongitudeYZPlane);
  22331. var count = 1;
  22332. cartesians.push(Cartesian3.clone(positions[0]));
  22333. var prev = cartesians[0];
  22334. var length = positions.length;
  22335. for (var i = 1; i < length; ++i) {
  22336. var cur = positions[i];
  22337. // intersects the IDL if either endpoint is on the negative side of the yz-plane
  22338. if (Plane.getPointDistance(yzPlane, prev) < 0.0 || Plane.getPointDistance(yzPlane, cur) < 0.0) {
  22339. // and intersects the xz-plane
  22340. var intersection = IntersectionTests.lineSegmentPlane(prev, cur, xzPlane, wrapLongitudeIntersection);
  22341. if (defined(intersection)) {
  22342. // move point on the xz-plane slightly away from the plane
  22343. var offset = Cartesian3.multiplyByScalar(xzNormal, 5.0e-9, wrapLongitudeOffset);
  22344. if (Plane.getPointDistance(xzPlane, prev) < 0.0) {
  22345. Cartesian3.negate(offset, offset);
  22346. }
  22347. cartesians.push(Cartesian3.add(intersection, offset, new Cartesian3()));
  22348. segments.push(count + 1);
  22349. Cartesian3.negate(offset, offset);
  22350. cartesians.push(Cartesian3.add(intersection, offset, new Cartesian3()));
  22351. count = 1;
  22352. }
  22353. }
  22354. cartesians.push(Cartesian3.clone(positions[i]));
  22355. count++;
  22356. prev = cur;
  22357. }
  22358. segments.push(count);
  22359. }
  22360. return {
  22361. positions : cartesians,
  22362. lengths : segments
  22363. };
  22364. };
  22365. /**
  22366. * Subdivides polyline and raises all points to the specified height. Returns an array of numbers to represent the positions.
  22367. * @param {Cartesian3[]} positions The array of type {Cartesian3} representing positions.
  22368. * @param {Number|Number[]} [height=0.0] A number or array of numbers representing the heights of each position.
  22369. * @param {Number} [granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  22370. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  22371. * @returns {Number[]} A new array of positions of type {Number} that have been subdivided and raised to the surface of the ellipsoid.
  22372. *
  22373. * @example
  22374. * var positions = Cesium.Cartesian3.fromDegreesArray([
  22375. * -105.0, 40.0,
  22376. * -100.0, 38.0,
  22377. * -105.0, 35.0,
  22378. * -100.0, 32.0
  22379. * ]);
  22380. * var surfacePositions = Cesium.PolylinePipeline.generateArc({
  22381. * positons: positions
  22382. * });
  22383. */
  22384. PolylinePipeline.generateArc = function(options) {
  22385. if (!defined(options)) {
  22386. options = {};
  22387. }
  22388. var positions = options.positions;
  22389. if (!defined(positions)) {
  22390. throw new DeveloperError('options.positions is required.');
  22391. }
  22392. var length = positions.length;
  22393. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  22394. var height = defaultValue(options.height, 0);
  22395. var hasHeightArray = isArray(height);
  22396. if (length < 1) {
  22397. return [];
  22398. } else if (length === 1) {
  22399. var p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
  22400. height = hasHeightArray ? height[0] : height;
  22401. if (height !== 0) {
  22402. var n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
  22403. Cartesian3.multiplyByScalar(n, height, n);
  22404. Cartesian3.add(p, n, p);
  22405. }
  22406. return [p.x, p.y, p.z];
  22407. }
  22408. var minDistance = options.minDistance;
  22409. if (!defined(minDistance)) {
  22410. var granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  22411. minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
  22412. }
  22413. var numPoints = 0;
  22414. var i;
  22415. for (i = 0; i < length -1; i++) {
  22416. numPoints += PolylinePipeline.numberOfPoints(positions[i], positions[i+1], minDistance);
  22417. }
  22418. var arrayLength = (numPoints + 1) * 3;
  22419. var newPositions = new Array(arrayLength);
  22420. var offset = 0;
  22421. for (i = 0; i < length - 1; i++) {
  22422. var p0 = positions[i];
  22423. var p1 = positions[i + 1];
  22424. var h0 = hasHeightArray ? height[i] : height;
  22425. var h1 = hasHeightArray ? height[i + 1] : height;
  22426. offset = generateCartesianArc(p0, p1, minDistance, ellipsoid, h0, h1, newPositions, offset);
  22427. }
  22428. subdivideHeightsScratchArray.length = 0;
  22429. var lastPoint = positions[length - 1];
  22430. var carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
  22431. carto.height = hasHeightArray ? height[length - 1] : height;
  22432. var cart = ellipsoid.cartographicToCartesian(carto, cartesian);
  22433. Cartesian3.pack(cart, newPositions, arrayLength - 3);
  22434. return newPositions;
  22435. };
  22436. /**
  22437. * Subdivides polyline and raises all points to the specified height. Returns an array of new {Cartesian3} positions.
  22438. * @param {Cartesian3[]} positions The array of type {Cartesian3} representing positions.
  22439. * @param {Number|Number[]} [height=0.0] A number or array of numbers representing the heights of each position.
  22440. * @param {Number} [granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  22441. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  22442. * @returns {Cartesian3[]} A new array of cartesian3 positions that have been subdivided and raised to the surface of the ellipsoid.
  22443. *
  22444. * @example
  22445. * var positions = Cesium.Cartesian3.fromDegreesArray([
  22446. * -105.0, 40.0,
  22447. * -100.0, 38.0,
  22448. * -105.0, 35.0,
  22449. * -100.0, 32.0
  22450. * ]);
  22451. * var surfacePositions = Cesium.PolylinePipeline.generateCartesianArc({
  22452. * positons: positions
  22453. * });
  22454. */
  22455. PolylinePipeline.generateCartesianArc = function(options) {
  22456. var numberArray = PolylinePipeline.generateArc(options);
  22457. var size = numberArray.length/3;
  22458. var newPositions = new Array(size);
  22459. for (var i = 0; i < size; i++) {
  22460. newPositions[i] = Cartesian3.unpack(numberArray, i*3);
  22461. }
  22462. return newPositions;
  22463. };
  22464. return PolylinePipeline;
  22465. });
  22466. /*global define*/
  22467. define('Core/PolylineVolumeGeometryLibrary',[
  22468. './Cartesian2',
  22469. './Cartesian3',
  22470. './Cartesian4',
  22471. './Cartographic',
  22472. './CornerType',
  22473. './EllipsoidTangentPlane',
  22474. './Math',
  22475. './Matrix3',
  22476. './Matrix4',
  22477. './PolylinePipeline',
  22478. './Quaternion',
  22479. './Transforms'
  22480. ], function(
  22481. Cartesian2,
  22482. Cartesian3,
  22483. Cartesian4,
  22484. Cartographic,
  22485. CornerType,
  22486. EllipsoidTangentPlane,
  22487. CesiumMath,
  22488. Matrix3,
  22489. Matrix4,
  22490. PolylinePipeline,
  22491. Quaternion,
  22492. Transforms) {
  22493. 'use strict';
  22494. var scratch2Array = [new Cartesian3(), new Cartesian3()];
  22495. var scratchCartesian1 = new Cartesian3();
  22496. var scratchCartesian2 = new Cartesian3();
  22497. var scratchCartesian3 = new Cartesian3();
  22498. var scratchCartesian4 = new Cartesian3();
  22499. var scratchCartesian5 = new Cartesian3();
  22500. var scratchCartesian6 = new Cartesian3();
  22501. var scratchCartesian7 = new Cartesian3();
  22502. var scratchCartesian8 = new Cartesian3();
  22503. var scratchCartesian9 = new Cartesian3();
  22504. var scratch1 = new Cartesian3();
  22505. var scratch2 = new Cartesian3();
  22506. /**
  22507. * @private
  22508. */
  22509. var PolylineVolumeGeometryLibrary = {};
  22510. var cartographic = new Cartographic();
  22511. function scaleToSurface(positions, ellipsoid) {
  22512. var heights = new Array(positions.length);
  22513. for (var i = 0; i < positions.length; i++) {
  22514. var pos = positions[i];
  22515. cartographic = ellipsoid.cartesianToCartographic(pos, cartographic);
  22516. heights[i] = cartographic.height;
  22517. positions[i] = ellipsoid.scaleToGeodeticSurface(pos, pos);
  22518. }
  22519. return heights;
  22520. }
  22521. function subdivideHeights(points, h0, h1, granularity) {
  22522. var p0 = points[0];
  22523. var p1 = points[1];
  22524. var angleBetween = Cartesian3.angleBetween(p0, p1);
  22525. var numPoints = Math.ceil(angleBetween / granularity);
  22526. var heights = new Array(numPoints);
  22527. var i;
  22528. if (h0 === h1) {
  22529. for (i = 0; i < numPoints; i++) {
  22530. heights[i] = h0;
  22531. }
  22532. heights.push(h1);
  22533. return heights;
  22534. }
  22535. var dHeight = h1 - h0;
  22536. var heightPerVertex = dHeight / (numPoints);
  22537. for (i = 1; i < numPoints; i++) {
  22538. var h = h0 + i * heightPerVertex;
  22539. heights[i] = h;
  22540. }
  22541. heights[0] = h0;
  22542. heights.push(h1);
  22543. return heights;
  22544. }
  22545. function computeRotationAngle(start, end, position, ellipsoid) {
  22546. var tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
  22547. var next = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, start, nextScratch), nextScratch);
  22548. var prev = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, end, prevScratch), prevScratch);
  22549. var angle = Cartesian2.angleBetween(next, prev);
  22550. return (prev.x * next.y - prev.y * next.x >= 0.0) ? -angle : angle;
  22551. }
  22552. var negativeX = new Cartesian3(-1, 0, 0);
  22553. var transform = new Matrix4();
  22554. var translation = new Matrix4();
  22555. var rotationZ = new Matrix3();
  22556. var scaleMatrix = Matrix3.IDENTITY.clone();
  22557. var westScratch = new Cartesian3();
  22558. var finalPosScratch = new Cartesian4();
  22559. var heightCartesian = new Cartesian3();
  22560. function addPosition(center, left, shape, finalPositions, ellipsoid, height, xScalar, repeat) {
  22561. var west = westScratch;
  22562. var finalPosition = finalPosScratch;
  22563. transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, transform);
  22564. west = Matrix4.multiplyByPointAsVector(transform, negativeX, west);
  22565. west = Cartesian3.normalize(west, west);
  22566. var angle = computeRotationAngle(west, left, center, ellipsoid);
  22567. rotationZ = Matrix3.fromRotationZ(angle, rotationZ);
  22568. heightCartesian.z = height;
  22569. transform = Matrix4.multiplyTransformation(transform, Matrix4.fromRotationTranslation(rotationZ, heightCartesian, translation), transform);
  22570. var scale = scaleMatrix;
  22571. scale[0] = xScalar;
  22572. for (var j = 0; j < repeat; j++) {
  22573. for (var i = 0; i < shape.length; i += 3) {
  22574. finalPosition = Cartesian3.fromArray(shape, i, finalPosition);
  22575. finalPosition = Matrix3.multiplyByVector(scale, finalPosition, finalPosition);
  22576. finalPosition = Matrix4.multiplyByPoint(transform, finalPosition, finalPosition);
  22577. finalPositions.push(finalPosition.x, finalPosition.y, finalPosition.z);
  22578. }
  22579. }
  22580. return finalPositions;
  22581. }
  22582. var centerScratch = new Cartesian3();
  22583. function addPositions(centers, left, shape, finalPositions, ellipsoid, heights, xScalar) {
  22584. for (var i = 0; i < centers.length; i += 3) {
  22585. var center = Cartesian3.fromArray(centers, i, centerScratch);
  22586. finalPositions = addPosition(center, left, shape, finalPositions, ellipsoid, heights[i / 3], xScalar, 1);
  22587. }
  22588. return finalPositions;
  22589. }
  22590. function convertShapeTo3DDuplicate(shape2D, boundingRectangle) { //orientate 2D shape to XZ plane center at (0, 0, 0), duplicate points
  22591. var length = shape2D.length;
  22592. var shape = new Array(length * 6);
  22593. var index = 0;
  22594. var xOffset = boundingRectangle.x + boundingRectangle.width / 2;
  22595. var yOffset = boundingRectangle.y + boundingRectangle.height / 2;
  22596. var point = shape2D[0];
  22597. shape[index++] = point.x - xOffset;
  22598. shape[index++] = 0.0;
  22599. shape[index++] = point.y - yOffset;
  22600. for (var i = 1; i < length; i++) {
  22601. point = shape2D[i];
  22602. var x = point.x - xOffset;
  22603. var z = point.y - yOffset;
  22604. shape[index++] = x;
  22605. shape[index++] = 0.0;
  22606. shape[index++] = z;
  22607. shape[index++] = x;
  22608. shape[index++] = 0.0;
  22609. shape[index++] = z;
  22610. }
  22611. point = shape2D[0];
  22612. shape[index++] = point.x - xOffset;
  22613. shape[index++] = 0.0;
  22614. shape[index++] = point.y - yOffset;
  22615. return shape;
  22616. }
  22617. function convertShapeTo3D(shape2D, boundingRectangle) { //orientate 2D shape to XZ plane center at (0, 0, 0)
  22618. var length = shape2D.length;
  22619. var shape = new Array(length * 3);
  22620. var index = 0;
  22621. var xOffset = boundingRectangle.x + boundingRectangle.width / 2;
  22622. var yOffset = boundingRectangle.y + boundingRectangle.height / 2;
  22623. for (var i = 0; i < length; i++) {
  22624. shape[index++] = shape2D[i].x - xOffset;
  22625. shape[index++] = 0;
  22626. shape[index++] = shape2D[i].y - yOffset;
  22627. }
  22628. return shape;
  22629. }
  22630. var quaterion = new Quaternion();
  22631. var startPointScratch = new Cartesian3();
  22632. var rotMatrix = new Matrix3();
  22633. function computeRoundCorner(pivot, startPoint, endPoint, cornerType, leftIsOutside, ellipsoid, finalPositions, shape, height, duplicatePoints) {
  22634. var angle = Cartesian3.angleBetween(Cartesian3.subtract(startPoint, pivot, scratch1), Cartesian3.subtract(endPoint, pivot, scratch2));
  22635. var granularity = (cornerType === CornerType.BEVELED) ? 0 : Math.ceil(angle / CesiumMath.toRadians(5));
  22636. var m;
  22637. if (leftIsOutside) {
  22638. m = Matrix3.fromQuaternion(Quaternion.fromAxisAngle(Cartesian3.negate(pivot, scratch1), angle / (granularity + 1), quaterion), rotMatrix);
  22639. } else {
  22640. m = Matrix3.fromQuaternion(Quaternion.fromAxisAngle(pivot, angle / (granularity + 1), quaterion), rotMatrix);
  22641. }
  22642. var left;
  22643. var surfacePoint;
  22644. startPoint = Cartesian3.clone(startPoint, startPointScratch);
  22645. if (granularity > 0) {
  22646. var repeat = duplicatePoints ? 2 : 1;
  22647. for (var i = 0; i < granularity; i++) {
  22648. startPoint = Matrix3.multiplyByVector(m, startPoint, startPoint);
  22649. left = Cartesian3.subtract(startPoint, pivot, scratch1);
  22650. left = Cartesian3.normalize(left, left);
  22651. if (!leftIsOutside) {
  22652. left = Cartesian3.negate(left, left);
  22653. }
  22654. surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
  22655. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, repeat);
  22656. }
  22657. } else {
  22658. left = Cartesian3.subtract(startPoint, pivot, scratch1);
  22659. left = Cartesian3.normalize(left, left);
  22660. if (!leftIsOutside) {
  22661. left = Cartesian3.negate(left, left);
  22662. }
  22663. surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
  22664. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, 1);
  22665. endPoint = Cartesian3.clone(endPoint, startPointScratch);
  22666. left = Cartesian3.subtract(endPoint, pivot, scratch1);
  22667. left = Cartesian3.normalize(left, left);
  22668. if (!leftIsOutside) {
  22669. left = Cartesian3.negate(left, left);
  22670. }
  22671. surfacePoint = ellipsoid.scaleToGeodeticSurface(endPoint, scratch2);
  22672. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, 1);
  22673. }
  22674. return finalPositions;
  22675. }
  22676. PolylineVolumeGeometryLibrary.removeDuplicatesFromShape = function(shapePositions) {
  22677. var length = shapePositions.length;
  22678. var cleanedPositions = [];
  22679. for (var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  22680. var v0 = shapePositions[i0];
  22681. var v1 = shapePositions[i1];
  22682. if (!Cartesian2.equals(v0, v1)) {
  22683. cleanedPositions.push(v1); // Shallow copy!
  22684. }
  22685. }
  22686. return cleanedPositions;
  22687. };
  22688. var nextScratch = new Cartesian3();
  22689. var prevScratch = new Cartesian3();
  22690. PolylineVolumeGeometryLibrary.angleIsGreaterThanPi = function(forward, backward, position, ellipsoid) {
  22691. var tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
  22692. var next = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, forward, nextScratch), nextScratch);
  22693. var prev = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, backward, prevScratch), prevScratch);
  22694. return ((prev.x * next.y) - (prev.y * next.x)) >= 0.0;
  22695. };
  22696. var scratchForwardProjection = new Cartesian3();
  22697. var scratchBackwardProjection = new Cartesian3();
  22698. PolylineVolumeGeometryLibrary.computePositions = function(positions, shape2D, boundingRectangle, geometry, duplicatePoints) {
  22699. var ellipsoid = geometry._ellipsoid;
  22700. var heights = scaleToSurface(positions, ellipsoid);
  22701. var granularity = geometry._granularity;
  22702. var cornerType = geometry._cornerType;
  22703. var shapeForSides = duplicatePoints ? convertShapeTo3DDuplicate(shape2D, boundingRectangle) : convertShapeTo3D(shape2D, boundingRectangle);
  22704. var shapeForEnds = duplicatePoints ? convertShapeTo3D(shape2D, boundingRectangle) : undefined;
  22705. var heightOffset = boundingRectangle.height / 2;
  22706. var width = boundingRectangle.width / 2;
  22707. var length = positions.length;
  22708. var finalPositions = [];
  22709. var ends = duplicatePoints ? [] : undefined;
  22710. var forward = scratchCartesian1;
  22711. var backward = scratchCartesian2;
  22712. var cornerDirection = scratchCartesian3;
  22713. var surfaceNormal = scratchCartesian4;
  22714. var pivot = scratchCartesian5;
  22715. var start = scratchCartesian6;
  22716. var end = scratchCartesian7;
  22717. var left = scratchCartesian8;
  22718. var previousPosition = scratchCartesian9;
  22719. var position = positions[0];
  22720. var nextPosition = positions[1];
  22721. surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
  22722. forward = Cartesian3.subtract(nextPosition, position, forward);
  22723. forward = Cartesian3.normalize(forward, forward);
  22724. left = Cartesian3.cross(surfaceNormal, forward, left);
  22725. left = Cartesian3.normalize(left, left);
  22726. var h0 = heights[0];
  22727. var h1 = heights[1];
  22728. if (duplicatePoints) {
  22729. ends = addPosition(position, left, shapeForEnds, ends, ellipsoid, h0 + heightOffset, 1, 1);
  22730. }
  22731. previousPosition = Cartesian3.clone(position, previousPosition);
  22732. position = nextPosition;
  22733. backward = Cartesian3.negate(forward, backward);
  22734. var subdividedHeights;
  22735. var subdividedPositions;
  22736. for (var i = 1; i < length - 1; i++) {
  22737. var repeat = duplicatePoints ? 2 : 1;
  22738. nextPosition = positions[i + 1];
  22739. forward = Cartesian3.subtract(nextPosition, position, forward);
  22740. forward = Cartesian3.normalize(forward, forward);
  22741. cornerDirection = Cartesian3.add(forward, backward, cornerDirection);
  22742. cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
  22743. surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
  22744. var forwardProjection = Cartesian3.multiplyByScalar(surfaceNormal, Cartesian3.dot(forward, surfaceNormal), scratchForwardProjection);
  22745. Cartesian3.subtract(forward, forwardProjection, forwardProjection);
  22746. Cartesian3.normalize(forwardProjection, forwardProjection);
  22747. var backwardProjection = Cartesian3.multiplyByScalar(surfaceNormal, Cartesian3.dot(backward, surfaceNormal), scratchBackwardProjection);
  22748. Cartesian3.subtract(backward, backwardProjection, backwardProjection);
  22749. Cartesian3.normalize(backwardProjection, backwardProjection);
  22750. var doCorner = !CesiumMath.equalsEpsilon(Math.abs(Cartesian3.dot(forwardProjection, backwardProjection)), 1.0, CesiumMath.EPSILON7);
  22751. if (doCorner) {
  22752. cornerDirection = Cartesian3.cross(cornerDirection, surfaceNormal, cornerDirection);
  22753. cornerDirection = Cartesian3.cross(surfaceNormal, cornerDirection, cornerDirection);
  22754. cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
  22755. var scalar = 1 / Math.max(0.25, (Cartesian3.magnitude(Cartesian3.cross(cornerDirection, backward, scratch1))));
  22756. var leftIsOutside = PolylineVolumeGeometryLibrary.angleIsGreaterThanPi(forward, backward, position, ellipsoid);
  22757. if (leftIsOutside) {
  22758. pivot = Cartesian3.add(position, Cartesian3.multiplyByScalar(cornerDirection, scalar * width, cornerDirection), pivot);
  22759. start = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, width, start), start);
  22760. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  22761. scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
  22762. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  22763. subdividedPositions = PolylinePipeline.generateArc({
  22764. positions: scratch2Array,
  22765. granularity: granularity,
  22766. ellipsoid: ellipsoid
  22767. });
  22768. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  22769. left = Cartesian3.cross(surfaceNormal, forward, left);
  22770. left = Cartesian3.normalize(left, left);
  22771. end = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, width, end), end);
  22772. if (cornerType === CornerType.ROUNDED || cornerType === CornerType.BEVELED) {
  22773. computeRoundCorner(pivot, start, end, cornerType, leftIsOutside, ellipsoid, finalPositions, shapeForSides, h1 + heightOffset, duplicatePoints);
  22774. } else {
  22775. cornerDirection = Cartesian3.negate(cornerDirection, cornerDirection);
  22776. finalPositions = addPosition(position, cornerDirection, shapeForSides, finalPositions, ellipsoid, h1 + heightOffset, scalar, repeat);
  22777. }
  22778. previousPosition = Cartesian3.clone(end, previousPosition);
  22779. } else {
  22780. pivot = Cartesian3.add(position, Cartesian3.multiplyByScalar(cornerDirection, scalar * width, cornerDirection), pivot);
  22781. start = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, -width, start), start);
  22782. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  22783. scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
  22784. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  22785. subdividedPositions = PolylinePipeline.generateArc({
  22786. positions: scratch2Array,
  22787. granularity: granularity,
  22788. ellipsoid: ellipsoid
  22789. });
  22790. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  22791. left = Cartesian3.cross(surfaceNormal, forward, left);
  22792. left = Cartesian3.normalize(left, left);
  22793. end = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, -width, end), end);
  22794. if (cornerType === CornerType.ROUNDED || cornerType === CornerType.BEVELED) {
  22795. computeRoundCorner(pivot, start, end, cornerType, leftIsOutside, ellipsoid, finalPositions, shapeForSides, h1 + heightOffset, duplicatePoints);
  22796. } else {
  22797. finalPositions = addPosition(position, cornerDirection, shapeForSides, finalPositions, ellipsoid, h1 + heightOffset, scalar, repeat);
  22798. }
  22799. previousPosition = Cartesian3.clone(end, previousPosition);
  22800. }
  22801. backward = Cartesian3.negate(forward, backward);
  22802. } else {
  22803. finalPositions = addPosition(previousPosition, left, shapeForSides, finalPositions, ellipsoid, h0 + heightOffset, 1, 1);
  22804. previousPosition = position;
  22805. }
  22806. h0 = h1;
  22807. h1 = heights[i + 1];
  22808. position = nextPosition;
  22809. }
  22810. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  22811. scratch2Array[1] = Cartesian3.clone(position, scratch2Array[1]);
  22812. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  22813. subdividedPositions = PolylinePipeline.generateArc({
  22814. positions: scratch2Array,
  22815. granularity: granularity,
  22816. ellipsoid: ellipsoid
  22817. });
  22818. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  22819. if (duplicatePoints) {
  22820. ends = addPosition(position, left, shapeForEnds, ends, ellipsoid, h1 + heightOffset, 1, 1);
  22821. }
  22822. length = finalPositions.length;
  22823. var posLength = duplicatePoints ? length + ends.length : length;
  22824. var combinedPositions = new Float64Array(posLength);
  22825. combinedPositions.set(finalPositions);
  22826. if (duplicatePoints) {
  22827. combinedPositions.set(ends, length);
  22828. }
  22829. return combinedPositions;
  22830. };
  22831. return PolylineVolumeGeometryLibrary;
  22832. });
  22833. /*global define*/
  22834. define('Core/PolylineVolumeOutlineGeometry',[
  22835. './arrayRemoveDuplicates',
  22836. './BoundingRectangle',
  22837. './BoundingSphere',
  22838. './Cartesian2',
  22839. './Cartesian3',
  22840. './ComponentDatatype',
  22841. './CornerType',
  22842. './defaultValue',
  22843. './defined',
  22844. './DeveloperError',
  22845. './Ellipsoid',
  22846. './Geometry',
  22847. './GeometryAttribute',
  22848. './GeometryAttributes',
  22849. './IndexDatatype',
  22850. './Math',
  22851. './PolygonPipeline',
  22852. './PolylineVolumeGeometryLibrary',
  22853. './PrimitiveType',
  22854. './WindingOrder'
  22855. ], function(
  22856. arrayRemoveDuplicates,
  22857. BoundingRectangle,
  22858. BoundingSphere,
  22859. Cartesian2,
  22860. Cartesian3,
  22861. ComponentDatatype,
  22862. CornerType,
  22863. defaultValue,
  22864. defined,
  22865. DeveloperError,
  22866. Ellipsoid,
  22867. Geometry,
  22868. GeometryAttribute,
  22869. GeometryAttributes,
  22870. IndexDatatype,
  22871. CesiumMath,
  22872. PolygonPipeline,
  22873. PolylineVolumeGeometryLibrary,
  22874. PrimitiveType,
  22875. WindingOrder) {
  22876. 'use strict';
  22877. function computeAttributes(positions, shape) {
  22878. var attributes = new GeometryAttributes();
  22879. attributes.position = new GeometryAttribute({
  22880. componentDatatype : ComponentDatatype.DOUBLE,
  22881. componentsPerAttribute : 3,
  22882. values : positions
  22883. });
  22884. var shapeLength = shape.length;
  22885. var vertexCount = attributes.position.values.length / 3;
  22886. var positionLength = positions.length / 3;
  22887. var shapeCount = positionLength / shapeLength;
  22888. var indices = IndexDatatype.createTypedArray(vertexCount, 2 * shapeLength * (shapeCount + 1));
  22889. var i, j;
  22890. var index = 0;
  22891. i = 0;
  22892. var offset = i * shapeLength;
  22893. for (j = 0; j < shapeLength - 1; j++) {
  22894. indices[index++] = j + offset;
  22895. indices[index++] = j + offset + 1;
  22896. }
  22897. indices[index++] = shapeLength - 1 + offset;
  22898. indices[index++] = offset;
  22899. i = shapeCount - 1;
  22900. offset = i * shapeLength;
  22901. for (j = 0; j < shapeLength - 1; j++) {
  22902. indices[index++] = j + offset;
  22903. indices[index++] = j + offset + 1;
  22904. }
  22905. indices[index++] = shapeLength - 1 + offset;
  22906. indices[index++] = offset;
  22907. for (i = 0; i < shapeCount - 1; i++) {
  22908. var firstOffset = shapeLength * i;
  22909. var secondOffset = firstOffset + shapeLength;
  22910. for (j = 0; j < shapeLength; j++) {
  22911. indices[index++] = j + firstOffset;
  22912. indices[index++] = j + secondOffset;
  22913. }
  22914. }
  22915. var geometry = new Geometry({
  22916. attributes : attributes,
  22917. indices : IndexDatatype.createTypedArray(vertexCount, indices),
  22918. boundingSphere : BoundingSphere.fromVertices(positions),
  22919. primitiveType : PrimitiveType.LINES
  22920. });
  22921. return geometry;
  22922. }
  22923. /**
  22924. * A description of a polyline with a volume (a 2D shape extruded along a polyline).
  22925. *
  22926. * @alias PolylineVolumeOutlineGeometry
  22927. * @constructor
  22928. *
  22929. * @param {Object} options Object with the following properties:
  22930. * @param {Cartesian3[]} options.polylinePositions An array of positions that define the center of the polyline volume.
  22931. * @param {Cartesian2[]} options.shapePositions An array of positions that define the shape to be extruded along the polyline
  22932. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  22933. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  22934. * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
  22935. *
  22936. * @see PolylineVolumeOutlineGeometry#createGeometry
  22937. *
  22938. * @example
  22939. * function computeCircle(radius) {
  22940. * var positions = [];
  22941. * for (var i = 0; i < 360; i++) {
  22942. * var radians = Cesium.Math.toRadians(i);
  22943. * positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
  22944. * }
  22945. * return positions;
  22946. * }
  22947. *
  22948. * var volumeOutline = new Cesium.PolylineVolumeOutlineGeometry({
  22949. * polylinePositions : Cesium.Cartesian3.fromDegreesArray([
  22950. * -72.0, 40.0,
  22951. * -70.0, 35.0
  22952. * ]),
  22953. * shapePositions : computeCircle(100000.0)
  22954. * });
  22955. */
  22956. function PolylineVolumeOutlineGeometry(options) {
  22957. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  22958. var positions = options.polylinePositions;
  22959. var shape = options.shapePositions;
  22960. if (!defined(positions)) {
  22961. throw new DeveloperError('options.polylinePositions is required.');
  22962. }
  22963. if (!defined(shape)) {
  22964. throw new DeveloperError('options.shapePositions is required.');
  22965. }
  22966. this._positions = positions;
  22967. this._shape = shape;
  22968. this._ellipsoid = Ellipsoid.clone(defaultValue(options.ellipsoid, Ellipsoid.WGS84));
  22969. this._cornerType = defaultValue(options.cornerType, CornerType.ROUNDED);
  22970. this._granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  22971. this._workerName = 'createPolylineVolumeOutlineGeometry';
  22972. var numComponents = 1 + positions.length * Cartesian3.packedLength;
  22973. numComponents += 1 + shape.length * Cartesian2.packedLength;
  22974. /**
  22975. * The number of elements used to pack the object into an array.
  22976. * @type {Number}
  22977. */
  22978. this.packedLength = numComponents + Ellipsoid.packedLength + 2;
  22979. }
  22980. /**
  22981. * Stores the provided instance into the provided array.
  22982. *
  22983. * @param {PolylineVolumeOutlineGeometry} value The value to pack.
  22984. * @param {Number[]} array The array to pack into.
  22985. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  22986. *
  22987. * @returns {Number[]} The array that was packed into
  22988. */
  22989. PolylineVolumeOutlineGeometry.pack = function(value, array, startingIndex) {
  22990. if (!defined(value)) {
  22991. throw new DeveloperError('value is required');
  22992. }
  22993. if (!defined(array)) {
  22994. throw new DeveloperError('array is required');
  22995. }
  22996. startingIndex = defaultValue(startingIndex, 0);
  22997. var i;
  22998. var positions = value._positions;
  22999. var length = positions.length;
  23000. array[startingIndex++] = length;
  23001. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  23002. Cartesian3.pack(positions[i], array, startingIndex);
  23003. }
  23004. var shape = value._shape;
  23005. length = shape.length;
  23006. array[startingIndex++] = length;
  23007. for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
  23008. Cartesian2.pack(shape[i], array, startingIndex);
  23009. }
  23010. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  23011. startingIndex += Ellipsoid.packedLength;
  23012. array[startingIndex++] = value._cornerType;
  23013. array[startingIndex] = value._granularity;
  23014. return array;
  23015. };
  23016. var scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  23017. var scratchOptions = {
  23018. polylinePositions : undefined,
  23019. shapePositions : undefined,
  23020. ellipsoid : scratchEllipsoid,
  23021. height : undefined,
  23022. cornerType : undefined,
  23023. granularity : undefined
  23024. };
  23025. /**
  23026. * Retrieves an instance from a packed array.
  23027. *
  23028. * @param {Number[]} array The packed array.
  23029. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  23030. * @param {PolylineVolumeOutlineGeometry} [result] The object into which to store the result.
  23031. * @returns {PolylineVolumeOutlineGeometry} The modified result parameter or a new PolylineVolumeOutlineGeometry instance if one was not provided.
  23032. */
  23033. PolylineVolumeOutlineGeometry.unpack = function(array, startingIndex, result) {
  23034. if (!defined(array)) {
  23035. throw new DeveloperError('array is required');
  23036. }
  23037. startingIndex = defaultValue(startingIndex, 0);
  23038. var i;
  23039. var length = array[startingIndex++];
  23040. var positions = new Array(length);
  23041. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  23042. positions[i] = Cartesian3.unpack(array, startingIndex);
  23043. }
  23044. length = array[startingIndex++];
  23045. var shape = new Array(length);
  23046. for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
  23047. shape[i] = Cartesian2.unpack(array, startingIndex);
  23048. }
  23049. var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  23050. startingIndex += Ellipsoid.packedLength;
  23051. var cornerType = array[startingIndex++];
  23052. var granularity = array[startingIndex];
  23053. if (!defined(result)) {
  23054. scratchOptions.polylinePositions = positions;
  23055. scratchOptions.shapePositions = shape;
  23056. scratchOptions.cornerType = cornerType;
  23057. scratchOptions.granularity = granularity;
  23058. return new PolylineVolumeOutlineGeometry(scratchOptions);
  23059. }
  23060. result._positions = positions;
  23061. result._shape = shape;
  23062. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  23063. result._cornerType = cornerType;
  23064. result._granularity = granularity;
  23065. return result;
  23066. };
  23067. var brScratch = new BoundingRectangle();
  23068. /**
  23069. * Computes the geometric representation of the outline of a polyline with a volume, including its vertices, indices, and a bounding sphere.
  23070. *
  23071. * @param {PolylineVolumeOutlineGeometry} polylineVolumeOutlineGeometry A description of the polyline volume outline.
  23072. * @returns {Geometry|undefined} The computed vertices and indices.
  23073. */
  23074. PolylineVolumeOutlineGeometry.createGeometry = function(polylineVolumeOutlineGeometry) {
  23075. var positions = polylineVolumeOutlineGeometry._positions;
  23076. var cleanPositions = arrayRemoveDuplicates(positions, Cartesian3.equalsEpsilon);
  23077. var shape2D = polylineVolumeOutlineGeometry._shape;
  23078. shape2D = PolylineVolumeGeometryLibrary.removeDuplicatesFromShape(shape2D);
  23079. if (cleanPositions.length < 2 || shape2D.length < 3) {
  23080. return undefined;
  23081. }
  23082. if (PolygonPipeline.computeWindingOrder2D(shape2D) === WindingOrder.CLOCKWISE) {
  23083. shape2D.reverse();
  23084. }
  23085. var boundingRectangle = BoundingRectangle.fromPoints(shape2D, brScratch);
  23086. var computedPositions = PolylineVolumeGeometryLibrary.computePositions(cleanPositions, shape2D, boundingRectangle, polylineVolumeOutlineGeometry, false);
  23087. return computeAttributes(computedPositions, shape2D);
  23088. };
  23089. return PolylineVolumeOutlineGeometry;
  23090. });
  23091. /*global define*/
  23092. define('Workers/createPolylineVolumeOutlineGeometry',[
  23093. '../Core/defined',
  23094. '../Core/Ellipsoid',
  23095. '../Core/PolylineVolumeOutlineGeometry'
  23096. ], function(
  23097. defined,
  23098. Ellipsoid,
  23099. PolylineVolumeOutlineGeometry) {
  23100. 'use strict';
  23101. function createPolylineVolumeOutlineGeometry(polylineVolumeOutlineGeometry, offset) {
  23102. if (defined(offset)) {
  23103. polylineVolumeOutlineGeometry = PolylineVolumeOutlineGeometry.unpack(polylineVolumeOutlineGeometry, offset);
  23104. }
  23105. polylineVolumeOutlineGeometry._ellipsoid = Ellipsoid.clone(polylineVolumeOutlineGeometry._ellipsoid);
  23106. return PolylineVolumeOutlineGeometry.createGeometry(polylineVolumeOutlineGeometry);
  23107. }
  23108. return createPolylineVolumeOutlineGeometry;
  23109. });
  23110. }());