createVerticesFromHeightmap.js 930 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959
  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/Intersect',[
  3058. './freezeObject'
  3059. ], function(
  3060. freezeObject) {
  3061. 'use strict';
  3062. /**
  3063. * This enumerated type is used in determining where, relative to the frustum, an
  3064. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3065. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3066. * outside of the frustum's 6 planes (OUTSIDE).
  3067. *
  3068. * @exports Intersect
  3069. */
  3070. var Intersect = {
  3071. /**
  3072. * Represents that an object is not contained within the frustum.
  3073. *
  3074. * @type {Number}
  3075. * @constant
  3076. */
  3077. OUTSIDE : -1,
  3078. /**
  3079. * Represents that an object intersects one of the frustum's planes.
  3080. *
  3081. * @type {Number}
  3082. * @constant
  3083. */
  3084. INTERSECTING : 0,
  3085. /**
  3086. * Represents that an object is fully within the frustum.
  3087. *
  3088. * @type {Number}
  3089. * @constant
  3090. */
  3091. INSIDE : 1
  3092. };
  3093. return freezeObject(Intersect);
  3094. });
  3095. /*global define*/
  3096. define('Core/AxisAlignedBoundingBox',[
  3097. './Cartesian3',
  3098. './defaultValue',
  3099. './defined',
  3100. './DeveloperError',
  3101. './Intersect'
  3102. ], function(
  3103. Cartesian3,
  3104. defaultValue,
  3105. defined,
  3106. DeveloperError,
  3107. Intersect) {
  3108. 'use strict';
  3109. /**
  3110. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  3111. * @alias AxisAlignedBoundingBox
  3112. * @constructor
  3113. *
  3114. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  3115. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  3116. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  3117. *
  3118. * @see BoundingSphere
  3119. * @see BoundingRectangle
  3120. */
  3121. function AxisAlignedBoundingBox(minimum, maximum, center) {
  3122. /**
  3123. * The minimum point defining the bounding box.
  3124. * @type {Cartesian3}
  3125. * @default {@link Cartesian3.ZERO}
  3126. */
  3127. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  3128. /**
  3129. * The maximum point defining the bounding box.
  3130. * @type {Cartesian3}
  3131. * @default {@link Cartesian3.ZERO}
  3132. */
  3133. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  3134. //If center was not defined, compute it.
  3135. if (!defined(center)) {
  3136. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  3137. Cartesian3.multiplyByScalar(center, 0.5, center);
  3138. } else {
  3139. center = Cartesian3.clone(center);
  3140. }
  3141. /**
  3142. * The center point of the bounding box.
  3143. * @type {Cartesian3}
  3144. */
  3145. this.center = center;
  3146. }
  3147. /**
  3148. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  3149. * finding the points spaced the farthest apart on the x, y, and z axes.
  3150. *
  3151. * @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.
  3152. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3153. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  3154. *
  3155. * @example
  3156. * // Compute an axis aligned bounding box enclosing two points.
  3157. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  3158. */
  3159. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  3160. if (!defined(result)) {
  3161. result = new AxisAlignedBoundingBox();
  3162. }
  3163. if (!defined(positions) || positions.length === 0) {
  3164. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  3165. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  3166. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  3167. return result;
  3168. }
  3169. var minimumX = positions[0].x;
  3170. var minimumY = positions[0].y;
  3171. var minimumZ = positions[0].z;
  3172. var maximumX = positions[0].x;
  3173. var maximumY = positions[0].y;
  3174. var maximumZ = positions[0].z;
  3175. var length = positions.length;
  3176. for ( var i = 1; i < length; i++) {
  3177. var p = positions[i];
  3178. var x = p.x;
  3179. var y = p.y;
  3180. var z = p.z;
  3181. minimumX = Math.min(x, minimumX);
  3182. maximumX = Math.max(x, maximumX);
  3183. minimumY = Math.min(y, minimumY);
  3184. maximumY = Math.max(y, maximumY);
  3185. minimumZ = Math.min(z, minimumZ);
  3186. maximumZ = Math.max(z, maximumZ);
  3187. }
  3188. var minimum = result.minimum;
  3189. minimum.x = minimumX;
  3190. minimum.y = minimumY;
  3191. minimum.z = minimumZ;
  3192. var maximum = result.maximum;
  3193. maximum.x = maximumX;
  3194. maximum.y = maximumY;
  3195. maximum.z = maximumZ;
  3196. var center = Cartesian3.add(minimum, maximum, result.center);
  3197. Cartesian3.multiplyByScalar(center, 0.5, center);
  3198. return result;
  3199. };
  3200. /**
  3201. * Duplicates a AxisAlignedBoundingBox instance.
  3202. *
  3203. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  3204. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3205. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  3206. */
  3207. AxisAlignedBoundingBox.clone = function(box, result) {
  3208. if (!defined(box)) {
  3209. return undefined;
  3210. }
  3211. if (!defined(result)) {
  3212. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  3213. }
  3214. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  3215. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  3216. result.center = Cartesian3.clone(box.center, result.center);
  3217. return result;
  3218. };
  3219. /**
  3220. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  3221. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3222. *
  3223. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  3224. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  3225. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3226. */
  3227. AxisAlignedBoundingBox.equals = function(left, right) {
  3228. return (left === right) ||
  3229. ((defined(left)) &&
  3230. (defined(right)) &&
  3231. Cartesian3.equals(left.center, right.center) &&
  3232. Cartesian3.equals(left.minimum, right.minimum) &&
  3233. Cartesian3.equals(left.maximum, right.maximum));
  3234. };
  3235. var intersectScratch = new Cartesian3();
  3236. /**
  3237. * Determines which side of a plane a box is located.
  3238. *
  3239. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  3240. * @param {Plane} plane The plane to test against.
  3241. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  3242. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  3243. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  3244. * intersects the plane.
  3245. */
  3246. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  3247. if (!defined(box)) {
  3248. throw new DeveloperError('box is required.');
  3249. }
  3250. if (!defined(plane)) {
  3251. throw new DeveloperError('plane is required.');
  3252. }
  3253. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  3254. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  3255. var normal = plane.normal;
  3256. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  3257. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  3258. if (s - e > 0) {
  3259. return Intersect.INSIDE;
  3260. }
  3261. if (s + e < 0) {
  3262. //Not in front because normals point inward
  3263. return Intersect.OUTSIDE;
  3264. }
  3265. return Intersect.INTERSECTING;
  3266. };
  3267. /**
  3268. * Duplicates this AxisAlignedBoundingBox instance.
  3269. *
  3270. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  3271. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  3272. */
  3273. AxisAlignedBoundingBox.prototype.clone = function(result) {
  3274. return AxisAlignedBoundingBox.clone(this, result);
  3275. };
  3276. /**
  3277. * Determines which side of a plane this box is located.
  3278. *
  3279. * @param {Plane} plane The plane to test against.
  3280. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  3281. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  3282. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  3283. * intersects the plane.
  3284. */
  3285. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  3286. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  3287. };
  3288. /**
  3289. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  3290. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3291. *
  3292. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  3293. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3294. */
  3295. AxisAlignedBoundingBox.prototype.equals = function(right) {
  3296. return AxisAlignedBoundingBox.equals(this, right);
  3297. };
  3298. return AxisAlignedBoundingBox;
  3299. });
  3300. /*global define*/
  3301. define('Core/GeographicProjection',[
  3302. './Cartesian3',
  3303. './Cartographic',
  3304. './defaultValue',
  3305. './defined',
  3306. './defineProperties',
  3307. './DeveloperError',
  3308. './Ellipsoid'
  3309. ], function(
  3310. Cartesian3,
  3311. Cartographic,
  3312. defaultValue,
  3313. defined,
  3314. defineProperties,
  3315. DeveloperError,
  3316. Ellipsoid) {
  3317. 'use strict';
  3318. /**
  3319. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3320. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3321. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3322. * is also known as EPSG:4326.
  3323. *
  3324. * @alias GeographicProjection
  3325. * @constructor
  3326. *
  3327. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3328. *
  3329. * @see WebMercatorProjection
  3330. */
  3331. function GeographicProjection(ellipsoid) {
  3332. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3333. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3334. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3335. }
  3336. defineProperties(GeographicProjection.prototype, {
  3337. /**
  3338. * Gets the {@link Ellipsoid}.
  3339. *
  3340. * @memberof GeographicProjection.prototype
  3341. *
  3342. * @type {Ellipsoid}
  3343. * @readonly
  3344. */
  3345. ellipsoid : {
  3346. get : function() {
  3347. return this._ellipsoid;
  3348. }
  3349. }
  3350. });
  3351. /**
  3352. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3353. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3354. * ellipsoid. Z is the unmodified height.
  3355. *
  3356. * @param {Cartographic} cartographic The coordinates to project.
  3357. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3358. * undefined, a new instance is created and returned.
  3359. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3360. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3361. * created and returned.
  3362. */
  3363. GeographicProjection.prototype.project = function(cartographic, result) {
  3364. // Actually this is the special case of equidistant cylindrical called the plate carree
  3365. var semimajorAxis = this._semimajorAxis;
  3366. var x = cartographic.longitude * semimajorAxis;
  3367. var y = cartographic.latitude * semimajorAxis;
  3368. var z = cartographic.height;
  3369. if (!defined(result)) {
  3370. return new Cartesian3(x, y, z);
  3371. }
  3372. result.x = x;
  3373. result.y = y;
  3374. result.z = z;
  3375. return result;
  3376. };
  3377. /**
  3378. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3379. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3380. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3381. *
  3382. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3383. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3384. * undefined, a new instance is created and returned.
  3385. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3386. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3387. * created and returned.
  3388. */
  3389. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3390. if (!defined(cartesian)) {
  3391. throw new DeveloperError('cartesian is required');
  3392. }
  3393. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3394. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3395. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3396. var height = cartesian.z;
  3397. if (!defined(result)) {
  3398. return new Cartographic(longitude, latitude, height);
  3399. }
  3400. result.longitude = longitude;
  3401. result.latitude = latitude;
  3402. result.height = height;
  3403. return result;
  3404. };
  3405. return GeographicProjection;
  3406. });
  3407. /*global define*/
  3408. define('Core/Interval',[
  3409. './defaultValue'
  3410. ], function(
  3411. defaultValue) {
  3412. 'use strict';
  3413. /**
  3414. * Represents the closed interval [start, stop].
  3415. * @alias Interval
  3416. * @constructor
  3417. *
  3418. * @param {Number} [start=0.0] The beginning of the interval.
  3419. * @param {Number} [stop=0.0] The end of the interval.
  3420. */
  3421. function Interval(start, stop) {
  3422. /**
  3423. * The beginning of the interval.
  3424. * @type {Number}
  3425. * @default 0.0
  3426. */
  3427. this.start = defaultValue(start, 0.0);
  3428. /**
  3429. * The end of the interval.
  3430. * @type {Number}
  3431. * @default 0.0
  3432. */
  3433. this.stop = defaultValue(stop, 0.0);
  3434. }
  3435. return Interval;
  3436. });
  3437. /*global define*/
  3438. define('Core/Matrix3',[
  3439. './Cartesian3',
  3440. './defaultValue',
  3441. './defined',
  3442. './defineProperties',
  3443. './DeveloperError',
  3444. './freezeObject',
  3445. './Math'
  3446. ], function(
  3447. Cartesian3,
  3448. defaultValue,
  3449. defined,
  3450. defineProperties,
  3451. DeveloperError,
  3452. freezeObject,
  3453. CesiumMath) {
  3454. 'use strict';
  3455. /**
  3456. * A 3x3 matrix, indexable as a column-major order array.
  3457. * Constructor parameters are in row-major order for code readability.
  3458. * @alias Matrix3
  3459. * @constructor
  3460. *
  3461. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  3462. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  3463. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  3464. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  3465. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  3466. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  3467. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  3468. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  3469. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  3470. *
  3471. * @see Matrix3.fromColumnMajorArray
  3472. * @see Matrix3.fromRowMajorArray
  3473. * @see Matrix3.fromQuaternion
  3474. * @see Matrix3.fromScale
  3475. * @see Matrix3.fromUniformScale
  3476. * @see Matrix2
  3477. * @see Matrix4
  3478. */
  3479. function Matrix3(column0Row0, column1Row0, column2Row0,
  3480. column0Row1, column1Row1, column2Row1,
  3481. column0Row2, column1Row2, column2Row2) {
  3482. this[0] = defaultValue(column0Row0, 0.0);
  3483. this[1] = defaultValue(column0Row1, 0.0);
  3484. this[2] = defaultValue(column0Row2, 0.0);
  3485. this[3] = defaultValue(column1Row0, 0.0);
  3486. this[4] = defaultValue(column1Row1, 0.0);
  3487. this[5] = defaultValue(column1Row2, 0.0);
  3488. this[6] = defaultValue(column2Row0, 0.0);
  3489. this[7] = defaultValue(column2Row1, 0.0);
  3490. this[8] = defaultValue(column2Row2, 0.0);
  3491. }
  3492. /**
  3493. * The number of elements used to pack the object into an array.
  3494. * @type {Number}
  3495. */
  3496. Matrix3.packedLength = 9;
  3497. /**
  3498. * Stores the provided instance into the provided array.
  3499. *
  3500. * @param {Matrix3} value The value to pack.
  3501. * @param {Number[]} array The array to pack into.
  3502. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3503. *
  3504. * @returns {Number[]} The array that was packed into
  3505. */
  3506. Matrix3.pack = function(value, array, startingIndex) {
  3507. if (!defined(value)) {
  3508. throw new DeveloperError('value is required');
  3509. }
  3510. if (!defined(array)) {
  3511. throw new DeveloperError('array is required');
  3512. }
  3513. startingIndex = defaultValue(startingIndex, 0);
  3514. array[startingIndex++] = value[0];
  3515. array[startingIndex++] = value[1];
  3516. array[startingIndex++] = value[2];
  3517. array[startingIndex++] = value[3];
  3518. array[startingIndex++] = value[4];
  3519. array[startingIndex++] = value[5];
  3520. array[startingIndex++] = value[6];
  3521. array[startingIndex++] = value[7];
  3522. array[startingIndex++] = value[8];
  3523. return array;
  3524. };
  3525. /**
  3526. * Retrieves an instance from a packed array.
  3527. *
  3528. * @param {Number[]} array The packed array.
  3529. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3530. * @param {Matrix3} [result] The object into which to store the result.
  3531. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3532. */
  3533. Matrix3.unpack = function(array, startingIndex, result) {
  3534. if (!defined(array)) {
  3535. throw new DeveloperError('array is required');
  3536. }
  3537. startingIndex = defaultValue(startingIndex, 0);
  3538. if (!defined(result)) {
  3539. result = new Matrix3();
  3540. }
  3541. result[0] = array[startingIndex++];
  3542. result[1] = array[startingIndex++];
  3543. result[2] = array[startingIndex++];
  3544. result[3] = array[startingIndex++];
  3545. result[4] = array[startingIndex++];
  3546. result[5] = array[startingIndex++];
  3547. result[6] = array[startingIndex++];
  3548. result[7] = array[startingIndex++];
  3549. result[8] = array[startingIndex++];
  3550. return result;
  3551. };
  3552. /**
  3553. * Duplicates a Matrix3 instance.
  3554. *
  3555. * @param {Matrix3} matrix The matrix to duplicate.
  3556. * @param {Matrix3} [result] The object onto which to store the result.
  3557. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  3558. */
  3559. Matrix3.clone = function(values, result) {
  3560. if (!defined(values)) {
  3561. return undefined;
  3562. }
  3563. if (!defined(result)) {
  3564. return new Matrix3(values[0], values[3], values[6],
  3565. values[1], values[4], values[7],
  3566. values[2], values[5], values[8]);
  3567. }
  3568. result[0] = values[0];
  3569. result[1] = values[1];
  3570. result[2] = values[2];
  3571. result[3] = values[3];
  3572. result[4] = values[4];
  3573. result[5] = values[5];
  3574. result[6] = values[6];
  3575. result[7] = values[7];
  3576. result[8] = values[8];
  3577. return result;
  3578. };
  3579. /**
  3580. * Creates a Matrix3 from 9 consecutive elements in an array.
  3581. *
  3582. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  3583. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  3584. * @param {Matrix3} [result] The object onto which to store the result.
  3585. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3586. *
  3587. * @example
  3588. * // Create the Matrix3:
  3589. * // [1.0, 2.0, 3.0]
  3590. * // [1.0, 2.0, 3.0]
  3591. * // [1.0, 2.0, 3.0]
  3592. *
  3593. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3594. * var m = Cesium.Matrix3.fromArray(v);
  3595. *
  3596. * // Create same Matrix3 with using an offset into an array
  3597. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3598. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  3599. */
  3600. Matrix3.fromArray = function(array, startingIndex, result) {
  3601. if (!defined(array)) {
  3602. throw new DeveloperError('array is required');
  3603. }
  3604. startingIndex = defaultValue(startingIndex, 0);
  3605. if (!defined(result)) {
  3606. result = new Matrix3();
  3607. }
  3608. result[0] = array[startingIndex];
  3609. result[1] = array[startingIndex + 1];
  3610. result[2] = array[startingIndex + 2];
  3611. result[3] = array[startingIndex + 3];
  3612. result[4] = array[startingIndex + 4];
  3613. result[5] = array[startingIndex + 5];
  3614. result[6] = array[startingIndex + 6];
  3615. result[7] = array[startingIndex + 7];
  3616. result[8] = array[startingIndex + 8];
  3617. return result;
  3618. };
  3619. /**
  3620. * Creates a Matrix3 instance from a column-major order array.
  3621. *
  3622. * @param {Number[]} values The column-major order array.
  3623. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3624. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3625. */
  3626. Matrix3.fromColumnMajorArray = function(values, result) {
  3627. if (!defined(values)) {
  3628. throw new DeveloperError('values parameter is required');
  3629. }
  3630. return Matrix3.clone(values, result);
  3631. };
  3632. /**
  3633. * Creates a Matrix3 instance from a row-major order array.
  3634. * The resulting matrix will be in column-major order.
  3635. *
  3636. * @param {Number[]} values The row-major order array.
  3637. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3638. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3639. */
  3640. Matrix3.fromRowMajorArray = function(values, result) {
  3641. if (!defined(values)) {
  3642. throw new DeveloperError('values is required.');
  3643. }
  3644. if (!defined(result)) {
  3645. return new Matrix3(values[0], values[1], values[2],
  3646. values[3], values[4], values[5],
  3647. values[6], values[7], values[8]);
  3648. }
  3649. result[0] = values[0];
  3650. result[1] = values[3];
  3651. result[2] = values[6];
  3652. result[3] = values[1];
  3653. result[4] = values[4];
  3654. result[5] = values[7];
  3655. result[6] = values[2];
  3656. result[7] = values[5];
  3657. result[8] = values[8];
  3658. return result;
  3659. };
  3660. /**
  3661. * Computes a 3x3 rotation matrix from the provided quaternion.
  3662. *
  3663. * @param {Quaternion} quaternion the quaternion to use.
  3664. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3665. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  3666. */
  3667. Matrix3.fromQuaternion = function(quaternion, result) {
  3668. if (!defined(quaternion)) {
  3669. throw new DeveloperError('quaternion is required');
  3670. }
  3671. var x2 = quaternion.x * quaternion.x;
  3672. var xy = quaternion.x * quaternion.y;
  3673. var xz = quaternion.x * quaternion.z;
  3674. var xw = quaternion.x * quaternion.w;
  3675. var y2 = quaternion.y * quaternion.y;
  3676. var yz = quaternion.y * quaternion.z;
  3677. var yw = quaternion.y * quaternion.w;
  3678. var z2 = quaternion.z * quaternion.z;
  3679. var zw = quaternion.z * quaternion.w;
  3680. var w2 = quaternion.w * quaternion.w;
  3681. var m00 = x2 - y2 - z2 + w2;
  3682. var m01 = 2.0 * (xy - zw);
  3683. var m02 = 2.0 * (xz + yw);
  3684. var m10 = 2.0 * (xy + zw);
  3685. var m11 = -x2 + y2 - z2 + w2;
  3686. var m12 = 2.0 * (yz - xw);
  3687. var m20 = 2.0 * (xz - yw);
  3688. var m21 = 2.0 * (yz + xw);
  3689. var m22 = -x2 - y2 + z2 + w2;
  3690. if (!defined(result)) {
  3691. return new Matrix3(m00, m01, m02,
  3692. m10, m11, m12,
  3693. m20, m21, m22);
  3694. }
  3695. result[0] = m00;
  3696. result[1] = m10;
  3697. result[2] = m20;
  3698. result[3] = m01;
  3699. result[4] = m11;
  3700. result[5] = m21;
  3701. result[6] = m02;
  3702. result[7] = m12;
  3703. result[8] = m22;
  3704. return result;
  3705. };
  3706. /**
  3707. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  3708. *
  3709. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  3710. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3711. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  3712. */
  3713. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  3714. if (!defined(headingPitchRoll)) {
  3715. throw new DeveloperError('headingPitchRoll is required');
  3716. }
  3717. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  3718. var cosPsi = Math.cos(-headingPitchRoll.heading);
  3719. var cosPhi = Math.cos(headingPitchRoll.roll);
  3720. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  3721. var sinPsi = Math.sin(-headingPitchRoll.heading);
  3722. var sinPhi = Math.sin(headingPitchRoll.roll);
  3723. var m00 = cosTheta * cosPsi;
  3724. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  3725. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  3726. var m10 = cosTheta * sinPsi;
  3727. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  3728. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  3729. var m20 = -sinTheta;
  3730. var m21 = sinPhi * cosTheta;
  3731. var m22 = cosPhi * cosTheta;
  3732. if (!defined(result)) {
  3733. return new Matrix3(m00, m01, m02,
  3734. m10, m11, m12,
  3735. m20, m21, m22);
  3736. }
  3737. result[0] = m00;
  3738. result[1] = m10;
  3739. result[2] = m20;
  3740. result[3] = m01;
  3741. result[4] = m11;
  3742. result[5] = m21;
  3743. result[6] = m02;
  3744. result[7] = m12;
  3745. result[8] = m22;
  3746. return result;
  3747. };
  3748. /**
  3749. * Computes a Matrix3 instance representing a non-uniform scale.
  3750. *
  3751. * @param {Cartesian3} scale The x, y, and z scale factors.
  3752. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3753. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3754. *
  3755. * @example
  3756. * // Creates
  3757. * // [7.0, 0.0, 0.0]
  3758. * // [0.0, 8.0, 0.0]
  3759. * // [0.0, 0.0, 9.0]
  3760. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3761. */
  3762. Matrix3.fromScale = function(scale, result) {
  3763. if (!defined(scale)) {
  3764. throw new DeveloperError('scale is required.');
  3765. }
  3766. if (!defined(result)) {
  3767. return new Matrix3(
  3768. scale.x, 0.0, 0.0,
  3769. 0.0, scale.y, 0.0,
  3770. 0.0, 0.0, scale.z);
  3771. }
  3772. result[0] = scale.x;
  3773. result[1] = 0.0;
  3774. result[2] = 0.0;
  3775. result[3] = 0.0;
  3776. result[4] = scale.y;
  3777. result[5] = 0.0;
  3778. result[6] = 0.0;
  3779. result[7] = 0.0;
  3780. result[8] = scale.z;
  3781. return result;
  3782. };
  3783. /**
  3784. * Computes a Matrix3 instance representing a uniform scale.
  3785. *
  3786. * @param {Number} scale The uniform scale factor.
  3787. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3788. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3789. *
  3790. * @example
  3791. * // Creates
  3792. * // [2.0, 0.0, 0.0]
  3793. * // [0.0, 2.0, 0.0]
  3794. * // [0.0, 0.0, 2.0]
  3795. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  3796. */
  3797. Matrix3.fromUniformScale = function(scale, result) {
  3798. if (typeof scale !== 'number') {
  3799. throw new DeveloperError('scale is required.');
  3800. }
  3801. if (!defined(result)) {
  3802. return new Matrix3(
  3803. scale, 0.0, 0.0,
  3804. 0.0, scale, 0.0,
  3805. 0.0, 0.0, scale);
  3806. }
  3807. result[0] = scale;
  3808. result[1] = 0.0;
  3809. result[2] = 0.0;
  3810. result[3] = 0.0;
  3811. result[4] = scale;
  3812. result[5] = 0.0;
  3813. result[6] = 0.0;
  3814. result[7] = 0.0;
  3815. result[8] = scale;
  3816. return result;
  3817. };
  3818. /**
  3819. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  3820. *
  3821. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  3822. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3823. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3824. *
  3825. * @example
  3826. * // Creates
  3827. * // [0.0, -9.0, 8.0]
  3828. * // [9.0, 0.0, -7.0]
  3829. * // [-8.0, 7.0, 0.0]
  3830. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3831. */
  3832. Matrix3.fromCrossProduct = function(vector, result) {
  3833. if (!defined(vector)) {
  3834. throw new DeveloperError('vector is required.');
  3835. }
  3836. if (!defined(result)) {
  3837. return new Matrix3(
  3838. 0.0, -vector.z, vector.y,
  3839. vector.z, 0.0, -vector.x,
  3840. -vector.y, vector.x, 0.0);
  3841. }
  3842. result[0] = 0.0;
  3843. result[1] = vector.z;
  3844. result[2] = -vector.y;
  3845. result[3] = -vector.z;
  3846. result[4] = 0.0;
  3847. result[5] = vector.x;
  3848. result[6] = vector.y;
  3849. result[7] = -vector.x;
  3850. result[8] = 0.0;
  3851. return result;
  3852. };
  3853. /**
  3854. * Creates a rotation matrix around the x-axis.
  3855. *
  3856. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3857. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3858. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3859. *
  3860. * @example
  3861. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  3862. * var p = new Cesium.Cartesian3(5, 6, 7);
  3863. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  3864. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3865. */
  3866. Matrix3.fromRotationX = function(angle, result) {
  3867. if (!defined(angle)) {
  3868. throw new DeveloperError('angle is required.');
  3869. }
  3870. var cosAngle = Math.cos(angle);
  3871. var sinAngle = Math.sin(angle);
  3872. if (!defined(result)) {
  3873. return new Matrix3(
  3874. 1.0, 0.0, 0.0,
  3875. 0.0, cosAngle, -sinAngle,
  3876. 0.0, sinAngle, cosAngle);
  3877. }
  3878. result[0] = 1.0;
  3879. result[1] = 0.0;
  3880. result[2] = 0.0;
  3881. result[3] = 0.0;
  3882. result[4] = cosAngle;
  3883. result[5] = sinAngle;
  3884. result[6] = 0.0;
  3885. result[7] = -sinAngle;
  3886. result[8] = cosAngle;
  3887. return result;
  3888. };
  3889. /**
  3890. * Creates a rotation matrix around the y-axis.
  3891. *
  3892. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3893. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3894. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3895. *
  3896. * @example
  3897. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  3898. * var p = new Cesium.Cartesian3(5, 6, 7);
  3899. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  3900. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3901. */
  3902. Matrix3.fromRotationY = function(angle, result) {
  3903. if (!defined(angle)) {
  3904. throw new DeveloperError('angle is required.');
  3905. }
  3906. var cosAngle = Math.cos(angle);
  3907. var sinAngle = Math.sin(angle);
  3908. if (!defined(result)) {
  3909. return new Matrix3(
  3910. cosAngle, 0.0, sinAngle,
  3911. 0.0, 1.0, 0.0,
  3912. -sinAngle, 0.0, cosAngle);
  3913. }
  3914. result[0] = cosAngle;
  3915. result[1] = 0.0;
  3916. result[2] = -sinAngle;
  3917. result[3] = 0.0;
  3918. result[4] = 1.0;
  3919. result[5] = 0.0;
  3920. result[6] = sinAngle;
  3921. result[7] = 0.0;
  3922. result[8] = cosAngle;
  3923. return result;
  3924. };
  3925. /**
  3926. * Creates a rotation matrix around the z-axis.
  3927. *
  3928. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3929. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3930. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3931. *
  3932. * @example
  3933. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  3934. * var p = new Cesium.Cartesian3(5, 6, 7);
  3935. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  3936. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3937. */
  3938. Matrix3.fromRotationZ = function(angle, result) {
  3939. if (!defined(angle)) {
  3940. throw new DeveloperError('angle is required.');
  3941. }
  3942. var cosAngle = Math.cos(angle);
  3943. var sinAngle = Math.sin(angle);
  3944. if (!defined(result)) {
  3945. return new Matrix3(
  3946. cosAngle, -sinAngle, 0.0,
  3947. sinAngle, cosAngle, 0.0,
  3948. 0.0, 0.0, 1.0);
  3949. }
  3950. result[0] = cosAngle;
  3951. result[1] = sinAngle;
  3952. result[2] = 0.0;
  3953. result[3] = -sinAngle;
  3954. result[4] = cosAngle;
  3955. result[5] = 0.0;
  3956. result[6] = 0.0;
  3957. result[7] = 0.0;
  3958. result[8] = 1.0;
  3959. return result;
  3960. };
  3961. /**
  3962. * Creates an Array from the provided Matrix3 instance.
  3963. * The array will be in column-major order.
  3964. *
  3965. * @param {Matrix3} matrix The matrix to use..
  3966. * @param {Number[]} [result] The Array onto which to store the result.
  3967. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  3968. */
  3969. Matrix3.toArray = function(matrix, result) {
  3970. if (!defined(matrix)) {
  3971. throw new DeveloperError('matrix is required');
  3972. }
  3973. if (!defined(result)) {
  3974. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  3975. }
  3976. result[0] = matrix[0];
  3977. result[1] = matrix[1];
  3978. result[2] = matrix[2];
  3979. result[3] = matrix[3];
  3980. result[4] = matrix[4];
  3981. result[5] = matrix[5];
  3982. result[6] = matrix[6];
  3983. result[7] = matrix[7];
  3984. result[8] = matrix[8];
  3985. return result;
  3986. };
  3987. /**
  3988. * Computes the array index of the element at the provided row and column.
  3989. *
  3990. * @param {Number} row The zero-based index of the row.
  3991. * @param {Number} column The zero-based index of the column.
  3992. * @returns {Number} The index of the element at the provided row and column.
  3993. *
  3994. * @exception {DeveloperError} row must be 0, 1, or 2.
  3995. * @exception {DeveloperError} column must be 0, 1, or 2.
  3996. *
  3997. * @example
  3998. * var myMatrix = new Cesium.Matrix3();
  3999. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  4000. * var column1Row0 = myMatrix[column1Row0Index]
  4001. * myMatrix[column1Row0Index] = 10.0;
  4002. */
  4003. Matrix3.getElementIndex = function(column, row) {
  4004. if (typeof row !== 'number' || row < 0 || row > 2) {
  4005. throw new DeveloperError('row must be 0, 1, or 2.');
  4006. }
  4007. if (typeof column !== 'number' || column < 0 || column > 2) {
  4008. throw new DeveloperError('column must be 0, 1, or 2.');
  4009. }
  4010. return column * 3 + row;
  4011. };
  4012. /**
  4013. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  4014. *
  4015. * @param {Matrix3} matrix The matrix to use.
  4016. * @param {Number} index The zero-based index of the column to retrieve.
  4017. * @param {Cartesian3} result The object onto which to store the result.
  4018. * @returns {Cartesian3} The modified result parameter.
  4019. *
  4020. * @exception {DeveloperError} index must be 0, 1, or 2.
  4021. */
  4022. Matrix3.getColumn = function(matrix, index, result) {
  4023. if (!defined(matrix)) {
  4024. throw new DeveloperError('matrix is required.');
  4025. }
  4026. if (typeof index !== 'number' || index < 0 || index > 2) {
  4027. throw new DeveloperError('index must be 0, 1, or 2.');
  4028. }
  4029. if (!defined(result)) {
  4030. throw new DeveloperError('result is required');
  4031. }
  4032. var startIndex = index * 3;
  4033. var x = matrix[startIndex];
  4034. var y = matrix[startIndex + 1];
  4035. var z = matrix[startIndex + 2];
  4036. result.x = x;
  4037. result.y = y;
  4038. result.z = z;
  4039. return result;
  4040. };
  4041. /**
  4042. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  4043. *
  4044. * @param {Matrix3} matrix The matrix to use.
  4045. * @param {Number} index The zero-based index of the column to set.
  4046. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  4047. * @param {Matrix3} result The object onto which to store the result.
  4048. * @returns {Matrix3} The modified result parameter.
  4049. *
  4050. * @exception {DeveloperError} index must be 0, 1, or 2.
  4051. */
  4052. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  4053. if (!defined(matrix)) {
  4054. throw new DeveloperError('matrix is required');
  4055. }
  4056. if (!defined(cartesian)) {
  4057. throw new DeveloperError('cartesian is required');
  4058. }
  4059. if (typeof index !== 'number' || index < 0 || index > 2) {
  4060. throw new DeveloperError('index must be 0, 1, or 2.');
  4061. }
  4062. if (!defined(result)) {
  4063. throw new DeveloperError('result is required');
  4064. }
  4065. result = Matrix3.clone(matrix, result);
  4066. var startIndex = index * 3;
  4067. result[startIndex] = cartesian.x;
  4068. result[startIndex + 1] = cartesian.y;
  4069. result[startIndex + 2] = cartesian.z;
  4070. return result;
  4071. };
  4072. /**
  4073. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  4074. *
  4075. * @param {Matrix3} matrix The matrix to use.
  4076. * @param {Number} index The zero-based index of the row to retrieve.
  4077. * @param {Cartesian3} result The object onto which to store the result.
  4078. * @returns {Cartesian3} The modified result parameter.
  4079. *
  4080. * @exception {DeveloperError} index must be 0, 1, or 2.
  4081. */
  4082. Matrix3.getRow = function(matrix, index, result) {
  4083. if (!defined(matrix)) {
  4084. throw new DeveloperError('matrix is required.');
  4085. }
  4086. if (typeof index !== 'number' || index < 0 || index > 2) {
  4087. throw new DeveloperError('index must be 0, 1, or 2.');
  4088. }
  4089. if (!defined(result)) {
  4090. throw new DeveloperError('result is required');
  4091. }
  4092. var x = matrix[index];
  4093. var y = matrix[index + 3];
  4094. var z = matrix[index + 6];
  4095. result.x = x;
  4096. result.y = y;
  4097. result.z = z;
  4098. return result;
  4099. };
  4100. /**
  4101. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  4102. *
  4103. * @param {Matrix3} matrix The matrix to use.
  4104. * @param {Number} index The zero-based index of the row to set.
  4105. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  4106. * @param {Matrix3} result The object onto which to store the result.
  4107. * @returns {Matrix3} The modified result parameter.
  4108. *
  4109. * @exception {DeveloperError} index must be 0, 1, or 2.
  4110. */
  4111. Matrix3.setRow = function(matrix, index, cartesian, result) {
  4112. if (!defined(matrix)) {
  4113. throw new DeveloperError('matrix is required');
  4114. }
  4115. if (!defined(cartesian)) {
  4116. throw new DeveloperError('cartesian is required');
  4117. }
  4118. if (typeof index !== 'number' || index < 0 || index > 2) {
  4119. throw new DeveloperError('index must be 0, 1, or 2.');
  4120. }
  4121. if (!defined(result)) {
  4122. throw new DeveloperError('result is required');
  4123. }
  4124. result = Matrix3.clone(matrix, result);
  4125. result[index] = cartesian.x;
  4126. result[index + 3] = cartesian.y;
  4127. result[index + 6] = cartesian.z;
  4128. return result;
  4129. };
  4130. var scratchColumn = new Cartesian3();
  4131. /**
  4132. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  4133. *
  4134. * @param {Matrix3} matrix The matrix.
  4135. * @param {Cartesian3} result The object onto which to store the result.
  4136. * @returns {Cartesian3} The modified result parameter.
  4137. */
  4138. Matrix3.getScale = function(matrix, result) {
  4139. if (!defined(matrix)) {
  4140. throw new DeveloperError('matrix is required.');
  4141. }
  4142. if (!defined(result)) {
  4143. throw new DeveloperError('result is required');
  4144. }
  4145. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  4146. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  4147. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  4148. return result;
  4149. };
  4150. var scratchScale = new Cartesian3();
  4151. /**
  4152. * Computes the maximum scale assuming the matrix is an affine transformation.
  4153. * The maximum scale is the maximum length of the column vectors.
  4154. *
  4155. * @param {Matrix3} matrix The matrix.
  4156. * @returns {Number} The maximum scale.
  4157. */
  4158. Matrix3.getMaximumScale = function(matrix) {
  4159. Matrix3.getScale(matrix, scratchScale);
  4160. return Cartesian3.maximumComponent(scratchScale);
  4161. };
  4162. /**
  4163. * Computes the product of two matrices.
  4164. *
  4165. * @param {Matrix3} left The first matrix.
  4166. * @param {Matrix3} right The second matrix.
  4167. * @param {Matrix3} result The object onto which to store the result.
  4168. * @returns {Matrix3} The modified result parameter.
  4169. */
  4170. Matrix3.multiply = function(left, right, result) {
  4171. if (!defined(left)) {
  4172. throw new DeveloperError('left is required');
  4173. }
  4174. if (!defined(right)) {
  4175. throw new DeveloperError('right is required');
  4176. }
  4177. if (!defined(result)) {
  4178. throw new DeveloperError('result is required');
  4179. }
  4180. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  4181. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  4182. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  4183. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  4184. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  4185. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  4186. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  4187. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  4188. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  4189. result[0] = column0Row0;
  4190. result[1] = column0Row1;
  4191. result[2] = column0Row2;
  4192. result[3] = column1Row0;
  4193. result[4] = column1Row1;
  4194. result[5] = column1Row2;
  4195. result[6] = column2Row0;
  4196. result[7] = column2Row1;
  4197. result[8] = column2Row2;
  4198. return result;
  4199. };
  4200. /**
  4201. * Computes the sum of two matrices.
  4202. *
  4203. * @param {Matrix3} left The first matrix.
  4204. * @param {Matrix3} right The second matrix.
  4205. * @param {Matrix3} result The object onto which to store the result.
  4206. * @returns {Matrix3} The modified result parameter.
  4207. */
  4208. Matrix3.add = function(left, right, result) {
  4209. if (!defined(left)) {
  4210. throw new DeveloperError('left is required');
  4211. }
  4212. if (!defined(right)) {
  4213. throw new DeveloperError('right is required');
  4214. }
  4215. if (!defined(result)) {
  4216. throw new DeveloperError('result is required');
  4217. }
  4218. result[0] = left[0] + right[0];
  4219. result[1] = left[1] + right[1];
  4220. result[2] = left[2] + right[2];
  4221. result[3] = left[3] + right[3];
  4222. result[4] = left[4] + right[4];
  4223. result[5] = left[5] + right[5];
  4224. result[6] = left[6] + right[6];
  4225. result[7] = left[7] + right[7];
  4226. result[8] = left[8] + right[8];
  4227. return result;
  4228. };
  4229. /**
  4230. * Computes the difference of two matrices.
  4231. *
  4232. * @param {Matrix3} left The first matrix.
  4233. * @param {Matrix3} right The second matrix.
  4234. * @param {Matrix3} result The object onto which to store the result.
  4235. * @returns {Matrix3} The modified result parameter.
  4236. */
  4237. Matrix3.subtract = function(left, right, result) {
  4238. if (!defined(left)) {
  4239. throw new DeveloperError('left is required');
  4240. }
  4241. if (!defined(right)) {
  4242. throw new DeveloperError('right is required');
  4243. }
  4244. if (!defined(result)) {
  4245. throw new DeveloperError('result is required');
  4246. }
  4247. result[0] = left[0] - right[0];
  4248. result[1] = left[1] - right[1];
  4249. result[2] = left[2] - right[2];
  4250. result[3] = left[3] - right[3];
  4251. result[4] = left[4] - right[4];
  4252. result[5] = left[5] - right[5];
  4253. result[6] = left[6] - right[6];
  4254. result[7] = left[7] - right[7];
  4255. result[8] = left[8] - right[8];
  4256. return result;
  4257. };
  4258. /**
  4259. * Computes the product of a matrix and a column vector.
  4260. *
  4261. * @param {Matrix3} matrix The matrix.
  4262. * @param {Cartesian3} cartesian The column.
  4263. * @param {Cartesian3} result The object onto which to store the result.
  4264. * @returns {Cartesian3} The modified result parameter.
  4265. */
  4266. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  4267. if (!defined(matrix)) {
  4268. throw new DeveloperError('matrix is required');
  4269. }
  4270. if (!defined(cartesian)) {
  4271. throw new DeveloperError('cartesian is required');
  4272. }
  4273. if (!defined(result)) {
  4274. throw new DeveloperError('result is required');
  4275. }
  4276. var vX = cartesian.x;
  4277. var vY = cartesian.y;
  4278. var vZ = cartesian.z;
  4279. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  4280. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  4281. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  4282. result.x = x;
  4283. result.y = y;
  4284. result.z = z;
  4285. return result;
  4286. };
  4287. /**
  4288. * Computes the product of a matrix and a scalar.
  4289. *
  4290. * @param {Matrix3} matrix The matrix.
  4291. * @param {Number} scalar The number to multiply by.
  4292. * @param {Matrix3} result The object onto which to store the result.
  4293. * @returns {Matrix3} The modified result parameter.
  4294. */
  4295. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  4296. if (!defined(matrix)) {
  4297. throw new DeveloperError('matrix is required');
  4298. }
  4299. if (typeof scalar !== 'number') {
  4300. throw new DeveloperError('scalar must be a number');
  4301. }
  4302. if (!defined(result)) {
  4303. throw new DeveloperError('result is required');
  4304. }
  4305. result[0] = matrix[0] * scalar;
  4306. result[1] = matrix[1] * scalar;
  4307. result[2] = matrix[2] * scalar;
  4308. result[3] = matrix[3] * scalar;
  4309. result[4] = matrix[4] * scalar;
  4310. result[5] = matrix[5] * scalar;
  4311. result[6] = matrix[6] * scalar;
  4312. result[7] = matrix[7] * scalar;
  4313. result[8] = matrix[8] * scalar;
  4314. return result;
  4315. };
  4316. /**
  4317. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  4318. *
  4319. * @param {Matrix3} matrix The matrix on the left-hand side.
  4320. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  4321. * @param {Matrix3} result The object onto which to store the result.
  4322. * @returns {Matrix3} The modified result parameter.
  4323. *
  4324. *
  4325. * @example
  4326. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  4327. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  4328. *
  4329. * @see Matrix3.fromScale
  4330. * @see Matrix3.multiplyByUniformScale
  4331. */
  4332. Matrix3.multiplyByScale = function(matrix, scale, result) {
  4333. if (!defined(matrix)) {
  4334. throw new DeveloperError('matrix is required');
  4335. }
  4336. if (!defined(scale)) {
  4337. throw new DeveloperError('scale is required');
  4338. }
  4339. if (!defined(result)) {
  4340. throw new DeveloperError('result is required');
  4341. }
  4342. result[0] = matrix[0] * scale.x;
  4343. result[1] = matrix[1] * scale.x;
  4344. result[2] = matrix[2] * scale.x;
  4345. result[3] = matrix[3] * scale.y;
  4346. result[4] = matrix[4] * scale.y;
  4347. result[5] = matrix[5] * scale.y;
  4348. result[6] = matrix[6] * scale.z;
  4349. result[7] = matrix[7] * scale.z;
  4350. result[8] = matrix[8] * scale.z;
  4351. return result;
  4352. };
  4353. /**
  4354. * Creates a negated copy of the provided matrix.
  4355. *
  4356. * @param {Matrix3} matrix The matrix to negate.
  4357. * @param {Matrix3} result The object onto which to store the result.
  4358. * @returns {Matrix3} The modified result parameter.
  4359. */
  4360. Matrix3.negate = function(matrix, result) {
  4361. if (!defined(matrix)) {
  4362. throw new DeveloperError('matrix is required');
  4363. }
  4364. if (!defined(result)) {
  4365. throw new DeveloperError('result is required');
  4366. }
  4367. result[0] = -matrix[0];
  4368. result[1] = -matrix[1];
  4369. result[2] = -matrix[2];
  4370. result[3] = -matrix[3];
  4371. result[4] = -matrix[4];
  4372. result[5] = -matrix[5];
  4373. result[6] = -matrix[6];
  4374. result[7] = -matrix[7];
  4375. result[8] = -matrix[8];
  4376. return result;
  4377. };
  4378. /**
  4379. * Computes the transpose of the provided matrix.
  4380. *
  4381. * @param {Matrix3} matrix The matrix to transpose.
  4382. * @param {Matrix3} result The object onto which to store the result.
  4383. * @returns {Matrix3} The modified result parameter.
  4384. */
  4385. Matrix3.transpose = function(matrix, result) {
  4386. if (!defined(matrix)) {
  4387. throw new DeveloperError('matrix is required');
  4388. }
  4389. if (!defined(result)) {
  4390. throw new DeveloperError('result is required');
  4391. }
  4392. var column0Row0 = matrix[0];
  4393. var column0Row1 = matrix[3];
  4394. var column0Row2 = matrix[6];
  4395. var column1Row0 = matrix[1];
  4396. var column1Row1 = matrix[4];
  4397. var column1Row2 = matrix[7];
  4398. var column2Row0 = matrix[2];
  4399. var column2Row1 = matrix[5];
  4400. var column2Row2 = matrix[8];
  4401. result[0] = column0Row0;
  4402. result[1] = column0Row1;
  4403. result[2] = column0Row2;
  4404. result[3] = column1Row0;
  4405. result[4] = column1Row1;
  4406. result[5] = column1Row2;
  4407. result[6] = column2Row0;
  4408. result[7] = column2Row1;
  4409. result[8] = column2Row2;
  4410. return result;
  4411. };
  4412. function computeFrobeniusNorm(matrix) {
  4413. var norm = 0.0;
  4414. for (var i = 0; i < 9; ++i) {
  4415. var temp = matrix[i];
  4416. norm += temp * temp;
  4417. }
  4418. return Math.sqrt(norm);
  4419. }
  4420. var rowVal = [1, 0, 0];
  4421. var colVal = [2, 2, 1];
  4422. function offDiagonalFrobeniusNorm(matrix) {
  4423. // Computes the "off-diagonal" Frobenius norm.
  4424. // Assumes matrix is symmetric.
  4425. var norm = 0.0;
  4426. for (var i = 0; i < 3; ++i) {
  4427. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  4428. norm += 2.0 * temp * temp;
  4429. }
  4430. return Math.sqrt(norm);
  4431. }
  4432. function shurDecomposition(matrix, result) {
  4433. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4434. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  4435. //
  4436. // The routine takes a matrix, which is assumed to be symmetric, and
  4437. // finds the largest off-diagonal term, and then creates
  4438. // a matrix (result) which can be used to help reduce it
  4439. var tolerance = CesiumMath.EPSILON15;
  4440. var maxDiagonal = 0.0;
  4441. var rotAxis = 1;
  4442. // find pivot (rotAxis) based on max diagonal of matrix
  4443. for (var i = 0; i < 3; ++i) {
  4444. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  4445. if (temp > maxDiagonal) {
  4446. rotAxis = i;
  4447. maxDiagonal = temp;
  4448. }
  4449. }
  4450. var c = 1.0;
  4451. var s = 0.0;
  4452. var p = rowVal[rotAxis];
  4453. var q = colVal[rotAxis];
  4454. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  4455. var qq = matrix[Matrix3.getElementIndex(q, q)];
  4456. var pp = matrix[Matrix3.getElementIndex(p, p)];
  4457. var qp = matrix[Matrix3.getElementIndex(q, p)];
  4458. var tau = (qq - pp) / 2.0 / qp;
  4459. var t;
  4460. if (tau < 0.0) {
  4461. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  4462. } else {
  4463. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  4464. }
  4465. c = 1.0 / Math.sqrt(1.0 + t * t);
  4466. s = t * c;
  4467. }
  4468. result = Matrix3.clone(Matrix3.IDENTITY, result);
  4469. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  4470. result[Matrix3.getElementIndex(q, p)] = s;
  4471. result[Matrix3.getElementIndex(p, q)] = -s;
  4472. return result;
  4473. }
  4474. var jMatrix = new Matrix3();
  4475. var jMatrixTranspose = new Matrix3();
  4476. /**
  4477. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  4478. * <p>
  4479. * Returns a diagonal matrix and unitary matrix such that:
  4480. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  4481. * </p>
  4482. * <p>
  4483. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  4484. * of the unitary matrix are the corresponding eigenvectors.
  4485. * </p>
  4486. *
  4487. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  4488. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  4489. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  4490. *
  4491. * @example
  4492. * var a = //... symetric matrix
  4493. * var result = {
  4494. * unitary : new Cesium.Matrix3(),
  4495. * diagonal : new Cesium.Matrix3()
  4496. * };
  4497. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  4498. *
  4499. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  4500. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  4501. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  4502. *
  4503. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  4504. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  4505. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  4506. */
  4507. Matrix3.computeEigenDecomposition = function(matrix, result) {
  4508. if (!defined(matrix)) {
  4509. throw new DeveloperError('matrix is required.');
  4510. }
  4511. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4512. // section 8.4.3 The Classical Jacobi Algorithm
  4513. var tolerance = CesiumMath.EPSILON20;
  4514. var maxSweeps = 10;
  4515. var count = 0;
  4516. var sweep = 0;
  4517. if (!defined(result)) {
  4518. result = {};
  4519. }
  4520. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  4521. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  4522. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  4523. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  4524. shurDecomposition(diagMatrix, jMatrix);
  4525. Matrix3.transpose(jMatrix, jMatrixTranspose);
  4526. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  4527. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  4528. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  4529. if (++count > 2) {
  4530. ++sweep;
  4531. count = 0;
  4532. }
  4533. }
  4534. return result;
  4535. };
  4536. /**
  4537. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  4538. *
  4539. * @param {Matrix3} matrix The matrix with signed elements.
  4540. * @param {Matrix3} result The object onto which to store the result.
  4541. * @returns {Matrix3} The modified result parameter.
  4542. */
  4543. Matrix3.abs = function(matrix, result) {
  4544. if (!defined(matrix)) {
  4545. throw new DeveloperError('matrix is required');
  4546. }
  4547. if (!defined(result)) {
  4548. throw new DeveloperError('result is required');
  4549. }
  4550. result[0] = Math.abs(matrix[0]);
  4551. result[1] = Math.abs(matrix[1]);
  4552. result[2] = Math.abs(matrix[2]);
  4553. result[3] = Math.abs(matrix[3]);
  4554. result[4] = Math.abs(matrix[4]);
  4555. result[5] = Math.abs(matrix[5]);
  4556. result[6] = Math.abs(matrix[6]);
  4557. result[7] = Math.abs(matrix[7]);
  4558. result[8] = Math.abs(matrix[8]);
  4559. return result;
  4560. };
  4561. /**
  4562. * Computes the determinant of the provided matrix.
  4563. *
  4564. * @param {Matrix3} matrix The matrix to use.
  4565. * @returns {Number} The value of the determinant of the matrix.
  4566. */
  4567. Matrix3.determinant = function(matrix) {
  4568. if (!defined(matrix)) {
  4569. throw new DeveloperError('matrix is required');
  4570. }
  4571. var m11 = matrix[0];
  4572. var m21 = matrix[3];
  4573. var m31 = matrix[6];
  4574. var m12 = matrix[1];
  4575. var m22 = matrix[4];
  4576. var m32 = matrix[7];
  4577. var m13 = matrix[2];
  4578. var m23 = matrix[5];
  4579. var m33 = matrix[8];
  4580. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  4581. };
  4582. /**
  4583. * Computes the inverse of the provided matrix.
  4584. *
  4585. * @param {Matrix3} matrix The matrix to invert.
  4586. * @param {Matrix3} result The object onto which to store the result.
  4587. * @returns {Matrix3} The modified result parameter.
  4588. *
  4589. * @exception {DeveloperError} matrix is not invertible.
  4590. */
  4591. Matrix3.inverse = function(matrix, result) {
  4592. if (!defined(matrix)) {
  4593. throw new DeveloperError('matrix is required');
  4594. }
  4595. if (!defined(result)) {
  4596. throw new DeveloperError('result is required');
  4597. }
  4598. var m11 = matrix[0];
  4599. var m21 = matrix[1];
  4600. var m31 = matrix[2];
  4601. var m12 = matrix[3];
  4602. var m22 = matrix[4];
  4603. var m32 = matrix[5];
  4604. var m13 = matrix[6];
  4605. var m23 = matrix[7];
  4606. var m33 = matrix[8];
  4607. var determinant = Matrix3.determinant(matrix);
  4608. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  4609. throw new DeveloperError('matrix is not invertible');
  4610. }
  4611. result[0] = m22 * m33 - m23 * m32;
  4612. result[1] = m23 * m31 - m21 * m33;
  4613. result[2] = m21 * m32 - m22 * m31;
  4614. result[3] = m13 * m32 - m12 * m33;
  4615. result[4] = m11 * m33 - m13 * m31;
  4616. result[5] = m12 * m31 - m11 * m32;
  4617. result[6] = m12 * m23 - m13 * m22;
  4618. result[7] = m13 * m21 - m11 * m23;
  4619. result[8] = m11 * m22 - m12 * m21;
  4620. var scale = 1.0 / determinant;
  4621. return Matrix3.multiplyByScalar(result, scale, result);
  4622. };
  4623. /**
  4624. * Compares the provided matrices componentwise and returns
  4625. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4626. *
  4627. * @param {Matrix3} [left] The first matrix.
  4628. * @param {Matrix3} [right] The second matrix.
  4629. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4630. */
  4631. Matrix3.equals = function(left, right) {
  4632. return (left === right) ||
  4633. (defined(left) &&
  4634. defined(right) &&
  4635. left[0] === right[0] &&
  4636. left[1] === right[1] &&
  4637. left[2] === right[2] &&
  4638. left[3] === right[3] &&
  4639. left[4] === right[4] &&
  4640. left[5] === right[5] &&
  4641. left[6] === right[6] &&
  4642. left[7] === right[7] &&
  4643. left[8] === right[8]);
  4644. };
  4645. /**
  4646. * Compares the provided matrices componentwise and returns
  4647. * <code>true</code> if they are within the provided epsilon,
  4648. * <code>false</code> otherwise.
  4649. *
  4650. * @param {Matrix3} [left] The first matrix.
  4651. * @param {Matrix3} [right] The second matrix.
  4652. * @param {Number} epsilon The epsilon to use for equality testing.
  4653. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  4654. */
  4655. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  4656. if (typeof epsilon !== 'number') {
  4657. throw new DeveloperError('epsilon must be a number');
  4658. }
  4659. return (left === right) ||
  4660. (defined(left) &&
  4661. defined(right) &&
  4662. Math.abs(left[0] - right[0]) <= epsilon &&
  4663. Math.abs(left[1] - right[1]) <= epsilon &&
  4664. Math.abs(left[2] - right[2]) <= epsilon &&
  4665. Math.abs(left[3] - right[3]) <= epsilon &&
  4666. Math.abs(left[4] - right[4]) <= epsilon &&
  4667. Math.abs(left[5] - right[5]) <= epsilon &&
  4668. Math.abs(left[6] - right[6]) <= epsilon &&
  4669. Math.abs(left[7] - right[7]) <= epsilon &&
  4670. Math.abs(left[8] - right[8]) <= epsilon);
  4671. };
  4672. /**
  4673. * An immutable Matrix3 instance initialized to the identity matrix.
  4674. *
  4675. * @type {Matrix3}
  4676. * @constant
  4677. */
  4678. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  4679. 0.0, 1.0, 0.0,
  4680. 0.0, 0.0, 1.0));
  4681. /**
  4682. * An immutable Matrix3 instance initialized to the zero matrix.
  4683. *
  4684. * @type {Matrix3}
  4685. * @constant
  4686. */
  4687. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  4688. 0.0, 0.0, 0.0,
  4689. 0.0, 0.0, 0.0));
  4690. /**
  4691. * The index into Matrix3 for column 0, row 0.
  4692. *
  4693. * @type {Number}
  4694. * @constant
  4695. */
  4696. Matrix3.COLUMN0ROW0 = 0;
  4697. /**
  4698. * The index into Matrix3 for column 0, row 1.
  4699. *
  4700. * @type {Number}
  4701. * @constant
  4702. */
  4703. Matrix3.COLUMN0ROW1 = 1;
  4704. /**
  4705. * The index into Matrix3 for column 0, row 2.
  4706. *
  4707. * @type {Number}
  4708. * @constant
  4709. */
  4710. Matrix3.COLUMN0ROW2 = 2;
  4711. /**
  4712. * The index into Matrix3 for column 1, row 0.
  4713. *
  4714. * @type {Number}
  4715. * @constant
  4716. */
  4717. Matrix3.COLUMN1ROW0 = 3;
  4718. /**
  4719. * The index into Matrix3 for column 1, row 1.
  4720. *
  4721. * @type {Number}
  4722. * @constant
  4723. */
  4724. Matrix3.COLUMN1ROW1 = 4;
  4725. /**
  4726. * The index into Matrix3 for column 1, row 2.
  4727. *
  4728. * @type {Number}
  4729. * @constant
  4730. */
  4731. Matrix3.COLUMN1ROW2 = 5;
  4732. /**
  4733. * The index into Matrix3 for column 2, row 0.
  4734. *
  4735. * @type {Number}
  4736. * @constant
  4737. */
  4738. Matrix3.COLUMN2ROW0 = 6;
  4739. /**
  4740. * The index into Matrix3 for column 2, row 1.
  4741. *
  4742. * @type {Number}
  4743. * @constant
  4744. */
  4745. Matrix3.COLUMN2ROW1 = 7;
  4746. /**
  4747. * The index into Matrix3 for column 2, row 2.
  4748. *
  4749. * @type {Number}
  4750. * @constant
  4751. */
  4752. Matrix3.COLUMN2ROW2 = 8;
  4753. defineProperties(Matrix3.prototype, {
  4754. /**
  4755. * Gets the number of items in the collection.
  4756. * @memberof Matrix3.prototype
  4757. *
  4758. * @type {Number}
  4759. */
  4760. length : {
  4761. get : function() {
  4762. return Matrix3.packedLength;
  4763. }
  4764. }
  4765. });
  4766. /**
  4767. * Duplicates the provided Matrix3 instance.
  4768. *
  4769. * @param {Matrix3} [result] The object onto which to store the result.
  4770. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  4771. */
  4772. Matrix3.prototype.clone = function(result) {
  4773. return Matrix3.clone(this, result);
  4774. };
  4775. /**
  4776. * Compares this matrix to the provided matrix componentwise and returns
  4777. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4778. *
  4779. * @param {Matrix3} [right] The right hand side matrix.
  4780. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4781. */
  4782. Matrix3.prototype.equals = function(right) {
  4783. return Matrix3.equals(this, right);
  4784. };
  4785. /**
  4786. * @private
  4787. */
  4788. Matrix3.equalsArray = function(matrix, array, offset) {
  4789. return matrix[0] === array[offset] &&
  4790. matrix[1] === array[offset + 1] &&
  4791. matrix[2] === array[offset + 2] &&
  4792. matrix[3] === array[offset + 3] &&
  4793. matrix[4] === array[offset + 4] &&
  4794. matrix[5] === array[offset + 5] &&
  4795. matrix[6] === array[offset + 6] &&
  4796. matrix[7] === array[offset + 7] &&
  4797. matrix[8] === array[offset + 8];
  4798. };
  4799. /**
  4800. * Compares this matrix to the provided matrix componentwise and returns
  4801. * <code>true</code> if they are within the provided epsilon,
  4802. * <code>false</code> otherwise.
  4803. *
  4804. * @param {Matrix3} [right] The right hand side matrix.
  4805. * @param {Number} epsilon The epsilon to use for equality testing.
  4806. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  4807. */
  4808. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  4809. return Matrix3.equalsEpsilon(this, right, epsilon);
  4810. };
  4811. /**
  4812. * Creates a string representing this Matrix with each row being
  4813. * on a separate line and in the format '(column0, column1, column2)'.
  4814. *
  4815. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  4816. */
  4817. Matrix3.prototype.toString = function() {
  4818. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  4819. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  4820. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  4821. };
  4822. return Matrix3;
  4823. });
  4824. /*global define*/
  4825. define('Core/Cartesian4',[
  4826. './defaultValue',
  4827. './defined',
  4828. './DeveloperError',
  4829. './freezeObject',
  4830. './Math'
  4831. ], function(
  4832. defaultValue,
  4833. defined,
  4834. DeveloperError,
  4835. freezeObject,
  4836. CesiumMath) {
  4837. 'use strict';
  4838. /**
  4839. * A 4D Cartesian point.
  4840. * @alias Cartesian4
  4841. * @constructor
  4842. *
  4843. * @param {Number} [x=0.0] The X component.
  4844. * @param {Number} [y=0.0] The Y component.
  4845. * @param {Number} [z=0.0] The Z component.
  4846. * @param {Number} [w=0.0] The W component.
  4847. *
  4848. * @see Cartesian2
  4849. * @see Cartesian3
  4850. * @see Packable
  4851. */
  4852. function Cartesian4(x, y, z, w) {
  4853. /**
  4854. * The X component.
  4855. * @type {Number}
  4856. * @default 0.0
  4857. */
  4858. this.x = defaultValue(x, 0.0);
  4859. /**
  4860. * The Y component.
  4861. * @type {Number}
  4862. * @default 0.0
  4863. */
  4864. this.y = defaultValue(y, 0.0);
  4865. /**
  4866. * The Z component.
  4867. * @type {Number}
  4868. * @default 0.0
  4869. */
  4870. this.z = defaultValue(z, 0.0);
  4871. /**
  4872. * The W component.
  4873. * @type {Number}
  4874. * @default 0.0
  4875. */
  4876. this.w = defaultValue(w, 0.0);
  4877. }
  4878. /**
  4879. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  4880. *
  4881. * @param {Number} x The x coordinate.
  4882. * @param {Number} y The y coordinate.
  4883. * @param {Number} z The z coordinate.
  4884. * @param {Number} w The w coordinate.
  4885. * @param {Cartesian4} [result] The object onto which to store the result.
  4886. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4887. */
  4888. Cartesian4.fromElements = function(x, y, z, w, result) {
  4889. if (!defined(result)) {
  4890. return new Cartesian4(x, y, z, w);
  4891. }
  4892. result.x = x;
  4893. result.y = y;
  4894. result.z = z;
  4895. result.w = w;
  4896. return result;
  4897. };
  4898. /**
  4899. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  4900. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  4901. *
  4902. * @param {Color} color The source color.
  4903. * @param {Cartesian4} [result] The object onto which to store the result.
  4904. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4905. */
  4906. Cartesian4.fromColor = function(color, result) {
  4907. if (!defined(color)) {
  4908. throw new DeveloperError('color is required');
  4909. }
  4910. if (!defined(result)) {
  4911. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  4912. }
  4913. result.x = color.red;
  4914. result.y = color.green;
  4915. result.z = color.blue;
  4916. result.w = color.alpha;
  4917. return result;
  4918. };
  4919. /**
  4920. * Duplicates a Cartesian4 instance.
  4921. *
  4922. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  4923. * @param {Cartesian4} [result] The object onto which to store the result.
  4924. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  4925. */
  4926. Cartesian4.clone = function(cartesian, result) {
  4927. if (!defined(cartesian)) {
  4928. return undefined;
  4929. }
  4930. if (!defined(result)) {
  4931. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4932. }
  4933. result.x = cartesian.x;
  4934. result.y = cartesian.y;
  4935. result.z = cartesian.z;
  4936. result.w = cartesian.w;
  4937. return result;
  4938. };
  4939. /**
  4940. * The number of elements used to pack the object into an array.
  4941. * @type {Number}
  4942. */
  4943. Cartesian4.packedLength = 4;
  4944. /**
  4945. * Stores the provided instance into the provided array.
  4946. *
  4947. * @param {Cartesian4} value The value to pack.
  4948. * @param {Number[]} array The array to pack into.
  4949. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4950. *
  4951. * @returns {Number[]} The array that was packed into
  4952. */
  4953. Cartesian4.pack = function(value, array, startingIndex) {
  4954. if (!defined(value)) {
  4955. throw new DeveloperError('value is required');
  4956. }
  4957. if (!defined(array)) {
  4958. throw new DeveloperError('array is required');
  4959. }
  4960. startingIndex = defaultValue(startingIndex, 0);
  4961. array[startingIndex++] = value.x;
  4962. array[startingIndex++] = value.y;
  4963. array[startingIndex++] = value.z;
  4964. array[startingIndex] = value.w;
  4965. return array;
  4966. };
  4967. /**
  4968. * Retrieves an instance from a packed array.
  4969. *
  4970. * @param {Number[]} array The packed array.
  4971. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4972. * @param {Cartesian4} [result] The object into which to store the result.
  4973. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4974. */
  4975. Cartesian4.unpack = function(array, startingIndex, result) {
  4976. if (!defined(array)) {
  4977. throw new DeveloperError('array is required');
  4978. }
  4979. startingIndex = defaultValue(startingIndex, 0);
  4980. if (!defined(result)) {
  4981. result = new Cartesian4();
  4982. }
  4983. result.x = array[startingIndex++];
  4984. result.y = array[startingIndex++];
  4985. result.z = array[startingIndex++];
  4986. result.w = array[startingIndex];
  4987. return result;
  4988. };
  4989. /**
  4990. * Flattens an array of Cartesian4s into and array of components.
  4991. *
  4992. * @param {Cartesian4[]} array The array of cartesians to pack.
  4993. * @param {Number[]} result The array onto which to store the result.
  4994. * @returns {Number[]} The packed array.
  4995. */
  4996. Cartesian4.packArray = function(array, result) {
  4997. if (!defined(array)) {
  4998. throw new DeveloperError('array is required');
  4999. }
  5000. var length = array.length;
  5001. if (!defined(result)) {
  5002. result = new Array(length * 4);
  5003. } else {
  5004. result.length = length * 4;
  5005. }
  5006. for (var i = 0; i < length; ++i) {
  5007. Cartesian4.pack(array[i], result, i * 4);
  5008. }
  5009. return result;
  5010. };
  5011. /**
  5012. * Unpacks an array of cartesian components into and array of Cartesian4s.
  5013. *
  5014. * @param {Number[]} array The array of components to unpack.
  5015. * @param {Cartesian4[]} result The array onto which to store the result.
  5016. * @returns {Cartesian4[]} The unpacked array.
  5017. */
  5018. Cartesian4.unpackArray = function(array, result) {
  5019. if (!defined(array)) {
  5020. throw new DeveloperError('array is required');
  5021. }
  5022. var length = array.length;
  5023. if (!defined(result)) {
  5024. result = new Array(length / 4);
  5025. } else {
  5026. result.length = length / 4;
  5027. }
  5028. for (var i = 0; i < length; i += 4) {
  5029. var index = i / 4;
  5030. result[index] = Cartesian4.unpack(array, i, result[index]);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a Cartesian4 from four consecutive elements in an array.
  5036. * @function
  5037. *
  5038. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  5039. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  5040. * @param {Cartesian4} [result] The object onto which to store the result.
  5041. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5042. *
  5043. * @example
  5044. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  5045. * var v = [1.0, 2.0, 3.0, 4.0];
  5046. * var p = Cesium.Cartesian4.fromArray(v);
  5047. *
  5048. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  5049. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  5050. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  5051. */
  5052. Cartesian4.fromArray = Cartesian4.unpack;
  5053. /**
  5054. * Computes the value of the maximum component for the supplied Cartesian.
  5055. *
  5056. * @param {Cartesian4} cartesian The cartesian to use.
  5057. * @returns {Number} The value of the maximum component.
  5058. */
  5059. Cartesian4.maximumComponent = function(cartesian) {
  5060. if (!defined(cartesian)) {
  5061. throw new DeveloperError('cartesian is required');
  5062. }
  5063. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  5064. };
  5065. /**
  5066. * Computes the value of the minimum component for the supplied Cartesian.
  5067. *
  5068. * @param {Cartesian4} cartesian The cartesian to use.
  5069. * @returns {Number} The value of the minimum component.
  5070. */
  5071. Cartesian4.minimumComponent = function(cartesian) {
  5072. if (!defined(cartesian)) {
  5073. throw new DeveloperError('cartesian is required');
  5074. }
  5075. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  5076. };
  5077. /**
  5078. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  5079. *
  5080. * @param {Cartesian4} first A cartesian to compare.
  5081. * @param {Cartesian4} second A cartesian to compare.
  5082. * @param {Cartesian4} result The object into which to store the result.
  5083. * @returns {Cartesian4} A cartesian with the minimum components.
  5084. */
  5085. Cartesian4.minimumByComponent = function(first, second, result) {
  5086. if (!defined(first)) {
  5087. throw new DeveloperError('first is required.');
  5088. }
  5089. if (!defined(second)) {
  5090. throw new DeveloperError('second is required.');
  5091. }
  5092. if (!defined(result)) {
  5093. throw new DeveloperError('result is required.');
  5094. }
  5095. result.x = Math.min(first.x, second.x);
  5096. result.y = Math.min(first.y, second.y);
  5097. result.z = Math.min(first.z, second.z);
  5098. result.w = Math.min(first.w, second.w);
  5099. return result;
  5100. };
  5101. /**
  5102. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  5103. *
  5104. * @param {Cartesian4} first A cartesian to compare.
  5105. * @param {Cartesian4} second A cartesian to compare.
  5106. * @param {Cartesian4} result The object into which to store the result.
  5107. * @returns {Cartesian4} A cartesian with the maximum components.
  5108. */
  5109. Cartesian4.maximumByComponent = function(first, second, result) {
  5110. if (!defined(first)) {
  5111. throw new DeveloperError('first is required.');
  5112. }
  5113. if (!defined(second)) {
  5114. throw new DeveloperError('second is required.');
  5115. }
  5116. if (!defined(result)) {
  5117. throw new DeveloperError('result is required.');
  5118. }
  5119. result.x = Math.max(first.x, second.x);
  5120. result.y = Math.max(first.y, second.y);
  5121. result.z = Math.max(first.z, second.z);
  5122. result.w = Math.max(first.w, second.w);
  5123. return result;
  5124. };
  5125. /**
  5126. * Computes the provided Cartesian's squared magnitude.
  5127. *
  5128. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  5129. * @returns {Number} The squared magnitude.
  5130. */
  5131. Cartesian4.magnitudeSquared = function(cartesian) {
  5132. if (!defined(cartesian)) {
  5133. throw new DeveloperError('cartesian is required');
  5134. }
  5135. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  5136. };
  5137. /**
  5138. * Computes the Cartesian's magnitude (length).
  5139. *
  5140. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  5141. * @returns {Number} The magnitude.
  5142. */
  5143. Cartesian4.magnitude = function(cartesian) {
  5144. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  5145. };
  5146. var distanceScratch = new Cartesian4();
  5147. /**
  5148. * Computes the 4-space distance between two points.
  5149. *
  5150. * @param {Cartesian4} left The first point to compute the distance from.
  5151. * @param {Cartesian4} right The second point to compute the distance to.
  5152. * @returns {Number} The distance between two points.
  5153. *
  5154. * @example
  5155. * // Returns 1.0
  5156. * var d = Cesium.Cartesian4.distance(
  5157. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  5158. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  5159. */
  5160. Cartesian4.distance = function(left, right) {
  5161. if (!defined(left) || !defined(right)) {
  5162. throw new DeveloperError('left and right are required.');
  5163. }
  5164. Cartesian4.subtract(left, right, distanceScratch);
  5165. return Cartesian4.magnitude(distanceScratch);
  5166. };
  5167. /**
  5168. * Computes the squared distance between two points. Comparing squared distances
  5169. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  5170. *
  5171. * @param {Cartesian4} left The first point to compute the distance from.
  5172. * @param {Cartesian4} right The second point to compute the distance to.
  5173. * @returns {Number} The distance between two points.
  5174. *
  5175. * @example
  5176. * // Returns 4.0, not 2.0
  5177. * var d = Cesium.Cartesian4.distance(
  5178. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  5179. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  5180. */
  5181. Cartesian4.distanceSquared = function(left, right) {
  5182. if (!defined(left) || !defined(right)) {
  5183. throw new DeveloperError('left and right are required.');
  5184. }
  5185. Cartesian4.subtract(left, right, distanceScratch);
  5186. return Cartesian4.magnitudeSquared(distanceScratch);
  5187. };
  5188. /**
  5189. * Computes the normalized form of the supplied Cartesian.
  5190. *
  5191. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  5192. * @param {Cartesian4} result The object onto which to store the result.
  5193. * @returns {Cartesian4} The modified result parameter.
  5194. */
  5195. Cartesian4.normalize = function(cartesian, result) {
  5196. if (!defined(cartesian)) {
  5197. throw new DeveloperError('cartesian is required');
  5198. }
  5199. if (!defined(result)) {
  5200. throw new DeveloperError('result is required');
  5201. }
  5202. var magnitude = Cartesian4.magnitude(cartesian);
  5203. result.x = cartesian.x / magnitude;
  5204. result.y = cartesian.y / magnitude;
  5205. result.z = cartesian.z / magnitude;
  5206. result.w = cartesian.w / magnitude;
  5207. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  5208. throw new DeveloperError('normalized result is not a number');
  5209. }
  5210. return result;
  5211. };
  5212. /**
  5213. * Computes the dot (scalar) product of two Cartesians.
  5214. *
  5215. * @param {Cartesian4} left The first Cartesian.
  5216. * @param {Cartesian4} right The second Cartesian.
  5217. * @returns {Number} The dot product.
  5218. */
  5219. Cartesian4.dot = function(left, right) {
  5220. if (!defined(left)) {
  5221. throw new DeveloperError('left is required');
  5222. }
  5223. if (!defined(right)) {
  5224. throw new DeveloperError('right is required');
  5225. }
  5226. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  5227. };
  5228. /**
  5229. * Computes the componentwise product of two Cartesians.
  5230. *
  5231. * @param {Cartesian4} left The first Cartesian.
  5232. * @param {Cartesian4} right The second Cartesian.
  5233. * @param {Cartesian4} result The object onto which to store the result.
  5234. * @returns {Cartesian4} The modified result parameter.
  5235. */
  5236. Cartesian4.multiplyComponents = function(left, right, result) {
  5237. if (!defined(left)) {
  5238. throw new DeveloperError('left is required');
  5239. }
  5240. if (!defined(right)) {
  5241. throw new DeveloperError('right is required');
  5242. }
  5243. if (!defined(result)) {
  5244. throw new DeveloperError('result is required');
  5245. }
  5246. result.x = left.x * right.x;
  5247. result.y = left.y * right.y;
  5248. result.z = left.z * right.z;
  5249. result.w = left.w * right.w;
  5250. return result;
  5251. };
  5252. /**
  5253. * Computes the componentwise quotient of two Cartesians.
  5254. *
  5255. * @param {Cartesian4} left The first Cartesian.
  5256. * @param {Cartesian4} right The second Cartesian.
  5257. * @param {Cartesian4} result The object onto which to store the result.
  5258. * @returns {Cartesian4} The modified result parameter.
  5259. */
  5260. Cartesian4.divideComponents = function(left, right, result) {
  5261. if (!defined(left)) {
  5262. throw new DeveloperError('left is required');
  5263. }
  5264. if (!defined(right)) {
  5265. throw new DeveloperError('right is required');
  5266. }
  5267. if (!defined(result)) {
  5268. throw new DeveloperError('result is required');
  5269. }
  5270. result.x = left.x / right.x;
  5271. result.y = left.y / right.y;
  5272. result.z = left.z / right.z;
  5273. result.w = left.w / right.w;
  5274. return result;
  5275. };
  5276. /**
  5277. * Computes the componentwise sum of two Cartesians.
  5278. *
  5279. * @param {Cartesian4} left The first Cartesian.
  5280. * @param {Cartesian4} right The second Cartesian.
  5281. * @param {Cartesian4} result The object onto which to store the result.
  5282. * @returns {Cartesian4} The modified result parameter.
  5283. */
  5284. Cartesian4.add = function(left, right, result) {
  5285. if (!defined(left)) {
  5286. throw new DeveloperError('left is required');
  5287. }
  5288. if (!defined(right)) {
  5289. throw new DeveloperError('right is required');
  5290. }
  5291. if (!defined(result)) {
  5292. throw new DeveloperError('result is required');
  5293. }
  5294. result.x = left.x + right.x;
  5295. result.y = left.y + right.y;
  5296. result.z = left.z + right.z;
  5297. result.w = left.w + right.w;
  5298. return result;
  5299. };
  5300. /**
  5301. * Computes the componentwise difference of two Cartesians.
  5302. *
  5303. * @param {Cartesian4} left The first Cartesian.
  5304. * @param {Cartesian4} right The second Cartesian.
  5305. * @param {Cartesian4} result The object onto which to store the result.
  5306. * @returns {Cartesian4} The modified result parameter.
  5307. */
  5308. Cartesian4.subtract = function(left, right, result) {
  5309. if (!defined(left)) {
  5310. throw new DeveloperError('left is required');
  5311. }
  5312. if (!defined(right)) {
  5313. throw new DeveloperError('right is required');
  5314. }
  5315. if (!defined(result)) {
  5316. throw new DeveloperError('result is required');
  5317. }
  5318. result.x = left.x - right.x;
  5319. result.y = left.y - right.y;
  5320. result.z = left.z - right.z;
  5321. result.w = left.w - right.w;
  5322. return result;
  5323. };
  5324. /**
  5325. * Multiplies the provided Cartesian componentwise by the provided scalar.
  5326. *
  5327. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  5328. * @param {Number} scalar The scalar to multiply with.
  5329. * @param {Cartesian4} result The object onto which to store the result.
  5330. * @returns {Cartesian4} The modified result parameter.
  5331. */
  5332. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  5333. if (!defined(cartesian)) {
  5334. throw new DeveloperError('cartesian is required');
  5335. }
  5336. if (typeof scalar !== 'number') {
  5337. throw new DeveloperError('scalar is required and must be a number.');
  5338. }
  5339. if (!defined(result)) {
  5340. throw new DeveloperError('result is required');
  5341. }
  5342. result.x = cartesian.x * scalar;
  5343. result.y = cartesian.y * scalar;
  5344. result.z = cartesian.z * scalar;
  5345. result.w = cartesian.w * scalar;
  5346. return result;
  5347. };
  5348. /**
  5349. * Divides the provided Cartesian componentwise by the provided scalar.
  5350. *
  5351. * @param {Cartesian4} cartesian The Cartesian to be divided.
  5352. * @param {Number} scalar The scalar to divide by.
  5353. * @param {Cartesian4} result The object onto which to store the result.
  5354. * @returns {Cartesian4} The modified result parameter.
  5355. */
  5356. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  5357. if (!defined(cartesian)) {
  5358. throw new DeveloperError('cartesian is required');
  5359. }
  5360. if (typeof scalar !== 'number') {
  5361. throw new DeveloperError('scalar is required and must be a number.');
  5362. }
  5363. if (!defined(result)) {
  5364. throw new DeveloperError('result is required');
  5365. }
  5366. result.x = cartesian.x / scalar;
  5367. result.y = cartesian.y / scalar;
  5368. result.z = cartesian.z / scalar;
  5369. result.w = cartesian.w / scalar;
  5370. return result;
  5371. };
  5372. /**
  5373. * Negates the provided Cartesian.
  5374. *
  5375. * @param {Cartesian4} cartesian The Cartesian to be negated.
  5376. * @param {Cartesian4} result The object onto which to store the result.
  5377. * @returns {Cartesian4} The modified result parameter.
  5378. */
  5379. Cartesian4.negate = function(cartesian, result) {
  5380. if (!defined(cartesian)) {
  5381. throw new DeveloperError('cartesian is required');
  5382. }
  5383. if (!defined(result)) {
  5384. throw new DeveloperError('result is required');
  5385. }
  5386. result.x = -cartesian.x;
  5387. result.y = -cartesian.y;
  5388. result.z = -cartesian.z;
  5389. result.w = -cartesian.w;
  5390. return result;
  5391. };
  5392. /**
  5393. * Computes the absolute value of the provided Cartesian.
  5394. *
  5395. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  5396. * @param {Cartesian4} result The object onto which to store the result.
  5397. * @returns {Cartesian4} The modified result parameter.
  5398. */
  5399. Cartesian4.abs = function(cartesian, result) {
  5400. if (!defined(cartesian)) {
  5401. throw new DeveloperError('cartesian is required');
  5402. }
  5403. if (!defined(result)) {
  5404. throw new DeveloperError('result is required');
  5405. }
  5406. result.x = Math.abs(cartesian.x);
  5407. result.y = Math.abs(cartesian.y);
  5408. result.z = Math.abs(cartesian.z);
  5409. result.w = Math.abs(cartesian.w);
  5410. return result;
  5411. };
  5412. var lerpScratch = new Cartesian4();
  5413. /**
  5414. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  5415. *
  5416. * @param {Cartesian4} start The value corresponding to t at 0.0.
  5417. * @param {Cartesian4}end The value corresponding to t at 1.0.
  5418. * @param {Number} t The point along t at which to interpolate.
  5419. * @param {Cartesian4} result The object onto which to store the result.
  5420. * @returns {Cartesian4} The modified result parameter.
  5421. */
  5422. Cartesian4.lerp = function(start, end, t, result) {
  5423. if (!defined(start)) {
  5424. throw new DeveloperError('start is required.');
  5425. }
  5426. if (!defined(end)) {
  5427. throw new DeveloperError('end is required.');
  5428. }
  5429. if (typeof t !== 'number') {
  5430. throw new DeveloperError('t is required and must be a number.');
  5431. }
  5432. if (!defined(result)) {
  5433. throw new DeveloperError('result is required.');
  5434. }
  5435. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  5436. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  5437. return Cartesian4.add(lerpScratch, result, result);
  5438. };
  5439. var mostOrthogonalAxisScratch = new Cartesian4();
  5440. /**
  5441. * Returns the axis that is most orthogonal to the provided Cartesian.
  5442. *
  5443. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  5444. * @param {Cartesian4} result The object onto which to store the result.
  5445. * @returns {Cartesian4} The most orthogonal axis.
  5446. */
  5447. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  5448. if (!defined(cartesian)) {
  5449. throw new DeveloperError('cartesian is required.');
  5450. }
  5451. if (!defined(result)) {
  5452. throw new DeveloperError('result is required.');
  5453. }
  5454. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  5455. Cartesian4.abs(f, f);
  5456. if (f.x <= f.y) {
  5457. if (f.x <= f.z) {
  5458. if (f.x <= f.w) {
  5459. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  5460. } else {
  5461. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5462. }
  5463. } else if (f.z <= f.w) {
  5464. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5465. } else {
  5466. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5467. }
  5468. } else if (f.y <= f.z) {
  5469. if (f.y <= f.w) {
  5470. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  5471. } else {
  5472. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5473. }
  5474. } else if (f.z <= f.w) {
  5475. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5476. } else {
  5477. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5478. }
  5479. return result;
  5480. };
  5481. /**
  5482. * Compares the provided Cartesians componentwise and returns
  5483. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5484. *
  5485. * @param {Cartesian4} [left] The first Cartesian.
  5486. * @param {Cartesian4} [right] The second Cartesian.
  5487. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5488. */
  5489. Cartesian4.equals = function(left, right) {
  5490. return (left === right) ||
  5491. ((defined(left)) &&
  5492. (defined(right)) &&
  5493. (left.x === right.x) &&
  5494. (left.y === right.y) &&
  5495. (left.z === right.z) &&
  5496. (left.w === right.w));
  5497. };
  5498. /**
  5499. * @private
  5500. */
  5501. Cartesian4.equalsArray = function(cartesian, array, offset) {
  5502. return cartesian.x === array[offset] &&
  5503. cartesian.y === array[offset + 1] &&
  5504. cartesian.z === array[offset + 2] &&
  5505. cartesian.w === array[offset + 3];
  5506. };
  5507. /**
  5508. * Compares the provided Cartesians componentwise and returns
  5509. * <code>true</code> if they pass an absolute or relative tolerance test,
  5510. * <code>false</code> otherwise.
  5511. *
  5512. * @param {Cartesian4} [left] The first Cartesian.
  5513. * @param {Cartesian4} [right] The second Cartesian.
  5514. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5515. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5516. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  5517. */
  5518. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  5519. return (left === right) ||
  5520. (defined(left) &&
  5521. defined(right) &&
  5522. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  5523. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  5524. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  5525. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  5526. };
  5527. /**
  5528. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  5529. *
  5530. * @type {Cartesian4}
  5531. * @constant
  5532. */
  5533. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  5534. /**
  5535. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  5536. *
  5537. * @type {Cartesian4}
  5538. * @constant
  5539. */
  5540. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  5541. /**
  5542. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  5543. *
  5544. * @type {Cartesian4}
  5545. * @constant
  5546. */
  5547. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  5548. /**
  5549. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  5550. *
  5551. * @type {Cartesian4}
  5552. * @constant
  5553. */
  5554. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  5555. /**
  5556. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  5557. *
  5558. * @type {Cartesian4}
  5559. * @constant
  5560. */
  5561. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  5562. /**
  5563. * Duplicates this Cartesian4 instance.
  5564. *
  5565. * @param {Cartesian4} [result] The object onto which to store the result.
  5566. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5567. */
  5568. Cartesian4.prototype.clone = function(result) {
  5569. return Cartesian4.clone(this, result);
  5570. };
  5571. /**
  5572. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5573. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5574. *
  5575. * @param {Cartesian4} [right] The right hand side Cartesian.
  5576. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5577. */
  5578. Cartesian4.prototype.equals = function(right) {
  5579. return Cartesian4.equals(this, right);
  5580. };
  5581. /**
  5582. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5583. * <code>true</code> if they pass an absolute or relative tolerance test,
  5584. * <code>false</code> otherwise.
  5585. *
  5586. * @param {Cartesian4} [right] The right hand side Cartesian.
  5587. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5588. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5589. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  5590. */
  5591. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  5592. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  5593. };
  5594. /**
  5595. * Creates a string representing this Cartesian in the format '(x, y)'.
  5596. *
  5597. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  5598. */
  5599. Cartesian4.prototype.toString = function() {
  5600. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  5601. };
  5602. return Cartesian4;
  5603. });
  5604. /*global define*/
  5605. define('Core/RuntimeError',[
  5606. './defined'
  5607. ], function(
  5608. defined) {
  5609. 'use strict';
  5610. /**
  5611. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  5612. * out of memory, could not compile shader, etc. If a function may throw this
  5613. * exception, the calling code should be prepared to catch it.
  5614. * <br /><br />
  5615. * On the other hand, a {@link DeveloperError} indicates an exception due
  5616. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  5617. * calling code.
  5618. *
  5619. * @alias RuntimeError
  5620. * @constructor
  5621. * @extends Error
  5622. *
  5623. * @param {String} [message] The error message for this exception.
  5624. *
  5625. * @see DeveloperError
  5626. */
  5627. function RuntimeError(message) {
  5628. /**
  5629. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  5630. * @type {String}
  5631. * @readonly
  5632. */
  5633. this.name = 'RuntimeError';
  5634. /**
  5635. * The explanation for why this exception was thrown.
  5636. * @type {String}
  5637. * @readonly
  5638. */
  5639. this.message = message;
  5640. //Browsers such as IE don't have a stack property until you actually throw the error.
  5641. var stack;
  5642. try {
  5643. throw new Error();
  5644. } catch (e) {
  5645. stack = e.stack;
  5646. }
  5647. /**
  5648. * The stack trace of this exception, if available.
  5649. * @type {String}
  5650. * @readonly
  5651. */
  5652. this.stack = stack;
  5653. }
  5654. if (defined(Object.create)) {
  5655. RuntimeError.prototype = Object.create(Error.prototype);
  5656. RuntimeError.prototype.constructor = RuntimeError;
  5657. }
  5658. RuntimeError.prototype.toString = function() {
  5659. var str = this.name + ': ' + this.message;
  5660. if (defined(this.stack)) {
  5661. str += '\n' + this.stack.toString();
  5662. }
  5663. return str;
  5664. };
  5665. return RuntimeError;
  5666. });
  5667. /*global define*/
  5668. define('Core/Matrix4',[
  5669. './Cartesian3',
  5670. './Cartesian4',
  5671. './defaultValue',
  5672. './defined',
  5673. './defineProperties',
  5674. './DeveloperError',
  5675. './freezeObject',
  5676. './Math',
  5677. './Matrix3',
  5678. './RuntimeError'
  5679. ], function(
  5680. Cartesian3,
  5681. Cartesian4,
  5682. defaultValue,
  5683. defined,
  5684. defineProperties,
  5685. DeveloperError,
  5686. freezeObject,
  5687. CesiumMath,
  5688. Matrix3,
  5689. RuntimeError) {
  5690. 'use strict';
  5691. /**
  5692. * A 4x4 matrix, indexable as a column-major order array.
  5693. * Constructor parameters are in row-major order for code readability.
  5694. * @alias Matrix4
  5695. * @constructor
  5696. *
  5697. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5698. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5699. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5700. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  5701. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5702. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5703. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5704. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  5705. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5706. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5707. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5708. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  5709. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  5710. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  5711. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  5712. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  5713. *
  5714. * @see Matrix4.fromColumnMajorArray
  5715. * @see Matrix4.fromRowMajorArray
  5716. * @see Matrix4.fromRotationTranslation
  5717. * @see Matrix4.fromTranslationRotationScale
  5718. * @see Matrix4.fromTranslationQuaternionRotationScale
  5719. * @see Matrix4.fromTranslation
  5720. * @see Matrix4.fromScale
  5721. * @see Matrix4.fromUniformScale
  5722. * @see Matrix4.fromCamera
  5723. * @see Matrix4.computePerspectiveFieldOfView
  5724. * @see Matrix4.computeOrthographicOffCenter
  5725. * @see Matrix4.computePerspectiveOffCenter
  5726. * @see Matrix4.computeInfinitePerspectiveOffCenter
  5727. * @see Matrix4.computeViewportTransformation
  5728. * @see Matrix4.computeView
  5729. * @see Matrix2
  5730. * @see Matrix3
  5731. * @see Packable
  5732. */
  5733. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  5734. column0Row1, column1Row1, column2Row1, column3Row1,
  5735. column0Row2, column1Row2, column2Row2, column3Row2,
  5736. column0Row3, column1Row3, column2Row3, column3Row3) {
  5737. this[0] = defaultValue(column0Row0, 0.0);
  5738. this[1] = defaultValue(column0Row1, 0.0);
  5739. this[2] = defaultValue(column0Row2, 0.0);
  5740. this[3] = defaultValue(column0Row3, 0.0);
  5741. this[4] = defaultValue(column1Row0, 0.0);
  5742. this[5] = defaultValue(column1Row1, 0.0);
  5743. this[6] = defaultValue(column1Row2, 0.0);
  5744. this[7] = defaultValue(column1Row3, 0.0);
  5745. this[8] = defaultValue(column2Row0, 0.0);
  5746. this[9] = defaultValue(column2Row1, 0.0);
  5747. this[10] = defaultValue(column2Row2, 0.0);
  5748. this[11] = defaultValue(column2Row3, 0.0);
  5749. this[12] = defaultValue(column3Row0, 0.0);
  5750. this[13] = defaultValue(column3Row1, 0.0);
  5751. this[14] = defaultValue(column3Row2, 0.0);
  5752. this[15] = defaultValue(column3Row3, 0.0);
  5753. }
  5754. /**
  5755. * The number of elements used to pack the object into an array.
  5756. * @type {Number}
  5757. */
  5758. Matrix4.packedLength = 16;
  5759. /**
  5760. * Stores the provided instance into the provided array.
  5761. *
  5762. * @param {Matrix4} value The value to pack.
  5763. * @param {Number[]} array The array to pack into.
  5764. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5765. *
  5766. * @returns {Number[]} The array that was packed into
  5767. */
  5768. Matrix4.pack = function(value, array, startingIndex) {
  5769. if (!defined(value)) {
  5770. throw new DeveloperError('value is required');
  5771. }
  5772. if (!defined(array)) {
  5773. throw new DeveloperError('array is required');
  5774. }
  5775. startingIndex = defaultValue(startingIndex, 0);
  5776. array[startingIndex++] = value[0];
  5777. array[startingIndex++] = value[1];
  5778. array[startingIndex++] = value[2];
  5779. array[startingIndex++] = value[3];
  5780. array[startingIndex++] = value[4];
  5781. array[startingIndex++] = value[5];
  5782. array[startingIndex++] = value[6];
  5783. array[startingIndex++] = value[7];
  5784. array[startingIndex++] = value[8];
  5785. array[startingIndex++] = value[9];
  5786. array[startingIndex++] = value[10];
  5787. array[startingIndex++] = value[11];
  5788. array[startingIndex++] = value[12];
  5789. array[startingIndex++] = value[13];
  5790. array[startingIndex++] = value[14];
  5791. array[startingIndex] = value[15];
  5792. return array;
  5793. };
  5794. /**
  5795. * Retrieves an instance from a packed array.
  5796. *
  5797. * @param {Number[]} array The packed array.
  5798. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5799. * @param {Matrix4} [result] The object into which to store the result.
  5800. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5801. */
  5802. Matrix4.unpack = function(array, startingIndex, result) {
  5803. if (!defined(array)) {
  5804. throw new DeveloperError('array is required');
  5805. }
  5806. startingIndex = defaultValue(startingIndex, 0);
  5807. if (!defined(result)) {
  5808. result = new Matrix4();
  5809. }
  5810. result[0] = array[startingIndex++];
  5811. result[1] = array[startingIndex++];
  5812. result[2] = array[startingIndex++];
  5813. result[3] = array[startingIndex++];
  5814. result[4] = array[startingIndex++];
  5815. result[5] = array[startingIndex++];
  5816. result[6] = array[startingIndex++];
  5817. result[7] = array[startingIndex++];
  5818. result[8] = array[startingIndex++];
  5819. result[9] = array[startingIndex++];
  5820. result[10] = array[startingIndex++];
  5821. result[11] = array[startingIndex++];
  5822. result[12] = array[startingIndex++];
  5823. result[13] = array[startingIndex++];
  5824. result[14] = array[startingIndex++];
  5825. result[15] = array[startingIndex];
  5826. return result;
  5827. };
  5828. /**
  5829. * Duplicates a Matrix4 instance.
  5830. *
  5831. * @param {Matrix4} matrix The matrix to duplicate.
  5832. * @param {Matrix4} [result] The object onto which to store the result.
  5833. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  5834. */
  5835. Matrix4.clone = function(matrix, result) {
  5836. if (!defined(matrix)) {
  5837. return undefined;
  5838. }
  5839. if (!defined(result)) {
  5840. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  5841. matrix[1], matrix[5], matrix[9], matrix[13],
  5842. matrix[2], matrix[6], matrix[10], matrix[14],
  5843. matrix[3], matrix[7], matrix[11], matrix[15]);
  5844. }
  5845. result[0] = matrix[0];
  5846. result[1] = matrix[1];
  5847. result[2] = matrix[2];
  5848. result[3] = matrix[3];
  5849. result[4] = matrix[4];
  5850. result[5] = matrix[5];
  5851. result[6] = matrix[6];
  5852. result[7] = matrix[7];
  5853. result[8] = matrix[8];
  5854. result[9] = matrix[9];
  5855. result[10] = matrix[10];
  5856. result[11] = matrix[11];
  5857. result[12] = matrix[12];
  5858. result[13] = matrix[13];
  5859. result[14] = matrix[14];
  5860. result[15] = matrix[15];
  5861. return result;
  5862. };
  5863. /**
  5864. * Creates a Matrix4 from 16 consecutive elements in an array.
  5865. * @function
  5866. *
  5867. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5868. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5869. * @param {Matrix4} [result] The object onto which to store the result.
  5870. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5871. *
  5872. * @example
  5873. * // Create the Matrix4:
  5874. * // [1.0, 2.0, 3.0, 4.0]
  5875. * // [1.0, 2.0, 3.0, 4.0]
  5876. * // [1.0, 2.0, 3.0, 4.0]
  5877. * // [1.0, 2.0, 3.0, 4.0]
  5878. *
  5879. * 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];
  5880. * var m = Cesium.Matrix4.fromArray(v);
  5881. *
  5882. * // Create same Matrix4 with using an offset into an array
  5883. * 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];
  5884. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  5885. */
  5886. Matrix4.fromArray = Matrix4.unpack;
  5887. /**
  5888. * Computes a Matrix4 instance from a column-major order array.
  5889. *
  5890. * @param {Number[]} values The column-major order array.
  5891. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5892. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5893. */
  5894. Matrix4.fromColumnMajorArray = function(values, result) {
  5895. if (!defined(values)) {
  5896. throw new DeveloperError('values is required');
  5897. }
  5898. return Matrix4.clone(values, result);
  5899. };
  5900. /**
  5901. * Computes a Matrix4 instance from a row-major order array.
  5902. * The resulting matrix will be in column-major order.
  5903. *
  5904. * @param {Number[]} values The row-major order array.
  5905. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5906. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5907. */
  5908. Matrix4.fromRowMajorArray = function(values, result) {
  5909. if (!defined(values)) {
  5910. throw new DeveloperError('values is required.');
  5911. }
  5912. if (!defined(result)) {
  5913. return new Matrix4(values[0], values[1], values[2], values[3],
  5914. values[4], values[5], values[6], values[7],
  5915. values[8], values[9], values[10], values[11],
  5916. values[12], values[13], values[14], values[15]);
  5917. }
  5918. result[0] = values[0];
  5919. result[1] = values[4];
  5920. result[2] = values[8];
  5921. result[3] = values[12];
  5922. result[4] = values[1];
  5923. result[5] = values[5];
  5924. result[6] = values[9];
  5925. result[7] = values[13];
  5926. result[8] = values[2];
  5927. result[9] = values[6];
  5928. result[10] = values[10];
  5929. result[11] = values[14];
  5930. result[12] = values[3];
  5931. result[13] = values[7];
  5932. result[14] = values[11];
  5933. result[15] = values[15];
  5934. return result;
  5935. };
  5936. /**
  5937. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  5938. * and a Cartesian3 representing the translation.
  5939. *
  5940. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  5941. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  5942. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5943. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5944. */
  5945. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  5946. if (!defined(rotation)) {
  5947. throw new DeveloperError('rotation is required.');
  5948. }
  5949. translation = defaultValue(translation, Cartesian3.ZERO);
  5950. if (!defined(result)) {
  5951. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  5952. rotation[1], rotation[4], rotation[7], translation.y,
  5953. rotation[2], rotation[5], rotation[8], translation.z,
  5954. 0.0, 0.0, 0.0, 1.0);
  5955. }
  5956. result[0] = rotation[0];
  5957. result[1] = rotation[1];
  5958. result[2] = rotation[2];
  5959. result[3] = 0.0;
  5960. result[4] = rotation[3];
  5961. result[5] = rotation[4];
  5962. result[6] = rotation[5];
  5963. result[7] = 0.0;
  5964. result[8] = rotation[6];
  5965. result[9] = rotation[7];
  5966. result[10] = rotation[8];
  5967. result[11] = 0.0;
  5968. result[12] = translation.x;
  5969. result[13] = translation.y;
  5970. result[14] = translation.z;
  5971. result[15] = 1.0;
  5972. return result;
  5973. };
  5974. /**
  5975. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  5976. * representation with the rotation represented as a quaternion.
  5977. *
  5978. * @param {Cartesian3} translation The translation transformation.
  5979. * @param {Quaternion} rotation The rotation transformation.
  5980. * @param {Cartesian3} scale The non-uniform scale transformation.
  5981. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5982. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5983. *
  5984. * @example
  5985. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  5986. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  5987. * Cesium.Quaternion.IDENTITY, // rotation
  5988. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  5989. * result);
  5990. */
  5991. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  5992. if (!defined(translation)) {
  5993. throw new DeveloperError('translation is required.');
  5994. }
  5995. if (!defined(rotation)) {
  5996. throw new DeveloperError('rotation is required.');
  5997. }
  5998. if (!defined(scale)) {
  5999. throw new DeveloperError('scale is required.');
  6000. }
  6001. if (!defined(result)) {
  6002. result = new Matrix4();
  6003. }
  6004. var scaleX = scale.x;
  6005. var scaleY = scale.y;
  6006. var scaleZ = scale.z;
  6007. var x2 = rotation.x * rotation.x;
  6008. var xy = rotation.x * rotation.y;
  6009. var xz = rotation.x * rotation.z;
  6010. var xw = rotation.x * rotation.w;
  6011. var y2 = rotation.y * rotation.y;
  6012. var yz = rotation.y * rotation.z;
  6013. var yw = rotation.y * rotation.w;
  6014. var z2 = rotation.z * rotation.z;
  6015. var zw = rotation.z * rotation.w;
  6016. var w2 = rotation.w * rotation.w;
  6017. var m00 = x2 - y2 - z2 + w2;
  6018. var m01 = 2.0 * (xy - zw);
  6019. var m02 = 2.0 * (xz + yw);
  6020. var m10 = 2.0 * (xy + zw);
  6021. var m11 = -x2 + y2 - z2 + w2;
  6022. var m12 = 2.0 * (yz - xw);
  6023. var m20 = 2.0 * (xz - yw);
  6024. var m21 = 2.0 * (yz + xw);
  6025. var m22 = -x2 - y2 + z2 + w2;
  6026. result[0] = m00 * scaleX;
  6027. result[1] = m10 * scaleX;
  6028. result[2] = m20 * scaleX;
  6029. result[3] = 0.0;
  6030. result[4] = m01 * scaleY;
  6031. result[5] = m11 * scaleY;
  6032. result[6] = m21 * scaleY;
  6033. result[7] = 0.0;
  6034. result[8] = m02 * scaleZ;
  6035. result[9] = m12 * scaleZ;
  6036. result[10] = m22 * scaleZ;
  6037. result[11] = 0.0;
  6038. result[12] = translation.x;
  6039. result[13] = translation.y;
  6040. result[14] = translation.z;
  6041. result[15] = 1.0;
  6042. return result;
  6043. };
  6044. /**
  6045. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  6046. *
  6047. * @param {TranslationRotationScale} translationRotationScale The instance.
  6048. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6049. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6050. */
  6051. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  6052. if (!defined(translationRotationScale)) {
  6053. throw new DeveloperError('translationRotationScale is required.');
  6054. }
  6055. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  6056. };
  6057. /**
  6058. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  6059. *
  6060. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  6061. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6062. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6063. *
  6064. * @see Matrix4.multiplyByTranslation
  6065. */
  6066. Matrix4.fromTranslation = function(translation, result) {
  6067. if (!defined(translation)) {
  6068. throw new DeveloperError('translation is required.');
  6069. }
  6070. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  6071. };
  6072. /**
  6073. * Computes a Matrix4 instance representing a non-uniform scale.
  6074. *
  6075. * @param {Cartesian3} scale The x, y, and z scale factors.
  6076. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6077. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6078. *
  6079. * @example
  6080. * // Creates
  6081. * // [7.0, 0.0, 0.0, 0.0]
  6082. * // [0.0, 8.0, 0.0, 0.0]
  6083. * // [0.0, 0.0, 9.0, 0.0]
  6084. * // [0.0, 0.0, 0.0, 1.0]
  6085. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  6086. */
  6087. Matrix4.fromScale = function(scale, result) {
  6088. if (!defined(scale)) {
  6089. throw new DeveloperError('scale is required.');
  6090. }
  6091. if (!defined(result)) {
  6092. return new Matrix4(
  6093. scale.x, 0.0, 0.0, 0.0,
  6094. 0.0, scale.y, 0.0, 0.0,
  6095. 0.0, 0.0, scale.z, 0.0,
  6096. 0.0, 0.0, 0.0, 1.0);
  6097. }
  6098. result[0] = scale.x;
  6099. result[1] = 0.0;
  6100. result[2] = 0.0;
  6101. result[3] = 0.0;
  6102. result[4] = 0.0;
  6103. result[5] = scale.y;
  6104. result[6] = 0.0;
  6105. result[7] = 0.0;
  6106. result[8] = 0.0;
  6107. result[9] = 0.0;
  6108. result[10] = scale.z;
  6109. result[11] = 0.0;
  6110. result[12] = 0.0;
  6111. result[13] = 0.0;
  6112. result[14] = 0.0;
  6113. result[15] = 1.0;
  6114. return result;
  6115. };
  6116. /**
  6117. * Computes a Matrix4 instance representing a uniform scale.
  6118. *
  6119. * @param {Number} scale The uniform scale factor.
  6120. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6121. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6122. *
  6123. * @example
  6124. * // Creates
  6125. * // [2.0, 0.0, 0.0, 0.0]
  6126. * // [0.0, 2.0, 0.0, 0.0]
  6127. * // [0.0, 0.0, 2.0, 0.0]
  6128. * // [0.0, 0.0, 0.0, 1.0]
  6129. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  6130. */
  6131. Matrix4.fromUniformScale = function(scale, result) {
  6132. if (typeof scale !== 'number') {
  6133. throw new DeveloperError('scale is required.');
  6134. }
  6135. if (!defined(result)) {
  6136. return new Matrix4(scale, 0.0, 0.0, 0.0,
  6137. 0.0, scale, 0.0, 0.0,
  6138. 0.0, 0.0, scale, 0.0,
  6139. 0.0, 0.0, 0.0, 1.0);
  6140. }
  6141. result[0] = scale;
  6142. result[1] = 0.0;
  6143. result[2] = 0.0;
  6144. result[3] = 0.0;
  6145. result[4] = 0.0;
  6146. result[5] = scale;
  6147. result[6] = 0.0;
  6148. result[7] = 0.0;
  6149. result[8] = 0.0;
  6150. result[9] = 0.0;
  6151. result[10] = scale;
  6152. result[11] = 0.0;
  6153. result[12] = 0.0;
  6154. result[13] = 0.0;
  6155. result[14] = 0.0;
  6156. result[15] = 1.0;
  6157. return result;
  6158. };
  6159. var fromCameraF = new Cartesian3();
  6160. var fromCameraR = new Cartesian3();
  6161. var fromCameraU = new Cartesian3();
  6162. /**
  6163. * Computes a Matrix4 instance from a Camera.
  6164. *
  6165. * @param {Camera} camera The camera to use.
  6166. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6167. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6168. */
  6169. Matrix4.fromCamera = function(camera, result) {
  6170. if (!defined(camera)) {
  6171. throw new DeveloperError('camera is required.');
  6172. }
  6173. var position = camera.position;
  6174. var direction = camera.direction;
  6175. var up = camera.up;
  6176. if (!defined(position)) {
  6177. throw new DeveloperError('camera.position is required.');
  6178. }
  6179. if (!defined(direction)) {
  6180. throw new DeveloperError('camera.direction is required.');
  6181. }
  6182. if (!defined(up)) {
  6183. throw new DeveloperError('camera.up is required.');
  6184. }
  6185. Cartesian3.normalize(direction, fromCameraF);
  6186. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  6187. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  6188. var sX = fromCameraR.x;
  6189. var sY = fromCameraR.y;
  6190. var sZ = fromCameraR.z;
  6191. var fX = fromCameraF.x;
  6192. var fY = fromCameraF.y;
  6193. var fZ = fromCameraF.z;
  6194. var uX = fromCameraU.x;
  6195. var uY = fromCameraU.y;
  6196. var uZ = fromCameraU.z;
  6197. var positionX = position.x;
  6198. var positionY = position.y;
  6199. var positionZ = position.z;
  6200. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  6201. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  6202. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  6203. // The code below this comment is an optimized
  6204. // version of the commented lines.
  6205. // Rather that create two matrices and then multiply,
  6206. // we just bake in the multiplcation as part of creation.
  6207. // var rotation = new Matrix4(
  6208. // sX, sY, sZ, 0.0,
  6209. // uX, uY, uZ, 0.0,
  6210. // -fX, -fY, -fZ, 0.0,
  6211. // 0.0, 0.0, 0.0, 1.0);
  6212. // var translation = new Matrix4(
  6213. // 1.0, 0.0, 0.0, -position.x,
  6214. // 0.0, 1.0, 0.0, -position.y,
  6215. // 0.0, 0.0, 1.0, -position.z,
  6216. // 0.0, 0.0, 0.0, 1.0);
  6217. // return rotation.multiply(translation);
  6218. if (!defined(result)) {
  6219. return new Matrix4(
  6220. sX, sY, sZ, t0,
  6221. uX, uY, uZ, t1,
  6222. -fX, -fY, -fZ, t2,
  6223. 0.0, 0.0, 0.0, 1.0);
  6224. }
  6225. result[0] = sX;
  6226. result[1] = uX;
  6227. result[2] = -fX;
  6228. result[3] = 0.0;
  6229. result[4] = sY;
  6230. result[5] = uY;
  6231. result[6] = -fY;
  6232. result[7] = 0.0;
  6233. result[8] = sZ;
  6234. result[9] = uZ;
  6235. result[10] = -fZ;
  6236. result[11] = 0.0;
  6237. result[12] = t0;
  6238. result[13] = t1;
  6239. result[14] = t2;
  6240. result[15] = 1.0;
  6241. return result;
  6242. };
  6243. /**
  6244. * Computes a Matrix4 instance representing a perspective transformation matrix.
  6245. *
  6246. * @param {Number} fovY The field of view along the Y axis in radians.
  6247. * @param {Number} aspectRatio The aspect ratio.
  6248. * @param {Number} near The distance to the near plane in meters.
  6249. * @param {Number} far The distance to the far plane in meters.
  6250. * @param {Matrix4} result The object in which the result will be stored.
  6251. * @returns {Matrix4} The modified result parameter.
  6252. *
  6253. * @exception {DeveloperError} fovY must be in (0, PI].
  6254. * @exception {DeveloperError} aspectRatio must be greater than zero.
  6255. * @exception {DeveloperError} near must be greater than zero.
  6256. * @exception {DeveloperError} far must be greater than zero.
  6257. */
  6258. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  6259. if (fovY <= 0.0 || fovY > Math.PI) {
  6260. throw new DeveloperError('fovY must be in (0, PI].');
  6261. }
  6262. if (aspectRatio <= 0.0) {
  6263. throw new DeveloperError('aspectRatio must be greater than zero.');
  6264. }
  6265. if (near <= 0.0) {
  6266. throw new DeveloperError('near must be greater than zero.');
  6267. }
  6268. if (far <= 0.0) {
  6269. throw new DeveloperError('far must be greater than zero.');
  6270. }
  6271. if (!defined(result)) {
  6272. throw new DeveloperError('result is required');
  6273. }
  6274. var bottom = Math.tan(fovY * 0.5);
  6275. var column1Row1 = 1.0 / bottom;
  6276. var column0Row0 = column1Row1 / aspectRatio;
  6277. var column2Row2 = (far + near) / (near - far);
  6278. var column3Row2 = (2.0 * far * near) / (near - far);
  6279. result[0] = column0Row0;
  6280. result[1] = 0.0;
  6281. result[2] = 0.0;
  6282. result[3] = 0.0;
  6283. result[4] = 0.0;
  6284. result[5] = column1Row1;
  6285. result[6] = 0.0;
  6286. result[7] = 0.0;
  6287. result[8] = 0.0;
  6288. result[9] = 0.0;
  6289. result[10] = column2Row2;
  6290. result[11] = -1.0;
  6291. result[12] = 0.0;
  6292. result[13] = 0.0;
  6293. result[14] = column3Row2;
  6294. result[15] = 0.0;
  6295. return result;
  6296. };
  6297. /**
  6298. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  6299. *
  6300. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6301. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6302. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6303. * @param {Number} top The number of meters above of the camera that will be in view.
  6304. * @param {Number} near The distance to the near plane in meters.
  6305. * @param {Number} far The distance to the far plane in meters.
  6306. * @param {Matrix4} result The object in which the result will be stored.
  6307. * @returns {Matrix4} The modified result parameter.
  6308. */
  6309. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  6310. if (!defined(left)) {
  6311. throw new DeveloperError('left is required.');
  6312. }
  6313. if (!defined(right)) {
  6314. throw new DeveloperError('right is required.');
  6315. }
  6316. if (!defined(bottom)) {
  6317. throw new DeveloperError('bottom is required.');
  6318. }
  6319. if (!defined(top)) {
  6320. throw new DeveloperError('top is required.');
  6321. }
  6322. if (!defined(near)) {
  6323. throw new DeveloperError('near is required.');
  6324. }
  6325. if (!defined(far)) {
  6326. throw new DeveloperError('far is required.');
  6327. }
  6328. if (!defined(result)) {
  6329. throw new DeveloperError('result is required');
  6330. }
  6331. var a = 1.0 / (right - left);
  6332. var b = 1.0 / (top - bottom);
  6333. var c = 1.0 / (far - near);
  6334. var tx = -(right + left) * a;
  6335. var ty = -(top + bottom) * b;
  6336. var tz = -(far + near) * c;
  6337. a *= 2.0;
  6338. b *= 2.0;
  6339. c *= -2.0;
  6340. result[0] = a;
  6341. result[1] = 0.0;
  6342. result[2] = 0.0;
  6343. result[3] = 0.0;
  6344. result[4] = 0.0;
  6345. result[5] = b;
  6346. result[6] = 0.0;
  6347. result[7] = 0.0;
  6348. result[8] = 0.0;
  6349. result[9] = 0.0;
  6350. result[10] = c;
  6351. result[11] = 0.0;
  6352. result[12] = tx;
  6353. result[13] = ty;
  6354. result[14] = tz;
  6355. result[15] = 1.0;
  6356. return result;
  6357. };
  6358. /**
  6359. * Computes a Matrix4 instance representing an off center perspective transformation.
  6360. *
  6361. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6362. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6363. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6364. * @param {Number} top The number of meters above of the camera that will be in view.
  6365. * @param {Number} near The distance to the near plane in meters.
  6366. * @param {Number} far The distance to the far plane in meters.
  6367. * @param {Matrix4} result The object in which the result will be stored.
  6368. * @returns {Matrix4} The modified result parameter.
  6369. */
  6370. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  6371. if (!defined(left)) {
  6372. throw new DeveloperError('left is required.');
  6373. }
  6374. if (!defined(right)) {
  6375. throw new DeveloperError('right is required.');
  6376. }
  6377. if (!defined(bottom)) {
  6378. throw new DeveloperError('bottom is required.');
  6379. }
  6380. if (!defined(top)) {
  6381. throw new DeveloperError('top is required.');
  6382. }
  6383. if (!defined(near)) {
  6384. throw new DeveloperError('near is required.');
  6385. }
  6386. if (!defined(far)) {
  6387. throw new DeveloperError('far is required.');
  6388. }
  6389. if (!defined(result)) {
  6390. throw new DeveloperError('result is required');
  6391. }
  6392. var column0Row0 = 2.0 * near / (right - left);
  6393. var column1Row1 = 2.0 * near / (top - bottom);
  6394. var column2Row0 = (right + left) / (right - left);
  6395. var column2Row1 = (top + bottom) / (top - bottom);
  6396. var column2Row2 = -(far + near) / (far - near);
  6397. var column2Row3 = -1.0;
  6398. var column3Row2 = -2.0 * far * near / (far - near);
  6399. result[0] = column0Row0;
  6400. result[1] = 0.0;
  6401. result[2] = 0.0;
  6402. result[3] = 0.0;
  6403. result[4] = 0.0;
  6404. result[5] = column1Row1;
  6405. result[6] = 0.0;
  6406. result[7] = 0.0;
  6407. result[8] = column2Row0;
  6408. result[9] = column2Row1;
  6409. result[10] = column2Row2;
  6410. result[11] = column2Row3;
  6411. result[12] = 0.0;
  6412. result[13] = 0.0;
  6413. result[14] = column3Row2;
  6414. result[15] = 0.0;
  6415. return result;
  6416. };
  6417. /**
  6418. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  6419. *
  6420. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6421. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6422. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6423. * @param {Number} top The number of meters above of the camera that will be in view.
  6424. * @param {Number} near The distance to the near plane in meters.
  6425. * @param {Matrix4} result The object in which the result will be stored.
  6426. * @returns {Matrix4} The modified result parameter.
  6427. */
  6428. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  6429. if (!defined(left)) {
  6430. throw new DeveloperError('left is required.');
  6431. }
  6432. if (!defined(right)) {
  6433. throw new DeveloperError('right is required.');
  6434. }
  6435. if (!defined(bottom)) {
  6436. throw new DeveloperError('bottom is required.');
  6437. }
  6438. if (!defined(top)) {
  6439. throw new DeveloperError('top is required.');
  6440. }
  6441. if (!defined(near)) {
  6442. throw new DeveloperError('near is required.');
  6443. }
  6444. if (!defined(result)) {
  6445. throw new DeveloperError('result is required');
  6446. }
  6447. var column0Row0 = 2.0 * near / (right - left);
  6448. var column1Row1 = 2.0 * near / (top - bottom);
  6449. var column2Row0 = (right + left) / (right - left);
  6450. var column2Row1 = (top + bottom) / (top - bottom);
  6451. var column2Row2 = -1.0;
  6452. var column2Row3 = -1.0;
  6453. var column3Row2 = -2.0 * near;
  6454. result[0] = column0Row0;
  6455. result[1] = 0.0;
  6456. result[2] = 0.0;
  6457. result[3] = 0.0;
  6458. result[4] = 0.0;
  6459. result[5] = column1Row1;
  6460. result[6] = 0.0;
  6461. result[7] = 0.0;
  6462. result[8] = column2Row0;
  6463. result[9] = column2Row1;
  6464. result[10] = column2Row2;
  6465. result[11] = column2Row3;
  6466. result[12] = 0.0;
  6467. result[13] = 0.0;
  6468. result[14] = column3Row2;
  6469. result[15] = 0.0;
  6470. return result;
  6471. };
  6472. /**
  6473. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  6474. *
  6475. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  6476. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  6477. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  6478. * @param {Matrix4} result The object in which the result will be stored.
  6479. * @returns {Matrix4} The modified result parameter.
  6480. *
  6481. * @example
  6482. * // Create viewport transformation using an explicit viewport and depth range.
  6483. * var m = Cesium.Matrix4.computeViewportTransformation({
  6484. * x : 0.0,
  6485. * y : 0.0,
  6486. * width : 1024.0,
  6487. * height : 768.0
  6488. * }, 0.0, 1.0, new Cesium.Matrix4());
  6489. */
  6490. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  6491. if (!defined(result)) {
  6492. throw new DeveloperError('result is required');
  6493. }
  6494. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  6495. var x = defaultValue(viewport.x, 0.0);
  6496. var y = defaultValue(viewport.y, 0.0);
  6497. var width = defaultValue(viewport.width, 0.0);
  6498. var height = defaultValue(viewport.height, 0.0);
  6499. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  6500. farDepthRange = defaultValue(farDepthRange, 1.0);
  6501. var halfWidth = width * 0.5;
  6502. var halfHeight = height * 0.5;
  6503. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  6504. var column0Row0 = halfWidth;
  6505. var column1Row1 = halfHeight;
  6506. var column2Row2 = halfDepth;
  6507. var column3Row0 = x + halfWidth;
  6508. var column3Row1 = y + halfHeight;
  6509. var column3Row2 = nearDepthRange + halfDepth;
  6510. var column3Row3 = 1.0;
  6511. result[0] = column0Row0;
  6512. result[1] = 0.0;
  6513. result[2] = 0.0;
  6514. result[3] = 0.0;
  6515. result[4] = 0.0;
  6516. result[5] = column1Row1;
  6517. result[6] = 0.0;
  6518. result[7] = 0.0;
  6519. result[8] = 0.0;
  6520. result[9] = 0.0;
  6521. result[10] = column2Row2;
  6522. result[11] = 0.0;
  6523. result[12] = column3Row0;
  6524. result[13] = column3Row1;
  6525. result[14] = column3Row2;
  6526. result[15] = column3Row3;
  6527. return result;
  6528. };
  6529. /**
  6530. * Computes a Matrix4 instance that transforms from world space to view space.
  6531. *
  6532. * @param {Cartesian3} position The position of the camera.
  6533. * @param {Cartesian3} direction The forward direction.
  6534. * @param {Cartesian3} up The up direction.
  6535. * @param {Cartesian3} right The right direction.
  6536. * @param {Matrix4} result The object in which the result will be stored.
  6537. * @returns {Matrix4} The modified result parameter.
  6538. */
  6539. Matrix4.computeView = function(position, direction, up, right, result) {
  6540. if (!defined(position)) {
  6541. throw new DeveloperError('position is required');
  6542. }
  6543. if (!defined(direction)) {
  6544. throw new DeveloperError('direction is required');
  6545. }
  6546. if (!defined(up)) {
  6547. throw new DeveloperError('up is required');
  6548. }
  6549. if (!defined(right)) {
  6550. throw new DeveloperError('right is required');
  6551. }
  6552. if (!defined(result)) {
  6553. throw new DeveloperError('result is required');
  6554. }
  6555. result[0] = right.x;
  6556. result[1] = up.x;
  6557. result[2] = -direction.x;
  6558. result[3] = 0.0;
  6559. result[4] = right.y;
  6560. result[5] = up.y;
  6561. result[6] = -direction.y;
  6562. result[7] = 0.0;
  6563. result[8] = right.z;
  6564. result[9] = up.z;
  6565. result[10] = -direction.z;
  6566. result[11] = 0.0;
  6567. result[12] = -Cartesian3.dot(right, position);
  6568. result[13] = -Cartesian3.dot(up, position);
  6569. result[14] = Cartesian3.dot(direction, position);
  6570. result[15] = 1.0;
  6571. return result;
  6572. };
  6573. /**
  6574. * Computes an Array from the provided Matrix4 instance.
  6575. * The array will be in column-major order.
  6576. *
  6577. * @param {Matrix4} matrix The matrix to use..
  6578. * @param {Number[]} [result] The Array onto which to store the result.
  6579. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  6580. *
  6581. * @example
  6582. * //create an array from an instance of Matrix4
  6583. * // m = [10.0, 14.0, 18.0, 22.0]
  6584. * // [11.0, 15.0, 19.0, 23.0]
  6585. * // [12.0, 16.0, 20.0, 24.0]
  6586. * // [13.0, 17.0, 21.0, 25.0]
  6587. * var a = Cesium.Matrix4.toArray(m);
  6588. *
  6589. * // m remains the same
  6590. * //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]
  6591. */
  6592. Matrix4.toArray = function(matrix, result) {
  6593. if (!defined(matrix)) {
  6594. throw new DeveloperError('matrix is required');
  6595. }
  6596. if (!defined(result)) {
  6597. return [matrix[0], matrix[1], matrix[2], matrix[3],
  6598. matrix[4], matrix[5], matrix[6], matrix[7],
  6599. matrix[8], matrix[9], matrix[10], matrix[11],
  6600. matrix[12], matrix[13], matrix[14], matrix[15]];
  6601. }
  6602. result[0] = matrix[0];
  6603. result[1] = matrix[1];
  6604. result[2] = matrix[2];
  6605. result[3] = matrix[3];
  6606. result[4] = matrix[4];
  6607. result[5] = matrix[5];
  6608. result[6] = matrix[6];
  6609. result[7] = matrix[7];
  6610. result[8] = matrix[8];
  6611. result[9] = matrix[9];
  6612. result[10] = matrix[10];
  6613. result[11] = matrix[11];
  6614. result[12] = matrix[12];
  6615. result[13] = matrix[13];
  6616. result[14] = matrix[14];
  6617. result[15] = matrix[15];
  6618. return result;
  6619. };
  6620. /**
  6621. * Computes the array index of the element at the provided row and column.
  6622. *
  6623. * @param {Number} row The zero-based index of the row.
  6624. * @param {Number} column The zero-based index of the column.
  6625. * @returns {Number} The index of the element at the provided row and column.
  6626. *
  6627. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  6628. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  6629. *
  6630. * @example
  6631. * var myMatrix = new Cesium.Matrix4();
  6632. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  6633. * var column1Row0 = myMatrix[column1Row0Index];
  6634. * myMatrix[column1Row0Index] = 10.0;
  6635. */
  6636. Matrix4.getElementIndex = function(column, row) {
  6637. if (typeof row !== 'number' || row < 0 || row > 3) {
  6638. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  6639. }
  6640. if (typeof column !== 'number' || column < 0 || column > 3) {
  6641. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  6642. }
  6643. return column * 4 + row;
  6644. };
  6645. /**
  6646. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  6647. *
  6648. * @param {Matrix4} matrix The matrix to use.
  6649. * @param {Number} index The zero-based index of the column to retrieve.
  6650. * @param {Cartesian4} result The object onto which to store the result.
  6651. * @returns {Cartesian4} The modified result parameter.
  6652. *
  6653. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6654. *
  6655. * @example
  6656. * //returns a Cartesian4 instance with values from the specified column
  6657. * // m = [10.0, 11.0, 12.0, 13.0]
  6658. * // [14.0, 15.0, 16.0, 17.0]
  6659. * // [18.0, 19.0, 20.0, 21.0]
  6660. * // [22.0, 23.0, 24.0, 25.0]
  6661. *
  6662. * //Example 1: Creates an instance of Cartesian
  6663. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  6664. *
  6665. * @example
  6666. * //Example 2: Sets values for Cartesian instance
  6667. * var a = new Cesium.Cartesian4();
  6668. * Cesium.Matrix4.getColumn(m, 2, a);
  6669. *
  6670. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  6671. */
  6672. Matrix4.getColumn = function(matrix, index, result) {
  6673. if (!defined(matrix)) {
  6674. throw new DeveloperError('matrix is required.');
  6675. }
  6676. if (typeof index !== 'number' || index < 0 || index > 3) {
  6677. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6678. }
  6679. if (!defined(result)) {
  6680. throw new DeveloperError('result is required');
  6681. }
  6682. var startIndex = index * 4;
  6683. var x = matrix[startIndex];
  6684. var y = matrix[startIndex + 1];
  6685. var z = matrix[startIndex + 2];
  6686. var w = matrix[startIndex + 3];
  6687. result.x = x;
  6688. result.y = y;
  6689. result.z = z;
  6690. result.w = w;
  6691. return result;
  6692. };
  6693. /**
  6694. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  6695. *
  6696. * @param {Matrix4} matrix The matrix to use.
  6697. * @param {Number} index The zero-based index of the column to set.
  6698. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  6699. * @param {Matrix4} result The object onto which to store the result.
  6700. * @returns {Matrix4} The modified result parameter.
  6701. *
  6702. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6703. *
  6704. * @example
  6705. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  6706. * // m = [10.0, 11.0, 12.0, 13.0]
  6707. * // [14.0, 15.0, 16.0, 17.0]
  6708. * // [18.0, 19.0, 20.0, 21.0]
  6709. * // [22.0, 23.0, 24.0, 25.0]
  6710. *
  6711. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6712. *
  6713. * // m remains the same
  6714. * // a = [10.0, 11.0, 99.0, 13.0]
  6715. * // [14.0, 15.0, 98.0, 17.0]
  6716. * // [18.0, 19.0, 97.0, 21.0]
  6717. * // [22.0, 23.0, 96.0, 25.0]
  6718. */
  6719. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  6720. if (!defined(matrix)) {
  6721. throw new DeveloperError('matrix is required');
  6722. }
  6723. if (!defined(cartesian)) {
  6724. throw new DeveloperError('cartesian is required');
  6725. }
  6726. if (typeof index !== 'number' || index < 0 || index > 3) {
  6727. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6728. }
  6729. if (!defined(result)) {
  6730. throw new DeveloperError('result is required');
  6731. }
  6732. result = Matrix4.clone(matrix, result);
  6733. var startIndex = index * 4;
  6734. result[startIndex] = cartesian.x;
  6735. result[startIndex + 1] = cartesian.y;
  6736. result[startIndex + 2] = cartesian.z;
  6737. result[startIndex + 3] = cartesian.w;
  6738. return result;
  6739. };
  6740. /**
  6741. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  6742. * matrix with the provided translation. This assumes the matrix is an affine transformation
  6743. *
  6744. * @param {Matrix4} matrix The matrix to use.
  6745. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  6746. * @param {Cartesian4} result The object onto which to store the result.
  6747. * @returns {Matrix4} The modified result parameter.
  6748. */
  6749. Matrix4.setTranslation = function(matrix, translation, result) {
  6750. if (!defined(matrix)) {
  6751. throw new DeveloperError('matrix is required');
  6752. }
  6753. if (!defined(translation)) {
  6754. throw new DeveloperError('translation is required');
  6755. }
  6756. if (!defined(result)) {
  6757. throw new DeveloperError('result is required');
  6758. }
  6759. result[0] = matrix[0];
  6760. result[1] = matrix[1];
  6761. result[2] = matrix[2];
  6762. result[3] = matrix[3];
  6763. result[4] = matrix[4];
  6764. result[5] = matrix[5];
  6765. result[6] = matrix[6];
  6766. result[7] = matrix[7];
  6767. result[8] = matrix[8];
  6768. result[9] = matrix[9];
  6769. result[10] = matrix[10];
  6770. result[11] = matrix[11];
  6771. result[12] = translation.x;
  6772. result[13] = translation.y;
  6773. result[14] = translation.z;
  6774. result[15] = matrix[15];
  6775. return result;
  6776. };
  6777. /**
  6778. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  6779. *
  6780. * @param {Matrix4} matrix The matrix to use.
  6781. * @param {Number} index The zero-based index of the row to retrieve.
  6782. * @param {Cartesian4} result The object onto which to store the result.
  6783. * @returns {Cartesian4} The modified result parameter.
  6784. *
  6785. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6786. *
  6787. * @example
  6788. * //returns a Cartesian4 instance with values from the specified column
  6789. * // m = [10.0, 11.0, 12.0, 13.0]
  6790. * // [14.0, 15.0, 16.0, 17.0]
  6791. * // [18.0, 19.0, 20.0, 21.0]
  6792. * // [22.0, 23.0, 24.0, 25.0]
  6793. *
  6794. * //Example 1: Returns an instance of Cartesian
  6795. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  6796. *
  6797. * @example
  6798. * //Example 2: Sets values for a Cartesian instance
  6799. * var a = new Cesium.Cartesian4();
  6800. * Cesium.Matrix4.getRow(m, 2, a);
  6801. *
  6802. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  6803. */
  6804. Matrix4.getRow = function(matrix, index, result) {
  6805. if (!defined(matrix)) {
  6806. throw new DeveloperError('matrix is required.');
  6807. }
  6808. if (typeof index !== 'number' || index < 0 || index > 3) {
  6809. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6810. }
  6811. if (!defined(result)) {
  6812. throw new DeveloperError('result is required');
  6813. }
  6814. var x = matrix[index];
  6815. var y = matrix[index + 4];
  6816. var z = matrix[index + 8];
  6817. var w = matrix[index + 12];
  6818. result.x = x;
  6819. result.y = y;
  6820. result.z = z;
  6821. result.w = w;
  6822. return result;
  6823. };
  6824. /**
  6825. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  6826. *
  6827. * @param {Matrix4} matrix The matrix to use.
  6828. * @param {Number} index The zero-based index of the row to set.
  6829. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  6830. * @param {Matrix4} result The object onto which to store the result.
  6831. * @returns {Matrix4} The modified result parameter.
  6832. *
  6833. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6834. *
  6835. * @example
  6836. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  6837. * // m = [10.0, 11.0, 12.0, 13.0]
  6838. * // [14.0, 15.0, 16.0, 17.0]
  6839. * // [18.0, 19.0, 20.0, 21.0]
  6840. * // [22.0, 23.0, 24.0, 25.0]
  6841. *
  6842. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6843. *
  6844. * // m remains the same
  6845. * // a = [10.0, 11.0, 12.0, 13.0]
  6846. * // [14.0, 15.0, 16.0, 17.0]
  6847. * // [99.0, 98.0, 97.0, 96.0]
  6848. * // [22.0, 23.0, 24.0, 25.0]
  6849. */
  6850. Matrix4.setRow = function(matrix, index, cartesian, result) {
  6851. if (!defined(matrix)) {
  6852. throw new DeveloperError('matrix is required');
  6853. }
  6854. if (!defined(cartesian)) {
  6855. throw new DeveloperError('cartesian is required');
  6856. }
  6857. if (typeof index !== 'number' || index < 0 || index > 3) {
  6858. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6859. }
  6860. if (!defined(result)) {
  6861. throw new DeveloperError('result is required');
  6862. }
  6863. result = Matrix4.clone(matrix, result);
  6864. result[index] = cartesian.x;
  6865. result[index + 4] = cartesian.y;
  6866. result[index + 8] = cartesian.z;
  6867. result[index + 12] = cartesian.w;
  6868. return result;
  6869. };
  6870. var scratchColumn = new Cartesian3();
  6871. /**
  6872. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  6873. *
  6874. * @param {Matrix4} matrix The matrix.
  6875. * @param {Cartesian3} result The object onto which to store the result.
  6876. * @returns {Cartesian3} The modified result parameter
  6877. */
  6878. Matrix4.getScale = function(matrix, result) {
  6879. if (!defined(matrix)) {
  6880. throw new DeveloperError('matrix is required.');
  6881. }
  6882. if (!defined(result)) {
  6883. throw new DeveloperError('result is required');
  6884. }
  6885. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  6886. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  6887. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  6888. return result;
  6889. };
  6890. var scratchScale = new Cartesian3();
  6891. /**
  6892. * Computes the maximum scale assuming the matrix is an affine transformation.
  6893. * The maximum scale is the maximum length of the column vectors in the upper-left
  6894. * 3x3 matrix.
  6895. *
  6896. * @param {Matrix4} matrix The matrix.
  6897. * @returns {Number} The maximum scale.
  6898. */
  6899. Matrix4.getMaximumScale = function(matrix) {
  6900. Matrix4.getScale(matrix, scratchScale);
  6901. return Cartesian3.maximumComponent(scratchScale);
  6902. };
  6903. /**
  6904. * Computes the product of two matrices.
  6905. *
  6906. * @param {Matrix4} left The first matrix.
  6907. * @param {Matrix4} right The second matrix.
  6908. * @param {Matrix4} result The object onto which to store the result.
  6909. * @returns {Matrix4} The modified result parameter.
  6910. */
  6911. Matrix4.multiply = function(left, right, result) {
  6912. if (!defined(left)) {
  6913. throw new DeveloperError('left is required');
  6914. }
  6915. if (!defined(right)) {
  6916. throw new DeveloperError('right is required');
  6917. }
  6918. if (!defined(result)) {
  6919. throw new DeveloperError('result is required');
  6920. }
  6921. var left0 = left[0];
  6922. var left1 = left[1];
  6923. var left2 = left[2];
  6924. var left3 = left[3];
  6925. var left4 = left[4];
  6926. var left5 = left[5];
  6927. var left6 = left[6];
  6928. var left7 = left[7];
  6929. var left8 = left[8];
  6930. var left9 = left[9];
  6931. var left10 = left[10];
  6932. var left11 = left[11];
  6933. var left12 = left[12];
  6934. var left13 = left[13];
  6935. var left14 = left[14];
  6936. var left15 = left[15];
  6937. var right0 = right[0];
  6938. var right1 = right[1];
  6939. var right2 = right[2];
  6940. var right3 = right[3];
  6941. var right4 = right[4];
  6942. var right5 = right[5];
  6943. var right6 = right[6];
  6944. var right7 = right[7];
  6945. var right8 = right[8];
  6946. var right9 = right[9];
  6947. var right10 = right[10];
  6948. var right11 = right[11];
  6949. var right12 = right[12];
  6950. var right13 = right[13];
  6951. var right14 = right[14];
  6952. var right15 = right[15];
  6953. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  6954. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  6955. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  6956. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  6957. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  6958. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  6959. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  6960. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  6961. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  6962. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  6963. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  6964. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  6965. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  6966. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  6967. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  6968. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  6969. result[0] = column0Row0;
  6970. result[1] = column0Row1;
  6971. result[2] = column0Row2;
  6972. result[3] = column0Row3;
  6973. result[4] = column1Row0;
  6974. result[5] = column1Row1;
  6975. result[6] = column1Row2;
  6976. result[7] = column1Row3;
  6977. result[8] = column2Row0;
  6978. result[9] = column2Row1;
  6979. result[10] = column2Row2;
  6980. result[11] = column2Row3;
  6981. result[12] = column3Row0;
  6982. result[13] = column3Row1;
  6983. result[14] = column3Row2;
  6984. result[15] = column3Row3;
  6985. return result;
  6986. };
  6987. /**
  6988. * Computes the sum of two matrices.
  6989. *
  6990. * @param {Matrix4} left The first matrix.
  6991. * @param {Matrix4} right The second matrix.
  6992. * @param {Matrix4} result The object onto which to store the result.
  6993. * @returns {Matrix4} The modified result parameter.
  6994. */
  6995. Matrix4.add = function(left, right, result) {
  6996. if (!defined(left)) {
  6997. throw new DeveloperError('left is required');
  6998. }
  6999. if (!defined(right)) {
  7000. throw new DeveloperError('right is required');
  7001. }
  7002. if (!defined(result)) {
  7003. throw new DeveloperError('result is required');
  7004. }
  7005. result[0] = left[0] + right[0];
  7006. result[1] = left[1] + right[1];
  7007. result[2] = left[2] + right[2];
  7008. result[3] = left[3] + right[3];
  7009. result[4] = left[4] + right[4];
  7010. result[5] = left[5] + right[5];
  7011. result[6] = left[6] + right[6];
  7012. result[7] = left[7] + right[7];
  7013. result[8] = left[8] + right[8];
  7014. result[9] = left[9] + right[9];
  7015. result[10] = left[10] + right[10];
  7016. result[11] = left[11] + right[11];
  7017. result[12] = left[12] + right[12];
  7018. result[13] = left[13] + right[13];
  7019. result[14] = left[14] + right[14];
  7020. result[15] = left[15] + right[15];
  7021. return result;
  7022. };
  7023. /**
  7024. * Computes the difference of two matrices.
  7025. *
  7026. * @param {Matrix4} left The first matrix.
  7027. * @param {Matrix4} right The second matrix.
  7028. * @param {Matrix4} result The object onto which to store the result.
  7029. * @returns {Matrix4} The modified result parameter.
  7030. */
  7031. Matrix4.subtract = function(left, right, result) {
  7032. if (!defined(left)) {
  7033. throw new DeveloperError('left is required');
  7034. }
  7035. if (!defined(right)) {
  7036. throw new DeveloperError('right is required');
  7037. }
  7038. if (!defined(result)) {
  7039. throw new DeveloperError('result is required');
  7040. }
  7041. result[0] = left[0] - right[0];
  7042. result[1] = left[1] - right[1];
  7043. result[2] = left[2] - right[2];
  7044. result[3] = left[3] - right[3];
  7045. result[4] = left[4] - right[4];
  7046. result[5] = left[5] - right[5];
  7047. result[6] = left[6] - right[6];
  7048. result[7] = left[7] - right[7];
  7049. result[8] = left[8] - right[8];
  7050. result[9] = left[9] - right[9];
  7051. result[10] = left[10] - right[10];
  7052. result[11] = left[11] - right[11];
  7053. result[12] = left[12] - right[12];
  7054. result[13] = left[13] - right[13];
  7055. result[14] = left[14] - right[14];
  7056. result[15] = left[15] - right[15];
  7057. return result;
  7058. };
  7059. /**
  7060. * Computes the product of two matrices assuming the matrices are
  7061. * affine transformation matrices, where the upper left 3x3 elements
  7062. * are a rotation matrix, and the upper three elements in the fourth
  7063. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  7064. * The matrix is not verified to be in the proper form.
  7065. * This method is faster than computing the product for general 4x4
  7066. * matrices using {@link Matrix4.multiply}.
  7067. *
  7068. * @param {Matrix4} left The first matrix.
  7069. * @param {Matrix4} right The second matrix.
  7070. * @param {Matrix4} result The object onto which to store the result.
  7071. * @returns {Matrix4} The modified result parameter.
  7072. *
  7073. * @example
  7074. * 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);
  7075. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  7076. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  7077. */
  7078. Matrix4.multiplyTransformation = function(left, right, result) {
  7079. if (!defined(left)) {
  7080. throw new DeveloperError('left is required');
  7081. }
  7082. if (!defined(right)) {
  7083. throw new DeveloperError('right is required');
  7084. }
  7085. if (!defined(result)) {
  7086. throw new DeveloperError('result is required');
  7087. }
  7088. var left0 = left[0];
  7089. var left1 = left[1];
  7090. var left2 = left[2];
  7091. var left4 = left[4];
  7092. var left5 = left[5];
  7093. var left6 = left[6];
  7094. var left8 = left[8];
  7095. var left9 = left[9];
  7096. var left10 = left[10];
  7097. var left12 = left[12];
  7098. var left13 = left[13];
  7099. var left14 = left[14];
  7100. var right0 = right[0];
  7101. var right1 = right[1];
  7102. var right2 = right[2];
  7103. var right4 = right[4];
  7104. var right5 = right[5];
  7105. var right6 = right[6];
  7106. var right8 = right[8];
  7107. var right9 = right[9];
  7108. var right10 = right[10];
  7109. var right12 = right[12];
  7110. var right13 = right[13];
  7111. var right14 = right[14];
  7112. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  7113. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  7114. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  7115. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  7116. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  7117. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  7118. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  7119. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  7120. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  7121. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  7122. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  7123. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  7124. result[0] = column0Row0;
  7125. result[1] = column0Row1;
  7126. result[2] = column0Row2;
  7127. result[3] = 0.0;
  7128. result[4] = column1Row0;
  7129. result[5] = column1Row1;
  7130. result[6] = column1Row2;
  7131. result[7] = 0.0;
  7132. result[8] = column2Row0;
  7133. result[9] = column2Row1;
  7134. result[10] = column2Row2;
  7135. result[11] = 0.0;
  7136. result[12] = column3Row0;
  7137. result[13] = column3Row1;
  7138. result[14] = column3Row2;
  7139. result[15] = 1.0;
  7140. return result;
  7141. };
  7142. /**
  7143. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7144. * by a 3x3 rotation matrix. This is an optimization
  7145. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  7146. *
  7147. * @param {Matrix4} matrix The matrix on the left-hand side.
  7148. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  7149. * @param {Matrix4} result The object onto which to store the result.
  7150. * @returns {Matrix4} The modified result parameter.
  7151. *
  7152. * @example
  7153. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  7154. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  7155. */
  7156. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  7157. if (!defined(matrix)) {
  7158. throw new DeveloperError('matrix is required');
  7159. }
  7160. if (!defined(rotation)) {
  7161. throw new DeveloperError('rotation is required');
  7162. }
  7163. if (!defined(result)) {
  7164. throw new DeveloperError('result is required');
  7165. }
  7166. var left0 = matrix[0];
  7167. var left1 = matrix[1];
  7168. var left2 = matrix[2];
  7169. var left4 = matrix[4];
  7170. var left5 = matrix[5];
  7171. var left6 = matrix[6];
  7172. var left8 = matrix[8];
  7173. var left9 = matrix[9];
  7174. var left10 = matrix[10];
  7175. var right0 = rotation[0];
  7176. var right1 = rotation[1];
  7177. var right2 = rotation[2];
  7178. var right4 = rotation[3];
  7179. var right5 = rotation[4];
  7180. var right6 = rotation[5];
  7181. var right8 = rotation[6];
  7182. var right9 = rotation[7];
  7183. var right10 = rotation[8];
  7184. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  7185. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  7186. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  7187. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  7188. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  7189. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  7190. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  7191. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  7192. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  7193. result[0] = column0Row0;
  7194. result[1] = column0Row1;
  7195. result[2] = column0Row2;
  7196. result[3] = 0.0;
  7197. result[4] = column1Row0;
  7198. result[5] = column1Row1;
  7199. result[6] = column1Row2;
  7200. result[7] = 0.0;
  7201. result[8] = column2Row0;
  7202. result[9] = column2Row1;
  7203. result[10] = column2Row2;
  7204. result[11] = 0.0;
  7205. result[12] = matrix[12];
  7206. result[13] = matrix[13];
  7207. result[14] = matrix[14];
  7208. result[15] = matrix[15];
  7209. return result;
  7210. };
  7211. /**
  7212. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7213. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  7214. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  7215. *
  7216. * @param {Matrix4} matrix The matrix on the left-hand side.
  7217. * @param {Cartesian3} translation The translation on the right-hand side.
  7218. * @param {Matrix4} result The object onto which to store the result.
  7219. * @returns {Matrix4} The modified result parameter.
  7220. *
  7221. * @example
  7222. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  7223. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  7224. */
  7225. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  7226. if (!defined(matrix)) {
  7227. throw new DeveloperError('matrix is required');
  7228. }
  7229. if (!defined(translation)) {
  7230. throw new DeveloperError('translation is required');
  7231. }
  7232. if (!defined(result)) {
  7233. throw new DeveloperError('result is required');
  7234. }
  7235. var x = translation.x;
  7236. var y = translation.y;
  7237. var z = translation.z;
  7238. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  7239. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  7240. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  7241. result[0] = matrix[0];
  7242. result[1] = matrix[1];
  7243. result[2] = matrix[2];
  7244. result[3] = matrix[3];
  7245. result[4] = matrix[4];
  7246. result[5] = matrix[5];
  7247. result[6] = matrix[6];
  7248. result[7] = matrix[7];
  7249. result[8] = matrix[8];
  7250. result[9] = matrix[9];
  7251. result[10] = matrix[10];
  7252. result[11] = matrix[11];
  7253. result[12] = tx;
  7254. result[13] = ty;
  7255. result[14] = tz;
  7256. result[15] = matrix[15];
  7257. return result;
  7258. };
  7259. var uniformScaleScratch = new Cartesian3();
  7260. /**
  7261. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7262. * by an implicit uniform scale matrix. This is an optimization
  7263. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7264. * <code>m</code> must be an affine matrix.
  7265. * This function performs fewer allocations and arithmetic operations.
  7266. *
  7267. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7268. * @param {Number} scale The uniform scale on the right-hand side.
  7269. * @param {Matrix4} result The object onto which to store the result.
  7270. * @returns {Matrix4} The modified result parameter.
  7271. *
  7272. *
  7273. * @example
  7274. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  7275. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  7276. *
  7277. * @see Matrix4.fromUniformScale
  7278. * @see Matrix4.multiplyByScale
  7279. */
  7280. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  7281. if (!defined(matrix)) {
  7282. throw new DeveloperError('matrix is required');
  7283. }
  7284. if (typeof scale !== 'number') {
  7285. throw new DeveloperError('scale is required');
  7286. }
  7287. if (!defined(result)) {
  7288. throw new DeveloperError('result is required');
  7289. }
  7290. uniformScaleScratch.x = scale;
  7291. uniformScaleScratch.y = scale;
  7292. uniformScaleScratch.z = scale;
  7293. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  7294. };
  7295. /**
  7296. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7297. * by an implicit non-uniform scale matrix. This is an optimization
  7298. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7299. * <code>m</code> must be an affine matrix.
  7300. * This function performs fewer allocations and arithmetic operations.
  7301. *
  7302. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7303. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  7304. * @param {Matrix4} result The object onto which to store the result.
  7305. * @returns {Matrix4} The modified result parameter.
  7306. *
  7307. *
  7308. * @example
  7309. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  7310. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  7311. *
  7312. * @see Matrix4.fromScale
  7313. * @see Matrix4.multiplyByUniformScale
  7314. */
  7315. Matrix4.multiplyByScale = function(matrix, scale, result) {
  7316. if (!defined(matrix)) {
  7317. throw new DeveloperError('matrix is required');
  7318. }
  7319. if (!defined(scale)) {
  7320. throw new DeveloperError('scale is required');
  7321. }
  7322. if (!defined(result)) {
  7323. throw new DeveloperError('result is required');
  7324. }
  7325. var scaleX = scale.x;
  7326. var scaleY = scale.y;
  7327. var scaleZ = scale.z;
  7328. // Faster than Cartesian3.equals
  7329. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  7330. return Matrix4.clone(matrix, result);
  7331. }
  7332. result[0] = scaleX * matrix[0];
  7333. result[1] = scaleX * matrix[1];
  7334. result[2] = scaleX * matrix[2];
  7335. result[3] = 0.0;
  7336. result[4] = scaleY * matrix[4];
  7337. result[5] = scaleY * matrix[5];
  7338. result[6] = scaleY * matrix[6];
  7339. result[7] = 0.0;
  7340. result[8] = scaleZ * matrix[8];
  7341. result[9] = scaleZ * matrix[9];
  7342. result[10] = scaleZ * matrix[10];
  7343. result[11] = 0.0;
  7344. result[12] = matrix[12];
  7345. result[13] = matrix[13];
  7346. result[14] = matrix[14];
  7347. result[15] = 1.0;
  7348. return result;
  7349. };
  7350. /**
  7351. * Computes the product of a matrix and a column vector.
  7352. *
  7353. * @param {Matrix4} matrix The matrix.
  7354. * @param {Cartesian4} cartesian The vector.
  7355. * @param {Cartesian4} result The object onto which to store the result.
  7356. * @returns {Cartesian4} The modified result parameter.
  7357. */
  7358. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  7359. if (!defined(matrix)) {
  7360. throw new DeveloperError('matrix is required');
  7361. }
  7362. if (!defined(cartesian)) {
  7363. throw new DeveloperError('cartesian is required');
  7364. }
  7365. if (!defined(result)) {
  7366. throw new DeveloperError('result is required');
  7367. }
  7368. var vX = cartesian.x;
  7369. var vY = cartesian.y;
  7370. var vZ = cartesian.z;
  7371. var vW = cartesian.w;
  7372. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  7373. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  7374. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  7375. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  7376. result.x = x;
  7377. result.y = y;
  7378. result.z = z;
  7379. result.w = w;
  7380. return result;
  7381. };
  7382. /**
  7383. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7384. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  7385. *
  7386. * @param {Matrix4} matrix The matrix.
  7387. * @param {Cartesian3} cartesian The point.
  7388. * @param {Cartesian3} result The object onto which to store the result.
  7389. * @returns {Cartesian3} The modified result parameter.
  7390. *
  7391. * @example
  7392. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7393. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  7394. * // A shortcut for
  7395. * // Cartesian3 p = ...
  7396. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  7397. */
  7398. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  7399. if (!defined(matrix)) {
  7400. throw new DeveloperError('matrix is required');
  7401. }
  7402. if (!defined(cartesian)) {
  7403. throw new DeveloperError('cartesian is required');
  7404. }
  7405. if (!defined(result)) {
  7406. throw new DeveloperError('result is required');
  7407. }
  7408. var vX = cartesian.x;
  7409. var vY = cartesian.y;
  7410. var vZ = cartesian.z;
  7411. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  7412. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  7413. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  7414. result.x = x;
  7415. result.y = y;
  7416. result.z = z;
  7417. return result;
  7418. };
  7419. /**
  7420. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7421. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  7422. *
  7423. * @param {Matrix4} matrix The matrix.
  7424. * @param {Cartesian3} cartesian The point.
  7425. * @param {Cartesian3} result The object onto which to store the result.
  7426. * @returns {Cartesian3} The modified result parameter.
  7427. *
  7428. * @example
  7429. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7430. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  7431. */
  7432. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  7433. if (!defined(matrix)) {
  7434. throw new DeveloperError('matrix is required');
  7435. }
  7436. if (!defined(cartesian)) {
  7437. throw new DeveloperError('cartesian is required');
  7438. }
  7439. if (!defined(result)) {
  7440. throw new DeveloperError('result is required');
  7441. }
  7442. var vX = cartesian.x;
  7443. var vY = cartesian.y;
  7444. var vZ = cartesian.z;
  7445. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  7446. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  7447. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  7448. result.x = x;
  7449. result.y = y;
  7450. result.z = z;
  7451. return result;
  7452. };
  7453. /**
  7454. * Computes the product of a matrix and a scalar.
  7455. *
  7456. * @param {Matrix4} matrix The matrix.
  7457. * @param {Number} scalar The number to multiply by.
  7458. * @param {Matrix4} result The object onto which to store the result.
  7459. * @returns {Matrix4} The modified result parameter.
  7460. *
  7461. * @example
  7462. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  7463. * // m = [10.0, 11.0, 12.0, 13.0]
  7464. * // [14.0, 15.0, 16.0, 17.0]
  7465. * // [18.0, 19.0, 20.0, 21.0]
  7466. * // [22.0, 23.0, 24.0, 25.0]
  7467. *
  7468. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  7469. *
  7470. * // m remains the same
  7471. * // a = [-20.0, -22.0, -24.0, -26.0]
  7472. * // [-28.0, -30.0, -32.0, -34.0]
  7473. * // [-36.0, -38.0, -40.0, -42.0]
  7474. * // [-44.0, -46.0, -48.0, -50.0]
  7475. */
  7476. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  7477. if (!defined(matrix)) {
  7478. throw new DeveloperError('matrix is required');
  7479. }
  7480. if (typeof scalar !== 'number') {
  7481. throw new DeveloperError('scalar must be a number');
  7482. }
  7483. if (!defined(result)) {
  7484. throw new DeveloperError('result is required');
  7485. }
  7486. result[0] = matrix[0] * scalar;
  7487. result[1] = matrix[1] * scalar;
  7488. result[2] = matrix[2] * scalar;
  7489. result[3] = matrix[3] * scalar;
  7490. result[4] = matrix[4] * scalar;
  7491. result[5] = matrix[5] * scalar;
  7492. result[6] = matrix[6] * scalar;
  7493. result[7] = matrix[7] * scalar;
  7494. result[8] = matrix[8] * scalar;
  7495. result[9] = matrix[9] * scalar;
  7496. result[10] = matrix[10] * scalar;
  7497. result[11] = matrix[11] * scalar;
  7498. result[12] = matrix[12] * scalar;
  7499. result[13] = matrix[13] * scalar;
  7500. result[14] = matrix[14] * scalar;
  7501. result[15] = matrix[15] * scalar;
  7502. return result;
  7503. };
  7504. /**
  7505. * Computes a negated copy of the provided matrix.
  7506. *
  7507. * @param {Matrix4} matrix The matrix to negate.
  7508. * @param {Matrix4} result The object onto which to store the result.
  7509. * @returns {Matrix4} The modified result parameter.
  7510. *
  7511. * @example
  7512. * //create a new Matrix4 instance which is a negation of a Matrix4
  7513. * // m = [10.0, 11.0, 12.0, 13.0]
  7514. * // [14.0, 15.0, 16.0, 17.0]
  7515. * // [18.0, 19.0, 20.0, 21.0]
  7516. * // [22.0, 23.0, 24.0, 25.0]
  7517. *
  7518. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  7519. *
  7520. * // m remains the same
  7521. * // a = [-10.0, -11.0, -12.0, -13.0]
  7522. * // [-14.0, -15.0, -16.0, -17.0]
  7523. * // [-18.0, -19.0, -20.0, -21.0]
  7524. * // [-22.0, -23.0, -24.0, -25.0]
  7525. */
  7526. Matrix4.negate = function(matrix, result) {
  7527. if (!defined(matrix)) {
  7528. throw new DeveloperError('matrix is required');
  7529. }
  7530. if (!defined(result)) {
  7531. throw new DeveloperError('result is required');
  7532. }
  7533. result[0] = -matrix[0];
  7534. result[1] = -matrix[1];
  7535. result[2] = -matrix[2];
  7536. result[3] = -matrix[3];
  7537. result[4] = -matrix[4];
  7538. result[5] = -matrix[5];
  7539. result[6] = -matrix[6];
  7540. result[7] = -matrix[7];
  7541. result[8] = -matrix[8];
  7542. result[9] = -matrix[9];
  7543. result[10] = -matrix[10];
  7544. result[11] = -matrix[11];
  7545. result[12] = -matrix[12];
  7546. result[13] = -matrix[13];
  7547. result[14] = -matrix[14];
  7548. result[15] = -matrix[15];
  7549. return result;
  7550. };
  7551. /**
  7552. * Computes the transpose of the provided matrix.
  7553. *
  7554. * @param {Matrix4} matrix The matrix to transpose.
  7555. * @param {Matrix4} result The object onto which to store the result.
  7556. * @returns {Matrix4} The modified result parameter.
  7557. *
  7558. * @example
  7559. * //returns transpose of a Matrix4
  7560. * // m = [10.0, 11.0, 12.0, 13.0]
  7561. * // [14.0, 15.0, 16.0, 17.0]
  7562. * // [18.0, 19.0, 20.0, 21.0]
  7563. * // [22.0, 23.0, 24.0, 25.0]
  7564. *
  7565. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  7566. *
  7567. * // m remains the same
  7568. * // a = [10.0, 14.0, 18.0, 22.0]
  7569. * // [11.0, 15.0, 19.0, 23.0]
  7570. * // [12.0, 16.0, 20.0, 24.0]
  7571. * // [13.0, 17.0, 21.0, 25.0]
  7572. */
  7573. Matrix4.transpose = function(matrix, result) {
  7574. if (!defined(matrix)) {
  7575. throw new DeveloperError('matrix is required');
  7576. }
  7577. if (!defined(result)) {
  7578. throw new DeveloperError('result is required');
  7579. }
  7580. var matrix1 = matrix[1];
  7581. var matrix2 = matrix[2];
  7582. var matrix3 = matrix[3];
  7583. var matrix6 = matrix[6];
  7584. var matrix7 = matrix[7];
  7585. var matrix11 = matrix[11];
  7586. result[0] = matrix[0];
  7587. result[1] = matrix[4];
  7588. result[2] = matrix[8];
  7589. result[3] = matrix[12];
  7590. result[4] = matrix1;
  7591. result[5] = matrix[5];
  7592. result[6] = matrix[9];
  7593. result[7] = matrix[13];
  7594. result[8] = matrix2;
  7595. result[9] = matrix6;
  7596. result[10] = matrix[10];
  7597. result[11] = matrix[14];
  7598. result[12] = matrix3;
  7599. result[13] = matrix7;
  7600. result[14] = matrix11;
  7601. result[15] = matrix[15];
  7602. return result;
  7603. };
  7604. /**
  7605. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  7606. *
  7607. * @param {Matrix4} matrix The matrix with signed elements.
  7608. * @param {Matrix4} result The object onto which to store the result.
  7609. * @returns {Matrix4} The modified result parameter.
  7610. */
  7611. Matrix4.abs = function(matrix, result) {
  7612. if (!defined(matrix)) {
  7613. throw new DeveloperError('matrix is required');
  7614. }
  7615. if (!defined(result)) {
  7616. throw new DeveloperError('result is required');
  7617. }
  7618. result[0] = Math.abs(matrix[0]);
  7619. result[1] = Math.abs(matrix[1]);
  7620. result[2] = Math.abs(matrix[2]);
  7621. result[3] = Math.abs(matrix[3]);
  7622. result[4] = Math.abs(matrix[4]);
  7623. result[5] = Math.abs(matrix[5]);
  7624. result[6] = Math.abs(matrix[6]);
  7625. result[7] = Math.abs(matrix[7]);
  7626. result[8] = Math.abs(matrix[8]);
  7627. result[9] = Math.abs(matrix[9]);
  7628. result[10] = Math.abs(matrix[10]);
  7629. result[11] = Math.abs(matrix[11]);
  7630. result[12] = Math.abs(matrix[12]);
  7631. result[13] = Math.abs(matrix[13]);
  7632. result[14] = Math.abs(matrix[14]);
  7633. result[15] = Math.abs(matrix[15]);
  7634. return result;
  7635. };
  7636. /**
  7637. * Compares the provided matrices componentwise and returns
  7638. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7639. *
  7640. * @param {Matrix4} [left] The first matrix.
  7641. * @param {Matrix4} [right] The second matrix.
  7642. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7643. *
  7644. * @example
  7645. * //compares two Matrix4 instances
  7646. *
  7647. * // a = [10.0, 14.0, 18.0, 22.0]
  7648. * // [11.0, 15.0, 19.0, 23.0]
  7649. * // [12.0, 16.0, 20.0, 24.0]
  7650. * // [13.0, 17.0, 21.0, 25.0]
  7651. *
  7652. * // b = [10.0, 14.0, 18.0, 22.0]
  7653. * // [11.0, 15.0, 19.0, 23.0]
  7654. * // [12.0, 16.0, 20.0, 24.0]
  7655. * // [13.0, 17.0, 21.0, 25.0]
  7656. *
  7657. * if(Cesium.Matrix4.equals(a,b)) {
  7658. * console.log("Both matrices are equal");
  7659. * } else {
  7660. * console.log("They are not equal");
  7661. * }
  7662. *
  7663. * //Prints "Both matrices are equal" on the console
  7664. */
  7665. Matrix4.equals = function(left, right) {
  7666. // Given that most matrices will be transformation matrices, the elements
  7667. // are tested in order such that the test is likely to fail as early
  7668. // as possible. I _think_ this is just as friendly to the L1 cache
  7669. // as testing in index order. It is certainty faster in practice.
  7670. return (left === right) ||
  7671. (defined(left) &&
  7672. defined(right) &&
  7673. // Translation
  7674. left[12] === right[12] &&
  7675. left[13] === right[13] &&
  7676. left[14] === right[14] &&
  7677. // Rotation/scale
  7678. left[0] === right[0] &&
  7679. left[1] === right[1] &&
  7680. left[2] === right[2] &&
  7681. left[4] === right[4] &&
  7682. left[5] === right[5] &&
  7683. left[6] === right[6] &&
  7684. left[8] === right[8] &&
  7685. left[9] === right[9] &&
  7686. left[10] === right[10] &&
  7687. // Bottom row
  7688. left[3] === right[3] &&
  7689. left[7] === right[7] &&
  7690. left[11] === right[11] &&
  7691. left[15] === right[15]);
  7692. };
  7693. /**
  7694. * Compares the provided matrices componentwise and returns
  7695. * <code>true</code> if they are within the provided epsilon,
  7696. * <code>false</code> otherwise.
  7697. *
  7698. * @param {Matrix4} [left] The first matrix.
  7699. * @param {Matrix4} [right] The second matrix.
  7700. * @param {Number} epsilon The epsilon to use for equality testing.
  7701. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7702. *
  7703. * @example
  7704. * //compares two Matrix4 instances
  7705. *
  7706. * // a = [10.5, 14.5, 18.5, 22.5]
  7707. * // [11.5, 15.5, 19.5, 23.5]
  7708. * // [12.5, 16.5, 20.5, 24.5]
  7709. * // [13.5, 17.5, 21.5, 25.5]
  7710. *
  7711. * // b = [10.0, 14.0, 18.0, 22.0]
  7712. * // [11.0, 15.0, 19.0, 23.0]
  7713. * // [12.0, 16.0, 20.0, 24.0]
  7714. * // [13.0, 17.0, 21.0, 25.0]
  7715. *
  7716. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  7717. * console.log("Difference between both the matrices is less than 0.1");
  7718. * } else {
  7719. * console.log("Difference between both the matrices is not less than 0.1");
  7720. * }
  7721. *
  7722. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  7723. */
  7724. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  7725. if (typeof epsilon !== 'number') {
  7726. throw new DeveloperError('epsilon must be a number');
  7727. }
  7728. return (left === right) ||
  7729. (defined(left) &&
  7730. defined(right) &&
  7731. Math.abs(left[0] - right[0]) <= epsilon &&
  7732. Math.abs(left[1] - right[1]) <= epsilon &&
  7733. Math.abs(left[2] - right[2]) <= epsilon &&
  7734. Math.abs(left[3] - right[3]) <= epsilon &&
  7735. Math.abs(left[4] - right[4]) <= epsilon &&
  7736. Math.abs(left[5] - right[5]) <= epsilon &&
  7737. Math.abs(left[6] - right[6]) <= epsilon &&
  7738. Math.abs(left[7] - right[7]) <= epsilon &&
  7739. Math.abs(left[8] - right[8]) <= epsilon &&
  7740. Math.abs(left[9] - right[9]) <= epsilon &&
  7741. Math.abs(left[10] - right[10]) <= epsilon &&
  7742. Math.abs(left[11] - right[11]) <= epsilon &&
  7743. Math.abs(left[12] - right[12]) <= epsilon &&
  7744. Math.abs(left[13] - right[13]) <= epsilon &&
  7745. Math.abs(left[14] - right[14]) <= epsilon &&
  7746. Math.abs(left[15] - right[15]) <= epsilon);
  7747. };
  7748. /**
  7749. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  7750. *
  7751. * @param {Matrix4} matrix The matrix to use.
  7752. * @param {Cartesian3} result The object onto which to store the result.
  7753. * @returns {Cartesian3} The modified result parameter.
  7754. */
  7755. Matrix4.getTranslation = function(matrix, result) {
  7756. if (!defined(matrix)) {
  7757. throw new DeveloperError('matrix is required');
  7758. }
  7759. if (!defined(result)) {
  7760. throw new DeveloperError('result is required');
  7761. }
  7762. result.x = matrix[12];
  7763. result.y = matrix[13];
  7764. result.z = matrix[14];
  7765. return result;
  7766. };
  7767. /**
  7768. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  7769. *
  7770. * @param {Matrix4} matrix The matrix to use.
  7771. * @param {Matrix3} result The object onto which to store the result.
  7772. * @returns {Matrix3} The modified result parameter.
  7773. *
  7774. * @example
  7775. * // returns a Matrix3 instance from a Matrix4 instance
  7776. *
  7777. * // m = [10.0, 14.0, 18.0, 22.0]
  7778. * // [11.0, 15.0, 19.0, 23.0]
  7779. * // [12.0, 16.0, 20.0, 24.0]
  7780. * // [13.0, 17.0, 21.0, 25.0]
  7781. *
  7782. * var b = new Cesium.Matrix3();
  7783. * Cesium.Matrix4.getRotation(m,b);
  7784. *
  7785. * // b = [10.0, 14.0, 18.0]
  7786. * // [11.0, 15.0, 19.0]
  7787. * // [12.0, 16.0, 20.0]
  7788. */
  7789. Matrix4.getRotation = function(matrix, result) {
  7790. if (!defined(matrix)) {
  7791. throw new DeveloperError('matrix is required');
  7792. }
  7793. if (!defined(result)) {
  7794. throw new DeveloperError('result is required');
  7795. }
  7796. result[0] = matrix[0];
  7797. result[1] = matrix[1];
  7798. result[2] = matrix[2];
  7799. result[3] = matrix[4];
  7800. result[4] = matrix[5];
  7801. result[5] = matrix[6];
  7802. result[6] = matrix[8];
  7803. result[7] = matrix[9];
  7804. result[8] = matrix[10];
  7805. return result;
  7806. };
  7807. var scratchInverseRotation = new Matrix3();
  7808. var scratchMatrix3Zero = new Matrix3();
  7809. var scratchBottomRow = new Cartesian4();
  7810. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  7811. /**
  7812. * Computes the inverse of the provided matrix using Cramers Rule.
  7813. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  7814. * If the matrix is an affine transformation matrix, it is more efficient
  7815. * to invert it with {@link Matrix4.inverseTransformation}.
  7816. *
  7817. * @param {Matrix4} matrix The matrix to invert.
  7818. * @param {Matrix4} result The object onto which to store the result.
  7819. * @returns {Matrix4} The modified result parameter.
  7820. *
  7821. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  7822. */
  7823. Matrix4.inverse = function(matrix, result) {
  7824. if (!defined(matrix)) {
  7825. throw new DeveloperError('matrix is required');
  7826. }
  7827. if (!defined(result)) {
  7828. throw new DeveloperError('result is required');
  7829. }
  7830. // Special case for a zero scale matrix that can occur, for example,
  7831. // when a model's node has a [0, 0, 0] scale.
  7832. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  7833. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  7834. result[0] = 0.0;
  7835. result[1] = 0.0;
  7836. result[2] = 0.0;
  7837. result[3] = 0.0;
  7838. result[4] = 0.0;
  7839. result[5] = 0.0;
  7840. result[6] = 0.0;
  7841. result[7] = 0.0;
  7842. result[8] = 0.0;
  7843. result[9] = 0.0;
  7844. result[10] = 0.0;
  7845. result[11] = 0.0;
  7846. result[12] = -matrix[12];
  7847. result[13] = -matrix[13];
  7848. result[14] = -matrix[14];
  7849. result[15] = 1.0;
  7850. return result;
  7851. }
  7852. //
  7853. // Ported from:
  7854. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  7855. //
  7856. var src0 = matrix[0];
  7857. var src1 = matrix[4];
  7858. var src2 = matrix[8];
  7859. var src3 = matrix[12];
  7860. var src4 = matrix[1];
  7861. var src5 = matrix[5];
  7862. var src6 = matrix[9];
  7863. var src7 = matrix[13];
  7864. var src8 = matrix[2];
  7865. var src9 = matrix[6];
  7866. var src10 = matrix[10];
  7867. var src11 = matrix[14];
  7868. var src12 = matrix[3];
  7869. var src13 = matrix[7];
  7870. var src14 = matrix[11];
  7871. var src15 = matrix[15];
  7872. // calculate pairs for first 8 elements (cofactors)
  7873. var tmp0 = src10 * src15;
  7874. var tmp1 = src11 * src14;
  7875. var tmp2 = src9 * src15;
  7876. var tmp3 = src11 * src13;
  7877. var tmp4 = src9 * src14;
  7878. var tmp5 = src10 * src13;
  7879. var tmp6 = src8 * src15;
  7880. var tmp7 = src11 * src12;
  7881. var tmp8 = src8 * src14;
  7882. var tmp9 = src10 * src12;
  7883. var tmp10 = src8 * src13;
  7884. var tmp11 = src9 * src12;
  7885. // calculate first 8 elements (cofactors)
  7886. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  7887. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  7888. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  7889. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  7890. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  7891. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  7892. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  7893. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  7894. // calculate pairs for second 8 elements (cofactors)
  7895. tmp0 = src2 * src7;
  7896. tmp1 = src3 * src6;
  7897. tmp2 = src1 * src7;
  7898. tmp3 = src3 * src5;
  7899. tmp4 = src1 * src6;
  7900. tmp5 = src2 * src5;
  7901. tmp6 = src0 * src7;
  7902. tmp7 = src3 * src4;
  7903. tmp8 = src0 * src6;
  7904. tmp9 = src2 * src4;
  7905. tmp10 = src0 * src5;
  7906. tmp11 = src1 * src4;
  7907. // calculate second 8 elements (cofactors)
  7908. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  7909. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  7910. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  7911. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  7912. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  7913. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  7914. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  7915. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  7916. // calculate determinant
  7917. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  7918. if (Math.abs(det) < CesiumMath.EPSILON20) {
  7919. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  7920. }
  7921. // calculate matrix inverse
  7922. det = 1.0 / det;
  7923. result[0] = dst0 * det;
  7924. result[1] = dst1 * det;
  7925. result[2] = dst2 * det;
  7926. result[3] = dst3 * det;
  7927. result[4] = dst4 * det;
  7928. result[5] = dst5 * det;
  7929. result[6] = dst6 * det;
  7930. result[7] = dst7 * det;
  7931. result[8] = dst8 * det;
  7932. result[9] = dst9 * det;
  7933. result[10] = dst10 * det;
  7934. result[11] = dst11 * det;
  7935. result[12] = dst12 * det;
  7936. result[13] = dst13 * det;
  7937. result[14] = dst14 * det;
  7938. result[15] = dst15 * det;
  7939. return result;
  7940. };
  7941. /**
  7942. * Computes the inverse of the provided matrix assuming it is
  7943. * an affine transformation matrix, where the upper left 3x3 elements
  7944. * are a rotation matrix, and the upper three elements in the fourth
  7945. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  7946. * The matrix is not verified to be in the proper form.
  7947. * This method is faster than computing the inverse for a general 4x4
  7948. * matrix using {@link Matrix4.inverse}.
  7949. *
  7950. * @param {Matrix4} matrix The matrix to invert.
  7951. * @param {Matrix4} result The object onto which to store the result.
  7952. * @returns {Matrix4} The modified result parameter.
  7953. */
  7954. Matrix4.inverseTransformation = function(matrix, result) {
  7955. if (!defined(matrix)) {
  7956. throw new DeveloperError('matrix is required');
  7957. }
  7958. if (!defined(result)) {
  7959. throw new DeveloperError('result is required');
  7960. }
  7961. //This function is an optimized version of the below 4 lines.
  7962. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  7963. //var rTN = Matrix3.negate(rT);
  7964. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  7965. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  7966. var matrix0 = matrix[0];
  7967. var matrix1 = matrix[1];
  7968. var matrix2 = matrix[2];
  7969. var matrix4 = matrix[4];
  7970. var matrix5 = matrix[5];
  7971. var matrix6 = matrix[6];
  7972. var matrix8 = matrix[8];
  7973. var matrix9 = matrix[9];
  7974. var matrix10 = matrix[10];
  7975. var vX = matrix[12];
  7976. var vY = matrix[13];
  7977. var vZ = matrix[14];
  7978. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  7979. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  7980. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  7981. result[0] = matrix0;
  7982. result[1] = matrix4;
  7983. result[2] = matrix8;
  7984. result[3] = 0.0;
  7985. result[4] = matrix1;
  7986. result[5] = matrix5;
  7987. result[6] = matrix9;
  7988. result[7] = 0.0;
  7989. result[8] = matrix2;
  7990. result[9] = matrix6;
  7991. result[10] = matrix10;
  7992. result[11] = 0.0;
  7993. result[12] = x;
  7994. result[13] = y;
  7995. result[14] = z;
  7996. result[15] = 1.0;
  7997. return result;
  7998. };
  7999. /**
  8000. * An immutable Matrix4 instance initialized to the identity matrix.
  8001. *
  8002. * @type {Matrix4}
  8003. * @constant
  8004. */
  8005. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  8006. 0.0, 1.0, 0.0, 0.0,
  8007. 0.0, 0.0, 1.0, 0.0,
  8008. 0.0, 0.0, 0.0, 1.0));
  8009. /**
  8010. * An immutable Matrix4 instance initialized to the zero matrix.
  8011. *
  8012. * @type {Matrix4}
  8013. * @constant
  8014. */
  8015. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  8016. 0.0, 0.0, 0.0, 0.0,
  8017. 0.0, 0.0, 0.0, 0.0,
  8018. 0.0, 0.0, 0.0, 0.0));
  8019. /**
  8020. * The index into Matrix4 for column 0, row 0.
  8021. *
  8022. * @type {Number}
  8023. * @constant
  8024. */
  8025. Matrix4.COLUMN0ROW0 = 0;
  8026. /**
  8027. * The index into Matrix4 for column 0, row 1.
  8028. *
  8029. * @type {Number}
  8030. * @constant
  8031. */
  8032. Matrix4.COLUMN0ROW1 = 1;
  8033. /**
  8034. * The index into Matrix4 for column 0, row 2.
  8035. *
  8036. * @type {Number}
  8037. * @constant
  8038. */
  8039. Matrix4.COLUMN0ROW2 = 2;
  8040. /**
  8041. * The index into Matrix4 for column 0, row 3.
  8042. *
  8043. * @type {Number}
  8044. * @constant
  8045. */
  8046. Matrix4.COLUMN0ROW3 = 3;
  8047. /**
  8048. * The index into Matrix4 for column 1, row 0.
  8049. *
  8050. * @type {Number}
  8051. * @constant
  8052. */
  8053. Matrix4.COLUMN1ROW0 = 4;
  8054. /**
  8055. * The index into Matrix4 for column 1, row 1.
  8056. *
  8057. * @type {Number}
  8058. * @constant
  8059. */
  8060. Matrix4.COLUMN1ROW1 = 5;
  8061. /**
  8062. * The index into Matrix4 for column 1, row 2.
  8063. *
  8064. * @type {Number}
  8065. * @constant
  8066. */
  8067. Matrix4.COLUMN1ROW2 = 6;
  8068. /**
  8069. * The index into Matrix4 for column 1, row 3.
  8070. *
  8071. * @type {Number}
  8072. * @constant
  8073. */
  8074. Matrix4.COLUMN1ROW3 = 7;
  8075. /**
  8076. * The index into Matrix4 for column 2, row 0.
  8077. *
  8078. * @type {Number}
  8079. * @constant
  8080. */
  8081. Matrix4.COLUMN2ROW0 = 8;
  8082. /**
  8083. * The index into Matrix4 for column 2, row 1.
  8084. *
  8085. * @type {Number}
  8086. * @constant
  8087. */
  8088. Matrix4.COLUMN2ROW1 = 9;
  8089. /**
  8090. * The index into Matrix4 for column 2, row 2.
  8091. *
  8092. * @type {Number}
  8093. * @constant
  8094. */
  8095. Matrix4.COLUMN2ROW2 = 10;
  8096. /**
  8097. * The index into Matrix4 for column 2, row 3.
  8098. *
  8099. * @type {Number}
  8100. * @constant
  8101. */
  8102. Matrix4.COLUMN2ROW3 = 11;
  8103. /**
  8104. * The index into Matrix4 for column 3, row 0.
  8105. *
  8106. * @type {Number}
  8107. * @constant
  8108. */
  8109. Matrix4.COLUMN3ROW0 = 12;
  8110. /**
  8111. * The index into Matrix4 for column 3, row 1.
  8112. *
  8113. * @type {Number}
  8114. * @constant
  8115. */
  8116. Matrix4.COLUMN3ROW1 = 13;
  8117. /**
  8118. * The index into Matrix4 for column 3, row 2.
  8119. *
  8120. * @type {Number}
  8121. * @constant
  8122. */
  8123. Matrix4.COLUMN3ROW2 = 14;
  8124. /**
  8125. * The index into Matrix4 for column 3, row 3.
  8126. *
  8127. * @type {Number}
  8128. * @constant
  8129. */
  8130. Matrix4.COLUMN3ROW3 = 15;
  8131. defineProperties(Matrix4.prototype, {
  8132. /**
  8133. * Gets the number of items in the collection.
  8134. * @memberof Matrix4.prototype
  8135. *
  8136. * @type {Number}
  8137. */
  8138. length : {
  8139. get : function() {
  8140. return Matrix4.packedLength;
  8141. }
  8142. }
  8143. });
  8144. /**
  8145. * Duplicates the provided Matrix4 instance.
  8146. *
  8147. * @param {Matrix4} [result] The object onto which to store the result.
  8148. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  8149. */
  8150. Matrix4.prototype.clone = function(result) {
  8151. return Matrix4.clone(this, result);
  8152. };
  8153. /**
  8154. * Compares this matrix to the provided matrix componentwise and returns
  8155. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8156. *
  8157. * @param {Matrix4} [right] The right hand side matrix.
  8158. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  8159. */
  8160. Matrix4.prototype.equals = function(right) {
  8161. return Matrix4.equals(this, right);
  8162. };
  8163. /**
  8164. * @private
  8165. */
  8166. Matrix4.equalsArray = function(matrix, array, offset) {
  8167. return matrix[0] === array[offset] &&
  8168. matrix[1] === array[offset + 1] &&
  8169. matrix[2] === array[offset + 2] &&
  8170. matrix[3] === array[offset + 3] &&
  8171. matrix[4] === array[offset + 4] &&
  8172. matrix[5] === array[offset + 5] &&
  8173. matrix[6] === array[offset + 6] &&
  8174. matrix[7] === array[offset + 7] &&
  8175. matrix[8] === array[offset + 8] &&
  8176. matrix[9] === array[offset + 9] &&
  8177. matrix[10] === array[offset + 10] &&
  8178. matrix[11] === array[offset + 11] &&
  8179. matrix[12] === array[offset + 12] &&
  8180. matrix[13] === array[offset + 13] &&
  8181. matrix[14] === array[offset + 14] &&
  8182. matrix[15] === array[offset + 15];
  8183. };
  8184. /**
  8185. * Compares this matrix to the provided matrix componentwise and returns
  8186. * <code>true</code> if they are within the provided epsilon,
  8187. * <code>false</code> otherwise.
  8188. *
  8189. * @param {Matrix4} [right] The right hand side matrix.
  8190. * @param {Number} epsilon The epsilon to use for equality testing.
  8191. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  8192. */
  8193. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  8194. return Matrix4.equalsEpsilon(this, right, epsilon);
  8195. };
  8196. /**
  8197. * Computes a string representing this Matrix with each row being
  8198. * on a separate line and in the format '(column0, column1, column2, column3)'.
  8199. *
  8200. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  8201. */
  8202. Matrix4.prototype.toString = function() {
  8203. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  8204. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  8205. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  8206. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  8207. };
  8208. return Matrix4;
  8209. });
  8210. /*global define*/
  8211. define('Core/Rectangle',[
  8212. './Cartographic',
  8213. './defaultValue',
  8214. './defined',
  8215. './defineProperties',
  8216. './DeveloperError',
  8217. './Ellipsoid',
  8218. './freezeObject',
  8219. './Math'
  8220. ], function(
  8221. Cartographic,
  8222. defaultValue,
  8223. defined,
  8224. defineProperties,
  8225. DeveloperError,
  8226. Ellipsoid,
  8227. freezeObject,
  8228. CesiumMath) {
  8229. 'use strict';
  8230. /**
  8231. * A two dimensional region specified as longitude and latitude coordinates.
  8232. *
  8233. * @alias Rectangle
  8234. * @constructor
  8235. *
  8236. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  8237. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8238. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  8239. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8240. *
  8241. * @see Packable
  8242. */
  8243. function Rectangle(west, south, east, north) {
  8244. /**
  8245. * The westernmost longitude in radians in the range [-Pi, Pi].
  8246. *
  8247. * @type {Number}
  8248. * @default 0.0
  8249. */
  8250. this.west = defaultValue(west, 0.0);
  8251. /**
  8252. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  8253. *
  8254. * @type {Number}
  8255. * @default 0.0
  8256. */
  8257. this.south = defaultValue(south, 0.0);
  8258. /**
  8259. * The easternmost longitude in radians in the range [-Pi, Pi].
  8260. *
  8261. * @type {Number}
  8262. * @default 0.0
  8263. */
  8264. this.east = defaultValue(east, 0.0);
  8265. /**
  8266. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  8267. *
  8268. * @type {Number}
  8269. * @default 0.0
  8270. */
  8271. this.north = defaultValue(north, 0.0);
  8272. }
  8273. defineProperties(Rectangle.prototype, {
  8274. /**
  8275. * Gets the width of the rectangle in radians.
  8276. * @memberof Rectangle.prototype
  8277. * @type {Number}
  8278. */
  8279. width : {
  8280. get : function() {
  8281. return Rectangle.computeWidth(this);
  8282. }
  8283. },
  8284. /**
  8285. * Gets the height of the rectangle in radians.
  8286. * @memberof Rectangle.prototype
  8287. * @type {Number}
  8288. */
  8289. height : {
  8290. get : function() {
  8291. return Rectangle.computeHeight(this);
  8292. }
  8293. }
  8294. });
  8295. /**
  8296. * The number of elements used to pack the object into an array.
  8297. * @type {Number}
  8298. */
  8299. Rectangle.packedLength = 4;
  8300. /**
  8301. * Stores the provided instance into the provided array.
  8302. *
  8303. * @param {Rectangle} value The value to pack.
  8304. * @param {Number[]} array The array to pack into.
  8305. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  8306. *
  8307. * @returns {Number[]} The array that was packed into
  8308. */
  8309. Rectangle.pack = function(value, array, startingIndex) {
  8310. if (!defined(value)) {
  8311. throw new DeveloperError('value is required');
  8312. }
  8313. if (!defined(array)) {
  8314. throw new DeveloperError('array is required');
  8315. }
  8316. startingIndex = defaultValue(startingIndex, 0);
  8317. array[startingIndex++] = value.west;
  8318. array[startingIndex++] = value.south;
  8319. array[startingIndex++] = value.east;
  8320. array[startingIndex] = value.north;
  8321. return array;
  8322. };
  8323. /**
  8324. * Retrieves an instance from a packed array.
  8325. *
  8326. * @param {Number[]} array The packed array.
  8327. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  8328. * @param {Rectangle} [result] The object into which to store the result.
  8329. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8330. */
  8331. Rectangle.unpack = function(array, startingIndex, result) {
  8332. if (!defined(array)) {
  8333. throw new DeveloperError('array is required');
  8334. }
  8335. startingIndex = defaultValue(startingIndex, 0);
  8336. if (!defined(result)) {
  8337. result = new Rectangle();
  8338. }
  8339. result.west = array[startingIndex++];
  8340. result.south = array[startingIndex++];
  8341. result.east = array[startingIndex++];
  8342. result.north = array[startingIndex];
  8343. return result;
  8344. };
  8345. /**
  8346. * Computes the width of a rectangle in radians.
  8347. * @param {Rectangle} rectangle The rectangle to compute the width of.
  8348. * @returns {Number} The width.
  8349. */
  8350. Rectangle.computeWidth = function(rectangle) {
  8351. if (!defined(rectangle)) {
  8352. throw new DeveloperError('rectangle is required.');
  8353. }
  8354. var east = rectangle.east;
  8355. var west = rectangle.west;
  8356. if (east < west) {
  8357. east += CesiumMath.TWO_PI;
  8358. }
  8359. return east - west;
  8360. };
  8361. /**
  8362. * Computes the height of a rectangle in radians.
  8363. * @param {Rectangle} rectangle The rectangle to compute the height of.
  8364. * @returns {Number} The height.
  8365. */
  8366. Rectangle.computeHeight = function(rectangle) {
  8367. if (!defined(rectangle)) {
  8368. throw new DeveloperError('rectangle is required.');
  8369. }
  8370. return rectangle.north - rectangle.south;
  8371. };
  8372. /**
  8373. * Creates an rectangle given the boundary longitude and latitude in degrees.
  8374. *
  8375. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  8376. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  8377. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  8378. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  8379. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8380. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8381. *
  8382. * @example
  8383. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  8384. */
  8385. Rectangle.fromDegrees = function(west, south, east, north, result) {
  8386. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  8387. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  8388. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  8389. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  8390. if (!defined(result)) {
  8391. return new Rectangle(west, south, east, north);
  8392. }
  8393. result.west = west;
  8394. result.south = south;
  8395. result.east = east;
  8396. result.north = north;
  8397. return result;
  8398. };
  8399. /**
  8400. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8401. *
  8402. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  8403. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8404. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8405. */
  8406. Rectangle.fromCartographicArray = function(cartographics, result) {
  8407. if (!defined(cartographics)) {
  8408. throw new DeveloperError('cartographics is required.');
  8409. }
  8410. var west = Number.MAX_VALUE;
  8411. var east = -Number.MAX_VALUE;
  8412. var westOverIDL = Number.MAX_VALUE;
  8413. var eastOverIDL = -Number.MAX_VALUE;
  8414. var south = Number.MAX_VALUE;
  8415. var north = -Number.MAX_VALUE;
  8416. for ( var i = 0, len = cartographics.length; i < len; i++) {
  8417. var position = cartographics[i];
  8418. west = Math.min(west, position.longitude);
  8419. east = Math.max(east, position.longitude);
  8420. south = Math.min(south, position.latitude);
  8421. north = Math.max(north, position.latitude);
  8422. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8423. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8424. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8425. }
  8426. if(east - west > eastOverIDL - westOverIDL) {
  8427. west = westOverIDL;
  8428. east = eastOverIDL;
  8429. if (east > CesiumMath.PI) {
  8430. east = east - CesiumMath.TWO_PI;
  8431. }
  8432. if (west > CesiumMath.PI) {
  8433. west = west - CesiumMath.TWO_PI;
  8434. }
  8435. }
  8436. if (!defined(result)) {
  8437. return new Rectangle(west, south, east, north);
  8438. }
  8439. result.west = west;
  8440. result.south = south;
  8441. result.east = east;
  8442. result.north = north;
  8443. return result;
  8444. };
  8445. /**
  8446. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8447. *
  8448. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  8449. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  8450. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8451. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8452. */
  8453. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  8454. if (!defined(cartesians)) {
  8455. throw new DeveloperError('cartesians is required.');
  8456. }
  8457. var west = Number.MAX_VALUE;
  8458. var east = -Number.MAX_VALUE;
  8459. var westOverIDL = Number.MAX_VALUE;
  8460. var eastOverIDL = -Number.MAX_VALUE;
  8461. var south = Number.MAX_VALUE;
  8462. var north = -Number.MAX_VALUE;
  8463. for ( var i = 0, len = cartesians.length; i < len; i++) {
  8464. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  8465. west = Math.min(west, position.longitude);
  8466. east = Math.max(east, position.longitude);
  8467. south = Math.min(south, position.latitude);
  8468. north = Math.max(north, position.latitude);
  8469. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8470. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8471. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8472. }
  8473. if(east - west > eastOverIDL - westOverIDL) {
  8474. west = westOverIDL;
  8475. east = eastOverIDL;
  8476. if (east > CesiumMath.PI) {
  8477. east = east - CesiumMath.TWO_PI;
  8478. }
  8479. if (west > CesiumMath.PI) {
  8480. west = west - CesiumMath.TWO_PI;
  8481. }
  8482. }
  8483. if (!defined(result)) {
  8484. return new Rectangle(west, south, east, north);
  8485. }
  8486. result.west = west;
  8487. result.south = south;
  8488. result.east = east;
  8489. result.north = north;
  8490. return result;
  8491. };
  8492. /**
  8493. * Duplicates an Rectangle.
  8494. *
  8495. * @param {Rectangle} rectangle The rectangle to clone.
  8496. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8497. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  8498. */
  8499. Rectangle.clone = function(rectangle, result) {
  8500. if (!defined(rectangle)) {
  8501. return undefined;
  8502. }
  8503. if (!defined(result)) {
  8504. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  8505. }
  8506. result.west = rectangle.west;
  8507. result.south = rectangle.south;
  8508. result.east = rectangle.east;
  8509. result.north = rectangle.north;
  8510. return result;
  8511. };
  8512. /**
  8513. * Duplicates this Rectangle.
  8514. *
  8515. * @param {Rectangle} [result] The object onto which to store the result.
  8516. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8517. */
  8518. Rectangle.prototype.clone = function(result) {
  8519. return Rectangle.clone(this, result);
  8520. };
  8521. /**
  8522. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8523. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8524. *
  8525. * @param {Rectangle} [other] The Rectangle to compare.
  8526. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  8527. */
  8528. Rectangle.prototype.equals = function(other) {
  8529. return Rectangle.equals(this, other);
  8530. };
  8531. /**
  8532. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  8533. * <code>false</code> otherwise.
  8534. *
  8535. * @param {Rectangle} [left] The first Rectangle.
  8536. * @param {Rectangle} [right] The second Rectangle.
  8537. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  8538. */
  8539. Rectangle.equals = function(left, right) {
  8540. return (left === right) ||
  8541. ((defined(left)) &&
  8542. (defined(right)) &&
  8543. (left.west === right.west) &&
  8544. (left.south === right.south) &&
  8545. (left.east === right.east) &&
  8546. (left.north === right.north));
  8547. };
  8548. /**
  8549. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8550. * <code>true</code> if they are within the provided epsilon,
  8551. * <code>false</code> otherwise.
  8552. *
  8553. * @param {Rectangle} [other] The Rectangle to compare.
  8554. * @param {Number} epsilon The epsilon to use for equality testing.
  8555. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  8556. */
  8557. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  8558. if (typeof epsilon !== 'number') {
  8559. throw new DeveloperError('epsilon is required and must be a number.');
  8560. }
  8561. return defined(other) &&
  8562. (Math.abs(this.west - other.west) <= epsilon) &&
  8563. (Math.abs(this.south - other.south) <= epsilon) &&
  8564. (Math.abs(this.east - other.east) <= epsilon) &&
  8565. (Math.abs(this.north - other.north) <= epsilon);
  8566. };
  8567. /**
  8568. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  8569. *
  8570. * @param {Rectangle} rectangle The rectangle to validate
  8571. *
  8572. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8573. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8574. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8575. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8576. */
  8577. Rectangle.validate = function(rectangle) {
  8578. if (!defined(rectangle)) {
  8579. throw new DeveloperError('rectangle is required');
  8580. }
  8581. var north = rectangle.north;
  8582. if (typeof north !== 'number') {
  8583. throw new DeveloperError('north is required to be a number.');
  8584. }
  8585. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  8586. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  8587. }
  8588. var south = rectangle.south;
  8589. if (typeof south !== 'number') {
  8590. throw new DeveloperError('south is required to be a number.');
  8591. }
  8592. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  8593. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  8594. }
  8595. var west = rectangle.west;
  8596. if (typeof west !== 'number') {
  8597. throw new DeveloperError('west is required to be a number.');
  8598. }
  8599. if (west < -Math.PI || west > Math.PI) {
  8600. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  8601. }
  8602. var east = rectangle.east;
  8603. if (typeof east !== 'number') {
  8604. throw new DeveloperError('east is required to be a number.');
  8605. }
  8606. if (east < -Math.PI || east > Math.PI) {
  8607. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  8608. }
  8609. };
  8610. /**
  8611. * Computes the southwest corner of an rectangle.
  8612. *
  8613. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8614. * @param {Cartographic} [result] The object onto which to store the result.
  8615. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8616. */
  8617. Rectangle.southwest = function(rectangle, result) {
  8618. if (!defined(rectangle)) {
  8619. throw new DeveloperError('rectangle is required');
  8620. }
  8621. if (!defined(result)) {
  8622. return new Cartographic(rectangle.west, rectangle.south);
  8623. }
  8624. result.longitude = rectangle.west;
  8625. result.latitude = rectangle.south;
  8626. result.height = 0.0;
  8627. return result;
  8628. };
  8629. /**
  8630. * Computes the northwest corner of an rectangle.
  8631. *
  8632. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8633. * @param {Cartographic} [result] The object onto which to store the result.
  8634. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8635. */
  8636. Rectangle.northwest = function(rectangle, result) {
  8637. if (!defined(rectangle)) {
  8638. throw new DeveloperError('rectangle is required');
  8639. }
  8640. if (!defined(result)) {
  8641. return new Cartographic(rectangle.west, rectangle.north);
  8642. }
  8643. result.longitude = rectangle.west;
  8644. result.latitude = rectangle.north;
  8645. result.height = 0.0;
  8646. return result;
  8647. };
  8648. /**
  8649. * Computes the northeast corner of an rectangle.
  8650. *
  8651. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8652. * @param {Cartographic} [result] The object onto which to store the result.
  8653. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8654. */
  8655. Rectangle.northeast = function(rectangle, result) {
  8656. if (!defined(rectangle)) {
  8657. throw new DeveloperError('rectangle is required');
  8658. }
  8659. if (!defined(result)) {
  8660. return new Cartographic(rectangle.east, rectangle.north);
  8661. }
  8662. result.longitude = rectangle.east;
  8663. result.latitude = rectangle.north;
  8664. result.height = 0.0;
  8665. return result;
  8666. };
  8667. /**
  8668. * Computes the southeast corner of an rectangle.
  8669. *
  8670. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8671. * @param {Cartographic} [result] The object onto which to store the result.
  8672. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8673. */
  8674. Rectangle.southeast = function(rectangle, result) {
  8675. if (!defined(rectangle)) {
  8676. throw new DeveloperError('rectangle is required');
  8677. }
  8678. if (!defined(result)) {
  8679. return new Cartographic(rectangle.east, rectangle.south);
  8680. }
  8681. result.longitude = rectangle.east;
  8682. result.latitude = rectangle.south;
  8683. result.height = 0.0;
  8684. return result;
  8685. };
  8686. /**
  8687. * Computes the center of an rectangle.
  8688. *
  8689. * @param {Rectangle} rectangle The rectangle for which to find the center
  8690. * @param {Cartographic} [result] The object onto which to store the result.
  8691. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8692. */
  8693. Rectangle.center = function(rectangle, result) {
  8694. if (!defined(rectangle)) {
  8695. throw new DeveloperError('rectangle is required');
  8696. }
  8697. var east = rectangle.east;
  8698. var west = rectangle.west;
  8699. if (east < west) {
  8700. east += CesiumMath.TWO_PI;
  8701. }
  8702. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  8703. var latitude = (rectangle.south + rectangle.north) * 0.5;
  8704. if (!defined(result)) {
  8705. return new Cartographic(longitude, latitude);
  8706. }
  8707. result.longitude = longitude;
  8708. result.latitude = latitude;
  8709. result.height = 0.0;
  8710. return result;
  8711. };
  8712. /**
  8713. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  8714. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  8715. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  8716. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  8717. * coordinates, see {@link Rectangle.simpleIntersection}.
  8718. *
  8719. * @param {Rectangle} rectangle On rectangle to find an intersection
  8720. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8721. * @param {Rectangle} [result] The object onto which to store the result.
  8722. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8723. */
  8724. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  8725. if (!defined(rectangle)) {
  8726. throw new DeveloperError('rectangle is required');
  8727. }
  8728. if (!defined(otherRectangle)) {
  8729. throw new DeveloperError('otherRectangle is required.');
  8730. }
  8731. var rectangleEast = rectangle.east;
  8732. var rectangleWest = rectangle.west;
  8733. var otherRectangleEast = otherRectangle.east;
  8734. var otherRectangleWest = otherRectangle.west;
  8735. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8736. rectangleEast += CesiumMath.TWO_PI;
  8737. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8738. otherRectangleEast += CesiumMath.TWO_PI;
  8739. }
  8740. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8741. otherRectangleWest += CesiumMath.TWO_PI;
  8742. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8743. rectangleWest += CesiumMath.TWO_PI;
  8744. }
  8745. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  8746. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  8747. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  8748. return undefined;
  8749. }
  8750. var south = Math.max(rectangle.south, otherRectangle.south);
  8751. var north = Math.min(rectangle.north, otherRectangle.north);
  8752. if (south >= north) {
  8753. return undefined;
  8754. }
  8755. if (!defined(result)) {
  8756. return new Rectangle(west, south, east, north);
  8757. }
  8758. result.west = west;
  8759. result.south = south;
  8760. result.east = east;
  8761. result.north = north;
  8762. return result;
  8763. };
  8764. /**
  8765. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  8766. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  8767. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  8768. * and longitude (i.e. projected coordinates).
  8769. *
  8770. * @param {Rectangle} rectangle On rectangle to find an intersection
  8771. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8772. * @param {Rectangle} [result] The object onto which to store the result.
  8773. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8774. */
  8775. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  8776. if (!defined(rectangle)) {
  8777. throw new DeveloperError('rectangle is required');
  8778. }
  8779. if (!defined(otherRectangle)) {
  8780. throw new DeveloperError('otherRectangle is required.');
  8781. }
  8782. var west = Math.max(rectangle.west, otherRectangle.west);
  8783. var south = Math.max(rectangle.south, otherRectangle.south);
  8784. var east = Math.min(rectangle.east, otherRectangle.east);
  8785. var north = Math.min(rectangle.north, otherRectangle.north);
  8786. if (south >= north || west >= east) {
  8787. return undefined;
  8788. }
  8789. if (!defined(result)) {
  8790. return new Rectangle(west, south, east, north);
  8791. }
  8792. result.west = west;
  8793. result.south = south;
  8794. result.east = east;
  8795. result.north = north;
  8796. return result;
  8797. };
  8798. /**
  8799. * Computes a rectangle that is the union of two rectangles.
  8800. *
  8801. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  8802. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  8803. * @param {Rectangle} [result] The object onto which to store the result.
  8804. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8805. */
  8806. Rectangle.union = function(rectangle, otherRectangle, result) {
  8807. if (!defined(rectangle)) {
  8808. throw new DeveloperError('rectangle is required');
  8809. }
  8810. if (!defined(otherRectangle)) {
  8811. throw new DeveloperError('otherRectangle is required.');
  8812. }
  8813. if (!defined(result)) {
  8814. result = new Rectangle();
  8815. }
  8816. var rectangleEast = rectangle.east;
  8817. var rectangleWest = rectangle.west;
  8818. var otherRectangleEast = otherRectangle.east;
  8819. var otherRectangleWest = otherRectangle.west;
  8820. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8821. rectangleEast += CesiumMath.TWO_PI;
  8822. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8823. otherRectangleEast += CesiumMath.TWO_PI;
  8824. }
  8825. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8826. otherRectangleWest += CesiumMath.TWO_PI;
  8827. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8828. rectangleWest += CesiumMath.TWO_PI;
  8829. }
  8830. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  8831. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  8832. result.west = west;
  8833. result.south = Math.min(rectangle.south, otherRectangle.south);
  8834. result.east = east;
  8835. result.north = Math.max(rectangle.north, otherRectangle.north);
  8836. return result;
  8837. };
  8838. /**
  8839. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  8840. *
  8841. * @param {Rectangle} rectangle A rectangle to expand.
  8842. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  8843. * @param {Rectangle} [result] The object onto which to store the result.
  8844. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8845. */
  8846. Rectangle.expand = function(rectangle, cartographic, result) {
  8847. if (!defined(rectangle)) {
  8848. throw new DeveloperError('rectangle is required.');
  8849. }
  8850. if (!defined(cartographic)) {
  8851. throw new DeveloperError('cartographic is required.');
  8852. }
  8853. if (!defined(result)) {
  8854. result = new Rectangle();
  8855. }
  8856. result.west = Math.min(rectangle.west, cartographic.longitude);
  8857. result.south = Math.min(rectangle.south, cartographic.latitude);
  8858. result.east = Math.max(rectangle.east, cartographic.longitude);
  8859. result.north = Math.max(rectangle.north, cartographic.latitude);
  8860. return result;
  8861. };
  8862. /**
  8863. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  8864. *
  8865. * @param {Rectangle} rectangle The rectangle
  8866. * @param {Cartographic} cartographic The cartographic to test.
  8867. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  8868. */
  8869. Rectangle.contains = function(rectangle, cartographic) {
  8870. if (!defined(rectangle)) {
  8871. throw new DeveloperError('rectangle is required');
  8872. }
  8873. if (!defined(cartographic)) {
  8874. throw new DeveloperError('cartographic is required.');
  8875. }
  8876. var longitude = cartographic.longitude;
  8877. var latitude = cartographic.latitude;
  8878. var west = rectangle.west;
  8879. var east = rectangle.east;
  8880. if (east < west) {
  8881. east += CesiumMath.TWO_PI;
  8882. if (longitude < 0.0) {
  8883. longitude += CesiumMath.TWO_PI;
  8884. }
  8885. }
  8886. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  8887. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  8888. latitude >= rectangle.south &&
  8889. latitude <= rectangle.north;
  8890. };
  8891. var subsampleLlaScratch = new Cartographic();
  8892. /**
  8893. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  8894. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  8895. * for rectangles that cover the poles or cross the equator.
  8896. *
  8897. * @param {Rectangle} rectangle The rectangle to subsample.
  8898. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  8899. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  8900. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  8901. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  8902. */
  8903. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  8904. if (!defined(rectangle)) {
  8905. throw new DeveloperError('rectangle is required');
  8906. }
  8907. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  8908. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  8909. if (!defined(result)) {
  8910. result = [];
  8911. }
  8912. var length = 0;
  8913. var north = rectangle.north;
  8914. var south = rectangle.south;
  8915. var east = rectangle.east;
  8916. var west = rectangle.west;
  8917. var lla = subsampleLlaScratch;
  8918. lla.height = surfaceHeight;
  8919. lla.longitude = west;
  8920. lla.latitude = north;
  8921. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8922. length++;
  8923. lla.longitude = east;
  8924. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8925. length++;
  8926. lla.latitude = south;
  8927. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8928. length++;
  8929. lla.longitude = west;
  8930. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8931. length++;
  8932. if (north < 0.0) {
  8933. lla.latitude = north;
  8934. } else if (south > 0.0) {
  8935. lla.latitude = south;
  8936. } else {
  8937. lla.latitude = 0.0;
  8938. }
  8939. for ( var i = 1; i < 8; ++i) {
  8940. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  8941. if (Rectangle.contains(rectangle, lla)) {
  8942. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8943. length++;
  8944. }
  8945. }
  8946. if (lla.latitude === 0.0) {
  8947. lla.longitude = west;
  8948. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8949. length++;
  8950. lla.longitude = east;
  8951. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8952. length++;
  8953. }
  8954. result.length = length;
  8955. return result;
  8956. };
  8957. /**
  8958. * The largest possible rectangle.
  8959. *
  8960. * @type {Rectangle}
  8961. * @constant
  8962. */
  8963. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  8964. return Rectangle;
  8965. });
  8966. /*global define*/
  8967. define('Core/BoundingSphere',[
  8968. './Cartesian3',
  8969. './Cartographic',
  8970. './defaultValue',
  8971. './defined',
  8972. './DeveloperError',
  8973. './Ellipsoid',
  8974. './GeographicProjection',
  8975. './Intersect',
  8976. './Interval',
  8977. './Matrix3',
  8978. './Matrix4',
  8979. './Rectangle'
  8980. ], function(
  8981. Cartesian3,
  8982. Cartographic,
  8983. defaultValue,
  8984. defined,
  8985. DeveloperError,
  8986. Ellipsoid,
  8987. GeographicProjection,
  8988. Intersect,
  8989. Interval,
  8990. Matrix3,
  8991. Matrix4,
  8992. Rectangle) {
  8993. 'use strict';
  8994. /**
  8995. * A bounding sphere with a center and a radius.
  8996. * @alias BoundingSphere
  8997. * @constructor
  8998. *
  8999. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  9000. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  9001. *
  9002. * @see AxisAlignedBoundingBox
  9003. * @see BoundingRectangle
  9004. * @see Packable
  9005. */
  9006. function BoundingSphere(center, radius) {
  9007. /**
  9008. * The center point of the sphere.
  9009. * @type {Cartesian3}
  9010. * @default {@link Cartesian3.ZERO}
  9011. */
  9012. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  9013. /**
  9014. * The radius of the sphere.
  9015. * @type {Number}
  9016. * @default 0.0
  9017. */
  9018. this.radius = defaultValue(radius, 0.0);
  9019. }
  9020. var fromPointsXMin = new Cartesian3();
  9021. var fromPointsYMin = new Cartesian3();
  9022. var fromPointsZMin = new Cartesian3();
  9023. var fromPointsXMax = new Cartesian3();
  9024. var fromPointsYMax = new Cartesian3();
  9025. var fromPointsZMax = new Cartesian3();
  9026. var fromPointsCurrentPos = new Cartesian3();
  9027. var fromPointsScratch = new Cartesian3();
  9028. var fromPointsRitterCenter = new Cartesian3();
  9029. var fromPointsMinBoxPt = new Cartesian3();
  9030. var fromPointsMaxBoxPt = new Cartesian3();
  9031. var fromPointsNaiveCenterScratch = new Cartesian3();
  9032. /**
  9033. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  9034. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  9035. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  9036. *
  9037. * @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.
  9038. * @param {BoundingSphere} [result] The object onto which to store the result.
  9039. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9040. *
  9041. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9042. */
  9043. BoundingSphere.fromPoints = function(positions, result) {
  9044. if (!defined(result)) {
  9045. result = new BoundingSphere();
  9046. }
  9047. if (!defined(positions) || positions.length === 0) {
  9048. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9049. result.radius = 0.0;
  9050. return result;
  9051. }
  9052. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  9053. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9054. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9055. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9056. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9057. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9058. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9059. var numPositions = positions.length;
  9060. for (var i = 1; i < numPositions; i++) {
  9061. Cartesian3.clone(positions[i], currentPos);
  9062. var x = currentPos.x;
  9063. var y = currentPos.y;
  9064. var z = currentPos.z;
  9065. // Store points containing the the smallest and largest components
  9066. if (x < xMin.x) {
  9067. Cartesian3.clone(currentPos, xMin);
  9068. }
  9069. if (x > xMax.x) {
  9070. Cartesian3.clone(currentPos, xMax);
  9071. }
  9072. if (y < yMin.y) {
  9073. Cartesian3.clone(currentPos, yMin);
  9074. }
  9075. if (y > yMax.y) {
  9076. Cartesian3.clone(currentPos, yMax);
  9077. }
  9078. if (z < zMin.z) {
  9079. Cartesian3.clone(currentPos, zMin);
  9080. }
  9081. if (z > zMax.z) {
  9082. Cartesian3.clone(currentPos, zMax);
  9083. }
  9084. }
  9085. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9086. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9087. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9088. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9089. // Set the diameter endpoints to the largest span.
  9090. var diameter1 = xMin;
  9091. var diameter2 = xMax;
  9092. var maxSpan = xSpan;
  9093. if (ySpan > maxSpan) {
  9094. maxSpan = ySpan;
  9095. diameter1 = yMin;
  9096. diameter2 = yMax;
  9097. }
  9098. if (zSpan > maxSpan) {
  9099. maxSpan = zSpan;
  9100. diameter1 = zMin;
  9101. diameter2 = zMax;
  9102. }
  9103. // Calculate the center of the initial sphere found by Ritter's algorithm
  9104. var ritterCenter = fromPointsRitterCenter;
  9105. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9106. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9107. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9108. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9109. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9110. var ritterRadius = Math.sqrt(radiusSquared);
  9111. // Find the center of the sphere found using the Naive method.
  9112. var minBoxPt = fromPointsMinBoxPt;
  9113. minBoxPt.x = xMin.x;
  9114. minBoxPt.y = yMin.y;
  9115. minBoxPt.z = zMin.z;
  9116. var maxBoxPt = fromPointsMaxBoxPt;
  9117. maxBoxPt.x = xMax.x;
  9118. maxBoxPt.y = yMax.y;
  9119. maxBoxPt.z = zMax.z;
  9120. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9121. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9122. var naiveRadius = 0;
  9123. for (i = 0; i < numPositions; i++) {
  9124. Cartesian3.clone(positions[i], currentPos);
  9125. // Find the furthest point from the naive center to calculate the naive radius.
  9126. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9127. if (r > naiveRadius) {
  9128. naiveRadius = r;
  9129. }
  9130. // Make adjustments to the Ritter Sphere to include all points.
  9131. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9132. if (oldCenterToPointSquared > radiusSquared) {
  9133. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9134. // Calculate new radius to include the point that lies outside
  9135. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9136. radiusSquared = ritterRadius * ritterRadius;
  9137. // Calculate center of new Ritter sphere
  9138. var oldToNew = oldCenterToPoint - ritterRadius;
  9139. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9140. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9141. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9142. }
  9143. }
  9144. if (ritterRadius < naiveRadius) {
  9145. Cartesian3.clone(ritterCenter, result.center);
  9146. result.radius = ritterRadius;
  9147. } else {
  9148. Cartesian3.clone(naiveCenter, result.center);
  9149. result.radius = naiveRadius;
  9150. }
  9151. return result;
  9152. };
  9153. var defaultProjection = new GeographicProjection();
  9154. var fromRectangle2DLowerLeft = new Cartesian3();
  9155. var fromRectangle2DUpperRight = new Cartesian3();
  9156. var fromRectangle2DSouthwest = new Cartographic();
  9157. var fromRectangle2DNortheast = new Cartographic();
  9158. /**
  9159. * Computes a bounding sphere from an rectangle projected in 2D.
  9160. *
  9161. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  9162. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  9163. * @param {BoundingSphere} [result] The object onto which to store the result.
  9164. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9165. */
  9166. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  9167. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  9168. };
  9169. /**
  9170. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  9171. * object's minimum and maximum heights over the rectangle.
  9172. *
  9173. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  9174. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  9175. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  9176. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  9177. * @param {BoundingSphere} [result] The object onto which to store the result.
  9178. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9179. */
  9180. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  9181. if (!defined(result)) {
  9182. result = new BoundingSphere();
  9183. }
  9184. if (!defined(rectangle)) {
  9185. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9186. result.radius = 0.0;
  9187. return result;
  9188. }
  9189. projection = defaultValue(projection, defaultProjection);
  9190. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  9191. fromRectangle2DSouthwest.height = minimumHeight;
  9192. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  9193. fromRectangle2DNortheast.height = maximumHeight;
  9194. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  9195. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  9196. var width = upperRight.x - lowerLeft.x;
  9197. var height = upperRight.y - lowerLeft.y;
  9198. var elevation = upperRight.z - lowerLeft.z;
  9199. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  9200. var center = result.center;
  9201. center.x = lowerLeft.x + width * 0.5;
  9202. center.y = lowerLeft.y + height * 0.5;
  9203. center.z = lowerLeft.z + elevation * 0.5;
  9204. return result;
  9205. };
  9206. var fromRectangle3DScratch = [];
  9207. /**
  9208. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  9209. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  9210. *
  9211. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  9212. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  9213. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  9214. * @param {BoundingSphere} [result] The object onto which to store the result.
  9215. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9216. */
  9217. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  9218. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  9219. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  9220. var positions;
  9221. if (defined(rectangle)) {
  9222. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  9223. }
  9224. return BoundingSphere.fromPoints(positions, result);
  9225. };
  9226. /**
  9227. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  9228. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  9229. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9230. * ensure a tight fit.
  9231. *
  9232. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  9233. * is formed from three elements in the array in the order X, Y, Z.
  9234. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  9235. * origin of the coordinate system. This is useful when the positions are to be used for
  9236. * relative-to-center (RTC) rendering.
  9237. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  9238. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  9239. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  9240. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  9241. * the stride is 5, however, two array elements are skipped and the next position begins at array
  9242. * index 5.
  9243. * @param {BoundingSphere} [result] The object onto which to store the result.
  9244. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9245. *
  9246. * @example
  9247. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  9248. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  9249. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  9250. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9251. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  9252. * 4.0, 5.0, 6.0, 0.1, 0.2,
  9253. * 7.0, 8.0, 9.0, 0.1, 0.2];
  9254. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  9255. *
  9256. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9257. */
  9258. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  9259. if (!defined(result)) {
  9260. result = new BoundingSphere();
  9261. }
  9262. if (!defined(positions) || positions.length === 0) {
  9263. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9264. result.radius = 0.0;
  9265. return result;
  9266. }
  9267. center = defaultValue(center, Cartesian3.ZERO);
  9268. stride = defaultValue(stride, 3);
  9269. if (stride < 3) {
  9270. throw new DeveloperError('stride must be 3 or greater.');
  9271. }
  9272. var currentPos = fromPointsCurrentPos;
  9273. currentPos.x = positions[0] + center.x;
  9274. currentPos.y = positions[1] + center.y;
  9275. currentPos.z = positions[2] + center.z;
  9276. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9277. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9278. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9279. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9280. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9281. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9282. var numElements = positions.length;
  9283. for (var i = 0; i < numElements; i += stride) {
  9284. var x = positions[i] + center.x;
  9285. var y = positions[i + 1] + center.y;
  9286. var z = positions[i + 2] + center.z;
  9287. currentPos.x = x;
  9288. currentPos.y = y;
  9289. currentPos.z = z;
  9290. // Store points containing the the smallest and largest components
  9291. if (x < xMin.x) {
  9292. Cartesian3.clone(currentPos, xMin);
  9293. }
  9294. if (x > xMax.x) {
  9295. Cartesian3.clone(currentPos, xMax);
  9296. }
  9297. if (y < yMin.y) {
  9298. Cartesian3.clone(currentPos, yMin);
  9299. }
  9300. if (y > yMax.y) {
  9301. Cartesian3.clone(currentPos, yMax);
  9302. }
  9303. if (z < zMin.z) {
  9304. Cartesian3.clone(currentPos, zMin);
  9305. }
  9306. if (z > zMax.z) {
  9307. Cartesian3.clone(currentPos, zMax);
  9308. }
  9309. }
  9310. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9311. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9312. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9313. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9314. // Set the diameter endpoints to the largest span.
  9315. var diameter1 = xMin;
  9316. var diameter2 = xMax;
  9317. var maxSpan = xSpan;
  9318. if (ySpan > maxSpan) {
  9319. maxSpan = ySpan;
  9320. diameter1 = yMin;
  9321. diameter2 = yMax;
  9322. }
  9323. if (zSpan > maxSpan) {
  9324. maxSpan = zSpan;
  9325. diameter1 = zMin;
  9326. diameter2 = zMax;
  9327. }
  9328. // Calculate the center of the initial sphere found by Ritter's algorithm
  9329. var ritterCenter = fromPointsRitterCenter;
  9330. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9331. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9332. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9333. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9334. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9335. var ritterRadius = Math.sqrt(radiusSquared);
  9336. // Find the center of the sphere found using the Naive method.
  9337. var minBoxPt = fromPointsMinBoxPt;
  9338. minBoxPt.x = xMin.x;
  9339. minBoxPt.y = yMin.y;
  9340. minBoxPt.z = zMin.z;
  9341. var maxBoxPt = fromPointsMaxBoxPt;
  9342. maxBoxPt.x = xMax.x;
  9343. maxBoxPt.y = yMax.y;
  9344. maxBoxPt.z = zMax.z;
  9345. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9346. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9347. var naiveRadius = 0;
  9348. for (i = 0; i < numElements; i += stride) {
  9349. currentPos.x = positions[i] + center.x;
  9350. currentPos.y = positions[i + 1] + center.y;
  9351. currentPos.z = positions[i + 2] + center.z;
  9352. // Find the furthest point from the naive center to calculate the naive radius.
  9353. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9354. if (r > naiveRadius) {
  9355. naiveRadius = r;
  9356. }
  9357. // Make adjustments to the Ritter Sphere to include all points.
  9358. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9359. if (oldCenterToPointSquared > radiusSquared) {
  9360. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9361. // Calculate new radius to include the point that lies outside
  9362. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9363. radiusSquared = ritterRadius * ritterRadius;
  9364. // Calculate center of new Ritter sphere
  9365. var oldToNew = oldCenterToPoint - ritterRadius;
  9366. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9367. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9368. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9369. }
  9370. }
  9371. if (ritterRadius < naiveRadius) {
  9372. Cartesian3.clone(ritterCenter, result.center);
  9373. result.radius = ritterRadius;
  9374. } else {
  9375. Cartesian3.clone(naiveCenter, result.center);
  9376. result.radius = naiveRadius;
  9377. }
  9378. return result;
  9379. };
  9380. /**
  9381. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  9382. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  9383. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9384. * ensure a tight fit.
  9385. *
  9386. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9387. * is formed from three elements in the array in the order X, Y, Z.
  9388. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9389. * is formed from three elements in the array in the order X, Y, Z.
  9390. * @param {BoundingSphere} [result] The object onto which to store the result.
  9391. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9392. *
  9393. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9394. */
  9395. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  9396. if (!defined(result)) {
  9397. result = new BoundingSphere();
  9398. }
  9399. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  9400. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9401. result.radius = 0.0;
  9402. return result;
  9403. }
  9404. var currentPos = fromPointsCurrentPos;
  9405. currentPos.x = positionsHigh[0] + positionsLow[0];
  9406. currentPos.y = positionsHigh[1] + positionsLow[1];
  9407. currentPos.z = positionsHigh[2] + positionsLow[2];
  9408. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9409. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9410. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9411. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9412. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9413. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9414. var numElements = positionsHigh.length;
  9415. for (var i = 0; i < numElements; i += 3) {
  9416. var x = positionsHigh[i] + positionsLow[i];
  9417. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  9418. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  9419. currentPos.x = x;
  9420. currentPos.y = y;
  9421. currentPos.z = z;
  9422. // Store points containing the the smallest and largest components
  9423. if (x < xMin.x) {
  9424. Cartesian3.clone(currentPos, xMin);
  9425. }
  9426. if (x > xMax.x) {
  9427. Cartesian3.clone(currentPos, xMax);
  9428. }
  9429. if (y < yMin.y) {
  9430. Cartesian3.clone(currentPos, yMin);
  9431. }
  9432. if (y > yMax.y) {
  9433. Cartesian3.clone(currentPos, yMax);
  9434. }
  9435. if (z < zMin.z) {
  9436. Cartesian3.clone(currentPos, zMin);
  9437. }
  9438. if (z > zMax.z) {
  9439. Cartesian3.clone(currentPos, zMax);
  9440. }
  9441. }
  9442. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9443. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9444. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9445. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9446. // Set the diameter endpoints to the largest span.
  9447. var diameter1 = xMin;
  9448. var diameter2 = xMax;
  9449. var maxSpan = xSpan;
  9450. if (ySpan > maxSpan) {
  9451. maxSpan = ySpan;
  9452. diameter1 = yMin;
  9453. diameter2 = yMax;
  9454. }
  9455. if (zSpan > maxSpan) {
  9456. maxSpan = zSpan;
  9457. diameter1 = zMin;
  9458. diameter2 = zMax;
  9459. }
  9460. // Calculate the center of the initial sphere found by Ritter's algorithm
  9461. var ritterCenter = fromPointsRitterCenter;
  9462. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9463. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9464. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9465. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9466. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9467. var ritterRadius = Math.sqrt(radiusSquared);
  9468. // Find the center of the sphere found using the Naive method.
  9469. var minBoxPt = fromPointsMinBoxPt;
  9470. minBoxPt.x = xMin.x;
  9471. minBoxPt.y = yMin.y;
  9472. minBoxPt.z = zMin.z;
  9473. var maxBoxPt = fromPointsMaxBoxPt;
  9474. maxBoxPt.x = xMax.x;
  9475. maxBoxPt.y = yMax.y;
  9476. maxBoxPt.z = zMax.z;
  9477. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9478. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9479. var naiveRadius = 0;
  9480. for (i = 0; i < numElements; i += 3) {
  9481. currentPos.x = positionsHigh[i] + positionsLow[i];
  9482. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  9483. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  9484. // Find the furthest point from the naive center to calculate the naive radius.
  9485. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9486. if (r > naiveRadius) {
  9487. naiveRadius = r;
  9488. }
  9489. // Make adjustments to the Ritter Sphere to include all points.
  9490. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9491. if (oldCenterToPointSquared > radiusSquared) {
  9492. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9493. // Calculate new radius to include the point that lies outside
  9494. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9495. radiusSquared = ritterRadius * ritterRadius;
  9496. // Calculate center of new Ritter sphere
  9497. var oldToNew = oldCenterToPoint - ritterRadius;
  9498. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9499. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9500. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9501. }
  9502. }
  9503. if (ritterRadius < naiveRadius) {
  9504. Cartesian3.clone(ritterCenter, result.center);
  9505. result.radius = ritterRadius;
  9506. } else {
  9507. Cartesian3.clone(naiveCenter, result.center);
  9508. result.radius = naiveRadius;
  9509. }
  9510. return result;
  9511. };
  9512. /**
  9513. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  9514. * tighly and fully encompases the box.
  9515. *
  9516. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  9517. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  9518. * @param {BoundingSphere} [result] The object onto which to store the result.
  9519. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9520. *
  9521. * @example
  9522. * // Create a bounding sphere around the unit cube
  9523. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  9524. */
  9525. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  9526. if (!defined(corner) || !defined(oppositeCorner)) {
  9527. throw new DeveloperError('corner and oppositeCorner are required.');
  9528. }
  9529. if (!defined(result)) {
  9530. result = new BoundingSphere();
  9531. }
  9532. var center = result.center;
  9533. Cartesian3.add(corner, oppositeCorner, center);
  9534. Cartesian3.multiplyByScalar(center, 0.5, center);
  9535. result.radius = Cartesian3.distance(center, oppositeCorner);
  9536. return result;
  9537. };
  9538. /**
  9539. * Creates a bounding sphere encompassing an ellipsoid.
  9540. *
  9541. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  9542. * @param {BoundingSphere} [result] The object onto which to store the result.
  9543. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9544. *
  9545. * @example
  9546. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  9547. */
  9548. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  9549. if (!defined(ellipsoid)) {
  9550. throw new DeveloperError('ellipsoid is required.');
  9551. }
  9552. if (!defined(result)) {
  9553. result = new BoundingSphere();
  9554. }
  9555. Cartesian3.clone(Cartesian3.ZERO, result.center);
  9556. result.radius = ellipsoid.maximumRadius;
  9557. return result;
  9558. };
  9559. var fromBoundingSpheresScratch = new Cartesian3();
  9560. /**
  9561. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  9562. *
  9563. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  9564. * @param {BoundingSphere} [result] The object onto which to store the result.
  9565. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9566. */
  9567. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  9568. if (!defined(result)) {
  9569. result = new BoundingSphere();
  9570. }
  9571. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  9572. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9573. result.radius = 0.0;
  9574. return result;
  9575. }
  9576. var length = boundingSpheres.length;
  9577. if (length === 1) {
  9578. return BoundingSphere.clone(boundingSpheres[0], result);
  9579. }
  9580. if (length === 2) {
  9581. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  9582. }
  9583. var positions = [];
  9584. for (var i = 0; i < length; i++) {
  9585. positions.push(boundingSpheres[i].center);
  9586. }
  9587. result = BoundingSphere.fromPoints(positions, result);
  9588. var center = result.center;
  9589. var radius = result.radius;
  9590. for (i = 0; i < length; i++) {
  9591. var tmp = boundingSpheres[i];
  9592. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  9593. }
  9594. result.radius = radius;
  9595. return result;
  9596. };
  9597. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  9598. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  9599. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  9600. /**
  9601. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  9602. *
  9603. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  9604. * @param {BoundingSphere} [result] The object onto which to store the result.
  9605. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9606. */
  9607. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  9608. if (!defined(result)) {
  9609. result = new BoundingSphere();
  9610. }
  9611. var halfAxes = orientedBoundingBox.halfAxes;
  9612. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  9613. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  9614. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  9615. var uHalf = Cartesian3.magnitude(u);
  9616. var vHalf = Cartesian3.magnitude(v);
  9617. var wHalf = Cartesian3.magnitude(w);
  9618. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  9619. result.radius = Math.max(uHalf, vHalf, wHalf);
  9620. return result;
  9621. };
  9622. /**
  9623. * Duplicates a BoundingSphere instance.
  9624. *
  9625. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  9626. * @param {BoundingSphere} [result] The object onto which to store the result.
  9627. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  9628. */
  9629. BoundingSphere.clone = function(sphere, result) {
  9630. if (!defined(sphere)) {
  9631. return undefined;
  9632. }
  9633. if (!defined(result)) {
  9634. return new BoundingSphere(sphere.center, sphere.radius);
  9635. }
  9636. result.center = Cartesian3.clone(sphere.center, result.center);
  9637. result.radius = sphere.radius;
  9638. return result;
  9639. };
  9640. /**
  9641. * The number of elements used to pack the object into an array.
  9642. * @type {Number}
  9643. */
  9644. BoundingSphere.packedLength = 4;
  9645. /**
  9646. * Stores the provided instance into the provided array.
  9647. *
  9648. * @param {BoundingSphere} value The value to pack.
  9649. * @param {Number[]} array The array to pack into.
  9650. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  9651. *
  9652. * @returns {Number[]} The array that was packed into
  9653. */
  9654. BoundingSphere.pack = function(value, array, startingIndex) {
  9655. if (!defined(value)) {
  9656. throw new DeveloperError('value is required');
  9657. }
  9658. if (!defined(array)) {
  9659. throw new DeveloperError('array is required');
  9660. }
  9661. startingIndex = defaultValue(startingIndex, 0);
  9662. var center = value.center;
  9663. array[startingIndex++] = center.x;
  9664. array[startingIndex++] = center.y;
  9665. array[startingIndex++] = center.z;
  9666. array[startingIndex] = value.radius;
  9667. return array;
  9668. };
  9669. /**
  9670. * Retrieves an instance from a packed array.
  9671. *
  9672. * @param {Number[]} array The packed array.
  9673. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  9674. * @param {BoundingSphere} [result] The object into which to store the result.
  9675. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9676. */
  9677. BoundingSphere.unpack = function(array, startingIndex, result) {
  9678. if (!defined(array)) {
  9679. throw new DeveloperError('array is required');
  9680. }
  9681. startingIndex = defaultValue(startingIndex, 0);
  9682. if (!defined(result)) {
  9683. result = new BoundingSphere();
  9684. }
  9685. var center = result.center;
  9686. center.x = array[startingIndex++];
  9687. center.y = array[startingIndex++];
  9688. center.z = array[startingIndex++];
  9689. result.radius = array[startingIndex];
  9690. return result;
  9691. };
  9692. var unionScratch = new Cartesian3();
  9693. var unionScratchCenter = new Cartesian3();
  9694. /**
  9695. * Computes a bounding sphere that contains both the left and right bounding spheres.
  9696. *
  9697. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  9698. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  9699. * @param {BoundingSphere} [result] The object onto which to store the result.
  9700. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9701. */
  9702. BoundingSphere.union = function(left, right, result) {
  9703. if (!defined(left)) {
  9704. throw new DeveloperError('left is required.');
  9705. }
  9706. if (!defined(right)) {
  9707. throw new DeveloperError('right is required.');
  9708. }
  9709. if (!defined(result)) {
  9710. result = new BoundingSphere();
  9711. }
  9712. var leftCenter = left.center;
  9713. var leftRadius = left.radius;
  9714. var rightCenter = right.center;
  9715. var rightRadius = right.radius;
  9716. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  9717. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  9718. if (leftRadius >= (centerSeparation + rightRadius)) {
  9719. // Left sphere wins.
  9720. left.clone(result);
  9721. return result;
  9722. }
  9723. if (rightRadius >= (centerSeparation + leftRadius)) {
  9724. // Right sphere wins.
  9725. right.clone(result);
  9726. return result;
  9727. }
  9728. // There are two tangent points, one on far side of each sphere.
  9729. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  9730. // Compute the center point halfway between the two tangent points.
  9731. var center = Cartesian3.multiplyByScalar(toRightCenter,
  9732. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  9733. Cartesian3.add(center, leftCenter, center);
  9734. Cartesian3.clone(center, result.center);
  9735. result.radius = halfDistanceBetweenTangentPoints;
  9736. return result;
  9737. };
  9738. var expandScratch = new Cartesian3();
  9739. /**
  9740. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  9741. *
  9742. * @param {BoundingSphere} sphere A sphere to expand.
  9743. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  9744. * @param {BoundingSphere} [result] The object onto which to store the result.
  9745. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9746. */
  9747. BoundingSphere.expand = function(sphere, point, result) {
  9748. if (!defined(sphere)) {
  9749. throw new DeveloperError('sphere is required.');
  9750. }
  9751. if (!defined(point)) {
  9752. throw new DeveloperError('point is required.');
  9753. }
  9754. result = BoundingSphere.clone(sphere, result);
  9755. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  9756. if (radius > result.radius) {
  9757. result.radius = radius;
  9758. }
  9759. return result;
  9760. };
  9761. /**
  9762. * Determines which side of a plane a sphere is located.
  9763. *
  9764. * @param {BoundingSphere} sphere The bounding sphere to test.
  9765. * @param {Plane} plane The plane to test against.
  9766. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  9767. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  9768. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  9769. * intersects the plane.
  9770. */
  9771. BoundingSphere.intersectPlane = function(sphere, plane) {
  9772. if (!defined(sphere)) {
  9773. throw new DeveloperError('sphere is required.');
  9774. }
  9775. if (!defined(plane)) {
  9776. throw new DeveloperError('plane is required.');
  9777. }
  9778. var center = sphere.center;
  9779. var radius = sphere.radius;
  9780. var normal = plane.normal;
  9781. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  9782. if (distanceToPlane < -radius) {
  9783. // The center point is negative side of the plane normal
  9784. return Intersect.OUTSIDE;
  9785. } else if (distanceToPlane < radius) {
  9786. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  9787. return Intersect.INTERSECTING;
  9788. }
  9789. return Intersect.INSIDE;
  9790. };
  9791. /**
  9792. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  9793. *
  9794. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9795. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9796. * @param {BoundingSphere} [result] The object onto which to store the result.
  9797. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9798. */
  9799. BoundingSphere.transform = function(sphere, transform, result) {
  9800. if (!defined(sphere)) {
  9801. throw new DeveloperError('sphere is required.');
  9802. }
  9803. if (!defined(transform)) {
  9804. throw new DeveloperError('transform is required.');
  9805. }
  9806. if (!defined(result)) {
  9807. result = new BoundingSphere();
  9808. }
  9809. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9810. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  9811. return result;
  9812. };
  9813. var distanceSquaredToScratch = new Cartesian3();
  9814. /**
  9815. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  9816. *
  9817. * @param {BoundingSphere} sphere The sphere.
  9818. * @param {Cartesian3} cartesian The point
  9819. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  9820. *
  9821. * @example
  9822. * // Sort bounding spheres from back to front
  9823. * spheres.sort(function(a, b) {
  9824. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  9825. * });
  9826. */
  9827. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  9828. if (!defined(sphere)) {
  9829. throw new DeveloperError('sphere is required.');
  9830. }
  9831. if (!defined(cartesian)) {
  9832. throw new DeveloperError('cartesian is required.');
  9833. }
  9834. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  9835. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  9836. };
  9837. /**
  9838. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  9839. * The transformation matrix is not verified to have a uniform scale of 1.
  9840. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  9841. *
  9842. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9843. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9844. * @param {BoundingSphere} [result] The object onto which to store the result.
  9845. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9846. *
  9847. * @example
  9848. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  9849. * var boundingSphere = new Cesium.BoundingSphere();
  9850. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  9851. */
  9852. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  9853. if (!defined(sphere)) {
  9854. throw new DeveloperError('sphere is required.');
  9855. }
  9856. if (!defined(transform)) {
  9857. throw new DeveloperError('transform is required.');
  9858. }
  9859. if (!defined(result)) {
  9860. result = new BoundingSphere();
  9861. }
  9862. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9863. result.radius = sphere.radius;
  9864. return result;
  9865. };
  9866. var scratchCartesian3 = new Cartesian3();
  9867. /**
  9868. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  9869. * plus/minus the radius of the bounding sphere.
  9870. * <br>
  9871. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  9872. * closest and farthest planes from position that intersect the bounding sphere.
  9873. *
  9874. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  9875. * @param {Cartesian3} position The position to calculate the distance from.
  9876. * @param {Cartesian3} direction The direction from position.
  9877. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  9878. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  9879. */
  9880. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  9881. if (!defined(sphere)) {
  9882. throw new DeveloperError('sphere is required.');
  9883. }
  9884. if (!defined(position)) {
  9885. throw new DeveloperError('position is required.');
  9886. }
  9887. if (!defined(direction)) {
  9888. throw new DeveloperError('direction is required.');
  9889. }
  9890. if (!defined(result)) {
  9891. result = new Interval();
  9892. }
  9893. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  9894. var mag = Cartesian3.dot(direction, toCenter);
  9895. result.start = mag - sphere.radius;
  9896. result.stop = mag + sphere.radius;
  9897. return result;
  9898. };
  9899. var projectTo2DNormalScratch = new Cartesian3();
  9900. var projectTo2DEastScratch = new Cartesian3();
  9901. var projectTo2DNorthScratch = new Cartesian3();
  9902. var projectTo2DWestScratch = new Cartesian3();
  9903. var projectTo2DSouthScratch = new Cartesian3();
  9904. var projectTo2DCartographicScratch = new Cartographic();
  9905. var projectTo2DPositionsScratch = new Array(8);
  9906. for (var n = 0; n < 8; ++n) {
  9907. projectTo2DPositionsScratch[n] = new Cartesian3();
  9908. }
  9909. var projectTo2DProjection = new GeographicProjection();
  9910. /**
  9911. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  9912. *
  9913. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  9914. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  9915. * @param {BoundingSphere} [result] The object onto which to store the result.
  9916. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9917. */
  9918. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  9919. if (!defined(sphere)) {
  9920. throw new DeveloperError('sphere is required.');
  9921. }
  9922. projection = defaultValue(projection, projectTo2DProjection);
  9923. var ellipsoid = projection.ellipsoid;
  9924. var center = sphere.center;
  9925. var radius = sphere.radius;
  9926. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  9927. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  9928. Cartesian3.normalize(east, east);
  9929. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  9930. Cartesian3.normalize(north, north);
  9931. Cartesian3.multiplyByScalar(normal, radius, normal);
  9932. Cartesian3.multiplyByScalar(north, radius, north);
  9933. Cartesian3.multiplyByScalar(east, radius, east);
  9934. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  9935. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  9936. var positions = projectTo2DPositionsScratch;
  9937. // top NE corner
  9938. var corner = positions[0];
  9939. Cartesian3.add(normal, north, corner);
  9940. Cartesian3.add(corner, east, corner);
  9941. // top NW corner
  9942. corner = positions[1];
  9943. Cartesian3.add(normal, north, corner);
  9944. Cartesian3.add(corner, west, corner);
  9945. // top SW corner
  9946. corner = positions[2];
  9947. Cartesian3.add(normal, south, corner);
  9948. Cartesian3.add(corner, west, corner);
  9949. // top SE corner
  9950. corner = positions[3];
  9951. Cartesian3.add(normal, south, corner);
  9952. Cartesian3.add(corner, east, corner);
  9953. Cartesian3.negate(normal, normal);
  9954. // bottom NE corner
  9955. corner = positions[4];
  9956. Cartesian3.add(normal, north, corner);
  9957. Cartesian3.add(corner, east, corner);
  9958. // bottom NW corner
  9959. corner = positions[5];
  9960. Cartesian3.add(normal, north, corner);
  9961. Cartesian3.add(corner, west, corner);
  9962. // bottom SW corner
  9963. corner = positions[6];
  9964. Cartesian3.add(normal, south, corner);
  9965. Cartesian3.add(corner, west, corner);
  9966. // bottom SE corner
  9967. corner = positions[7];
  9968. Cartesian3.add(normal, south, corner);
  9969. Cartesian3.add(corner, east, corner);
  9970. var length = positions.length;
  9971. for (var i = 0; i < length; ++i) {
  9972. var position = positions[i];
  9973. Cartesian3.add(center, position, position);
  9974. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  9975. projection.project(cartographic, position);
  9976. }
  9977. result = BoundingSphere.fromPoints(positions, result);
  9978. // swizzle center components
  9979. center = result.center;
  9980. var x = center.x;
  9981. var y = center.y;
  9982. var z = center.z;
  9983. center.x = z;
  9984. center.y = x;
  9985. center.z = y;
  9986. return result;
  9987. };
  9988. /**
  9989. * Determines whether or not a sphere is hidden from view by the occluder.
  9990. *
  9991. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  9992. * @param {Occluder} occluder The occluder.
  9993. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  9994. */
  9995. BoundingSphere.isOccluded = function(sphere, occluder) {
  9996. if (!defined(sphere)) {
  9997. throw new DeveloperError('sphere is required.');
  9998. }
  9999. if (!defined(occluder)) {
  10000. throw new DeveloperError('occluder is required.');
  10001. }
  10002. return !occluder.isBoundingSphereVisible(sphere);
  10003. };
  10004. /**
  10005. * Compares the provided BoundingSphere componentwise and returns
  10006. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10007. *
  10008. * @param {BoundingSphere} [left] The first BoundingSphere.
  10009. * @param {BoundingSphere} [right] The second BoundingSphere.
  10010. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10011. */
  10012. BoundingSphere.equals = function(left, right) {
  10013. return (left === right) ||
  10014. ((defined(left)) &&
  10015. (defined(right)) &&
  10016. Cartesian3.equals(left.center, right.center) &&
  10017. left.radius === right.radius);
  10018. };
  10019. /**
  10020. * Determines which side of a plane the sphere is located.
  10021. *
  10022. * @param {Plane} plane The plane to test against.
  10023. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10024. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10025. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10026. * intersects the plane.
  10027. */
  10028. BoundingSphere.prototype.intersectPlane = function(plane) {
  10029. return BoundingSphere.intersectPlane(this, plane);
  10030. };
  10031. /**
  10032. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10033. *
  10034. * @param {Cartesian3} cartesian The point
  10035. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10036. *
  10037. * @example
  10038. * // Sort bounding spheres from back to front
  10039. * spheres.sort(function(a, b) {
  10040. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  10041. * });
  10042. */
  10043. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  10044. return BoundingSphere.distanceSquaredTo(this, cartesian);
  10045. };
  10046. /**
  10047. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10048. * plus/minus the radius of the bounding sphere.
  10049. * <br>
  10050. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10051. * closest and farthest planes from position that intersect the bounding sphere.
  10052. *
  10053. * @param {Cartesian3} position The position to calculate the distance from.
  10054. * @param {Cartesian3} direction The direction from position.
  10055. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10056. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10057. */
  10058. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  10059. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  10060. };
  10061. /**
  10062. * Determines whether or not a sphere is hidden from view by the occluder.
  10063. *
  10064. * @param {Occluder} occluder The occluder.
  10065. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10066. */
  10067. BoundingSphere.prototype.isOccluded = function(occluder) {
  10068. return BoundingSphere.isOccluded(this, occluder);
  10069. };
  10070. /**
  10071. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  10072. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10073. *
  10074. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  10075. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  10076. */
  10077. BoundingSphere.prototype.equals = function(right) {
  10078. return BoundingSphere.equals(this, right);
  10079. };
  10080. /**
  10081. * Duplicates this BoundingSphere instance.
  10082. *
  10083. * @param {BoundingSphere} [result] The object onto which to store the result.
  10084. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10085. */
  10086. BoundingSphere.prototype.clone = function(result) {
  10087. return BoundingSphere.clone(this, result);
  10088. };
  10089. return BoundingSphere;
  10090. });
  10091. /*global define*/
  10092. define('Core/Cartesian2',[
  10093. './defaultValue',
  10094. './defined',
  10095. './DeveloperError',
  10096. './freezeObject',
  10097. './Math'
  10098. ], function(
  10099. defaultValue,
  10100. defined,
  10101. DeveloperError,
  10102. freezeObject,
  10103. CesiumMath) {
  10104. 'use strict';
  10105. /**
  10106. * A 2D Cartesian point.
  10107. * @alias Cartesian2
  10108. * @constructor
  10109. *
  10110. * @param {Number} [x=0.0] The X component.
  10111. * @param {Number} [y=0.0] The Y component.
  10112. *
  10113. * @see Cartesian3
  10114. * @see Cartesian4
  10115. * @see Packable
  10116. */
  10117. function Cartesian2(x, y) {
  10118. /**
  10119. * The X component.
  10120. * @type {Number}
  10121. * @default 0.0
  10122. */
  10123. this.x = defaultValue(x, 0.0);
  10124. /**
  10125. * The Y component.
  10126. * @type {Number}
  10127. * @default 0.0
  10128. */
  10129. this.y = defaultValue(y, 0.0);
  10130. }
  10131. /**
  10132. * Creates a Cartesian2 instance from x and y coordinates.
  10133. *
  10134. * @param {Number} x The x coordinate.
  10135. * @param {Number} y The y coordinate.
  10136. * @param {Cartesian2} [result] The object onto which to store the result.
  10137. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10138. */
  10139. Cartesian2.fromElements = function(x, y, result) {
  10140. if (!defined(result)) {
  10141. return new Cartesian2(x, y);
  10142. }
  10143. result.x = x;
  10144. result.y = y;
  10145. return result;
  10146. };
  10147. /**
  10148. * Duplicates a Cartesian2 instance.
  10149. *
  10150. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  10151. * @param {Cartesian2} [result] The object onto which to store the result.
  10152. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  10153. */
  10154. Cartesian2.clone = function(cartesian, result) {
  10155. if (!defined(cartesian)) {
  10156. return undefined;
  10157. }
  10158. if (!defined(result)) {
  10159. return new Cartesian2(cartesian.x, cartesian.y);
  10160. }
  10161. result.x = cartesian.x;
  10162. result.y = cartesian.y;
  10163. return result;
  10164. };
  10165. /**
  10166. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  10167. * x and y properties of the Cartesian3 and drops z.
  10168. * @function
  10169. *
  10170. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  10171. * @param {Cartesian2} [result] The object onto which to store the result.
  10172. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10173. */
  10174. Cartesian2.fromCartesian3 = Cartesian2.clone;
  10175. /**
  10176. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  10177. * x and y properties of the Cartesian4 and drops z and w.
  10178. * @function
  10179. *
  10180. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  10181. * @param {Cartesian2} [result] The object onto which to store the result.
  10182. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10183. */
  10184. Cartesian2.fromCartesian4 = Cartesian2.clone;
  10185. /**
  10186. * The number of elements used to pack the object into an array.
  10187. * @type {Number}
  10188. */
  10189. Cartesian2.packedLength = 2;
  10190. /**
  10191. * Stores the provided instance into the provided array.
  10192. *
  10193. * @param {Cartesian2} value The value to pack.
  10194. * @param {Number[]} array The array to pack into.
  10195. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  10196. *
  10197. * @returns {Number[]} The array that was packed into
  10198. */
  10199. Cartesian2.pack = function(value, array, startingIndex) {
  10200. if (!defined(value)) {
  10201. throw new DeveloperError('value is required');
  10202. }
  10203. if (!defined(array)) {
  10204. throw new DeveloperError('array is required');
  10205. }
  10206. startingIndex = defaultValue(startingIndex, 0);
  10207. array[startingIndex++] = value.x;
  10208. array[startingIndex] = value.y;
  10209. return array;
  10210. };
  10211. /**
  10212. * Retrieves an instance from a packed array.
  10213. *
  10214. * @param {Number[]} array The packed array.
  10215. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10216. * @param {Cartesian2} [result] The object into which to store the result.
  10217. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10218. */
  10219. Cartesian2.unpack = function(array, startingIndex, result) {
  10220. if (!defined(array)) {
  10221. throw new DeveloperError('array is required');
  10222. }
  10223. startingIndex = defaultValue(startingIndex, 0);
  10224. if (!defined(result)) {
  10225. result = new Cartesian2();
  10226. }
  10227. result.x = array[startingIndex++];
  10228. result.y = array[startingIndex];
  10229. return result;
  10230. };
  10231. /**
  10232. * Flattens an array of Cartesian2s into and array of components.
  10233. *
  10234. * @param {Cartesian2[]} array The array of cartesians to pack.
  10235. * @param {Number[]} result The array onto which to store the result.
  10236. * @returns {Number[]} The packed array.
  10237. */
  10238. Cartesian2.packArray = function(array, result) {
  10239. if (!defined(array)) {
  10240. throw new DeveloperError('array is required');
  10241. }
  10242. var length = array.length;
  10243. if (!defined(result)) {
  10244. result = new Array(length * 2);
  10245. } else {
  10246. result.length = length * 2;
  10247. }
  10248. for (var i = 0; i < length; ++i) {
  10249. Cartesian2.pack(array[i], result, i * 2);
  10250. }
  10251. return result;
  10252. };
  10253. /**
  10254. * Unpacks an array of cartesian components into and array of Cartesian2s.
  10255. *
  10256. * @param {Number[]} array The array of components to unpack.
  10257. * @param {Cartesian2[]} result The array onto which to store the result.
  10258. * @returns {Cartesian2[]} The unpacked array.
  10259. */
  10260. Cartesian2.unpackArray = function(array, result) {
  10261. if (!defined(array)) {
  10262. throw new DeveloperError('array is required');
  10263. }
  10264. var length = array.length;
  10265. if (!defined(result)) {
  10266. result = new Array(length / 2);
  10267. } else {
  10268. result.length = length / 2;
  10269. }
  10270. for (var i = 0; i < length; i += 2) {
  10271. var index = i / 2;
  10272. result[index] = Cartesian2.unpack(array, i, result[index]);
  10273. }
  10274. return result;
  10275. };
  10276. /**
  10277. * Creates a Cartesian2 from two consecutive elements in an array.
  10278. * @function
  10279. *
  10280. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  10281. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  10282. * @param {Cartesian2} [result] The object onto which to store the result.
  10283. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10284. *
  10285. * @example
  10286. * // Create a Cartesian2 with (1.0, 2.0)
  10287. * var v = [1.0, 2.0];
  10288. * var p = Cesium.Cartesian2.fromArray(v);
  10289. *
  10290. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  10291. * var v2 = [0.0, 0.0, 1.0, 2.0];
  10292. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  10293. */
  10294. Cartesian2.fromArray = Cartesian2.unpack;
  10295. /**
  10296. * Computes the value of the maximum component for the supplied Cartesian.
  10297. *
  10298. * @param {Cartesian2} cartesian The cartesian to use.
  10299. * @returns {Number} The value of the maximum component.
  10300. */
  10301. Cartesian2.maximumComponent = function(cartesian) {
  10302. if (!defined(cartesian)) {
  10303. throw new DeveloperError('cartesian is required');
  10304. }
  10305. return Math.max(cartesian.x, cartesian.y);
  10306. };
  10307. /**
  10308. * Computes the value of the minimum component for the supplied Cartesian.
  10309. *
  10310. * @param {Cartesian2} cartesian The cartesian to use.
  10311. * @returns {Number} The value of the minimum component.
  10312. */
  10313. Cartesian2.minimumComponent = function(cartesian) {
  10314. if (!defined(cartesian)) {
  10315. throw new DeveloperError('cartesian is required');
  10316. }
  10317. return Math.min(cartesian.x, cartesian.y);
  10318. };
  10319. /**
  10320. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  10321. *
  10322. * @param {Cartesian2} first A cartesian to compare.
  10323. * @param {Cartesian2} second A cartesian to compare.
  10324. * @param {Cartesian2} result The object into which to store the result.
  10325. * @returns {Cartesian2} A cartesian with the minimum components.
  10326. */
  10327. Cartesian2.minimumByComponent = function(first, second, result) {
  10328. if (!defined(first)) {
  10329. throw new DeveloperError('first is required.');
  10330. }
  10331. if (!defined(second)) {
  10332. throw new DeveloperError('second is required.');
  10333. }
  10334. if (!defined(result)) {
  10335. throw new DeveloperError('result is required.');
  10336. }
  10337. result.x = Math.min(first.x, second.x);
  10338. result.y = Math.min(first.y, second.y);
  10339. return result;
  10340. };
  10341. /**
  10342. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  10343. *
  10344. * @param {Cartesian2} first A cartesian to compare.
  10345. * @param {Cartesian2} second A cartesian to compare.
  10346. * @param {Cartesian2} result The object into which to store the result.
  10347. * @returns {Cartesian2} A cartesian with the maximum components.
  10348. */
  10349. Cartesian2.maximumByComponent = function(first, second, result) {
  10350. if (!defined(first)) {
  10351. throw new DeveloperError('first is required.');
  10352. }
  10353. if (!defined(second)) {
  10354. throw new DeveloperError('second is required.');
  10355. }
  10356. if (!defined(result)) {
  10357. throw new DeveloperError('result is required.');
  10358. }
  10359. result.x = Math.max(first.x, second.x);
  10360. result.y = Math.max(first.y, second.y);
  10361. return result;
  10362. };
  10363. /**
  10364. * Computes the provided Cartesian's squared magnitude.
  10365. *
  10366. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  10367. * @returns {Number} The squared magnitude.
  10368. */
  10369. Cartesian2.magnitudeSquared = function(cartesian) {
  10370. if (!defined(cartesian)) {
  10371. throw new DeveloperError('cartesian is required');
  10372. }
  10373. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  10374. };
  10375. /**
  10376. * Computes the Cartesian's magnitude (length).
  10377. *
  10378. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  10379. * @returns {Number} The magnitude.
  10380. */
  10381. Cartesian2.magnitude = function(cartesian) {
  10382. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  10383. };
  10384. var distanceScratch = new Cartesian2();
  10385. /**
  10386. * Computes the distance between two points.
  10387. *
  10388. * @param {Cartesian2} left The first point to compute the distance from.
  10389. * @param {Cartesian2} right The second point to compute the distance to.
  10390. * @returns {Number} The distance between two points.
  10391. *
  10392. * @example
  10393. * // Returns 1.0
  10394. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  10395. */
  10396. Cartesian2.distance = function(left, right) {
  10397. if (!defined(left) || !defined(right)) {
  10398. throw new DeveloperError('left and right are required.');
  10399. }
  10400. Cartesian2.subtract(left, right, distanceScratch);
  10401. return Cartesian2.magnitude(distanceScratch);
  10402. };
  10403. /**
  10404. * Computes the squared distance between two points. Comparing squared distances
  10405. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  10406. *
  10407. * @param {Cartesian2} left The first point to compute the distance from.
  10408. * @param {Cartesian2} right The second point to compute the distance to.
  10409. * @returns {Number} The distance between two points.
  10410. *
  10411. * @example
  10412. * // Returns 4.0, not 2.0
  10413. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  10414. */
  10415. Cartesian2.distanceSquared = function(left, right) {
  10416. if (!defined(left) || !defined(right)) {
  10417. throw new DeveloperError('left and right are required.');
  10418. }
  10419. Cartesian2.subtract(left, right, distanceScratch);
  10420. return Cartesian2.magnitudeSquared(distanceScratch);
  10421. };
  10422. /**
  10423. * Computes the normalized form of the supplied Cartesian.
  10424. *
  10425. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  10426. * @param {Cartesian2} result The object onto which to store the result.
  10427. * @returns {Cartesian2} The modified result parameter.
  10428. */
  10429. Cartesian2.normalize = function(cartesian, result) {
  10430. if (!defined(cartesian)) {
  10431. throw new DeveloperError('cartesian is required');
  10432. }
  10433. if (!defined(result)) {
  10434. throw new DeveloperError('result is required');
  10435. }
  10436. var magnitude = Cartesian2.magnitude(cartesian);
  10437. result.x = cartesian.x / magnitude;
  10438. result.y = cartesian.y / magnitude;
  10439. if (isNaN(result.x) || isNaN(result.y)) {
  10440. throw new DeveloperError('normalized result is not a number');
  10441. }
  10442. return result;
  10443. };
  10444. /**
  10445. * Computes the dot (scalar) product of two Cartesians.
  10446. *
  10447. * @param {Cartesian2} left The first Cartesian.
  10448. * @param {Cartesian2} right The second Cartesian.
  10449. * @returns {Number} The dot product.
  10450. */
  10451. Cartesian2.dot = function(left, right) {
  10452. if (!defined(left)) {
  10453. throw new DeveloperError('left is required');
  10454. }
  10455. if (!defined(right)) {
  10456. throw new DeveloperError('right is required');
  10457. }
  10458. return left.x * right.x + left.y * right.y;
  10459. };
  10460. /**
  10461. * Computes the componentwise product of two Cartesians.
  10462. *
  10463. * @param {Cartesian2} left The first Cartesian.
  10464. * @param {Cartesian2} right The second Cartesian.
  10465. * @param {Cartesian2} result The object onto which to store the result.
  10466. * @returns {Cartesian2} The modified result parameter.
  10467. */
  10468. Cartesian2.multiplyComponents = function(left, right, result) {
  10469. if (!defined(left)) {
  10470. throw new DeveloperError('left is required');
  10471. }
  10472. if (!defined(right)) {
  10473. throw new DeveloperError('right is required');
  10474. }
  10475. if (!defined(result)) {
  10476. throw new DeveloperError('result is required');
  10477. }
  10478. result.x = left.x * right.x;
  10479. result.y = left.y * right.y;
  10480. return result;
  10481. };
  10482. /**
  10483. * Computes the componentwise quotient of two Cartesians.
  10484. *
  10485. * @param {Cartesian2} left The first Cartesian.
  10486. * @param {Cartesian2} right The second Cartesian.
  10487. * @param {Cartesian2} result The object onto which to store the result.
  10488. * @returns {Cartesian2} The modified result parameter.
  10489. */
  10490. Cartesian2.divideComponents = function(left, right, result) {
  10491. if (!defined(left)) {
  10492. throw new DeveloperError('left is required');
  10493. }
  10494. if (!defined(right)) {
  10495. throw new DeveloperError('right is required');
  10496. }
  10497. if (!defined(result)) {
  10498. throw new DeveloperError('result is required');
  10499. }
  10500. result.x = left.x / right.x;
  10501. result.y = left.y / right.y;
  10502. return result;
  10503. };
  10504. /**
  10505. * Computes the componentwise sum of two Cartesians.
  10506. *
  10507. * @param {Cartesian2} left The first Cartesian.
  10508. * @param {Cartesian2} right The second Cartesian.
  10509. * @param {Cartesian2} result The object onto which to store the result.
  10510. * @returns {Cartesian2} The modified result parameter.
  10511. */
  10512. Cartesian2.add = function(left, right, result) {
  10513. if (!defined(left)) {
  10514. throw new DeveloperError('left is required');
  10515. }
  10516. if (!defined(right)) {
  10517. throw new DeveloperError('right is required');
  10518. }
  10519. if (!defined(result)) {
  10520. throw new DeveloperError('result is required');
  10521. }
  10522. result.x = left.x + right.x;
  10523. result.y = left.y + right.y;
  10524. return result;
  10525. };
  10526. /**
  10527. * Computes the componentwise difference of two Cartesians.
  10528. *
  10529. * @param {Cartesian2} left The first Cartesian.
  10530. * @param {Cartesian2} right The second Cartesian.
  10531. * @param {Cartesian2} result The object onto which to store the result.
  10532. * @returns {Cartesian2} The modified result parameter.
  10533. */
  10534. Cartesian2.subtract = function(left, right, result) {
  10535. if (!defined(left)) {
  10536. throw new DeveloperError('left is required');
  10537. }
  10538. if (!defined(right)) {
  10539. throw new DeveloperError('right is required');
  10540. }
  10541. if (!defined(result)) {
  10542. throw new DeveloperError('result is required');
  10543. }
  10544. result.x = left.x - right.x;
  10545. result.y = left.y - right.y;
  10546. return result;
  10547. };
  10548. /**
  10549. * Multiplies the provided Cartesian componentwise by the provided scalar.
  10550. *
  10551. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  10552. * @param {Number} scalar The scalar to multiply with.
  10553. * @param {Cartesian2} result The object onto which to store the result.
  10554. * @returns {Cartesian2} The modified result parameter.
  10555. */
  10556. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  10557. if (!defined(cartesian)) {
  10558. throw new DeveloperError('cartesian is required');
  10559. }
  10560. if (typeof scalar !== 'number') {
  10561. throw new DeveloperError('scalar is required and must be a number.');
  10562. }
  10563. if (!defined(result)) {
  10564. throw new DeveloperError('result is required');
  10565. }
  10566. result.x = cartesian.x * scalar;
  10567. result.y = cartesian.y * scalar;
  10568. return result;
  10569. };
  10570. /**
  10571. * Divides the provided Cartesian componentwise by the provided scalar.
  10572. *
  10573. * @param {Cartesian2} cartesian The Cartesian to be divided.
  10574. * @param {Number} scalar The scalar to divide by.
  10575. * @param {Cartesian2} result The object onto which to store the result.
  10576. * @returns {Cartesian2} The modified result parameter.
  10577. */
  10578. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  10579. if (!defined(cartesian)) {
  10580. throw new DeveloperError('cartesian is required');
  10581. }
  10582. if (typeof scalar !== 'number') {
  10583. throw new DeveloperError('scalar is required and must be a number.');
  10584. }
  10585. if (!defined(result)) {
  10586. throw new DeveloperError('result is required');
  10587. }
  10588. result.x = cartesian.x / scalar;
  10589. result.y = cartesian.y / scalar;
  10590. return result;
  10591. };
  10592. /**
  10593. * Negates the provided Cartesian.
  10594. *
  10595. * @param {Cartesian2} cartesian The Cartesian to be negated.
  10596. * @param {Cartesian2} result The object onto which to store the result.
  10597. * @returns {Cartesian2} The modified result parameter.
  10598. */
  10599. Cartesian2.negate = function(cartesian, result) {
  10600. if (!defined(cartesian)) {
  10601. throw new DeveloperError('cartesian is required');
  10602. }
  10603. if (!defined(result)) {
  10604. throw new DeveloperError('result is required');
  10605. }
  10606. result.x = -cartesian.x;
  10607. result.y = -cartesian.y;
  10608. return result;
  10609. };
  10610. /**
  10611. * Computes the absolute value of the provided Cartesian.
  10612. *
  10613. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  10614. * @param {Cartesian2} result The object onto which to store the result.
  10615. * @returns {Cartesian2} The modified result parameter.
  10616. */
  10617. Cartesian2.abs = function(cartesian, result) {
  10618. if (!defined(cartesian)) {
  10619. throw new DeveloperError('cartesian is required');
  10620. }
  10621. if (!defined(result)) {
  10622. throw new DeveloperError('result is required');
  10623. }
  10624. result.x = Math.abs(cartesian.x);
  10625. result.y = Math.abs(cartesian.y);
  10626. return result;
  10627. };
  10628. var lerpScratch = new Cartesian2();
  10629. /**
  10630. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  10631. *
  10632. * @param {Cartesian2} start The value corresponding to t at 0.0.
  10633. * @param {Cartesian2} end The value corresponding to t at 1.0.
  10634. * @param {Number} t The point along t at which to interpolate.
  10635. * @param {Cartesian2} result The object onto which to store the result.
  10636. * @returns {Cartesian2} The modified result parameter.
  10637. */
  10638. Cartesian2.lerp = function(start, end, t, result) {
  10639. if (!defined(start)) {
  10640. throw new DeveloperError('start is required.');
  10641. }
  10642. if (!defined(end)) {
  10643. throw new DeveloperError('end is required.');
  10644. }
  10645. if (typeof t !== 'number') {
  10646. throw new DeveloperError('t is required and must be a number.');
  10647. }
  10648. if (!defined(result)) {
  10649. throw new DeveloperError('result is required.');
  10650. }
  10651. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  10652. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  10653. return Cartesian2.add(lerpScratch, result, result);
  10654. };
  10655. var angleBetweenScratch = new Cartesian2();
  10656. var angleBetweenScratch2 = new Cartesian2();
  10657. /**
  10658. * Returns the angle, in radians, between the provided Cartesians.
  10659. *
  10660. * @param {Cartesian2} left The first Cartesian.
  10661. * @param {Cartesian2} right The second Cartesian.
  10662. * @returns {Number} The angle between the Cartesians.
  10663. */
  10664. Cartesian2.angleBetween = function(left, right) {
  10665. if (!defined(left)) {
  10666. throw new DeveloperError('left is required');
  10667. }
  10668. if (!defined(right)) {
  10669. throw new DeveloperError('right is required');
  10670. }
  10671. Cartesian2.normalize(left, angleBetweenScratch);
  10672. Cartesian2.normalize(right, angleBetweenScratch2);
  10673. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  10674. };
  10675. var mostOrthogonalAxisScratch = new Cartesian2();
  10676. /**
  10677. * Returns the axis that is most orthogonal to the provided Cartesian.
  10678. *
  10679. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  10680. * @param {Cartesian2} result The object onto which to store the result.
  10681. * @returns {Cartesian2} The most orthogonal axis.
  10682. */
  10683. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  10684. if (!defined(cartesian)) {
  10685. throw new DeveloperError('cartesian is required.');
  10686. }
  10687. if (!defined(result)) {
  10688. throw new DeveloperError('result is required.');
  10689. }
  10690. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  10691. Cartesian2.abs(f, f);
  10692. if (f.x <= f.y) {
  10693. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  10694. } else {
  10695. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  10696. }
  10697. return result;
  10698. };
  10699. /**
  10700. * Compares the provided Cartesians componentwise and returns
  10701. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10702. *
  10703. * @param {Cartesian2} [left] The first Cartesian.
  10704. * @param {Cartesian2} [right] The second Cartesian.
  10705. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10706. */
  10707. Cartesian2.equals = function(left, right) {
  10708. return (left === right) ||
  10709. ((defined(left)) &&
  10710. (defined(right)) &&
  10711. (left.x === right.x) &&
  10712. (left.y === right.y));
  10713. };
  10714. /**
  10715. * @private
  10716. */
  10717. Cartesian2.equalsArray = function(cartesian, array, offset) {
  10718. return cartesian.x === array[offset] &&
  10719. cartesian.y === array[offset + 1];
  10720. };
  10721. /**
  10722. * Compares the provided Cartesians componentwise and returns
  10723. * <code>true</code> if they pass an absolute or relative tolerance test,
  10724. * <code>false</code> otherwise.
  10725. *
  10726. * @param {Cartesian2} [left] The first Cartesian.
  10727. * @param {Cartesian2} [right] The second Cartesian.
  10728. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  10729. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  10730. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  10731. */
  10732. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  10733. return (left === right) ||
  10734. (defined(left) &&
  10735. defined(right) &&
  10736. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  10737. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  10738. };
  10739. /**
  10740. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  10741. *
  10742. * @type {Cartesian2}
  10743. * @constant
  10744. */
  10745. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  10746. /**
  10747. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  10748. *
  10749. * @type {Cartesian2}
  10750. * @constant
  10751. */
  10752. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  10753. /**
  10754. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  10755. *
  10756. * @type {Cartesian2}
  10757. * @constant
  10758. */
  10759. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  10760. /**
  10761. * Duplicates this Cartesian2 instance.
  10762. *
  10763. * @param {Cartesian2} [result] The object onto which to store the result.
  10764. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10765. */
  10766. Cartesian2.prototype.clone = function(result) {
  10767. return Cartesian2.clone(this, result);
  10768. };
  10769. /**
  10770. * Compares this Cartesian against the provided Cartesian componentwise and returns
  10771. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10772. *
  10773. * @param {Cartesian2} [right] The right hand side Cartesian.
  10774. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  10775. */
  10776. Cartesian2.prototype.equals = function(right) {
  10777. return Cartesian2.equals(this, right);
  10778. };
  10779. /**
  10780. * Compares this Cartesian against the provided Cartesian componentwise and returns
  10781. * <code>true</code> if they pass an absolute or relative tolerance test,
  10782. * <code>false</code> otherwise.
  10783. *
  10784. * @param {Cartesian2} [right] The right hand side Cartesian.
  10785. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  10786. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  10787. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  10788. */
  10789. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  10790. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  10791. };
  10792. /**
  10793. * Creates a string representing this Cartesian in the format '(x, y)'.
  10794. *
  10795. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  10796. */
  10797. Cartesian2.prototype.toString = function() {
  10798. return '(' + this.x + ', ' + this.y + ')';
  10799. };
  10800. return Cartesian2;
  10801. });
  10802. /*global define*/
  10803. define('Core/EllipsoidalOccluder',[
  10804. './BoundingSphere',
  10805. './Cartesian3',
  10806. './defaultValue',
  10807. './defined',
  10808. './defineProperties',
  10809. './DeveloperError',
  10810. './Rectangle'
  10811. ], function(
  10812. BoundingSphere,
  10813. Cartesian3,
  10814. defaultValue,
  10815. defined,
  10816. defineProperties,
  10817. DeveloperError,
  10818. Rectangle) {
  10819. 'use strict';
  10820. /**
  10821. * Determine whether or not other objects are visible or hidden behind the visible horizon defined by
  10822. * an {@link Ellipsoid} and a camera position. The ellipsoid is assumed to be located at the
  10823. * origin of the coordinate system. This class uses the algorithm described in the
  10824. * {@link http://cesiumjs.org/2013/04/25/Horizon-culling/|Horizon Culling} blog post.
  10825. *
  10826. * @alias EllipsoidalOccluder
  10827. *
  10828. * @param {Ellipsoid} ellipsoid The ellipsoid to use as an occluder.
  10829. * @param {Cartesian3} [cameraPosition] The coordinate of the viewer/camera. If this parameter is not
  10830. * specified, {@link EllipsoidalOccluder#cameraPosition} must be called before
  10831. * testing visibility.
  10832. *
  10833. * @constructor
  10834. *
  10835. * @example
  10836. * // Construct an ellipsoidal occluder with radii 1.0, 1.1, and 0.9.
  10837. * var cameraPosition = new Cesium.Cartesian3(5.0, 6.0, 7.0);
  10838. * var occluderEllipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
  10839. * var occluder = new Cesium.EllipsoidalOccluder(occluderEllipsoid, cameraPosition);
  10840. *
  10841. * @private
  10842. */
  10843. function EllipsoidalOccluder(ellipsoid, cameraPosition) {
  10844. if (!defined(ellipsoid)) {
  10845. throw new DeveloperError('ellipsoid is required.');
  10846. }
  10847. this._ellipsoid = ellipsoid;
  10848. this._cameraPosition = new Cartesian3();
  10849. this._cameraPositionInScaledSpace = new Cartesian3();
  10850. this._distanceToLimbInScaledSpaceSquared = 0.0;
  10851. // cameraPosition fills in the above values
  10852. if (defined(cameraPosition)) {
  10853. this.cameraPosition = cameraPosition;
  10854. }
  10855. }
  10856. defineProperties(EllipsoidalOccluder.prototype, {
  10857. /**
  10858. * Gets the occluding ellipsoid.
  10859. * @memberof EllipsoidalOccluder.prototype
  10860. * @type {Ellipsoid}
  10861. */
  10862. ellipsoid : {
  10863. get: function() {
  10864. return this._ellipsoid;
  10865. }
  10866. },
  10867. /**
  10868. * Gets or sets the position of the camera.
  10869. * @memberof EllipsoidalOccluder.prototype
  10870. * @type {Cartesian3}
  10871. */
  10872. cameraPosition : {
  10873. get : function() {
  10874. return this._cameraPosition;
  10875. },
  10876. set : function(cameraPosition) {
  10877. // See http://cesiumjs.org/2013/04/25/Horizon-culling/
  10878. var ellipsoid = this._ellipsoid;
  10879. var cv = ellipsoid.transformPositionToScaledSpace(cameraPosition, this._cameraPositionInScaledSpace);
  10880. var vhMagnitudeSquared = Cartesian3.magnitudeSquared(cv) - 1.0;
  10881. Cartesian3.clone(cameraPosition, this._cameraPosition);
  10882. this._cameraPositionInScaledSpace = cv;
  10883. this._distanceToLimbInScaledSpaceSquared = vhMagnitudeSquared;
  10884. }
  10885. }
  10886. });
  10887. var scratchCartesian = new Cartesian3();
  10888. /**
  10889. * Determines whether or not a point, the <code>occludee</code>, is hidden from view by the occluder.
  10890. *
  10891. * @param {Cartesian3} occludee The point to test for visibility.
  10892. * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
  10893. *
  10894. * @example
  10895. * var cameraPosition = new Cesium.Cartesian3(0, 0, 2.5);
  10896. * var ellipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
  10897. * var occluder = new Cesium.EllipsoidalOccluder(ellipsoid, cameraPosition);
  10898. * var point = new Cesium.Cartesian3(0, -3, -3);
  10899. * occluder.isPointVisible(point); //returns true
  10900. */
  10901. EllipsoidalOccluder.prototype.isPointVisible = function(occludee) {
  10902. var ellipsoid = this._ellipsoid;
  10903. var occludeeScaledSpacePosition = ellipsoid.transformPositionToScaledSpace(occludee, scratchCartesian);
  10904. return this.isScaledSpacePointVisible(occludeeScaledSpacePosition);
  10905. };
  10906. /**
  10907. * Determines whether or not a point expressed in the ellipsoid scaled space, is hidden from view by the
  10908. * occluder. To transform a Cartesian X, Y, Z position in the coordinate system aligned with the ellipsoid
  10909. * into the scaled space, call {@link Ellipsoid#transformPositionToScaledSpace}.
  10910. *
  10911. * @param {Cartesian3} occludeeScaledSpacePosition The point to test for visibility, represented in the scaled space.
  10912. * @returns {Boolean} <code>true</code> if the occludee is visible; otherwise <code>false</code>.
  10913. *
  10914. * @example
  10915. * var cameraPosition = new Cesium.Cartesian3(0, 0, 2.5);
  10916. * var ellipsoid = new Cesium.Ellipsoid(1.0, 1.1, 0.9);
  10917. * var occluder = new Cesium.EllipsoidalOccluder(ellipsoid, cameraPosition);
  10918. * var point = new Cesium.Cartesian3(0, -3, -3);
  10919. * var scaledSpacePoint = ellipsoid.transformPositionToScaledSpace(point);
  10920. * occluder.isScaledSpacePointVisible(scaledSpacePoint); //returns true
  10921. */
  10922. EllipsoidalOccluder.prototype.isScaledSpacePointVisible = function(occludeeScaledSpacePosition) {
  10923. // See http://cesiumjs.org/2013/04/25/Horizon-culling/
  10924. var cv = this._cameraPositionInScaledSpace;
  10925. var vhMagnitudeSquared = this._distanceToLimbInScaledSpaceSquared;
  10926. var vt = Cartesian3.subtract(occludeeScaledSpacePosition, cv, scratchCartesian);
  10927. var vtDotVc = -Cartesian3.dot(vt, cv);
  10928. // If vhMagnitudeSquared < 0 then we are below the surface of the ellipsoid and
  10929. // in this case, set the culling plane to be on V.
  10930. var isOccluded = vhMagnitudeSquared < 0 ? vtDotVc > 0 : (vtDotVc > vhMagnitudeSquared &&
  10931. vtDotVc * vtDotVc / Cartesian3.magnitudeSquared(vt) > vhMagnitudeSquared);
  10932. return !isOccluded;
  10933. };
  10934. /**
  10935. * Computes a point that can be used for horizon culling from a list of positions. If the point is below
  10936. * the horizon, all of the positions are guaranteed to be below the horizon as well. The returned point
  10937. * is expressed in the ellipsoid-scaled space and is suitable for use with
  10938. * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
  10939. *
  10940. * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
  10941. * A reasonable direction to use is the direction from the center of the ellipsoid to
  10942. * the center of the bounding sphere computed from the positions. The direction need not
  10943. * be normalized.
  10944. * @param {Cartesian3[]} positions The positions from which to compute the horizon culling point. The positions
  10945. * must be expressed in a reference frame centered at the ellipsoid and aligned with the
  10946. * ellipsoid's axes.
  10947. * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
  10948. * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
  10949. */
  10950. EllipsoidalOccluder.prototype.computeHorizonCullingPoint = function(directionToPoint, positions, result) {
  10951. if (!defined(directionToPoint)) {
  10952. throw new DeveloperError('directionToPoint is required');
  10953. }
  10954. if (!defined(positions)) {
  10955. throw new DeveloperError('positions is required');
  10956. }
  10957. if (!defined(result)) {
  10958. result = new Cartesian3();
  10959. }
  10960. var ellipsoid = this._ellipsoid;
  10961. var scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(ellipsoid, directionToPoint);
  10962. var resultMagnitude = 0.0;
  10963. for (var i = 0, len = positions.length; i < len; ++i) {
  10964. var position = positions[i];
  10965. var candidateMagnitude = computeMagnitude(ellipsoid, position, scaledSpaceDirectionToPoint);
  10966. resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
  10967. }
  10968. return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
  10969. };
  10970. var positionScratch = new Cartesian3();
  10971. /**
  10972. * Computes a point that can be used for horizon culling from a list of positions. If the point is below
  10973. * the horizon, all of the positions are guaranteed to be below the horizon as well. The returned point
  10974. * is expressed in the ellipsoid-scaled space and is suitable for use with
  10975. * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
  10976. *
  10977. * @param {Cartesian3} directionToPoint The direction that the computed point will lie along.
  10978. * A reasonable direction to use is the direction from the center of the ellipsoid to
  10979. * the center of the bounding sphere computed from the positions. The direction need not
  10980. * be normalized.
  10981. * @param {Number[]} vertices The vertices from which to compute the horizon culling point. The positions
  10982. * must be expressed in a reference frame centered at the ellipsoid and aligned with the
  10983. * ellipsoid's axes.
  10984. * @param {Number} [stride=3]
  10985. * @param {Cartesian3} [center=Cartesian3.ZERO]
  10986. * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
  10987. * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
  10988. */
  10989. EllipsoidalOccluder.prototype.computeHorizonCullingPointFromVertices = function(directionToPoint, vertices, stride, center, result) {
  10990. if (!defined(directionToPoint)) {
  10991. throw new DeveloperError('directionToPoint is required');
  10992. }
  10993. if (!defined(vertices)) {
  10994. throw new DeveloperError('vertices is required');
  10995. }
  10996. if (!defined(stride)) {
  10997. throw new DeveloperError('stride is required');
  10998. }
  10999. if (!defined(result)) {
  11000. result = new Cartesian3();
  11001. }
  11002. center = defaultValue(center, Cartesian3.ZERO);
  11003. var ellipsoid = this._ellipsoid;
  11004. var scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(ellipsoid, directionToPoint);
  11005. var resultMagnitude = 0.0;
  11006. for (var i = 0, len = vertices.length; i < len; i += stride) {
  11007. positionScratch.x = vertices[i] + center.x;
  11008. positionScratch.y = vertices[i + 1] + center.y;
  11009. positionScratch.z = vertices[i + 2] + center.z;
  11010. var candidateMagnitude = computeMagnitude(ellipsoid, positionScratch, scaledSpaceDirectionToPoint);
  11011. resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
  11012. }
  11013. return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
  11014. };
  11015. var subsampleScratch = [];
  11016. /**
  11017. * Computes a point that can be used for horizon culling of an rectangle. If the point is below
  11018. * the horizon, the ellipsoid-conforming rectangle is guaranteed to be below the horizon as well.
  11019. * The returned point is expressed in the ellipsoid-scaled space and is suitable for use with
  11020. * {@link EllipsoidalOccluder#isScaledSpacePointVisible}.
  11021. *
  11022. * @param {Rectangle} rectangle The rectangle for which to compute the horizon culling point.
  11023. * @param {Ellipsoid} ellipsoid The ellipsoid on which the rectangle is defined. This may be different from
  11024. * the ellipsoid used by this instance for occlusion testing.
  11025. * @param {Cartesian3} [result] The instance on which to store the result instead of allocating a new instance.
  11026. * @returns {Cartesian3} The computed horizon culling point, expressed in the ellipsoid-scaled space.
  11027. */
  11028. EllipsoidalOccluder.prototype.computeHorizonCullingPointFromRectangle = function(rectangle, ellipsoid, result) {
  11029. if (!defined(rectangle)) {
  11030. throw new DeveloperError('rectangle is required.');
  11031. }
  11032. var positions = Rectangle.subsample(rectangle, ellipsoid, 0.0, subsampleScratch);
  11033. var bs = BoundingSphere.fromPoints(positions);
  11034. // If the bounding sphere center is too close to the center of the occluder, it doesn't make
  11035. // sense to try to horizon cull it.
  11036. if (Cartesian3.magnitude(bs.center) < 0.1 * ellipsoid.minimumRadius) {
  11037. return undefined;
  11038. }
  11039. return this.computeHorizonCullingPoint(bs.center, positions, result);
  11040. };
  11041. var scaledSpaceScratch = new Cartesian3();
  11042. var directionScratch = new Cartesian3();
  11043. function computeMagnitude(ellipsoid, position, scaledSpaceDirectionToPoint) {
  11044. var scaledSpacePosition = ellipsoid.transformPositionToScaledSpace(position, scaledSpaceScratch);
  11045. var magnitudeSquared = Cartesian3.magnitudeSquared(scaledSpacePosition);
  11046. var magnitude = Math.sqrt(magnitudeSquared);
  11047. var direction = Cartesian3.divideByScalar(scaledSpacePosition, magnitude, directionScratch);
  11048. // For the purpose of this computation, points below the ellipsoid are consider to be on it instead.
  11049. magnitudeSquared = Math.max(1.0, magnitudeSquared);
  11050. magnitude = Math.max(1.0, magnitude);
  11051. var cosAlpha = Cartesian3.dot(direction, scaledSpaceDirectionToPoint);
  11052. var sinAlpha = Cartesian3.magnitude(Cartesian3.cross(direction, scaledSpaceDirectionToPoint, direction));
  11053. var cosBeta = 1.0 / magnitude;
  11054. var sinBeta = Math.sqrt(magnitudeSquared - 1.0) * cosBeta;
  11055. return 1.0 / (cosAlpha * cosBeta - sinAlpha * sinBeta);
  11056. }
  11057. function magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result) {
  11058. // The horizon culling point is undefined if there were no positions from which to compute it,
  11059. // the directionToPoint is pointing opposite all of the positions, or if we computed NaN or infinity.
  11060. if (resultMagnitude <= 0.0 || resultMagnitude === 1.0 / 0.0 || resultMagnitude !== resultMagnitude) {
  11061. return undefined;
  11062. }
  11063. return Cartesian3.multiplyByScalar(scaledSpaceDirectionToPoint, resultMagnitude, result);
  11064. }
  11065. var directionToPointScratch = new Cartesian3();
  11066. function computeScaledSpaceDirectionToPoint(ellipsoid, directionToPoint) {
  11067. if (Cartesian3.equals(directionToPoint, Cartesian3.ZERO)) {
  11068. return directionToPoint;
  11069. }
  11070. ellipsoid.transformPositionToScaledSpace(directionToPoint, directionToPointScratch);
  11071. return Cartesian3.normalize(directionToPointScratch, directionToPointScratch);
  11072. }
  11073. return EllipsoidalOccluder;
  11074. });
  11075. /*global define*/
  11076. define('Core/QuadraticRealPolynomial',[
  11077. './DeveloperError',
  11078. './Math'
  11079. ], function(
  11080. DeveloperError,
  11081. CesiumMath) {
  11082. 'use strict';
  11083. /**
  11084. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  11085. *
  11086. * @exports QuadraticRealPolynomial
  11087. */
  11088. var QuadraticRealPolynomial = {};
  11089. /**
  11090. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  11091. *
  11092. * @param {Number} a The coefficient of the 2nd order monomial.
  11093. * @param {Number} b The coefficient of the 1st order monomial.
  11094. * @param {Number} c The coefficient of the 0th order monomial.
  11095. * @returns {Number} The value of the discriminant.
  11096. */
  11097. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  11098. if (typeof a !== 'number') {
  11099. throw new DeveloperError('a is a required number.');
  11100. }
  11101. if (typeof b !== 'number') {
  11102. throw new DeveloperError('b is a required number.');
  11103. }
  11104. if (typeof c !== 'number') {
  11105. throw new DeveloperError('c is a required number.');
  11106. }
  11107. var discriminant = b * b - 4.0 * a * c;
  11108. return discriminant;
  11109. };
  11110. function addWithCancellationCheck(left, right, tolerance) {
  11111. var difference = left + right;
  11112. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  11113. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  11114. return 0.0;
  11115. }
  11116. return difference;
  11117. }
  11118. /**
  11119. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  11120. *
  11121. * @param {Number} a The coefficient of the 2nd order monomial.
  11122. * @param {Number} b The coefficient of the 1st order monomial.
  11123. * @param {Number} c The coefficient of the 0th order monomial.
  11124. * @returns {Number[]} The real valued roots.
  11125. */
  11126. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  11127. if (typeof a !== 'number') {
  11128. throw new DeveloperError('a is a required number.');
  11129. }
  11130. if (typeof b !== 'number') {
  11131. throw new DeveloperError('b is a required number.');
  11132. }
  11133. if (typeof c !== 'number') {
  11134. throw new DeveloperError('c is a required number.');
  11135. }
  11136. var ratio;
  11137. if (a === 0.0) {
  11138. if (b === 0.0) {
  11139. // Constant function: c = 0.
  11140. return [];
  11141. }
  11142. // Linear function: b * x + c = 0.
  11143. return [-c / b];
  11144. } else if (b === 0.0) {
  11145. if (c === 0.0) {
  11146. // 2nd order monomial: a * x^2 = 0.
  11147. return [0.0, 0.0];
  11148. }
  11149. var cMagnitude = Math.abs(c);
  11150. var aMagnitude = Math.abs(a);
  11151. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  11152. // 2nd order monomial: a * x^2 = 0.
  11153. return [0.0, 0.0];
  11154. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  11155. // Constant function: c = 0.
  11156. return [];
  11157. }
  11158. // a * x^2 + c = 0
  11159. ratio = -c / a;
  11160. if (ratio < 0.0) {
  11161. // Both roots are complex.
  11162. return [];
  11163. }
  11164. // Both roots are real.
  11165. var root = Math.sqrt(ratio);
  11166. return [-root, root];
  11167. } else if (c === 0.0) {
  11168. // a * x^2 + b * x = 0
  11169. ratio = -b / a;
  11170. if (ratio < 0.0) {
  11171. return [ratio, 0.0];
  11172. }
  11173. return [0.0, ratio];
  11174. }
  11175. // a * x^2 + b * x + c = 0
  11176. var b2 = b * b;
  11177. var four_ac = 4.0 * a * c;
  11178. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  11179. if (radicand < 0.0) {
  11180. // Both roots are complex.
  11181. return [];
  11182. }
  11183. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  11184. if (b > 0.0) {
  11185. return [q / a, c / q];
  11186. }
  11187. return [c / q, q / a];
  11188. };
  11189. return QuadraticRealPolynomial;
  11190. });
  11191. /*global define*/
  11192. define('Core/CubicRealPolynomial',[
  11193. './DeveloperError',
  11194. './QuadraticRealPolynomial'
  11195. ], function(
  11196. DeveloperError,
  11197. QuadraticRealPolynomial) {
  11198. 'use strict';
  11199. /**
  11200. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  11201. *
  11202. * @exports CubicRealPolynomial
  11203. */
  11204. var CubicRealPolynomial = {};
  11205. /**
  11206. * Provides the discriminant of the cubic equation from the supplied coefficients.
  11207. *
  11208. * @param {Number} a The coefficient of the 3rd order monomial.
  11209. * @param {Number} b The coefficient of the 2nd order monomial.
  11210. * @param {Number} c The coefficient of the 1st order monomial.
  11211. * @param {Number} d The coefficient of the 0th order monomial.
  11212. * @returns {Number} The value of the discriminant.
  11213. */
  11214. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  11215. if (typeof a !== 'number') {
  11216. throw new DeveloperError('a is a required number.');
  11217. }
  11218. if (typeof b !== 'number') {
  11219. throw new DeveloperError('b is a required number.');
  11220. }
  11221. if (typeof c !== 'number') {
  11222. throw new DeveloperError('c is a required number.');
  11223. }
  11224. if (typeof d !== 'number') {
  11225. throw new DeveloperError('d is a required number.');
  11226. }
  11227. var a2 = a * a;
  11228. var b2 = b * b;
  11229. var c2 = c * c;
  11230. var d2 = d * d;
  11231. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  11232. return discriminant;
  11233. };
  11234. function computeRealRoots(a, b, c, d) {
  11235. var A = a;
  11236. var B = b / 3.0;
  11237. var C = c / 3.0;
  11238. var D = d;
  11239. var AC = A * C;
  11240. var BD = B * D;
  11241. var B2 = B * B;
  11242. var C2 = C * C;
  11243. var delta1 = A * C - B2;
  11244. var delta2 = A * D - B * C;
  11245. var delta3 = B * D - C2;
  11246. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  11247. var temp;
  11248. var temp1;
  11249. if (discriminant < 0.0) {
  11250. var ABar;
  11251. var CBar;
  11252. var DBar;
  11253. if (B2 * BD >= AC * C2) {
  11254. ABar = A;
  11255. CBar = delta1;
  11256. DBar = -2.0 * B * delta1 + A * delta2;
  11257. } else {
  11258. ABar = D;
  11259. CBar = delta3;
  11260. DBar = -D * delta2 + 2.0 * C * delta3;
  11261. }
  11262. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  11263. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  11264. temp1 = -DBar + temp0;
  11265. var x = temp1 / 2.0;
  11266. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  11267. var q = (temp1 === temp0) ? -p : -CBar / p;
  11268. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  11269. if (B2 * BD >= AC * C2) {
  11270. return [(temp - B) / A];
  11271. }
  11272. return [-D / (temp + C)];
  11273. }
  11274. var CBarA = delta1;
  11275. var DBarA = -2.0 * B * delta1 + A * delta2;
  11276. var CBarD = delta3;
  11277. var DBarD = -D * delta2 + 2.0 * C * delta3;
  11278. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  11279. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  11280. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  11281. temp = 2.0 * Math.sqrt(-CBarA);
  11282. var cosine = Math.cos(theta);
  11283. temp1 = temp * cosine;
  11284. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  11285. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  11286. var denominatorLarge = A;
  11287. var root1 = numeratorLarge / denominatorLarge;
  11288. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  11289. temp = 2.0 * Math.sqrt(-CBarD);
  11290. cosine = Math.cos(theta);
  11291. temp1 = temp * cosine;
  11292. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  11293. var numeratorSmall = -D;
  11294. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  11295. var root3 = numeratorSmall / denominatorSmall;
  11296. var E = denominatorLarge * denominatorSmall;
  11297. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  11298. var G = numeratorLarge * numeratorSmall;
  11299. var root2 = (C * F - B * G) / (-B * F + C * E);
  11300. if (root1 <= root2) {
  11301. if (root1 <= root3) {
  11302. if (root2 <= root3) {
  11303. return [root1, root2, root3];
  11304. }
  11305. return [root1, root3, root2];
  11306. }
  11307. return [root3, root1, root2];
  11308. }
  11309. if (root1 <= root3) {
  11310. return [root2, root1, root3];
  11311. }
  11312. if (root2 <= root3) {
  11313. return [root2, root3, root1];
  11314. }
  11315. return [root3, root2, root1];
  11316. }
  11317. /**
  11318. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  11319. *
  11320. * @param {Number} a The coefficient of the 3rd order monomial.
  11321. * @param {Number} b The coefficient of the 2nd order monomial.
  11322. * @param {Number} c The coefficient of the 1st order monomial.
  11323. * @param {Number} d The coefficient of the 0th order monomial.
  11324. * @returns {Number[]} The real valued roots.
  11325. */
  11326. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  11327. if (typeof a !== 'number') {
  11328. throw new DeveloperError('a is a required number.');
  11329. }
  11330. if (typeof b !== 'number') {
  11331. throw new DeveloperError('b is a required number.');
  11332. }
  11333. if (typeof c !== 'number') {
  11334. throw new DeveloperError('c is a required number.');
  11335. }
  11336. if (typeof d !== 'number') {
  11337. throw new DeveloperError('d is a required number.');
  11338. }
  11339. var roots;
  11340. var ratio;
  11341. if (a === 0.0) {
  11342. // Quadratic function: b * x^2 + c * x + d = 0.
  11343. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  11344. } else if (b === 0.0) {
  11345. if (c === 0.0) {
  11346. if (d === 0.0) {
  11347. // 3rd order monomial: a * x^3 = 0.
  11348. return [0.0, 0.0, 0.0];
  11349. }
  11350. // a * x^3 + d = 0
  11351. ratio = -d / a;
  11352. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  11353. return [root, root, root];
  11354. } else if (d === 0.0) {
  11355. // x * (a * x^2 + c) = 0.
  11356. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  11357. // Return the roots in ascending order.
  11358. if (roots.Length === 0) {
  11359. return [0.0];
  11360. }
  11361. return [roots[0], 0.0, roots[1]];
  11362. }
  11363. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  11364. return computeRealRoots(a, 0, c, d);
  11365. } else if (c === 0.0) {
  11366. if (d === 0.0) {
  11367. // x^2 * (a * x + b) = 0.
  11368. ratio = -b / a;
  11369. if (ratio < 0.0) {
  11370. return [ratio, 0.0, 0.0];
  11371. }
  11372. return [0.0, 0.0, ratio];
  11373. }
  11374. // a * x^3 + b * x^2 + d = 0.
  11375. return computeRealRoots(a, b, 0, d);
  11376. } else if (d === 0.0) {
  11377. // x * (a * x^2 + b * x + c) = 0
  11378. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  11379. // Return the roots in ascending order.
  11380. if (roots.length === 0) {
  11381. return [0.0];
  11382. } else if (roots[1] <= 0.0) {
  11383. return [roots[0], roots[1], 0.0];
  11384. } else if (roots[0] >= 0.0) {
  11385. return [0.0, roots[0], roots[1]];
  11386. }
  11387. return [roots[0], 0.0, roots[1]];
  11388. }
  11389. return computeRealRoots(a, b, c, d);
  11390. };
  11391. return CubicRealPolynomial;
  11392. });
  11393. /*global define*/
  11394. define('Core/QuarticRealPolynomial',[
  11395. './CubicRealPolynomial',
  11396. './DeveloperError',
  11397. './Math',
  11398. './QuadraticRealPolynomial'
  11399. ], function(
  11400. CubicRealPolynomial,
  11401. DeveloperError,
  11402. CesiumMath,
  11403. QuadraticRealPolynomial) {
  11404. 'use strict';
  11405. /**
  11406. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  11407. *
  11408. * @exports QuarticRealPolynomial
  11409. */
  11410. var QuarticRealPolynomial = {};
  11411. /**
  11412. * Provides the discriminant of the quartic equation from the supplied coefficients.
  11413. *
  11414. * @param {Number} a The coefficient of the 4th order monomial.
  11415. * @param {Number} b The coefficient of the 3rd order monomial.
  11416. * @param {Number} c The coefficient of the 2nd order monomial.
  11417. * @param {Number} d The coefficient of the 1st order monomial.
  11418. * @param {Number} e The coefficient of the 0th order monomial.
  11419. * @returns {Number} The value of the discriminant.
  11420. */
  11421. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  11422. if (typeof a !== 'number') {
  11423. throw new DeveloperError('a is a required number.');
  11424. }
  11425. if (typeof b !== 'number') {
  11426. throw new DeveloperError('b is a required number.');
  11427. }
  11428. if (typeof c !== 'number') {
  11429. throw new DeveloperError('c is a required number.');
  11430. }
  11431. if (typeof d !== 'number') {
  11432. throw new DeveloperError('d is a required number.');
  11433. }
  11434. if (typeof e !== 'number') {
  11435. throw new DeveloperError('e is a required number.');
  11436. }
  11437. var a2 = a * a;
  11438. var a3 = a2 * a;
  11439. var b2 = b * b;
  11440. var b3 = b2 * b;
  11441. var c2 = c * c;
  11442. var c3 = c2 * c;
  11443. var d2 = d * d;
  11444. var d3 = d2 * d;
  11445. var e2 = e * e;
  11446. var e3 = e2 * e;
  11447. 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) +
  11448. 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) +
  11449. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  11450. return discriminant;
  11451. };
  11452. function original(a3, a2, a1, a0) {
  11453. var a3Squared = a3 * a3;
  11454. var p = a2 - 3.0 * a3Squared / 8.0;
  11455. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  11456. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  11457. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  11458. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  11459. if (cubicRoots.length > 0) {
  11460. var temp = -a3 / 4.0;
  11461. // Use the largest positive root.
  11462. var hSquared = cubicRoots[cubicRoots.length - 1];
  11463. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  11464. // y^4 + p y^2 + r = 0.
  11465. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  11466. if (roots.length === 2) {
  11467. var root0 = roots[0];
  11468. var root1 = roots[1];
  11469. var y;
  11470. if (root0 >= 0.0 && root1 >= 0.0) {
  11471. var y0 = Math.sqrt(root0);
  11472. var y1 = Math.sqrt(root1);
  11473. return [temp - y1, temp - y0, temp + y0, temp + y1];
  11474. } else if (root0 >= 0.0 && root1 < 0.0) {
  11475. y = Math.sqrt(root0);
  11476. return [temp - y, temp + y];
  11477. } else if (root0 < 0.0 && root1 >= 0.0) {
  11478. y = Math.sqrt(root1);
  11479. return [temp - y, temp + y];
  11480. }
  11481. }
  11482. return [];
  11483. } else if (hSquared > 0.0) {
  11484. var h = Math.sqrt(hSquared);
  11485. var m = (p + hSquared - q / h) / 2.0;
  11486. var n = (p + hSquared + q / h) / 2.0;
  11487. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  11488. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  11489. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  11490. if (roots1.length !== 0) {
  11491. roots1[0] += temp;
  11492. roots1[1] += temp;
  11493. if (roots2.length !== 0) {
  11494. roots2[0] += temp;
  11495. roots2[1] += temp;
  11496. if (roots1[1] <= roots2[0]) {
  11497. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  11498. } else if (roots2[1] <= roots1[0]) {
  11499. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  11500. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  11501. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  11502. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  11503. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  11504. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  11505. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  11506. }
  11507. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  11508. }
  11509. return roots1;
  11510. }
  11511. if (roots2.length !== 0) {
  11512. roots2[0] += temp;
  11513. roots2[1] += temp;
  11514. return roots2;
  11515. }
  11516. return [];
  11517. }
  11518. }
  11519. return [];
  11520. }
  11521. function neumark(a3, a2, a1, a0) {
  11522. var a1Squared = a1 * a1;
  11523. var a2Squared = a2 * a2;
  11524. var a3Squared = a3 * a3;
  11525. var p = -2.0 * a2;
  11526. var q = a1 * a3 + a2Squared - 4.0 * a0;
  11527. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  11528. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  11529. if (cubicRoots.length > 0) {
  11530. // Use the most positive root
  11531. var y = cubicRoots[0];
  11532. var temp = (a2 - y);
  11533. var tempSquared = temp * temp;
  11534. var g1 = a3 / 2.0;
  11535. var h1 = temp / 2.0;
  11536. var m = tempSquared - 4.0 * a0;
  11537. var mError = tempSquared + 4.0 * Math.abs(a0);
  11538. var n = a3Squared - 4.0 * y;
  11539. var nError = a3Squared + 4.0 * Math.abs(y);
  11540. var g2;
  11541. var h2;
  11542. if (y < 0.0 || (m * nError < n * mError)) {
  11543. var squareRootOfN = Math.sqrt(n);
  11544. g2 = squareRootOfN / 2.0;
  11545. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  11546. } else {
  11547. var squareRootOfM = Math.sqrt(m);
  11548. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  11549. h2 = squareRootOfM / 2.0;
  11550. }
  11551. var G;
  11552. var g;
  11553. if (g1 === 0.0 && g2 === 0.0) {
  11554. G = 0.0;
  11555. g = 0.0;
  11556. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  11557. G = g1 + g2;
  11558. g = y / G;
  11559. } else {
  11560. g = g1 - g2;
  11561. G = y / g;
  11562. }
  11563. var H;
  11564. var h;
  11565. if (h1 === 0.0 && h2 === 0.0) {
  11566. H = 0.0;
  11567. h = 0.0;
  11568. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  11569. H = h1 + h2;
  11570. h = a0 / H;
  11571. } else {
  11572. h = h1 - h2;
  11573. H = a0 / h;
  11574. }
  11575. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  11576. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  11577. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  11578. if (roots1.length !== 0) {
  11579. if (roots2.length !== 0) {
  11580. if (roots1[1] <= roots2[0]) {
  11581. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  11582. } else if (roots2[1] <= roots1[0]) {
  11583. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  11584. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  11585. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  11586. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  11587. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  11588. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  11589. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  11590. } else {
  11591. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  11592. }
  11593. }
  11594. return roots1;
  11595. }
  11596. if (roots2.length !== 0) {
  11597. return roots2;
  11598. }
  11599. }
  11600. return [];
  11601. }
  11602. /**
  11603. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  11604. *
  11605. * @param {Number} a The coefficient of the 4th order monomial.
  11606. * @param {Number} b The coefficient of the 3rd order monomial.
  11607. * @param {Number} c The coefficient of the 2nd order monomial.
  11608. * @param {Number} d The coefficient of the 1st order monomial.
  11609. * @param {Number} e The coefficient of the 0th order monomial.
  11610. * @returns {Number[]} The real valued roots.
  11611. */
  11612. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  11613. if (typeof a !== 'number') {
  11614. throw new DeveloperError('a is a required number.');
  11615. }
  11616. if (typeof b !== 'number') {
  11617. throw new DeveloperError('b is a required number.');
  11618. }
  11619. if (typeof c !== 'number') {
  11620. throw new DeveloperError('c is a required number.');
  11621. }
  11622. if (typeof d !== 'number') {
  11623. throw new DeveloperError('d is a required number.');
  11624. }
  11625. if (typeof e !== 'number') {
  11626. throw new DeveloperError('e is a required number.');
  11627. }
  11628. if (Math.abs(a) < CesiumMath.EPSILON15) {
  11629. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  11630. }
  11631. var a3 = b / a;
  11632. var a2 = c / a;
  11633. var a1 = d / a;
  11634. var a0 = e / a;
  11635. var k = (a3 < 0.0) ? 1 : 0;
  11636. k += (a2 < 0.0) ? k + 1 : k;
  11637. k += (a1 < 0.0) ? k + 1 : k;
  11638. k += (a0 < 0.0) ? k + 1 : k;
  11639. switch (k) {
  11640. case 0:
  11641. return original(a3, a2, a1, a0);
  11642. case 1:
  11643. return neumark(a3, a2, a1, a0);
  11644. case 2:
  11645. return neumark(a3, a2, a1, a0);
  11646. case 3:
  11647. return original(a3, a2, a1, a0);
  11648. case 4:
  11649. return original(a3, a2, a1, a0);
  11650. case 5:
  11651. return neumark(a3, a2, a1, a0);
  11652. case 6:
  11653. return original(a3, a2, a1, a0);
  11654. case 7:
  11655. return original(a3, a2, a1, a0);
  11656. case 8:
  11657. return neumark(a3, a2, a1, a0);
  11658. case 9:
  11659. return original(a3, a2, a1, a0);
  11660. case 10:
  11661. return original(a3, a2, a1, a0);
  11662. case 11:
  11663. return neumark(a3, a2, a1, a0);
  11664. case 12:
  11665. return original(a3, a2, a1, a0);
  11666. case 13:
  11667. return original(a3, a2, a1, a0);
  11668. case 14:
  11669. return original(a3, a2, a1, a0);
  11670. case 15:
  11671. return original(a3, a2, a1, a0);
  11672. default:
  11673. return undefined;
  11674. }
  11675. };
  11676. return QuarticRealPolynomial;
  11677. });
  11678. /*global define*/
  11679. define('Core/Ray',[
  11680. './Cartesian3',
  11681. './defaultValue',
  11682. './defined',
  11683. './DeveloperError'
  11684. ], function(
  11685. Cartesian3,
  11686. defaultValue,
  11687. defined,
  11688. DeveloperError) {
  11689. 'use strict';
  11690. /**
  11691. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  11692. * @alias Ray
  11693. * @constructor
  11694. *
  11695. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  11696. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  11697. */
  11698. function Ray(origin, direction) {
  11699. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  11700. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  11701. Cartesian3.normalize(direction, direction);
  11702. }
  11703. /**
  11704. * The origin of the ray.
  11705. * @type {Cartesian3}
  11706. * @default {@link Cartesian3.ZERO}
  11707. */
  11708. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  11709. /**
  11710. * The direction of the ray.
  11711. * @type {Cartesian3}
  11712. */
  11713. this.direction = direction;
  11714. }
  11715. /**
  11716. * Computes the point along the ray given by r(t) = o + t*d,
  11717. * where o is the origin of the ray and d is the direction.
  11718. *
  11719. * @param {Ray} ray The ray.
  11720. * @param {Number} t A scalar value.
  11721. * @param {Cartesian3} [result] The object in which the result will be stored.
  11722. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  11723. *
  11724. * @example
  11725. * //Get the first intersection point of a ray and an ellipsoid.
  11726. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  11727. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  11728. */
  11729. Ray.getPoint = function(ray, t, result) {
  11730. if (!defined(ray)){
  11731. throw new DeveloperError('ray is requred');
  11732. }
  11733. if (typeof t !== 'number') {
  11734. throw new DeveloperError('t is a required number');
  11735. }
  11736. if (!defined(result)) {
  11737. result = new Cartesian3();
  11738. }
  11739. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  11740. return Cartesian3.add(ray.origin, result, result);
  11741. };
  11742. return Ray;
  11743. });
  11744. /*global define*/
  11745. define('Core/IntersectionTests',[
  11746. './Cartesian3',
  11747. './Cartographic',
  11748. './defaultValue',
  11749. './defined',
  11750. './DeveloperError',
  11751. './Math',
  11752. './Matrix3',
  11753. './QuadraticRealPolynomial',
  11754. './QuarticRealPolynomial',
  11755. './Ray'
  11756. ], function(
  11757. Cartesian3,
  11758. Cartographic,
  11759. defaultValue,
  11760. defined,
  11761. DeveloperError,
  11762. CesiumMath,
  11763. Matrix3,
  11764. QuadraticRealPolynomial,
  11765. QuarticRealPolynomial,
  11766. Ray) {
  11767. 'use strict';
  11768. /**
  11769. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  11770. *
  11771. * @exports IntersectionTests
  11772. */
  11773. var IntersectionTests = {};
  11774. /**
  11775. * Computes the intersection of a ray and a plane.
  11776. *
  11777. * @param {Ray} ray The ray.
  11778. * @param {Plane} plane The plane.
  11779. * @param {Cartesian3} [result] The object onto which to store the result.
  11780. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  11781. */
  11782. IntersectionTests.rayPlane = function(ray, plane, result) {
  11783. if (!defined(ray)) {
  11784. throw new DeveloperError('ray is required.');
  11785. }
  11786. if (!defined(plane)) {
  11787. throw new DeveloperError('plane is required.');
  11788. }
  11789. if (!defined(result)) {
  11790. result = new Cartesian3();
  11791. }
  11792. var origin = ray.origin;
  11793. var direction = ray.direction;
  11794. var normal = plane.normal;
  11795. var denominator = Cartesian3.dot(normal, direction);
  11796. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  11797. // Ray is parallel to plane. The ray may be in the polygon's plane.
  11798. return undefined;
  11799. }
  11800. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  11801. if (t < 0) {
  11802. return undefined;
  11803. }
  11804. result = Cartesian3.multiplyByScalar(direction, t, result);
  11805. return Cartesian3.add(origin, result, result);
  11806. };
  11807. var scratchEdge0 = new Cartesian3();
  11808. var scratchEdge1 = new Cartesian3();
  11809. var scratchPVec = new Cartesian3();
  11810. var scratchTVec = new Cartesian3();
  11811. var scratchQVec = new Cartesian3();
  11812. /**
  11813. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  11814. *
  11815. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  11816. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  11817. *
  11818. * @memberof IntersectionTests
  11819. *
  11820. * @param {Ray} ray The ray.
  11821. * @param {Cartesian3} p0 The first vertex of the triangle.
  11822. * @param {Cartesian3} p1 The second vertex of the triangle.
  11823. * @param {Cartesian3} p2 The third vertex of the triangle.
  11824. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  11825. * and return undefined for intersections with the back face.
  11826. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  11827. */
  11828. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  11829. if (!defined(ray)) {
  11830. throw new DeveloperError('ray is required.');
  11831. }
  11832. if (!defined(p0)) {
  11833. throw new DeveloperError('p0 is required.');
  11834. }
  11835. if (!defined(p1)) {
  11836. throw new DeveloperError('p1 is required.');
  11837. }
  11838. if (!defined(p2)) {
  11839. throw new DeveloperError('p2 is required.');
  11840. }
  11841. cullBackFaces = defaultValue(cullBackFaces, false);
  11842. var origin = ray.origin;
  11843. var direction = ray.direction;
  11844. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  11845. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  11846. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  11847. var det = Cartesian3.dot(edge0, p);
  11848. var tvec;
  11849. var q;
  11850. var u;
  11851. var v;
  11852. var t;
  11853. if (cullBackFaces) {
  11854. if (det < CesiumMath.EPSILON6) {
  11855. return undefined;
  11856. }
  11857. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  11858. u = Cartesian3.dot(tvec, p);
  11859. if (u < 0.0 || u > det) {
  11860. return undefined;
  11861. }
  11862. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  11863. v = Cartesian3.dot(direction, q);
  11864. if (v < 0.0 || u + v > det) {
  11865. return undefined;
  11866. }
  11867. t = Cartesian3.dot(edge1, q) / det;
  11868. } else {
  11869. if (Math.abs(det) < CesiumMath.EPSILON6) {
  11870. return undefined;
  11871. }
  11872. var invDet = 1.0 / det;
  11873. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  11874. u = Cartesian3.dot(tvec, p) * invDet;
  11875. if (u < 0.0 || u > 1.0) {
  11876. return undefined;
  11877. }
  11878. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  11879. v = Cartesian3.dot(direction, q) * invDet;
  11880. if (v < 0.0 || u + v > 1.0) {
  11881. return undefined;
  11882. }
  11883. t = Cartesian3.dot(edge1, q) * invDet;
  11884. }
  11885. return t;
  11886. };
  11887. /**
  11888. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  11889. *
  11890. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  11891. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  11892. *
  11893. * @memberof IntersectionTests
  11894. *
  11895. * @param {Ray} ray The ray.
  11896. * @param {Cartesian3} p0 The first vertex of the triangle.
  11897. * @param {Cartesian3} p1 The second vertex of the triangle.
  11898. * @param {Cartesian3} p2 The third vertex of the triangle.
  11899. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  11900. * and return undefined for intersections with the back face.
  11901. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  11902. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  11903. */
  11904. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  11905. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  11906. if (!defined(t) || t < 0.0) {
  11907. return undefined;
  11908. }
  11909. if (!defined(result)) {
  11910. result = new Cartesian3();
  11911. }
  11912. Cartesian3.multiplyByScalar(ray.direction, t, result);
  11913. return Cartesian3.add(ray.origin, result, result);
  11914. };
  11915. var scratchLineSegmentTriangleRay = new Ray();
  11916. /**
  11917. * Computes the intersection of a line segment and a triangle.
  11918. * @memberof IntersectionTests
  11919. *
  11920. * @param {Cartesian3} v0 The an end point of the line segment.
  11921. * @param {Cartesian3} v1 The other end point of the line segment.
  11922. * @param {Cartesian3} p0 The first vertex of the triangle.
  11923. * @param {Cartesian3} p1 The second vertex of the triangle.
  11924. * @param {Cartesian3} p2 The third vertex of the triangle.
  11925. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  11926. * and return undefined for intersections with the back face.
  11927. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  11928. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  11929. */
  11930. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  11931. if (!defined(v0)) {
  11932. throw new DeveloperError('v0 is required.');
  11933. }
  11934. if (!defined(v1)) {
  11935. throw new DeveloperError('v1 is required.');
  11936. }
  11937. if (!defined(p0)) {
  11938. throw new DeveloperError('p0 is required.');
  11939. }
  11940. if (!defined(p1)) {
  11941. throw new DeveloperError('p1 is required.');
  11942. }
  11943. if (!defined(p2)) {
  11944. throw new DeveloperError('p2 is required.');
  11945. }
  11946. var ray = scratchLineSegmentTriangleRay;
  11947. Cartesian3.clone(v0, ray.origin);
  11948. Cartesian3.subtract(v1, v0, ray.direction);
  11949. Cartesian3.normalize(ray.direction, ray.direction);
  11950. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  11951. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  11952. return undefined;
  11953. }
  11954. if (!defined(result)) {
  11955. result = new Cartesian3();
  11956. }
  11957. Cartesian3.multiplyByScalar(ray.direction, t, result);
  11958. return Cartesian3.add(ray.origin, result, result);
  11959. };
  11960. function solveQuadratic(a, b, c, result) {
  11961. var det = b * b - 4.0 * a * c;
  11962. if (det < 0.0) {
  11963. return undefined;
  11964. } else if (det > 0.0) {
  11965. var denom = 1.0 / (2.0 * a);
  11966. var disc = Math.sqrt(det);
  11967. var root0 = (-b + disc) * denom;
  11968. var root1 = (-b - disc) * denom;
  11969. if (root0 < root1) {
  11970. result.root0 = root0;
  11971. result.root1 = root1;
  11972. } else {
  11973. result.root0 = root1;
  11974. result.root1 = root0;
  11975. }
  11976. return result;
  11977. }
  11978. var root = -b / (2.0 * a);
  11979. if (root === 0.0) {
  11980. return undefined;
  11981. }
  11982. result.root0 = result.root1 = root;
  11983. return result;
  11984. }
  11985. var raySphereRoots = {
  11986. root0 : 0.0,
  11987. root1 : 0.0
  11988. };
  11989. function raySphere(ray, sphere, result) {
  11990. if (!defined(result)) {
  11991. result = {};
  11992. }
  11993. var origin = ray.origin;
  11994. var direction = ray.direction;
  11995. var center = sphere.center;
  11996. var radiusSquared = sphere.radius * sphere.radius;
  11997. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  11998. var a = Cartesian3.dot(direction, direction);
  11999. var b = 2.0 * Cartesian3.dot(direction, diff);
  12000. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  12001. var roots = solveQuadratic(a, b, c, raySphereRoots);
  12002. if (!defined(roots)) {
  12003. return undefined;
  12004. }
  12005. result.start = roots.root0;
  12006. result.stop = roots.root1;
  12007. return result;
  12008. }
  12009. /**
  12010. * Computes the intersection points of a ray with a sphere.
  12011. * @memberof IntersectionTests
  12012. *
  12013. * @param {Ray} ray The ray.
  12014. * @param {BoundingSphere} sphere The sphere.
  12015. * @param {Object} [result] The result onto which to store the result.
  12016. * @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.
  12017. */
  12018. IntersectionTests.raySphere = function(ray, sphere, result) {
  12019. if (!defined(ray)) {
  12020. throw new DeveloperError('ray is required.');
  12021. }
  12022. if (!defined(sphere)) {
  12023. throw new DeveloperError('sphere is required.');
  12024. }
  12025. result = raySphere(ray, sphere, result);
  12026. if (!defined(result) || result.stop < 0.0) {
  12027. return undefined;
  12028. }
  12029. result.start = Math.max(result.start, 0.0);
  12030. return result;
  12031. };
  12032. var scratchLineSegmentRay = new Ray();
  12033. /**
  12034. * Computes the intersection points of a line segment with a sphere.
  12035. * @memberof IntersectionTests
  12036. *
  12037. * @param {Cartesian3} p0 An end point of the line segment.
  12038. * @param {Cartesian3} p1 The other end point of the line segment.
  12039. * @param {BoundingSphere} sphere The sphere.
  12040. * @param {Object} [result] The result onto which to store the result.
  12041. * @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.
  12042. */
  12043. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  12044. if (!defined(p0)) {
  12045. throw new DeveloperError('p0 is required.');
  12046. }
  12047. if (!defined(p1)) {
  12048. throw new DeveloperError('p1 is required.');
  12049. }
  12050. if (!defined(sphere)) {
  12051. throw new DeveloperError('sphere is required.');
  12052. }
  12053. var ray = scratchLineSegmentRay;
  12054. Cartesian3.clone(p0, ray.origin);
  12055. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  12056. var maxT = Cartesian3.magnitude(direction);
  12057. Cartesian3.normalize(direction, direction);
  12058. result = raySphere(ray, sphere, result);
  12059. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  12060. return undefined;
  12061. }
  12062. result.start = Math.max(result.start, 0.0);
  12063. result.stop = Math.min(result.stop, maxT);
  12064. return result;
  12065. };
  12066. var scratchQ = new Cartesian3();
  12067. var scratchW = new Cartesian3();
  12068. /**
  12069. * Computes the intersection points of a ray with an ellipsoid.
  12070. *
  12071. * @param {Ray} ray The ray.
  12072. * @param {Ellipsoid} ellipsoid The ellipsoid.
  12073. * @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.
  12074. */
  12075. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  12076. if (!defined(ray)) {
  12077. throw new DeveloperError('ray is required.');
  12078. }
  12079. if (!defined(ellipsoid)) {
  12080. throw new DeveloperError('ellipsoid is required.');
  12081. }
  12082. var inverseRadii = ellipsoid.oneOverRadii;
  12083. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  12084. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  12085. var q2 = Cartesian3.magnitudeSquared(q);
  12086. var qw = Cartesian3.dot(q, w);
  12087. var difference, w2, product, discriminant, temp;
  12088. if (q2 > 1.0) {
  12089. // Outside ellipsoid.
  12090. if (qw >= 0.0) {
  12091. // Looking outward or tangent (0 intersections).
  12092. return undefined;
  12093. }
  12094. // qw < 0.0.
  12095. var qw2 = qw * qw;
  12096. difference = q2 - 1.0; // Positively valued.
  12097. w2 = Cartesian3.magnitudeSquared(w);
  12098. product = w2 * difference;
  12099. if (qw2 < product) {
  12100. // Imaginary roots (0 intersections).
  12101. return undefined;
  12102. } else if (qw2 > product) {
  12103. // Distinct roots (2 intersections).
  12104. discriminant = qw * qw - product;
  12105. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  12106. var root0 = temp / w2;
  12107. var root1 = difference / temp;
  12108. if (root0 < root1) {
  12109. return {
  12110. start : root0,
  12111. stop : root1
  12112. };
  12113. }
  12114. return {
  12115. start : root1,
  12116. stop : root0
  12117. };
  12118. } else {
  12119. // qw2 == product. Repeated roots (2 intersections).
  12120. var root = Math.sqrt(difference / w2);
  12121. return {
  12122. start : root,
  12123. stop : root
  12124. };
  12125. }
  12126. } else if (q2 < 1.0) {
  12127. // Inside ellipsoid (2 intersections).
  12128. difference = q2 - 1.0; // Negatively valued.
  12129. w2 = Cartesian3.magnitudeSquared(w);
  12130. product = w2 * difference; // Negatively valued.
  12131. discriminant = qw * qw - product;
  12132. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  12133. return {
  12134. start : 0.0,
  12135. stop : temp / w2
  12136. };
  12137. } else {
  12138. // q2 == 1.0. On ellipsoid.
  12139. if (qw < 0.0) {
  12140. // Looking inward.
  12141. w2 = Cartesian3.magnitudeSquared(w);
  12142. return {
  12143. start : 0.0,
  12144. stop : -qw / w2
  12145. };
  12146. }
  12147. // qw >= 0.0. Looking outward or tangent.
  12148. return undefined;
  12149. }
  12150. };
  12151. function addWithCancellationCheck(left, right, tolerance) {
  12152. var difference = left + right;
  12153. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  12154. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  12155. return 0.0;
  12156. }
  12157. return difference;
  12158. }
  12159. function quadraticVectorExpression(A, b, c, x, w) {
  12160. var xSquared = x * x;
  12161. var wSquared = w * w;
  12162. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  12163. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  12164. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  12165. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  12166. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  12167. var cosines;
  12168. var solutions = [];
  12169. if (r0 === 0.0 && r1 === 0.0) {
  12170. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  12171. if (cosines.length === 0) {
  12172. return solutions;
  12173. }
  12174. var cosine0 = cosines[0];
  12175. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  12176. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  12177. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  12178. if (cosines.length === 2) {
  12179. var cosine1 = cosines[1];
  12180. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  12181. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  12182. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  12183. }
  12184. return solutions;
  12185. }
  12186. var r0Squared = r0 * r0;
  12187. var r1Squared = r1 * r1;
  12188. var l2Squared = l2 * l2;
  12189. var r0r1 = r0 * r1;
  12190. var c4 = l2Squared + r1Squared;
  12191. var c3 = 2.0 * (l1 * l2 + r0r1);
  12192. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  12193. var c1 = 2.0 * (l0 * l1 - r0r1);
  12194. var c0 = l0 * l0 - r0Squared;
  12195. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  12196. return solutions;
  12197. }
  12198. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  12199. var length = cosines.length;
  12200. if (length === 0) {
  12201. return solutions;
  12202. }
  12203. for ( var i = 0; i < length; ++i) {
  12204. var cosine = cosines[i];
  12205. var cosineSquared = cosine * cosine;
  12206. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  12207. var sine = Math.sqrt(sineSquared);
  12208. //var left = l2 * cosineSquared + l1 * cosine + l0;
  12209. var left;
  12210. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  12211. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  12212. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  12213. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  12214. } else {
  12215. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  12216. }
  12217. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  12218. var product = left * right;
  12219. if (product < 0.0) {
  12220. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12221. } else if (product > 0.0) {
  12222. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  12223. } else if (sine !== 0.0) {
  12224. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  12225. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12226. ++i;
  12227. } else {
  12228. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  12229. }
  12230. }
  12231. return solutions;
  12232. }
  12233. var firstAxisScratch = new Cartesian3();
  12234. var secondAxisScratch = new Cartesian3();
  12235. var thirdAxisScratch = new Cartesian3();
  12236. var referenceScratch = new Cartesian3();
  12237. var bCart = new Cartesian3();
  12238. var bScratch = new Matrix3();
  12239. var btScratch = new Matrix3();
  12240. var diScratch = new Matrix3();
  12241. var dScratch = new Matrix3();
  12242. var cScratch = new Matrix3();
  12243. var tempMatrix = new Matrix3();
  12244. var aScratch = new Matrix3();
  12245. var sScratch = new Cartesian3();
  12246. var closestScratch = new Cartesian3();
  12247. var surfPointScratch = new Cartographic();
  12248. /**
  12249. * Provides the point along the ray which is nearest to the ellipsoid.
  12250. *
  12251. * @param {Ray} ray The ray.
  12252. * @param {Ellipsoid} ellipsoid The ellipsoid.
  12253. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  12254. */
  12255. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  12256. if (!defined(ray)) {
  12257. throw new DeveloperError('ray is required.');
  12258. }
  12259. if (!defined(ellipsoid)) {
  12260. throw new DeveloperError('ellipsoid is required.');
  12261. }
  12262. var position = ray.origin;
  12263. var direction = ray.direction;
  12264. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  12265. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  12266. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  12267. return position;
  12268. }
  12269. }
  12270. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  12271. // Compute the scaled direction vector.
  12272. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  12273. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  12274. var firstAxis = Cartesian3.normalize(f, f);
  12275. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  12276. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  12277. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  12278. var B = bScratch;
  12279. B[0] = firstAxis.x;
  12280. B[1] = firstAxis.y;
  12281. B[2] = firstAxis.z;
  12282. B[3] = secondAxis.x;
  12283. B[4] = secondAxis.y;
  12284. B[5] = secondAxis.z;
  12285. B[6] = thirdAxis.x;
  12286. B[7] = thirdAxis.y;
  12287. B[8] = thirdAxis.z;
  12288. var B_T = Matrix3.transpose(B, btScratch);
  12289. // Get the scaling matrix and its inverse.
  12290. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  12291. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  12292. var C = cScratch;
  12293. C[0] = 0.0;
  12294. C[1] = -direction.z;
  12295. C[2] = direction.y;
  12296. C[3] = direction.z;
  12297. C[4] = 0.0;
  12298. C[5] = -direction.x;
  12299. C[6] = -direction.y;
  12300. C[7] = direction.x;
  12301. C[8] = 0.0;
  12302. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  12303. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  12304. var b = Matrix3.multiplyByVector(temp, position, bCart);
  12305. // Solve for the solutions to the expression in standard form:
  12306. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  12307. var s;
  12308. var altitude;
  12309. var length = solutions.length;
  12310. if (length > 0) {
  12311. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  12312. var maximumValue = Number.NEGATIVE_INFINITY;
  12313. for ( var i = 0; i < length; ++i) {
  12314. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  12315. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  12316. var dotProduct = Cartesian3.dot(v, direction);
  12317. if (dotProduct > maximumValue) {
  12318. maximumValue = dotProduct;
  12319. closest = Cartesian3.clone(s, closest);
  12320. }
  12321. }
  12322. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  12323. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  12324. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  12325. altitude = intersects ? -altitude : altitude;
  12326. surfacePoint.height = altitude;
  12327. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  12328. }
  12329. return undefined;
  12330. };
  12331. var lineSegmentPlaneDifference = new Cartesian3();
  12332. /**
  12333. * Computes the intersection of a line segment and a plane.
  12334. *
  12335. * @param {Cartesian3} endPoint0 An end point of the line segment.
  12336. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  12337. * @param {Plane} plane The plane.
  12338. * @param {Cartesian3} [result] The object onto which to store the result.
  12339. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  12340. *
  12341. * @example
  12342. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  12343. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  12344. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  12345. *
  12346. * var p0 = new Cesium.Cartesian3(...);
  12347. * var p1 = new Cesium.Cartesian3(...);
  12348. *
  12349. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  12350. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  12351. */
  12352. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  12353. if (!defined(endPoint0)) {
  12354. throw new DeveloperError('endPoint0 is required.');
  12355. }
  12356. if (!defined(endPoint1)) {
  12357. throw new DeveloperError('endPoint1 is required.');
  12358. }
  12359. if (!defined(plane)) {
  12360. throw new DeveloperError('plane is required.');
  12361. }
  12362. if (!defined(result)) {
  12363. result = new Cartesian3();
  12364. }
  12365. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  12366. var normal = plane.normal;
  12367. var nDotDiff = Cartesian3.dot(normal, difference);
  12368. // check if the segment and plane are parallel
  12369. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  12370. return undefined;
  12371. }
  12372. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  12373. var t = -(plane.distance + nDotP0) / nDotDiff;
  12374. // intersection only if t is in [0, 1]
  12375. if (t < 0.0 || t > 1.0) {
  12376. return undefined;
  12377. }
  12378. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  12379. Cartesian3.multiplyByScalar(difference, t, result);
  12380. Cartesian3.add(endPoint0, result, result);
  12381. return result;
  12382. };
  12383. /**
  12384. * Computes the intersection of a triangle and a plane
  12385. *
  12386. * @param {Cartesian3} p0 First point of the triangle
  12387. * @param {Cartesian3} p1 Second point of the triangle
  12388. * @param {Cartesian3} p2 Third point of the triangle
  12389. * @param {Plane} plane Intersection plane
  12390. * @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)
  12391. *
  12392. * @example
  12393. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  12394. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  12395. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  12396. *
  12397. * var p0 = new Cesium.Cartesian3(...);
  12398. * var p1 = new Cesium.Cartesian3(...);
  12399. * var p2 = new Cesium.Cartesian3(...);
  12400. *
  12401. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  12402. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  12403. */
  12404. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  12405. if ((!defined(p0)) ||
  12406. (!defined(p1)) ||
  12407. (!defined(p2)) ||
  12408. (!defined(plane))) {
  12409. throw new DeveloperError('p0, p1, p2, and plane are required.');
  12410. }
  12411. var planeNormal = plane.normal;
  12412. var planeD = plane.distance;
  12413. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  12414. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  12415. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  12416. // Given these dots products, the calls to lineSegmentPlaneIntersection
  12417. // always have defined results.
  12418. var numBehind = 0;
  12419. numBehind += p0Behind ? 1 : 0;
  12420. numBehind += p1Behind ? 1 : 0;
  12421. numBehind += p2Behind ? 1 : 0;
  12422. var u1, u2;
  12423. if (numBehind === 1 || numBehind === 2) {
  12424. u1 = new Cartesian3();
  12425. u2 = new Cartesian3();
  12426. }
  12427. if (numBehind === 1) {
  12428. if (p0Behind) {
  12429. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  12430. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  12431. return {
  12432. positions : [p0, p1, p2, u1, u2 ],
  12433. indices : [
  12434. // Behind
  12435. 0, 3, 4,
  12436. // In front
  12437. 1, 2, 4,
  12438. 1, 4, 3
  12439. ]
  12440. };
  12441. } else if (p1Behind) {
  12442. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  12443. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  12444. return {
  12445. positions : [p0, p1, p2, u1, u2 ],
  12446. indices : [
  12447. // Behind
  12448. 1, 3, 4,
  12449. // In front
  12450. 2, 0, 4,
  12451. 2, 4, 3
  12452. ]
  12453. };
  12454. } else if (p2Behind) {
  12455. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  12456. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  12457. return {
  12458. positions : [p0, p1, p2, u1, u2 ],
  12459. indices : [
  12460. // Behind
  12461. 2, 3, 4,
  12462. // In front
  12463. 0, 1, 4,
  12464. 0, 4, 3
  12465. ]
  12466. };
  12467. }
  12468. } else if (numBehind === 2) {
  12469. if (!p0Behind) {
  12470. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  12471. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  12472. return {
  12473. positions : [p0, p1, p2, u1, u2 ],
  12474. indices : [
  12475. // Behind
  12476. 1, 2, 4,
  12477. 1, 4, 3,
  12478. // In front
  12479. 0, 3, 4
  12480. ]
  12481. };
  12482. } else if (!p1Behind) {
  12483. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  12484. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  12485. return {
  12486. positions : [p0, p1, p2, u1, u2 ],
  12487. indices : [
  12488. // Behind
  12489. 2, 0, 4,
  12490. 2, 4, 3,
  12491. // In front
  12492. 1, 3, 4
  12493. ]
  12494. };
  12495. } else if (!p2Behind) {
  12496. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  12497. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  12498. return {
  12499. positions : [p0, p1, p2, u1, u2 ],
  12500. indices : [
  12501. // Behind
  12502. 0, 1, 4,
  12503. 0, 4, 3,
  12504. // In front
  12505. 2, 3, 4
  12506. ]
  12507. };
  12508. }
  12509. }
  12510. // if numBehind is 3, the triangle is completely behind the plane;
  12511. // otherwise, it is completely in front (numBehind is 0).
  12512. return undefined;
  12513. };
  12514. return IntersectionTests;
  12515. });
  12516. /*global define*/
  12517. define('Core/Plane',[
  12518. './Cartesian3',
  12519. './defined',
  12520. './DeveloperError',
  12521. './freezeObject'
  12522. ], function(
  12523. Cartesian3,
  12524. defined,
  12525. DeveloperError,
  12526. freezeObject) {
  12527. 'use strict';
  12528. /**
  12529. * A plane in Hessian Normal Form defined by
  12530. * <pre>
  12531. * ax + by + cz + d = 0
  12532. * </pre>
  12533. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  12534. * <code>distance</code> to the plane, and (x, y, z) is any point on
  12535. * the plane.
  12536. *
  12537. * @alias Plane
  12538. * @constructor
  12539. *
  12540. * @param {Cartesian3} normal The plane's normal (normalized).
  12541. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  12542. * <code>distance</code> determines which side of the plane the origin
  12543. * is on. If <code>distance</code> is positive, the origin is in the half-space
  12544. * in the direction of the normal; if negative, the origin is in the half-space
  12545. * opposite to the normal; if zero, the plane passes through the origin.
  12546. *
  12547. * @example
  12548. * // The plane x=0
  12549. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  12550. */
  12551. function Plane(normal, distance) {
  12552. if (!defined(normal)) {
  12553. throw new DeveloperError('normal is required.');
  12554. }
  12555. if (!defined(distance)) {
  12556. throw new DeveloperError('distance is required.');
  12557. }
  12558. /**
  12559. * The plane's normal.
  12560. *
  12561. * @type {Cartesian3}
  12562. */
  12563. this.normal = Cartesian3.clone(normal);
  12564. /**
  12565. * The shortest distance from the origin to the plane. The sign of
  12566. * <code>distance</code> determines which side of the plane the origin
  12567. * is on. If <code>distance</code> is positive, the origin is in the half-space
  12568. * in the direction of the normal; if negative, the origin is in the half-space
  12569. * opposite to the normal; if zero, the plane passes through the origin.
  12570. *
  12571. * @type {Number}
  12572. */
  12573. this.distance = distance;
  12574. }
  12575. /**
  12576. * Creates a plane from a normal and a point on the plane.
  12577. *
  12578. * @param {Cartesian3} point The point on the plane.
  12579. * @param {Cartesian3} normal The plane's normal (normalized).
  12580. * @param {Plane} [result] The object onto which to store the result.
  12581. * @returns {Plane} A new plane instance or the modified result parameter.
  12582. *
  12583. * @example
  12584. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  12585. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  12586. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  12587. */
  12588. Plane.fromPointNormal = function(point, normal, result) {
  12589. if (!defined(point)) {
  12590. throw new DeveloperError('point is required.');
  12591. }
  12592. if (!defined(normal)) {
  12593. throw new DeveloperError('normal is required.');
  12594. }
  12595. var distance = -Cartesian3.dot(normal, point);
  12596. if (!defined(result)) {
  12597. return new Plane(normal, distance);
  12598. }
  12599. Cartesian3.clone(normal, result.normal);
  12600. result.distance = distance;
  12601. return result;
  12602. };
  12603. var scratchNormal = new Cartesian3();
  12604. /**
  12605. * Creates a plane from the general equation
  12606. *
  12607. * @param {Cartesian4} coefficients The plane's normal (normalized).
  12608. * @param {Plane} [result] The object onto which to store the result.
  12609. * @returns {Plane} A new plane instance or the modified result parameter.
  12610. */
  12611. Plane.fromCartesian4 = function(coefficients, result) {
  12612. if (!defined(coefficients)) {
  12613. throw new DeveloperError('coefficients is required.');
  12614. }
  12615. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  12616. var distance = coefficients.w;
  12617. if (!defined(result)) {
  12618. return new Plane(normal, distance);
  12619. } else {
  12620. Cartesian3.clone(normal, result.normal);
  12621. result.distance = distance;
  12622. return result;
  12623. }
  12624. };
  12625. /**
  12626. * Computes the signed shortest distance of a point to a plane.
  12627. * The sign of the distance determines which side of the plane the point
  12628. * is on. If the distance is positive, the point is in the half-space
  12629. * in the direction of the normal; if negative, the point is in the half-space
  12630. * opposite to the normal; if zero, the plane passes through the point.
  12631. *
  12632. * @param {Plane} plane The plane.
  12633. * @param {Cartesian3} point The point.
  12634. * @returns {Number} The signed shortest distance of the point to the plane.
  12635. */
  12636. Plane.getPointDistance = function(plane, point) {
  12637. if (!defined(plane)) {
  12638. throw new DeveloperError('plane is required.');
  12639. }
  12640. if (!defined(point)) {
  12641. throw new DeveloperError('point is required.');
  12642. }
  12643. return Cartesian3.dot(plane.normal, point) + plane.distance;
  12644. };
  12645. /**
  12646. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  12647. *
  12648. * @type {Plane}
  12649. * @constant
  12650. */
  12651. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  12652. /**
  12653. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  12654. *
  12655. * @type {Plane}
  12656. * @constant
  12657. */
  12658. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  12659. /**
  12660. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  12661. *
  12662. * @type {Plane}
  12663. * @constant
  12664. */
  12665. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  12666. return Plane;
  12667. });
  12668. /**
  12669. @license
  12670. when.js - https://github.com/cujojs/when
  12671. MIT License (c) copyright B Cavalier & J Hann
  12672. * A lightweight CommonJS Promises/A and when() implementation
  12673. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  12674. *
  12675. * Licensed under the MIT License at:
  12676. * http://www.opensource.org/licenses/mit-license.php
  12677. *
  12678. * @version 1.7.1
  12679. */
  12680. (function(define) { 'use strict';
  12681. define('ThirdParty/when',[],function () {
  12682. var reduceArray, slice, undef;
  12683. //
  12684. // Public API
  12685. //
  12686. when.defer = defer; // Create a deferred
  12687. when.resolve = resolve; // Create a resolved promise
  12688. when.reject = reject; // Create a rejected promise
  12689. when.join = join; // Join 2 or more promises
  12690. when.all = all; // Resolve a list of promises
  12691. when.map = map; // Array.map() for promises
  12692. when.reduce = reduce; // Array.reduce() for promises
  12693. when.any = any; // One-winner race
  12694. when.some = some; // Multi-winner race
  12695. when.chain = chain; // Make a promise trigger another resolver
  12696. when.isPromise = isPromise; // Determine if a thing is a promise
  12697. /**
  12698. * Register an observer for a promise or immediate value.
  12699. *
  12700. * @param {*} promiseOrValue
  12701. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  12702. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  12703. * will be invoked immediately.
  12704. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  12705. * rejected.
  12706. * @param {function?} [onProgress] callback to be called when progress updates
  12707. * are issued for promiseOrValue.
  12708. * @returns {Promise} a new {@link Promise} that will complete with the return
  12709. * value of callback or errback or the completion value of promiseOrValue if
  12710. * callback and/or errback is not supplied.
  12711. */
  12712. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  12713. // Get a trusted promise for the input promiseOrValue, and then
  12714. // register promise handlers
  12715. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  12716. }
  12717. /**
  12718. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  12719. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  12720. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  12721. *
  12722. * @param {*} promiseOrValue
  12723. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  12724. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  12725. * whose resolution value is:
  12726. * * the resolution value of promiseOrValue if it's a foreign promise, or
  12727. * * promiseOrValue if it's a value
  12728. */
  12729. function resolve(promiseOrValue) {
  12730. var promise, deferred;
  12731. if(promiseOrValue instanceof Promise) {
  12732. // It's a when.js promise, so we trust it
  12733. promise = promiseOrValue;
  12734. } else {
  12735. // It's not a when.js promise. See if it's a foreign promise or a value.
  12736. if(isPromise(promiseOrValue)) {
  12737. // It's a thenable, but we don't know where it came from, so don't trust
  12738. // its implementation entirely. Introduce a trusted middleman when.js promise
  12739. deferred = defer();
  12740. // IMPORTANT: This is the only place when.js should ever call .then() on an
  12741. // untrusted promise. Don't expose the return value to the untrusted promise
  12742. promiseOrValue.then(
  12743. function(value) { deferred.resolve(value); },
  12744. function(reason) { deferred.reject(reason); },
  12745. function(update) { deferred.progress(update); }
  12746. );
  12747. promise = deferred.promise;
  12748. } else {
  12749. // It's a value, not a promise. Create a resolved promise for it.
  12750. promise = fulfilled(promiseOrValue);
  12751. }
  12752. }
  12753. return promise;
  12754. }
  12755. /**
  12756. * Returns a rejected promise for the supplied promiseOrValue. The returned
  12757. * promise will be rejected with:
  12758. * - promiseOrValue, if it is a value, or
  12759. * - if promiseOrValue is a promise
  12760. * - promiseOrValue's value after it is fulfilled
  12761. * - promiseOrValue's reason after it is rejected
  12762. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  12763. * @returns {Promise} rejected {@link Promise}
  12764. */
  12765. function reject(promiseOrValue) {
  12766. return when(promiseOrValue, rejected);
  12767. }
  12768. /**
  12769. * Trusted Promise constructor. A Promise created from this constructor is
  12770. * a trusted when.js promise. Any other duck-typed promise is considered
  12771. * untrusted.
  12772. * @constructor
  12773. * @name Promise
  12774. */
  12775. function Promise(then) {
  12776. this.then = then;
  12777. }
  12778. Promise.prototype = {
  12779. /**
  12780. * Register a callback that will be called when a promise is
  12781. * fulfilled or rejected. Optionally also register a progress handler.
  12782. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  12783. * @param {function?} [onFulfilledOrRejected]
  12784. * @param {function?} [onProgress]
  12785. * @returns {Promise}
  12786. */
  12787. always: function(onFulfilledOrRejected, onProgress) {
  12788. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  12789. },
  12790. /**
  12791. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  12792. * @param {function?} onRejected
  12793. * @returns {Promise}
  12794. */
  12795. otherwise: function(onRejected) {
  12796. return this.then(undef, onRejected);
  12797. },
  12798. /**
  12799. * Shortcut for .then(function() { return value; })
  12800. * @param {*} value
  12801. * @returns {Promise} a promise that:
  12802. * - is fulfilled if value is not a promise, or
  12803. * - if value is a promise, will fulfill with its value, or reject
  12804. * with its reason.
  12805. */
  12806. yield: function(value) {
  12807. return this.then(function() {
  12808. return value;
  12809. });
  12810. },
  12811. /**
  12812. * Assumes that this promise will fulfill with an array, and arranges
  12813. * for the onFulfilled to be called with the array as its argument list
  12814. * i.e. onFulfilled.spread(undefined, array).
  12815. * @param {function} onFulfilled function to receive spread arguments
  12816. * @returns {Promise}
  12817. */
  12818. spread: function(onFulfilled) {
  12819. return this.then(function(array) {
  12820. // array may contain promises, so resolve its contents.
  12821. return all(array, function(array) {
  12822. return onFulfilled.apply(undef, array);
  12823. });
  12824. });
  12825. }
  12826. };
  12827. /**
  12828. * Create an already-resolved promise for the supplied value
  12829. * @private
  12830. *
  12831. * @param {*} value
  12832. * @returns {Promise} fulfilled promise
  12833. */
  12834. function fulfilled(value) {
  12835. var p = new Promise(function(onFulfilled) {
  12836. // TODO: Promises/A+ check typeof onFulfilled
  12837. try {
  12838. return resolve(onFulfilled ? onFulfilled(value) : value);
  12839. } catch(e) {
  12840. return rejected(e);
  12841. }
  12842. });
  12843. return p;
  12844. }
  12845. /**
  12846. * Create an already-rejected {@link Promise} with the supplied
  12847. * rejection reason.
  12848. * @private
  12849. *
  12850. * @param {*} reason
  12851. * @returns {Promise} rejected promise
  12852. */
  12853. function rejected(reason) {
  12854. var p = new Promise(function(_, onRejected) {
  12855. // TODO: Promises/A+ check typeof onRejected
  12856. try {
  12857. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  12858. } catch(e) {
  12859. return rejected(e);
  12860. }
  12861. });
  12862. return p;
  12863. }
  12864. /**
  12865. * Creates a new, Deferred with fully isolated resolver and promise parts,
  12866. * either or both of which may be given out safely to consumers.
  12867. * The Deferred itself has the full API: resolve, reject, progress, and
  12868. * then. The resolver has resolve, reject, and progress. The promise
  12869. * only has then.
  12870. *
  12871. * @returns {Deferred}
  12872. */
  12873. function defer() {
  12874. var deferred, promise, handlers, progressHandlers,
  12875. _then, _progress, _resolve;
  12876. /**
  12877. * The promise for the new deferred
  12878. * @type {Promise}
  12879. */
  12880. promise = new Promise(then);
  12881. /**
  12882. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  12883. * @class Deferred
  12884. * @name Deferred
  12885. */
  12886. deferred = {
  12887. then: then, // DEPRECATED: use deferred.promise.then
  12888. resolve: promiseResolve,
  12889. reject: promiseReject,
  12890. // TODO: Consider renaming progress() to notify()
  12891. progress: promiseProgress,
  12892. promise: promise,
  12893. resolver: {
  12894. resolve: promiseResolve,
  12895. reject: promiseReject,
  12896. progress: promiseProgress
  12897. }
  12898. };
  12899. handlers = [];
  12900. progressHandlers = [];
  12901. /**
  12902. * Pre-resolution then() that adds the supplied callback, errback, and progback
  12903. * functions to the registered listeners
  12904. * @private
  12905. *
  12906. * @param {function?} [onFulfilled] resolution handler
  12907. * @param {function?} [onRejected] rejection handler
  12908. * @param {function?} [onProgress] progress handler
  12909. */
  12910. _then = function(onFulfilled, onRejected, onProgress) {
  12911. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  12912. var deferred, progressHandler;
  12913. deferred = defer();
  12914. progressHandler = typeof onProgress === 'function'
  12915. ? function(update) {
  12916. try {
  12917. // Allow progress handler to transform progress event
  12918. deferred.progress(onProgress(update));
  12919. } catch(e) {
  12920. // Use caught value as progress
  12921. deferred.progress(e);
  12922. }
  12923. }
  12924. : function(update) { deferred.progress(update); };
  12925. handlers.push(function(promise) {
  12926. promise.then(onFulfilled, onRejected)
  12927. .then(deferred.resolve, deferred.reject, progressHandler);
  12928. });
  12929. progressHandlers.push(progressHandler);
  12930. return deferred.promise;
  12931. };
  12932. /**
  12933. * Issue a progress event, notifying all progress listeners
  12934. * @private
  12935. * @param {*} update progress event payload to pass to all listeners
  12936. */
  12937. _progress = function(update) {
  12938. processQueue(progressHandlers, update);
  12939. return update;
  12940. };
  12941. /**
  12942. * Transition from pre-resolution state to post-resolution state, notifying
  12943. * all listeners of the resolution or rejection
  12944. * @private
  12945. * @param {*} value the value of this deferred
  12946. */
  12947. _resolve = function(value) {
  12948. value = resolve(value);
  12949. // Replace _then with one that directly notifies with the result.
  12950. _then = value.then;
  12951. // Replace _resolve so that this Deferred can only be resolved once
  12952. _resolve = resolve;
  12953. // Make _progress a noop, to disallow progress for the resolved promise.
  12954. _progress = noop;
  12955. // Notify handlers
  12956. processQueue(handlers, value);
  12957. // Free progressHandlers array since we'll never issue progress events
  12958. progressHandlers = handlers = undef;
  12959. return value;
  12960. };
  12961. return deferred;
  12962. /**
  12963. * Wrapper to allow _then to be replaced safely
  12964. * @param {function?} [onFulfilled] resolution handler
  12965. * @param {function?} [onRejected] rejection handler
  12966. * @param {function?} [onProgress] progress handler
  12967. * @returns {Promise} new promise
  12968. */
  12969. function then(onFulfilled, onRejected, onProgress) {
  12970. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  12971. return _then(onFulfilled, onRejected, onProgress);
  12972. }
  12973. /**
  12974. * Wrapper to allow _resolve to be replaced
  12975. */
  12976. function promiseResolve(val) {
  12977. return _resolve(val);
  12978. }
  12979. /**
  12980. * Wrapper to allow _reject to be replaced
  12981. */
  12982. function promiseReject(err) {
  12983. return _resolve(rejected(err));
  12984. }
  12985. /**
  12986. * Wrapper to allow _progress to be replaced
  12987. */
  12988. function promiseProgress(update) {
  12989. return _progress(update);
  12990. }
  12991. }
  12992. /**
  12993. * Determines if promiseOrValue is a promise or not. Uses the feature
  12994. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  12995. * promiseOrValue is a promise.
  12996. *
  12997. * @param {*} promiseOrValue anything
  12998. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  12999. */
  13000. function isPromise(promiseOrValue) {
  13001. return promiseOrValue && typeof promiseOrValue.then === 'function';
  13002. }
  13003. /**
  13004. * Initiates a competitive race, returning a promise that will resolve when
  13005. * howMany of the supplied promisesOrValues have resolved, or will reject when
  13006. * it becomes impossible for howMany to resolve, for example, when
  13007. * (promisesOrValues.length - howMany) + 1 input promises reject.
  13008. *
  13009. * @param {Array} promisesOrValues array of anything, may contain a mix
  13010. * of promises and values
  13011. * @param howMany {number} number of promisesOrValues to resolve
  13012. * @param {function?} [onFulfilled] resolution handler
  13013. * @param {function?} [onRejected] rejection handler
  13014. * @param {function?} [onProgress] progress handler
  13015. * @returns {Promise} promise that will resolve to an array of howMany values that
  13016. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  13017. * rejection reasons.
  13018. */
  13019. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  13020. checkCallbacks(2, arguments);
  13021. return when(promisesOrValues, function(promisesOrValues) {
  13022. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  13023. len = promisesOrValues.length >>> 0;
  13024. toResolve = Math.max(0, Math.min(howMany, len));
  13025. values = [];
  13026. toReject = (len - toResolve) + 1;
  13027. reasons = [];
  13028. deferred = defer();
  13029. // No items in the input, resolve immediately
  13030. if (!toResolve) {
  13031. deferred.resolve(values);
  13032. } else {
  13033. progress = deferred.progress;
  13034. rejectOne = function(reason) {
  13035. reasons.push(reason);
  13036. if(!--toReject) {
  13037. fulfillOne = rejectOne = noop;
  13038. deferred.reject(reasons);
  13039. }
  13040. };
  13041. fulfillOne = function(val) {
  13042. // This orders the values based on promise resolution order
  13043. // Another strategy would be to use the original position of
  13044. // the corresponding promise.
  13045. values.push(val);
  13046. if (!--toResolve) {
  13047. fulfillOne = rejectOne = noop;
  13048. deferred.resolve(values);
  13049. }
  13050. };
  13051. for(i = 0; i < len; ++i) {
  13052. if(i in promisesOrValues) {
  13053. when(promisesOrValues[i], fulfiller, rejecter, progress);
  13054. }
  13055. }
  13056. }
  13057. return deferred.then(onFulfilled, onRejected, onProgress);
  13058. function rejecter(reason) {
  13059. rejectOne(reason);
  13060. }
  13061. function fulfiller(val) {
  13062. fulfillOne(val);
  13063. }
  13064. });
  13065. }
  13066. /**
  13067. * Initiates a competitive race, returning a promise that will resolve when
  13068. * any one of the supplied promisesOrValues has resolved or will reject when
  13069. * *all* promisesOrValues have rejected.
  13070. *
  13071. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  13072. * of {@link Promise}s and values
  13073. * @param {function?} [onFulfilled] resolution handler
  13074. * @param {function?} [onRejected] rejection handler
  13075. * @param {function?} [onProgress] progress handler
  13076. * @returns {Promise} promise that will resolve to the value that resolved first, or
  13077. * will reject with an array of all rejected inputs.
  13078. */
  13079. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  13080. function unwrapSingleResult(val) {
  13081. return onFulfilled ? onFulfilled(val[0]) : val[0];
  13082. }
  13083. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  13084. }
  13085. /**
  13086. * Return a promise that will resolve only once all the supplied promisesOrValues
  13087. * have resolved. The resolution value of the returned promise will be an array
  13088. * containing the resolution values of each of the promisesOrValues.
  13089. * @memberOf when
  13090. *
  13091. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  13092. * of {@link Promise}s and values
  13093. * @param {function?} [onFulfilled] resolution handler
  13094. * @param {function?} [onRejected] rejection handler
  13095. * @param {function?} [onProgress] progress handler
  13096. * @returns {Promise}
  13097. */
  13098. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  13099. checkCallbacks(1, arguments);
  13100. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  13101. }
  13102. /**
  13103. * Joins multiple promises into a single returned promise.
  13104. * @returns {Promise} a promise that will fulfill when *all* the input promises
  13105. * have fulfilled, or will reject when *any one* of the input promises rejects.
  13106. */
  13107. function join(/* ...promises */) {
  13108. return map(arguments, identity);
  13109. }
  13110. /**
  13111. * Traditional map function, similar to `Array.prototype.map()`, but allows
  13112. * input to contain {@link Promise}s and/or values, and mapFunc may return
  13113. * either a value or a {@link Promise}
  13114. *
  13115. * @param {Array|Promise} promise array of anything, may contain a mix
  13116. * of {@link Promise}s and values
  13117. * @param {function} mapFunc mapping function mapFunc(value) which may return
  13118. * either a {@link Promise} or value
  13119. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  13120. * the mapped output values.
  13121. */
  13122. function map(promise, mapFunc) {
  13123. return when(promise, function(array) {
  13124. var results, len, toResolve, resolve, i, d;
  13125. // Since we know the resulting length, we can preallocate the results
  13126. // array to avoid array expansions.
  13127. toResolve = len = array.length >>> 0;
  13128. results = [];
  13129. d = defer();
  13130. if(!toResolve) {
  13131. d.resolve(results);
  13132. } else {
  13133. resolve = function resolveOne(item, i) {
  13134. when(item, mapFunc).then(function(mapped) {
  13135. results[i] = mapped;
  13136. if(!--toResolve) {
  13137. d.resolve(results);
  13138. }
  13139. }, d.reject);
  13140. };
  13141. // Since mapFunc may be async, get all invocations of it into flight
  13142. for(i = 0; i < len; i++) {
  13143. if(i in array) {
  13144. resolve(array[i], i);
  13145. } else {
  13146. --toResolve;
  13147. }
  13148. }
  13149. }
  13150. return d.promise;
  13151. });
  13152. }
  13153. /**
  13154. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  13155. * input may contain promises and/or values, and reduceFunc
  13156. * may return either a value or a promise, *and* initialValue may
  13157. * be a promise for the starting value.
  13158. *
  13159. * @param {Array|Promise} promise array or promise for an array of anything,
  13160. * may contain a mix of promises and values.
  13161. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  13162. * where total is the total number of items being reduced, and will be the same
  13163. * in each call to reduceFunc.
  13164. * @returns {Promise} that will resolve to the final reduced value
  13165. */
  13166. function reduce(promise, reduceFunc /*, initialValue */) {
  13167. var args = slice.call(arguments, 1);
  13168. return when(promise, function(array) {
  13169. var total;
  13170. total = array.length;
  13171. // Wrap the supplied reduceFunc with one that handles promises and then
  13172. // delegates to the supplied.
  13173. args[0] = function (current, val, i) {
  13174. return when(current, function (c) {
  13175. return when(val, function (value) {
  13176. return reduceFunc(c, value, i, total);
  13177. });
  13178. });
  13179. };
  13180. return reduceArray.apply(array, args);
  13181. });
  13182. }
  13183. /**
  13184. * Ensure that resolution of promiseOrValue will trigger resolver with the
  13185. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  13186. *
  13187. * @param promiseOrValue
  13188. * @param {Object} resolver
  13189. * @param {function} resolver.resolve
  13190. * @param {function} resolver.reject
  13191. * @param {*} [resolveValue]
  13192. * @returns {Promise}
  13193. */
  13194. function chain(promiseOrValue, resolver, resolveValue) {
  13195. var useResolveValue = arguments.length > 2;
  13196. return when(promiseOrValue,
  13197. function(val) {
  13198. val = useResolveValue ? resolveValue : val;
  13199. resolver.resolve(val);
  13200. return val;
  13201. },
  13202. function(reason) {
  13203. resolver.reject(reason);
  13204. return rejected(reason);
  13205. },
  13206. resolver.progress
  13207. );
  13208. }
  13209. //
  13210. // Utility functions
  13211. //
  13212. /**
  13213. * Apply all functions in queue to value
  13214. * @param {Array} queue array of functions to execute
  13215. * @param {*} value argument passed to each function
  13216. */
  13217. function processQueue(queue, value) {
  13218. var handler, i = 0;
  13219. while (handler = queue[i++]) {
  13220. handler(value);
  13221. }
  13222. }
  13223. /**
  13224. * Helper that checks arrayOfCallbacks to ensure that each element is either
  13225. * a function, or null or undefined.
  13226. * @private
  13227. * @param {number} start index at which to start checking items in arrayOfCallbacks
  13228. * @param {Array} arrayOfCallbacks array to check
  13229. * @throws {Error} if any element of arrayOfCallbacks is something other than
  13230. * a functions, null, or undefined.
  13231. */
  13232. function checkCallbacks(start, arrayOfCallbacks) {
  13233. // TODO: Promises/A+ update type checking and docs
  13234. var arg, i = arrayOfCallbacks.length;
  13235. while(i > start) {
  13236. arg = arrayOfCallbacks[--i];
  13237. if (arg != null && typeof arg != 'function') {
  13238. throw new Error('arg '+i+' must be a function');
  13239. }
  13240. }
  13241. }
  13242. /**
  13243. * No-Op function used in method replacement
  13244. * @private
  13245. */
  13246. function noop() {}
  13247. slice = [].slice;
  13248. // ES5 reduce implementation if native not available
  13249. // See: http://es5.github.com/#x15.4.4.21 as there are many
  13250. // specifics and edge cases.
  13251. reduceArray = [].reduce ||
  13252. function(reduceFunc /*, initialValue */) {
  13253. /*jshint maxcomplexity: 7*/
  13254. // ES5 dictates that reduce.length === 1
  13255. // This implementation deviates from ES5 spec in the following ways:
  13256. // 1. It does not check if reduceFunc is a Callable
  13257. var arr, args, reduced, len, i;
  13258. i = 0;
  13259. // This generates a jshint warning, despite being valid
  13260. // "Missing 'new' prefix when invoking a constructor."
  13261. // See https://github.com/jshint/jshint/issues/392
  13262. arr = Object(this);
  13263. len = arr.length >>> 0;
  13264. args = arguments;
  13265. // If no initialValue, use first item of array (we know length !== 0 here)
  13266. // and adjust i to start at second item
  13267. if(args.length <= 1) {
  13268. // Skip to the first real element in the array
  13269. for(;;) {
  13270. if(i in arr) {
  13271. reduced = arr[i++];
  13272. break;
  13273. }
  13274. // If we reached the end of the array without finding any real
  13275. // elements, it's a TypeError
  13276. if(++i >= len) {
  13277. throw new TypeError();
  13278. }
  13279. }
  13280. } else {
  13281. // If initialValue provided, use it
  13282. reduced = args[1];
  13283. }
  13284. // Do the actual reduce
  13285. for(;i < len; ++i) {
  13286. // Skip holes
  13287. if(i in arr) {
  13288. reduced = reduceFunc(reduced, arr[i], i, arr);
  13289. }
  13290. }
  13291. return reduced;
  13292. };
  13293. function identity(x) {
  13294. return x;
  13295. }
  13296. return when;
  13297. });
  13298. })(typeof define == 'function' && define.amd
  13299. ? define
  13300. : function (factory) { typeof exports === 'object'
  13301. ? (module.exports = factory())
  13302. : (this.when = factory());
  13303. }
  13304. // Boilerplate for AMD, Node, and browser global
  13305. );
  13306. /*global define*/
  13307. define('Core/oneTimeWarning',[
  13308. './defaultValue',
  13309. './defined',
  13310. './DeveloperError'
  13311. ], function(
  13312. defaultValue,
  13313. defined,
  13314. DeveloperError) {
  13315. "use strict";
  13316. var warnings = {};
  13317. /**
  13318. * Logs a one time message to the console. Use this function instead of
  13319. * <code>console.log</code> directly since this does not log duplicate messages
  13320. * unless it is called from multiple workers.
  13321. *
  13322. * @exports oneTimeWarning
  13323. *
  13324. * @param {String} identifier The unique identifier for this warning.
  13325. * @param {String} [message=identifier] The message to log to the console.
  13326. *
  13327. * @example
  13328. * for(var i=0;i<foo.length;++i) {
  13329. * if (!defined(foo[i].bar)) {
  13330. * // Something that can be recovered from but may happen a lot
  13331. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  13332. * foo[i].bar = 0;
  13333. * // ...
  13334. * }
  13335. * }
  13336. *
  13337. * @private
  13338. */
  13339. function oneTimeWarning(identifier, message) {
  13340. if (!defined(identifier)) {
  13341. throw new DeveloperError('identifier is required.');
  13342. }
  13343. if (!defined(warnings[identifier])) {
  13344. warnings[identifier] = true;
  13345. console.log(defaultValue(message, identifier));
  13346. }
  13347. }
  13348. 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.';
  13349. return oneTimeWarning;
  13350. });
  13351. /*global define*/
  13352. define('Core/deprecationWarning',[
  13353. './defined',
  13354. './DeveloperError',
  13355. './oneTimeWarning'
  13356. ], function(
  13357. defined,
  13358. DeveloperError,
  13359. oneTimeWarning) {
  13360. 'use strict';
  13361. /**
  13362. * Logs a deprecation message to the console. Use this function instead of
  13363. * <code>console.log</code> directly since this does not log duplicate messages
  13364. * unless it is called from multiple workers.
  13365. *
  13366. * @exports deprecationWarning
  13367. *
  13368. * @param {String} identifier The unique identifier for this deprecated API.
  13369. * @param {String} message The message to log to the console.
  13370. *
  13371. * @example
  13372. * // Deprecated function or class
  13373. * function Foo() {
  13374. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  13375. * // ...
  13376. * }
  13377. *
  13378. * // Deprecated function
  13379. * Bar.prototype.func = function() {
  13380. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  13381. * // ...
  13382. * };
  13383. *
  13384. * // Deprecated property
  13385. * defineProperties(Bar.prototype, {
  13386. * prop : {
  13387. * get : function() {
  13388. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  13389. * // ...
  13390. * },
  13391. * set : function(value) {
  13392. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  13393. * // ...
  13394. * }
  13395. * }
  13396. * });
  13397. *
  13398. * @private
  13399. */
  13400. function deprecationWarning(identifier, message) {
  13401. if (!defined(identifier) || !defined(message)) {
  13402. throw new DeveloperError('identifier and message are required.');
  13403. }
  13404. oneTimeWarning(identifier, message);
  13405. }
  13406. return deprecationWarning;
  13407. });
  13408. /*global define*/
  13409. define('Core/binarySearch',[
  13410. './defined',
  13411. './DeveloperError'
  13412. ], function(
  13413. defined,
  13414. DeveloperError) {
  13415. 'use strict';
  13416. /**
  13417. * Finds an item in a sorted array.
  13418. *
  13419. * @exports binarySearch
  13420. *
  13421. * @param {Array} array The sorted array to search.
  13422. * @param {Object} itemToFind The item to find in the array.
  13423. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  13424. * elements in the array.
  13425. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  13426. * does not exist, the return value is a negative number which is the bitwise complement (~)
  13427. * of the index before which the itemToFind should be inserted in order to maintain the
  13428. * sorted order of the array.
  13429. *
  13430. * @example
  13431. * // Create a comparator function to search through an array of numbers.
  13432. * function comparator(a, b) {
  13433. * return a - b;
  13434. * };
  13435. * var numbers = [0, 2, 4, 6, 8];
  13436. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  13437. */
  13438. function binarySearch(array, itemToFind, comparator) {
  13439. if (!defined(array)) {
  13440. throw new DeveloperError('array is required.');
  13441. }
  13442. if (!defined(itemToFind)) {
  13443. throw new DeveloperError('itemToFind is required.');
  13444. }
  13445. if (!defined(comparator)) {
  13446. throw new DeveloperError('comparator is required.');
  13447. }
  13448. var low = 0;
  13449. var high = array.length - 1;
  13450. var i;
  13451. var comparison;
  13452. while (low <= high) {
  13453. i = ~~((low + high) / 2);
  13454. comparison = comparator(array[i], itemToFind);
  13455. if (comparison < 0) {
  13456. low = i + 1;
  13457. continue;
  13458. }
  13459. if (comparison > 0) {
  13460. high = i - 1;
  13461. continue;
  13462. }
  13463. return i;
  13464. }
  13465. return ~(high + 1);
  13466. }
  13467. /**
  13468. * A function used to compare two items while performing a binary search.
  13469. * @callback binarySearch~Comparator
  13470. *
  13471. * @param {Object} a An item in the array.
  13472. * @param {Object} b The item being searched for.
  13473. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  13474. * a positive value if <code>a</code> is greater than <code>b</code>, or
  13475. * 0 if <code>a</code> is equal to <code>b</code>.
  13476. *
  13477. * @example
  13478. * function compareNumbers(a, b) {
  13479. * return a - b;
  13480. * }
  13481. */
  13482. return binarySearch;
  13483. });
  13484. /*global define*/
  13485. define('Core/EarthOrientationParametersSample',[],function() {
  13486. 'use strict';
  13487. /**
  13488. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  13489. *
  13490. * @alias EarthOrientationParametersSample
  13491. * @constructor
  13492. *
  13493. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  13494. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  13495. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  13496. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  13497. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  13498. *
  13499. * @private
  13500. */
  13501. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  13502. /**
  13503. * The pole wander about the X axis, in radians.
  13504. * @type {Number}
  13505. */
  13506. this.xPoleWander = xPoleWander;
  13507. /**
  13508. * The pole wander about the Y axis, in radians.
  13509. * @type {Number}
  13510. */
  13511. this.yPoleWander = yPoleWander;
  13512. /**
  13513. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  13514. * @type {Number}
  13515. */
  13516. this.xPoleOffset = xPoleOffset;
  13517. /**
  13518. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  13519. * @type {Number}
  13520. */
  13521. this.yPoleOffset = yPoleOffset;
  13522. /**
  13523. * The difference in time standards, UT1 - UTC, in seconds.
  13524. * @type {Number}
  13525. */
  13526. this.ut1MinusUtc = ut1MinusUtc;
  13527. }
  13528. return EarthOrientationParametersSample;
  13529. });
  13530. /**
  13531. @license
  13532. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  13533. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  13534. php.js is copyright 2012 Kevin van Zonneveld.
  13535. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  13536. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  13537. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  13538. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  13539. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  13540. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  13541. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  13542. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  13543. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  13544. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  13545. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  13546. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  13547. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  13548. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  13549. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  13550. (http://geekfg.blogspot.com), Andrea Giammarchi
  13551. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  13552. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  13553. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  13554. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  13555. Marc Palau, Martin
  13556. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  13557. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  13558. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  13559. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  13560. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  13561. Ariede (http://caioariede.com), Robin, Kankrelune
  13562. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  13563. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  13564. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  13565. David, Aman Gupta, Michael White, Public Domain
  13566. (http://www.json.org/json2.js), Steven Levithan
  13567. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  13568. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  13569. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  13570. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  13571. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  13572. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  13573. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  13574. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  13575. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  13576. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  13577. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  13578. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  13579. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  13580. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  13581. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  13582. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  13583. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  13584. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  13585. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  13586. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  13587. (http://yass.meetcweb.com), Peter-Paul Koch
  13588. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  13589. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  13590. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  13591. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  13592. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  13593. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  13594. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  13595. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  13596. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  13597. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  13598. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  13599. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  13600. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  13601. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  13602. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  13603. (http://www.premasolutions.com/), Philippe Jausions
  13604. (http://pear.php.net/user/jausions), Aidan Lister
  13605. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  13606. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  13607. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  13608. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  13609. (http://www.pedrotainha.com), James, Arnout Kazemier
  13610. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  13611. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  13612. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  13613. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  13614. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  13615. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  13616. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  13617. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  13618. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  13619. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  13620. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  13621. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  13622. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  13623. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  13624. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  13625. (http://benblume.co.uk/), DtTvB
  13626. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  13627. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  13628. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  13629. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  13630. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  13631. Bryan
  13632. Licensed under the MIT (MIT-LICENSE.txt) license.
  13633. Permission is hereby granted, free of charge, to any person obtaining a
  13634. copy of this software and associated documentation files (the
  13635. "Software"), to deal in the Software without restriction, including
  13636. without limitation the rights to use, copy, modify, merge, publish,
  13637. distribute, sublicense, and/or sell copies of the Software, and to
  13638. permit persons to whom the Software is furnished to do so, subject to
  13639. the following conditions:
  13640. The above copyright notice and this permission notice shall be included
  13641. in all copies or substantial portions of the Software.
  13642. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13643. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13644. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  13645. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  13646. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  13647. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  13648. OTHER DEALINGS IN THE SOFTWARE.
  13649. */
  13650. /*global define*/
  13651. define('ThirdParty/sprintf',[],function() {
  13652. function sprintf () {
  13653. // http://kevin.vanzonneveld.net
  13654. // + original by: Ash Searle (http://hexmen.com/blog/)
  13655. // + namespaced by: Michael White (http://getsprink.com)
  13656. // + tweaked by: Jack
  13657. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  13658. // + input by: Paulo Freitas
  13659. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  13660. // + input by: Brett Zamir (http://brett-zamir.me)
  13661. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  13662. // + improved by: Dj
  13663. // + improved by: Allidylls
  13664. // * example 1: sprintf("%01.2f", 123.1);
  13665. // * returns 1: 123.10
  13666. // * example 2: sprintf("[%10s]", 'monkey');
  13667. // * returns 2: '[ monkey]'
  13668. // * example 3: sprintf("[%'#10s]", 'monkey');
  13669. // * returns 3: '[####monkey]'
  13670. // * example 4: sprintf("%d", 123456789012345);
  13671. // * returns 4: '123456789012345'
  13672. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  13673. var a = arguments,
  13674. i = 0,
  13675. format = a[i++];
  13676. // pad()
  13677. var pad = function (str, len, chr, leftJustify) {
  13678. if (!chr) {
  13679. chr = ' ';
  13680. }
  13681. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  13682. return leftJustify ? str + padding : padding + str;
  13683. };
  13684. // justify()
  13685. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  13686. var diff = minWidth - value.length;
  13687. if (diff > 0) {
  13688. if (leftJustify || !zeroPad) {
  13689. value = pad(value, minWidth, customPadChar, leftJustify);
  13690. } else {
  13691. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  13692. }
  13693. }
  13694. return value;
  13695. };
  13696. // formatBaseX()
  13697. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  13698. // Note: casts negative numbers to positive ones
  13699. var number = value >>> 0;
  13700. prefix = prefix && number && {
  13701. '2': '0b',
  13702. '8': '0',
  13703. '16': '0x'
  13704. }[base] || '';
  13705. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  13706. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  13707. };
  13708. // formatString()
  13709. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  13710. if (precision != null) {
  13711. value = value.slice(0, precision);
  13712. }
  13713. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  13714. };
  13715. // doFormat()
  13716. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  13717. var number;
  13718. var prefix;
  13719. var method;
  13720. var textTransform;
  13721. var value;
  13722. if (substring == '%%') {
  13723. return '%';
  13724. }
  13725. // parse flags
  13726. var leftJustify = false,
  13727. positivePrefix = '',
  13728. zeroPad = false,
  13729. prefixBaseX = false,
  13730. customPadChar = ' ';
  13731. var flagsl = flags.length;
  13732. for (var j = 0; flags && j < flagsl; j++) {
  13733. switch (flags.charAt(j)) {
  13734. case ' ':
  13735. positivePrefix = ' ';
  13736. break;
  13737. case '+':
  13738. positivePrefix = '+';
  13739. break;
  13740. case '-':
  13741. leftJustify = true;
  13742. break;
  13743. case "'":
  13744. customPadChar = flags.charAt(j + 1);
  13745. break;
  13746. case '0':
  13747. zeroPad = true;
  13748. break;
  13749. case '#':
  13750. prefixBaseX = true;
  13751. break;
  13752. }
  13753. }
  13754. // parameters may be null, undefined, empty-string or real valued
  13755. // we want to ignore null, undefined and empty-string values
  13756. if (!minWidth) {
  13757. minWidth = 0;
  13758. } else if (minWidth == '*') {
  13759. minWidth = +a[i++];
  13760. } else if (minWidth.charAt(0) == '*') {
  13761. minWidth = +a[minWidth.slice(1, -1)];
  13762. } else {
  13763. minWidth = +minWidth;
  13764. }
  13765. // Note: undocumented perl feature:
  13766. if (minWidth < 0) {
  13767. minWidth = -minWidth;
  13768. leftJustify = true;
  13769. }
  13770. if (!isFinite(minWidth)) {
  13771. throw new Error('sprintf: (minimum-)width must be finite');
  13772. }
  13773. if (!precision) {
  13774. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  13775. } else if (precision == '*') {
  13776. precision = +a[i++];
  13777. } else if (precision.charAt(0) == '*') {
  13778. precision = +a[precision.slice(1, -1)];
  13779. } else {
  13780. precision = +precision;
  13781. }
  13782. // grab value using valueIndex if required?
  13783. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  13784. switch (type) {
  13785. case 's':
  13786. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  13787. case 'c':
  13788. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  13789. case 'b':
  13790. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  13791. case 'o':
  13792. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  13793. case 'x':
  13794. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  13795. case 'X':
  13796. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  13797. case 'u':
  13798. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  13799. case 'i':
  13800. case 'd':
  13801. number = +value || 0;
  13802. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  13803. prefix = number < 0 ? '-' : positivePrefix;
  13804. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  13805. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  13806. case 'e':
  13807. case 'E':
  13808. case 'f': // Should handle locales (as per setlocale)
  13809. case 'F':
  13810. case 'g':
  13811. case 'G':
  13812. number = +value;
  13813. prefix = number < 0 ? '-' : positivePrefix;
  13814. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  13815. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  13816. value = prefix + Math.abs(number)[method](precision);
  13817. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  13818. default:
  13819. return substring;
  13820. }
  13821. };
  13822. return format.replace(regex, doFormat);
  13823. }
  13824. return sprintf;
  13825. });
  13826. /*global define*/
  13827. define('Core/GregorianDate',[],function() {
  13828. 'use strict';
  13829. /**
  13830. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  13831. * In addition to submillisecond precision, this object can also represent leap seconds.
  13832. * @alias GregorianDate
  13833. * @constructor
  13834. *
  13835. * @see JulianDate#toGregorianDate
  13836. */
  13837. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  13838. /**
  13839. * Gets or sets the year as a whole number.
  13840. * @type {Number}
  13841. */
  13842. this.year = year;
  13843. /**
  13844. * Gets or sets the month as a whole number with range [1, 12].
  13845. * @type {Number}
  13846. */
  13847. this.month = month;
  13848. /**
  13849. * Gets or sets the day of the month as a whole number starting at 1.
  13850. * @type {Number}
  13851. */
  13852. this.day = day;
  13853. /**
  13854. * Gets or sets the hour as a whole number with range [0, 23].
  13855. * @type {Number}
  13856. */
  13857. this.hour = hour;
  13858. /**
  13859. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  13860. * @type {Number}
  13861. */
  13862. this.minute = minute;
  13863. /**
  13864. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  13865. * @type {Number}
  13866. */
  13867. this.second = second;
  13868. /**
  13869. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  13870. * @type {Number}
  13871. */
  13872. this.millisecond = millisecond;
  13873. /**
  13874. * Gets or sets whether this time is during a leap second.
  13875. * @type {Boolean}
  13876. */
  13877. this.isLeapSecond = isLeapSecond;
  13878. }
  13879. return GregorianDate;
  13880. });
  13881. /*global define*/
  13882. define('Core/isLeapYear',[
  13883. './DeveloperError'
  13884. ], function(
  13885. DeveloperError) {
  13886. 'use strict';
  13887. /**
  13888. * Determines if a given date is a leap year.
  13889. *
  13890. * @exports isLeapYear
  13891. *
  13892. * @param {Number} year The year to be tested.
  13893. * @returns {Boolean} True if <code>year</code> is a leap year.
  13894. *
  13895. * @example
  13896. * var leapYear = Cesium.isLeapYear(2000); // true
  13897. */
  13898. function isLeapYear(year) {
  13899. if (year === null || isNaN(year)) {
  13900. throw new DeveloperError('year is required and must be a number.');
  13901. }
  13902. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  13903. }
  13904. return isLeapYear;
  13905. });
  13906. /*global define*/
  13907. define('Core/LeapSecond',[],function() {
  13908. 'use strict';
  13909. /**
  13910. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  13911. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  13912. * @alias LeapSecond
  13913. * @constructor
  13914. *
  13915. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  13916. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  13917. */
  13918. function LeapSecond(date, offset) {
  13919. /**
  13920. * Gets or sets the date at which this leap second occurs.
  13921. * @type {JulianDate}
  13922. */
  13923. this.julianDate = date;
  13924. /**
  13925. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  13926. * of this leap second.
  13927. * @type {Number}
  13928. */
  13929. this.offset = offset;
  13930. }
  13931. return LeapSecond;
  13932. });
  13933. /*global define*/
  13934. define('Core/TimeConstants',[
  13935. './freezeObject'
  13936. ], function(
  13937. freezeObject) {
  13938. 'use strict';
  13939. /**
  13940. * Constants for time conversions like those done by {@link JulianDate}.
  13941. *
  13942. * @exports TimeConstants
  13943. *
  13944. * @see JulianDate
  13945. *
  13946. * @private
  13947. */
  13948. var TimeConstants = {
  13949. /**
  13950. * The number of seconds in one millisecond: <code>0.001</code>
  13951. * @type {Number}
  13952. * @constant
  13953. */
  13954. SECONDS_PER_MILLISECOND : 0.001,
  13955. /**
  13956. * The number of seconds in one minute: <code>60</code>.
  13957. * @type {Number}
  13958. * @constant
  13959. */
  13960. SECONDS_PER_MINUTE : 60.0,
  13961. /**
  13962. * The number of minutes in one hour: <code>60</code>.
  13963. * @type {Number}
  13964. * @constant
  13965. */
  13966. MINUTES_PER_HOUR : 60.0,
  13967. /**
  13968. * The number of hours in one day: <code>24</code>.
  13969. * @type {Number}
  13970. * @constant
  13971. */
  13972. HOURS_PER_DAY : 24.0,
  13973. /**
  13974. * The number of seconds in one hour: <code>3600</code>.
  13975. * @type {Number}
  13976. * @constant
  13977. */
  13978. SECONDS_PER_HOUR : 3600.0,
  13979. /**
  13980. * The number of minutes in one day: <code>1440</code>.
  13981. * @type {Number}
  13982. * @constant
  13983. */
  13984. MINUTES_PER_DAY : 1440.0,
  13985. /**
  13986. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  13987. * @type {Number}
  13988. * @constant
  13989. */
  13990. SECONDS_PER_DAY : 86400.0,
  13991. /**
  13992. * The number of days in one Julian century: <code>36525</code>.
  13993. * @type {Number}
  13994. * @constant
  13995. */
  13996. DAYS_PER_JULIAN_CENTURY : 36525.0,
  13997. /**
  13998. * One trillionth of a second.
  13999. * @type {Number}
  14000. * @constant
  14001. */
  14002. PICOSECOND : 0.000000001,
  14003. /**
  14004. * The number of days to subtract from a Julian date to determine the
  14005. * modified Julian date, which gives the number of days since midnight
  14006. * on November 17, 1858.
  14007. * @type {Number}
  14008. * @constant
  14009. */
  14010. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  14011. };
  14012. return freezeObject(TimeConstants);
  14013. });
  14014. /*global define*/
  14015. define('Core/TimeStandard',[
  14016. './freezeObject'
  14017. ], function(
  14018. freezeObject) {
  14019. 'use strict';
  14020. /**
  14021. * Provides the type of time standards which JulianDate can take as input.
  14022. *
  14023. * @exports TimeStandard
  14024. *
  14025. * @see JulianDate
  14026. */
  14027. var TimeStandard = {
  14028. /**
  14029. * Represents the coordinated Universal Time (UTC) time standard.
  14030. *
  14031. * UTC is related to TAI according to the relationship
  14032. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  14033. * seconds which have been introduced as of the time in TAI.
  14034. *
  14035. */
  14036. UTC : 0,
  14037. /**
  14038. * Represents the International Atomic Time (TAI) time standard.
  14039. * TAI is the principal time standard to which the other time standards are related.
  14040. */
  14041. TAI : 1
  14042. };
  14043. return freezeObject(TimeStandard);
  14044. });
  14045. /*global define*/
  14046. define('Core/JulianDate',[
  14047. '../ThirdParty/sprintf',
  14048. './binarySearch',
  14049. './defaultValue',
  14050. './defined',
  14051. './DeveloperError',
  14052. './GregorianDate',
  14053. './isLeapYear',
  14054. './LeapSecond',
  14055. './TimeConstants',
  14056. './TimeStandard'
  14057. ], function(
  14058. sprintf,
  14059. binarySearch,
  14060. defaultValue,
  14061. defined,
  14062. DeveloperError,
  14063. GregorianDate,
  14064. isLeapYear,
  14065. LeapSecond,
  14066. TimeConstants,
  14067. TimeStandard) {
  14068. 'use strict';
  14069. var gregorianDateScratch = new GregorianDate();
  14070. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  14071. var daysInLeapFeburary = 29;
  14072. function compareLeapSecondDates(leapSecond, dateToFind) {
  14073. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  14074. }
  14075. // we don't really need a leap second instance, anything with a julianDate property will do
  14076. var binarySearchScratchLeapSecond = new LeapSecond();
  14077. function convertUtcToTai(julianDate) {
  14078. //Even though julianDate is in UTC, we'll treat it as TAI and
  14079. //search the leap second table for it.
  14080. binarySearchScratchLeapSecond.julianDate = julianDate;
  14081. var leapSeconds = JulianDate.leapSeconds;
  14082. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  14083. if (index < 0) {
  14084. index = ~index;
  14085. }
  14086. if (index >= leapSeconds.length) {
  14087. index = leapSeconds.length - 1;
  14088. }
  14089. var offset = leapSeconds[index].offset;
  14090. if (index > 0) {
  14091. //Now we have the index of the closest leap second that comes on or after our UTC time.
  14092. //However, if the difference between the UTC date being converted and the TAI
  14093. //defined leap second is greater than the offset, we are off by one and need to use
  14094. //the previous leap second.
  14095. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  14096. if (difference > offset) {
  14097. index--;
  14098. offset = leapSeconds[index].offset;
  14099. }
  14100. }
  14101. JulianDate.addSeconds(julianDate, offset, julianDate);
  14102. }
  14103. function convertTaiToUtc(julianDate, result) {
  14104. binarySearchScratchLeapSecond.julianDate = julianDate;
  14105. var leapSeconds = JulianDate.leapSeconds;
  14106. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  14107. if (index < 0) {
  14108. index = ~index;
  14109. }
  14110. //All times before our first leap second get the first offset.
  14111. if (index === 0) {
  14112. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  14113. }
  14114. //All times after our leap second get the last offset.
  14115. if (index >= leapSeconds.length) {
  14116. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  14117. }
  14118. //Compute the difference between the found leap second and the time we are converting.
  14119. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  14120. if (difference === 0) {
  14121. //The date is in our leap second table.
  14122. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  14123. }
  14124. if (difference <= 1.0) {
  14125. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  14126. return undefined;
  14127. }
  14128. //The time is in between two leap seconds, index is the leap second after the date
  14129. //we're converting, so we subtract one to get the correct LeapSecond instance.
  14130. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  14131. }
  14132. function setComponents(wholeDays, secondsOfDay, julianDate) {
  14133. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  14134. wholeDays += extraDays;
  14135. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  14136. if (secondsOfDay < 0) {
  14137. wholeDays--;
  14138. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  14139. }
  14140. julianDate.dayNumber = wholeDays;
  14141. julianDate.secondsOfDay = secondsOfDay;
  14142. return julianDate;
  14143. }
  14144. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  14145. // Algorithm from page 604 of the Explanatory Supplement to the
  14146. // Astronomical Almanac (Seidelmann 1992).
  14147. var a = ((month - 14) / 12) | 0;
  14148. var b = year + 4800 + a;
  14149. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  14150. // JulianDates are noon-based
  14151. hour = hour - 12;
  14152. if (hour < 0) {
  14153. hour += 24;
  14154. }
  14155. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  14156. if (secondsOfDay >= 43200.0) {
  14157. dayNumber -= 1;
  14158. }
  14159. return [dayNumber, secondsOfDay];
  14160. }
  14161. //Regular expressions used for ISO8601 date parsing.
  14162. //YYYY
  14163. var matchCalendarYear = /^(\d{4})$/;
  14164. //YYYY-MM (YYYYMM is invalid)
  14165. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  14166. //YYYY-DDD or YYYYDDD
  14167. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  14168. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  14169. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  14170. //YYYY-MM-DD or YYYYMMDD
  14171. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  14172. // Match utc offset
  14173. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  14174. // Match hours HH or HH.xxxxx
  14175. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  14176. // Match hours/minutes HH:MM HHMM.xxxxx
  14177. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  14178. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  14179. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  14180. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  14181. /**
  14182. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  14183. * For increased precision, this class stores the whole number part of the date and the seconds
  14184. * part of the date in separate components. In order to be safe for arithmetic and represent
  14185. * leap seconds, the date is always stored in the International Atomic Time standard
  14186. * {@link TimeStandard.TAI}.
  14187. * @alias JulianDate
  14188. * @constructor
  14189. *
  14190. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  14191. * @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.
  14192. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  14193. */
  14194. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  14195. /**
  14196. * Gets or sets the number of whole days.
  14197. * @type {Number}
  14198. */
  14199. this.dayNumber = undefined;
  14200. /**
  14201. * Gets or sets the number of seconds into the current day.
  14202. * @type {Number}
  14203. */
  14204. this.secondsOfDay = undefined;
  14205. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  14206. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  14207. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  14208. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  14209. var wholeDays = julianDayNumber | 0;
  14210. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  14211. setComponents(wholeDays, secondsOfDay, this);
  14212. if (timeStandard === TimeStandard.UTC) {
  14213. convertUtcToTai(this);
  14214. }
  14215. }
  14216. /**
  14217. * Creates a new instance from a JavaScript Date.
  14218. *
  14219. * @param {Date} date A JavaScript Date.
  14220. * @param {JulianDate} [result] An existing instance to use for the result.
  14221. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14222. *
  14223. * @exception {DeveloperError} date must be a valid JavaScript Date.
  14224. */
  14225. JulianDate.fromDate = function(date, result) {
  14226. if (!(date instanceof Date) || isNaN(date.getTime())) {
  14227. throw new DeveloperError('date must be a valid JavaScript Date.');
  14228. }
  14229. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  14230. if (!defined(result)) {
  14231. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  14232. }
  14233. setComponents(components[0], components[1], result);
  14234. convertUtcToTai(result);
  14235. return result;
  14236. };
  14237. /**
  14238. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  14239. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  14240. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  14241. *
  14242. * @param {String} iso8601String An ISO 8601 date.
  14243. * @param {JulianDate} [result] An existing instance to use for the result.
  14244. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14245. *
  14246. * @exception {DeveloperError} Invalid ISO 8601 date.
  14247. */
  14248. JulianDate.fromIso8601 = function(iso8601String, result) {
  14249. if (typeof iso8601String !== 'string') {
  14250. throw new DeveloperError(iso8601ErrorMessage);
  14251. }
  14252. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  14253. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  14254. iso8601String = iso8601String.replace(',', '.');
  14255. //Split the string into its date and time components, denoted by a mandatory T
  14256. var tokens = iso8601String.split('T');
  14257. var year;
  14258. var month = 1;
  14259. var day = 1;
  14260. var hour = 0;
  14261. var minute = 0;
  14262. var second = 0;
  14263. var millisecond = 0;
  14264. //Lacking a time is okay, but a missing date is illegal.
  14265. var date = tokens[0];
  14266. var time = tokens[1];
  14267. var tmp;
  14268. var inLeapYear;
  14269. if (!defined(date)) {
  14270. throw new DeveloperError(iso8601ErrorMessage);
  14271. }
  14272. var dashCount;
  14273. //First match the date against possible regular expressions.
  14274. tokens = date.match(matchCalendarDate);
  14275. if (tokens !== null) {
  14276. dashCount = date.split('-').length - 1;
  14277. if (dashCount > 0 && dashCount !== 2) {
  14278. throw new DeveloperError(iso8601ErrorMessage);
  14279. }
  14280. year = +tokens[1];
  14281. month = +tokens[2];
  14282. day = +tokens[3];
  14283. } else {
  14284. tokens = date.match(matchCalendarMonth);
  14285. if (tokens !== null) {
  14286. year = +tokens[1];
  14287. month = +tokens[2];
  14288. } else {
  14289. tokens = date.match(matchCalendarYear);
  14290. if (tokens !== null) {
  14291. year = +tokens[1];
  14292. } else {
  14293. //Not a year/month/day so it must be an ordinal date.
  14294. var dayOfYear;
  14295. tokens = date.match(matchOrdinalDate);
  14296. if (tokens !== null) {
  14297. year = +tokens[1];
  14298. dayOfYear = +tokens[2];
  14299. inLeapYear = isLeapYear(year);
  14300. //This validation is only applicable for this format.
  14301. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  14302. throw new DeveloperError(iso8601ErrorMessage);
  14303. }
  14304. } else {
  14305. tokens = date.match(matchWeekDate);
  14306. if (tokens !== null) {
  14307. //ISO week date to ordinal date from
  14308. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  14309. year = +tokens[1];
  14310. var weekNumber = +tokens[2];
  14311. var dayOfWeek = +tokens[3] || 0;
  14312. dashCount = date.split('-').length - 1;
  14313. if (dashCount > 0 &&
  14314. ((!defined(tokens[3]) && dashCount !== 1) ||
  14315. (defined(tokens[3]) && dashCount !== 2))) {
  14316. throw new DeveloperError(iso8601ErrorMessage);
  14317. }
  14318. var january4 = new Date(Date.UTC(year, 0, 4));
  14319. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  14320. } else {
  14321. //None of our regular expressions succeeded in parsing the date properly.
  14322. throw new DeveloperError(iso8601ErrorMessage);
  14323. }
  14324. }
  14325. //Split an ordinal date into month/day.
  14326. tmp = new Date(Date.UTC(year, 0, 1));
  14327. tmp.setUTCDate(dayOfYear);
  14328. month = tmp.getUTCMonth() + 1;
  14329. day = tmp.getUTCDate();
  14330. }
  14331. }
  14332. }
  14333. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  14334. inLeapYear = isLeapYear(year);
  14335. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  14336. throw new DeveloperError(iso8601ErrorMessage);
  14337. }
  14338. //Not move onto the time string, which is much simpler.
  14339. var offsetIndex;
  14340. if (defined(time)) {
  14341. tokens = time.match(matchHoursMinutesSeconds);
  14342. if (tokens !== null) {
  14343. dashCount = time.split(':').length - 1;
  14344. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  14345. throw new DeveloperError(iso8601ErrorMessage);
  14346. }
  14347. hour = +tokens[1];
  14348. minute = +tokens[2];
  14349. second = +tokens[3];
  14350. millisecond = +(tokens[4] || 0) * 1000.0;
  14351. offsetIndex = 5;
  14352. } else {
  14353. tokens = time.match(matchHoursMinutes);
  14354. if (tokens !== null) {
  14355. dashCount = time.split(':').length - 1;
  14356. if (dashCount > 2) {
  14357. throw new DeveloperError(iso8601ErrorMessage);
  14358. }
  14359. hour = +tokens[1];
  14360. minute = +tokens[2];
  14361. second = +(tokens[3] || 0) * 60.0;
  14362. offsetIndex = 4;
  14363. } else {
  14364. tokens = time.match(matchHours);
  14365. if (tokens !== null) {
  14366. hour = +tokens[1];
  14367. minute = +(tokens[2] || 0) * 60.0;
  14368. offsetIndex = 3;
  14369. } else {
  14370. throw new DeveloperError(iso8601ErrorMessage);
  14371. }
  14372. }
  14373. }
  14374. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  14375. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  14376. throw new DeveloperError(iso8601ErrorMessage);
  14377. }
  14378. //Check the UTC offset value, if no value exists, use local time
  14379. //a Z indicates UTC, + or - are offsets.
  14380. var offset = tokens[offsetIndex];
  14381. var offsetHours = +(tokens[offsetIndex + 1]);
  14382. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  14383. switch (offset) {
  14384. case '+':
  14385. hour = hour - offsetHours;
  14386. minute = minute - offsetMinutes;
  14387. break;
  14388. case '-':
  14389. hour = hour + offsetHours;
  14390. minute = minute + offsetMinutes;
  14391. break;
  14392. case 'Z':
  14393. break;
  14394. default:
  14395. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  14396. break;
  14397. }
  14398. } else {
  14399. //If no time is specified, it is considered the beginning of the day, local time.
  14400. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  14401. }
  14402. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  14403. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  14404. //Then we add it back in after converting to TAI.
  14405. var isLeapSecond = second === 60;
  14406. if (isLeapSecond) {
  14407. second--;
  14408. }
  14409. //Even if we successfully parsed the string into its components, after applying UTC offset or
  14410. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  14411. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  14412. while (minute >= 60) {
  14413. minute -= 60;
  14414. hour++;
  14415. }
  14416. while (hour >= 24) {
  14417. hour -= 24;
  14418. day++;
  14419. }
  14420. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  14421. while (day > tmp) {
  14422. day -= tmp;
  14423. month++;
  14424. if (month > 12) {
  14425. month -= 12;
  14426. year++;
  14427. }
  14428. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  14429. }
  14430. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  14431. while (minute < 0) {
  14432. minute += 60;
  14433. hour--;
  14434. }
  14435. while (hour < 0) {
  14436. hour += 24;
  14437. day--;
  14438. }
  14439. while (day < 1) {
  14440. month--;
  14441. if (month < 1) {
  14442. month += 12;
  14443. year--;
  14444. }
  14445. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  14446. day += tmp;
  14447. }
  14448. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  14449. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  14450. if (!defined(result)) {
  14451. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  14452. } else {
  14453. setComponents(components[0], components[1], result);
  14454. convertUtcToTai(result);
  14455. }
  14456. //If we were on a leap second, add it back.
  14457. if (isLeapSecond) {
  14458. JulianDate.addSeconds(result, 1, result);
  14459. }
  14460. return result;
  14461. };
  14462. /**
  14463. * Creates a new instance that represents the current system time.
  14464. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  14465. *
  14466. * @param {JulianDate} [result] An existing instance to use for the result.
  14467. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14468. */
  14469. JulianDate.now = function(result) {
  14470. return JulianDate.fromDate(new Date(), result);
  14471. };
  14472. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  14473. /**
  14474. * Creates a {@link GregorianDate} from the provided instance.
  14475. *
  14476. * @param {JulianDate} julianDate The date to be converted.
  14477. * @param {GregorianDate} [result] An existing instance to use for the result.
  14478. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  14479. */
  14480. JulianDate.toGregorianDate = function(julianDate, result) {
  14481. if (!defined(julianDate)) {
  14482. throw new DeveloperError('julianDate is required.');
  14483. }
  14484. var isLeapSecond = false;
  14485. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  14486. if (!defined(thisUtc)) {
  14487. //Conversion to UTC will fail if we are during a leap second.
  14488. //If that's the case, subtract a second and convert again.
  14489. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  14490. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  14491. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  14492. isLeapSecond = true;
  14493. }
  14494. var julianDayNumber = thisUtc.dayNumber;
  14495. var secondsOfDay = thisUtc.secondsOfDay;
  14496. if (secondsOfDay >= 43200.0) {
  14497. julianDayNumber += 1;
  14498. }
  14499. // Algorithm from page 604 of the Explanatory Supplement to the
  14500. // Astronomical Almanac (Seidelmann 1992).
  14501. var L = (julianDayNumber + 68569) | 0;
  14502. var N = (4 * L / 146097) | 0;
  14503. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  14504. var I = ((4000 * (L + 1)) / 1461001) | 0;
  14505. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  14506. var J = ((80 * L) / 2447) | 0;
  14507. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  14508. L = (J / 11) | 0;
  14509. var month = (J + 2 - 12 * L) | 0;
  14510. var year = (100 * (N - 49) + I + L) | 0;
  14511. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  14512. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  14513. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  14514. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  14515. var second = remainingSeconds | 0;
  14516. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  14517. // JulianDates are noon-based
  14518. hour += 12;
  14519. if (hour > 23) {
  14520. hour -= 24;
  14521. }
  14522. //If we were on a leap second, add it back.
  14523. if (isLeapSecond) {
  14524. second += 1;
  14525. }
  14526. if (!defined(result)) {
  14527. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  14528. }
  14529. result.year = year;
  14530. result.month = month;
  14531. result.day = day;
  14532. result.hour = hour;
  14533. result.minute = minute;
  14534. result.second = second;
  14535. result.millisecond = millisecond;
  14536. result.isLeapSecond = isLeapSecond;
  14537. return result;
  14538. };
  14539. /**
  14540. * Creates a JavaScript Date from the provided instance.
  14541. * Since JavaScript dates are only accurate to the nearest millisecond and
  14542. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  14543. * If the provided JulianDate is during a leap second, the previous second is used.
  14544. *
  14545. * @param {JulianDate} julianDate The date to be converted.
  14546. * @returns {Date} A new instance representing the provided date.
  14547. */
  14548. JulianDate.toDate = function(julianDate) {
  14549. if (!defined(julianDate)) {
  14550. throw new DeveloperError('julianDate is required.');
  14551. }
  14552. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  14553. var second = gDate.second;
  14554. if (gDate.isLeapSecond) {
  14555. second -= 1;
  14556. }
  14557. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  14558. };
  14559. /**
  14560. * Creates an ISO8601 representation of the provided date.
  14561. *
  14562. * @param {JulianDate} julianDate The date to be converted.
  14563. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  14564. * @returns {String} The ISO8601 representation of the provided date.
  14565. */
  14566. JulianDate.toIso8601 = function(julianDate, precision) {
  14567. if (!defined(julianDate)) {
  14568. throw new DeveloperError('julianDate is required.');
  14569. }
  14570. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  14571. var millisecondStr;
  14572. if (!defined(precision) && gDate.millisecond !== 0) {
  14573. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  14574. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  14575. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  14576. }
  14577. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  14578. if (!defined(precision) || precision === 0) {
  14579. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  14580. }
  14581. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  14582. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  14583. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  14584. };
  14585. /**
  14586. * Duplicates a JulianDate instance.
  14587. *
  14588. * @param {JulianDate} julianDate The date to duplicate.
  14589. * @param {JulianDate} [result] An existing instance to use for the result.
  14590. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  14591. */
  14592. JulianDate.clone = function(julianDate, result) {
  14593. if (!defined(julianDate)) {
  14594. return undefined;
  14595. }
  14596. if (!defined(result)) {
  14597. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  14598. }
  14599. result.dayNumber = julianDate.dayNumber;
  14600. result.secondsOfDay = julianDate.secondsOfDay;
  14601. return result;
  14602. };
  14603. /**
  14604. * Compares two instances.
  14605. *
  14606. * @param {JulianDate} left The first instance.
  14607. * @param {JulianDate} right The second instance.
  14608. * @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.
  14609. */
  14610. JulianDate.compare = function(left, right) {
  14611. if (!defined(left)) {
  14612. throw new DeveloperError('left is required.');
  14613. }
  14614. if (!defined(right)) {
  14615. throw new DeveloperError('right is required.');
  14616. }
  14617. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  14618. if (julianDayNumberDifference !== 0) {
  14619. return julianDayNumberDifference;
  14620. }
  14621. return left.secondsOfDay - right.secondsOfDay;
  14622. };
  14623. /**
  14624. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  14625. *
  14626. * @param {JulianDate} [left] The first instance.
  14627. * @param {JulianDate} [right] The second instance.
  14628. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  14629. */
  14630. JulianDate.equals = function(left, right) {
  14631. return (left === right) ||
  14632. (defined(left) &&
  14633. defined(right) &&
  14634. left.dayNumber === right.dayNumber &&
  14635. left.secondsOfDay === right.secondsOfDay);
  14636. };
  14637. /**
  14638. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  14639. * each other. That is, in order for the dates to be considered equal (and for
  14640. * this function to return <code>true</code>), the absolute value of the difference between them, in
  14641. * seconds, must be less than <code>epsilon</code>.
  14642. *
  14643. * @param {JulianDate} [left] The first instance.
  14644. * @param {JulianDate} [right] The second instance.
  14645. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  14646. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  14647. */
  14648. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  14649. if (!defined(epsilon)) {
  14650. throw new DeveloperError('epsilon is required.');
  14651. }
  14652. return (left === right) ||
  14653. (defined(left) &&
  14654. defined(right) &&
  14655. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  14656. };
  14657. /**
  14658. * Computes the total number of whole and fractional days represented by the provided instance.
  14659. *
  14660. * @param {JulianDate} julianDate The date.
  14661. * @returns {Number} The Julian date as single floating point number.
  14662. */
  14663. JulianDate.totalDays = function(julianDate) {
  14664. if (!defined(julianDate)) {
  14665. throw new DeveloperError('julianDate is required.');
  14666. }
  14667. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  14668. };
  14669. /**
  14670. * Computes the difference in seconds between the provided instance.
  14671. *
  14672. * @param {JulianDate} left The first instance.
  14673. * @param {JulianDate} right The second instance.
  14674. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  14675. */
  14676. JulianDate.secondsDifference = function(left, right) {
  14677. if (!defined(left)) {
  14678. throw new DeveloperError('left is required.');
  14679. }
  14680. if (!defined(right)) {
  14681. throw new DeveloperError('right is required.');
  14682. }
  14683. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  14684. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  14685. };
  14686. /**
  14687. * Computes the difference in days between the provided instance.
  14688. *
  14689. * @param {JulianDate} left The first instance.
  14690. * @param {JulianDate} right The second instance.
  14691. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  14692. */
  14693. JulianDate.daysDifference = function(left, right) {
  14694. if (!defined(left)) {
  14695. throw new DeveloperError('left is required.');
  14696. }
  14697. if (!defined(right)) {
  14698. throw new DeveloperError('right is required.');
  14699. }
  14700. var dayDifference = (left.dayNumber - right.dayNumber);
  14701. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  14702. return dayDifference + secondDifference;
  14703. };
  14704. /**
  14705. * Computes the number of seconds the provided instance is ahead of UTC.
  14706. *
  14707. * @param {JulianDate} julianDate The date.
  14708. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  14709. */
  14710. JulianDate.computeTaiMinusUtc = function(julianDate) {
  14711. binarySearchScratchLeapSecond.julianDate = julianDate;
  14712. var leapSeconds = JulianDate.leapSeconds;
  14713. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  14714. if (index < 0) {
  14715. index = ~index;
  14716. --index;
  14717. if (index < 0) {
  14718. index = 0;
  14719. }
  14720. }
  14721. return leapSeconds[index].offset;
  14722. };
  14723. /**
  14724. * Adds the provided number of seconds to the provided date instance.
  14725. *
  14726. * @param {JulianDate} julianDate The date.
  14727. * @param {Number} seconds The number of seconds to add or subtract.
  14728. * @param {JulianDate} result An existing instance to use for the result.
  14729. * @returns {JulianDate} The modified result parameter.
  14730. */
  14731. JulianDate.addSeconds = function(julianDate, seconds, result) {
  14732. if (!defined(julianDate)) {
  14733. throw new DeveloperError('julianDate is required.');
  14734. }
  14735. if (!defined(seconds)) {
  14736. throw new DeveloperError('seconds is required.');
  14737. }
  14738. if (!defined(result)) {
  14739. throw new DeveloperError('result is required.');
  14740. }
  14741. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  14742. };
  14743. /**
  14744. * Adds the provided number of minutes to the provided date instance.
  14745. *
  14746. * @param {JulianDate} julianDate The date.
  14747. * @param {Number} minutes The number of minutes to add or subtract.
  14748. * @param {JulianDate} result An existing instance to use for the result.
  14749. * @returns {JulianDate} The modified result parameter.
  14750. */
  14751. JulianDate.addMinutes = function(julianDate, minutes, result) {
  14752. if (!defined(julianDate)) {
  14753. throw new DeveloperError('julianDate is required.');
  14754. }
  14755. if (!defined(minutes)) {
  14756. throw new DeveloperError('minutes is required.');
  14757. }
  14758. if (!defined(result)) {
  14759. throw new DeveloperError('result is required.');
  14760. }
  14761. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  14762. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  14763. };
  14764. /**
  14765. * Adds the provided number of hours to the provided date instance.
  14766. *
  14767. * @param {JulianDate} julianDate The date.
  14768. * @param {Number} hours The number of hours to add or subtract.
  14769. * @param {JulianDate} result An existing instance to use for the result.
  14770. * @returns {JulianDate} The modified result parameter.
  14771. */
  14772. JulianDate.addHours = function(julianDate, hours, result) {
  14773. if (!defined(julianDate)) {
  14774. throw new DeveloperError('julianDate is required.');
  14775. }
  14776. if (!defined(hours)) {
  14777. throw new DeveloperError('hours is required.');
  14778. }
  14779. if (!defined(result)) {
  14780. throw new DeveloperError('result is required.');
  14781. }
  14782. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  14783. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  14784. };
  14785. /**
  14786. * Adds the provided number of days to the provided date instance.
  14787. *
  14788. * @param {JulianDate} julianDate The date.
  14789. * @param {Number} days The number of days to add or subtract.
  14790. * @param {JulianDate} result An existing instance to use for the result.
  14791. * @returns {JulianDate} The modified result parameter.
  14792. */
  14793. JulianDate.addDays = function(julianDate, days, result) {
  14794. if (!defined(julianDate)) {
  14795. throw new DeveloperError('julianDate is required.');
  14796. }
  14797. if (!defined(days)) {
  14798. throw new DeveloperError('days is required.');
  14799. }
  14800. if (!defined(result)) {
  14801. throw new DeveloperError('result is required.');
  14802. }
  14803. var newJulianDayNumber = julianDate.dayNumber + days;
  14804. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  14805. };
  14806. /**
  14807. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  14808. *
  14809. * @param {JulianDate} left The first instance.
  14810. * @param {JulianDate} right The second instance.
  14811. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  14812. */
  14813. JulianDate.lessThan = function(left, right) {
  14814. return JulianDate.compare(left, right) < 0;
  14815. };
  14816. /**
  14817. * 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.
  14818. *
  14819. * @param {JulianDate} left The first instance.
  14820. * @param {JulianDate} right The second instance.
  14821. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  14822. */
  14823. JulianDate.lessThanOrEquals = function(left, right) {
  14824. return JulianDate.compare(left, right) <= 0;
  14825. };
  14826. /**
  14827. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  14828. *
  14829. * @param {JulianDate} left The first instance.
  14830. * @param {JulianDate} right The second instance.
  14831. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  14832. */
  14833. JulianDate.greaterThan = function(left, right) {
  14834. return JulianDate.compare(left, right) > 0;
  14835. };
  14836. /**
  14837. * 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.
  14838. *
  14839. * @param {JulianDate} left The first instance.
  14840. * @param {JulianDate} right The second instance.
  14841. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  14842. */
  14843. JulianDate.greaterThanOrEquals = function(left, right) {
  14844. return JulianDate.compare(left, right) >= 0;
  14845. };
  14846. /**
  14847. * Duplicates this instance.
  14848. *
  14849. * @param {JulianDate} [result] An existing instance to use for the result.
  14850. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  14851. */
  14852. JulianDate.prototype.clone = function(result) {
  14853. return JulianDate.clone(this, result);
  14854. };
  14855. /**
  14856. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  14857. *
  14858. * @param {JulianDate} [right] The second instance.
  14859. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  14860. */
  14861. JulianDate.prototype.equals = function(right) {
  14862. return JulianDate.equals(this, right);
  14863. };
  14864. /**
  14865. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  14866. * each other. That is, in order for the dates to be considered equal (and for
  14867. * this function to return <code>true</code>), the absolute value of the difference between them, in
  14868. * seconds, must be less than <code>epsilon</code>.
  14869. *
  14870. * @param {JulianDate} [right] The second instance.
  14871. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  14872. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  14873. */
  14874. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  14875. return JulianDate.equalsEpsilon(this, right, epsilon);
  14876. };
  14877. /**
  14878. * Creates a string representing this date in ISO8601 format.
  14879. *
  14880. * @returns {String} A string representing this date in ISO8601 format.
  14881. */
  14882. JulianDate.prototype.toString = function() {
  14883. return JulianDate.toIso8601(this);
  14884. };
  14885. /**
  14886. * Gets or sets the list of leap seconds used throughout Cesium.
  14887. * @memberof JulianDate
  14888. * @type {LeapSecond[]}
  14889. */
  14890. JulianDate.leapSeconds = [
  14891. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  14892. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  14893. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  14894. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  14895. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  14896. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  14897. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  14898. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  14899. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  14900. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  14901. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  14902. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  14903. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  14904. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  14905. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  14906. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  14907. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  14908. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  14909. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  14910. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  14911. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  14912. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  14913. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  14914. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  14915. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  14916. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  14917. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  14918. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  14919. ];
  14920. return JulianDate;
  14921. });
  14922. /*global define*/
  14923. define('Core/clone',[
  14924. './defaultValue'
  14925. ], function(
  14926. defaultValue) {
  14927. 'use strict';
  14928. /**
  14929. * Clones an object, returning a new object containing the same properties.
  14930. *
  14931. * @exports clone
  14932. *
  14933. * @param {Object} object The object to clone.
  14934. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  14935. * @returns {Object} The cloned object.
  14936. */
  14937. function clone(object, deep) {
  14938. if (object === null || typeof object !== 'object') {
  14939. return object;
  14940. }
  14941. deep = defaultValue(deep, false);
  14942. var result = new object.constructor();
  14943. for ( var propertyName in object) {
  14944. if (object.hasOwnProperty(propertyName)) {
  14945. var value = object[propertyName];
  14946. if (deep) {
  14947. value = clone(value, deep);
  14948. }
  14949. result[propertyName] = value;
  14950. }
  14951. }
  14952. return result;
  14953. }
  14954. return clone;
  14955. });
  14956. /*global define*/
  14957. define('Core/parseResponseHeaders',[], function() {
  14958. 'use strict';
  14959. /**
  14960. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  14961. * a dictionary.
  14962. *
  14963. * @exports parseResponseHeaders
  14964. *
  14965. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  14966. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  14967. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  14968. * is that header's value.
  14969. *
  14970. * @private
  14971. */
  14972. function parseResponseHeaders(headerString) {
  14973. var headers = {};
  14974. if (!headerString) {
  14975. return headers;
  14976. }
  14977. var headerPairs = headerString.split('\u000d\u000a');
  14978. for (var i = 0; i < headerPairs.length; ++i) {
  14979. var headerPair = headerPairs[i];
  14980. // Can't use split() here because it does the wrong thing
  14981. // if the header value has the string ": " in it.
  14982. var index = headerPair.indexOf('\u003a\u0020');
  14983. if (index > 0) {
  14984. var key = headerPair.substring(0, index);
  14985. var val = headerPair.substring(index + 2);
  14986. headers[key] = val;
  14987. }
  14988. }
  14989. return headers;
  14990. }
  14991. return parseResponseHeaders;
  14992. });
  14993. /*global define*/
  14994. define('Core/RequestErrorEvent',[
  14995. './defined',
  14996. './parseResponseHeaders'
  14997. ], function(
  14998. defined,
  14999. parseResponseHeaders) {
  15000. 'use strict';
  15001. /**
  15002. * An event that is raised when a request encounters an error.
  15003. *
  15004. * @constructor
  15005. * @alias RequestErrorEvent
  15006. *
  15007. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  15008. * @param {Object} [response] The response included along with the error.
  15009. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  15010. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  15011. */
  15012. function RequestErrorEvent(statusCode, response, responseHeaders) {
  15013. /**
  15014. * The HTTP error status code, such as 404. If the error does not have a particular
  15015. * HTTP code, this property will be undefined.
  15016. *
  15017. * @type {Number}
  15018. */
  15019. this.statusCode = statusCode;
  15020. /**
  15021. * The response included along with the error. If the error does not include a response,
  15022. * this property will be undefined.
  15023. *
  15024. * @type {Object}
  15025. */
  15026. this.response = response;
  15027. /**
  15028. * The headers included in the response, represented as an object literal of key/value pairs.
  15029. * If the error does not include any headers, this property will be undefined.
  15030. *
  15031. * @type {Object}
  15032. */
  15033. this.responseHeaders = responseHeaders;
  15034. if (typeof this.responseHeaders === 'string') {
  15035. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  15036. }
  15037. }
  15038. /**
  15039. * Creates a string representing this RequestErrorEvent.
  15040. * @memberof RequestErrorEvent
  15041. *
  15042. * @returns {String} A string representing the provided RequestErrorEvent.
  15043. */
  15044. RequestErrorEvent.prototype.toString = function() {
  15045. var str = 'Request has failed.';
  15046. if (defined(this.statusCode)) {
  15047. str += ' Status Code: ' + this.statusCode;
  15048. }
  15049. return str;
  15050. };
  15051. return RequestErrorEvent;
  15052. });
  15053. /**
  15054. * @license
  15055. *
  15056. * Grauw URI utilities
  15057. *
  15058. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  15059. *
  15060. * @author Laurens Holst (http://www.grauw.nl/)
  15061. *
  15062. * Copyright 2012 Laurens Holst
  15063. *
  15064. * Licensed under the Apache License, Version 2.0 (the "License");
  15065. * you may not use this file except in compliance with the License.
  15066. * You may obtain a copy of the License at
  15067. *
  15068. * http://www.apache.org/licenses/LICENSE-2.0
  15069. *
  15070. * Unless required by applicable law or agreed to in writing, software
  15071. * distributed under the License is distributed on an "AS IS" BASIS,
  15072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15073. * See the License for the specific language governing permissions and
  15074. * limitations under the License.
  15075. *
  15076. */
  15077. /*global define*/
  15078. define('ThirdParty/Uri',[],function() {
  15079. /**
  15080. * Constructs a URI object.
  15081. * @constructor
  15082. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  15083. * @param {string|URI} uri A string or URI object to create the object from.
  15084. */
  15085. function URI(uri) {
  15086. if (uri instanceof URI) { // copy constructor
  15087. this.scheme = uri.scheme;
  15088. this.authority = uri.authority;
  15089. this.path = uri.path;
  15090. this.query = uri.query;
  15091. this.fragment = uri.fragment;
  15092. } else if (uri) { // uri is URI string or cast to string
  15093. var c = parseRegex.exec(uri);
  15094. this.scheme = c[1];
  15095. this.authority = c[2];
  15096. this.path = c[3];
  15097. this.query = c[4];
  15098. this.fragment = c[5];
  15099. }
  15100. }
  15101. // Initial values on the prototype
  15102. URI.prototype.scheme = null;
  15103. URI.prototype.authority = null;
  15104. URI.prototype.path = '';
  15105. URI.prototype.query = null;
  15106. URI.prototype.fragment = null;
  15107. // Regular expression from RFC 3986 appendix B
  15108. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  15109. /**
  15110. * Returns the scheme part of the URI.
  15111. * In "http://example.com:80/a/b?x#y" this is "http".
  15112. */
  15113. URI.prototype.getScheme = function() {
  15114. return this.scheme;
  15115. };
  15116. /**
  15117. * Returns the authority part of the URI.
  15118. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  15119. */
  15120. URI.prototype.getAuthority = function() {
  15121. return this.authority;
  15122. };
  15123. /**
  15124. * Returns the path part of the URI.
  15125. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  15126. * In "mailto:mike@example.com" this is "mike@example.com".
  15127. */
  15128. URI.prototype.getPath = function() {
  15129. return this.path;
  15130. };
  15131. /**
  15132. * Returns the query part of the URI.
  15133. * In "http://example.com:80/a/b?x#y" this is "x".
  15134. */
  15135. URI.prototype.getQuery = function() {
  15136. return this.query;
  15137. };
  15138. /**
  15139. * Returns the fragment part of the URI.
  15140. * In "http://example.com:80/a/b?x#y" this is "y".
  15141. */
  15142. URI.prototype.getFragment = function() {
  15143. return this.fragment;
  15144. };
  15145. /**
  15146. * Tests whether the URI is an absolute URI.
  15147. * See RFC 3986 section 4.3.
  15148. */
  15149. URI.prototype.isAbsolute = function() {
  15150. return !!this.scheme && !this.fragment;
  15151. };
  15152. ///**
  15153. //* Extensive validation of the URI against the ABNF in RFC 3986
  15154. //*/
  15155. //URI.prototype.validate
  15156. /**
  15157. * Tests whether the URI is a same-document reference.
  15158. * See RFC 3986 section 4.4.
  15159. *
  15160. * To perform more thorough comparison, you can normalise the URI objects.
  15161. */
  15162. URI.prototype.isSameDocumentAs = function(uri) {
  15163. return uri.scheme == this.scheme &&
  15164. uri.authority == this.authority &&
  15165. uri.path == this.path &&
  15166. uri.query == this.query;
  15167. };
  15168. /**
  15169. * Simple String Comparison of two URIs.
  15170. * See RFC 3986 section 6.2.1.
  15171. *
  15172. * To perform more thorough comparison, you can normalise the URI objects.
  15173. */
  15174. URI.prototype.equals = function(uri) {
  15175. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  15176. };
  15177. /**
  15178. * Normalizes the URI using syntax-based normalization.
  15179. * This includes case normalization, percent-encoding normalization and path segment normalization.
  15180. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  15181. * (Although that would not be a valid URI in the first place. See validate().)
  15182. * See RFC 3986 section 6.2.2.
  15183. */
  15184. URI.prototype.normalize = function() {
  15185. this.removeDotSegments();
  15186. if (this.scheme)
  15187. this.scheme = this.scheme.toLowerCase();
  15188. if (this.authority)
  15189. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  15190. replace(caseRegex, replaceCase);
  15191. if (this.path)
  15192. this.path = this.path.replace(caseRegex, replaceCase);
  15193. if (this.query)
  15194. this.query = this.query.replace(caseRegex, replaceCase);
  15195. if (this.fragment)
  15196. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  15197. };
  15198. var caseRegex = /%[0-9a-z]{2}/gi;
  15199. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  15200. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  15201. function replaceCase(str) {
  15202. var dec = unescape(str);
  15203. return percentRegex.test(dec) ? dec : str.toUpperCase();
  15204. }
  15205. function replaceAuthority(str, p1, p2, p3) {
  15206. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  15207. }
  15208. /**
  15209. * Resolve a relative URI (this) against a base URI.
  15210. * The base URI must be an absolute URI.
  15211. * See RFC 3986 section 5.2
  15212. */
  15213. URI.prototype.resolve = function(baseURI) {
  15214. var uri = new URI();
  15215. if (this.scheme) {
  15216. uri.scheme = this.scheme;
  15217. uri.authority = this.authority;
  15218. uri.path = this.path;
  15219. uri.query = this.query;
  15220. } else {
  15221. uri.scheme = baseURI.scheme;
  15222. if (this.authority) {
  15223. uri.authority = this.authority;
  15224. uri.path = this.path;
  15225. uri.query = this.query;
  15226. } else {
  15227. uri.authority = baseURI.authority;
  15228. if (this.path == '') {
  15229. uri.path = baseURI.path;
  15230. uri.query = this.query || baseURI.query;
  15231. } else {
  15232. if (this.path.charAt(0) == '/') {
  15233. uri.path = this.path;
  15234. uri.removeDotSegments();
  15235. } else {
  15236. if (baseURI.authority && baseURI.path == '') {
  15237. uri.path = '/' + this.path;
  15238. } else {
  15239. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  15240. }
  15241. uri.removeDotSegments();
  15242. }
  15243. uri.query = this.query;
  15244. }
  15245. }
  15246. }
  15247. uri.fragment = this.fragment;
  15248. return uri;
  15249. };
  15250. /**
  15251. * Remove dot segments from path.
  15252. * See RFC 3986 section 5.2.4
  15253. * @private
  15254. */
  15255. URI.prototype.removeDotSegments = function() {
  15256. var input = this.path.split('/'),
  15257. output = [],
  15258. segment,
  15259. absPath = input[0] == '';
  15260. if (absPath)
  15261. input.shift();
  15262. var sFirst = input[0] == '' ? input.shift() : null;
  15263. while (input.length) {
  15264. segment = input.shift();
  15265. if (segment == '..') {
  15266. output.pop();
  15267. } else if (segment != '.') {
  15268. output.push(segment);
  15269. }
  15270. }
  15271. if (segment == '.' || segment == '..')
  15272. output.push('');
  15273. if (absPath)
  15274. output.unshift('');
  15275. this.path = output.join('/');
  15276. };
  15277. // We don't like this function because it builds up a cache that is never cleared.
  15278. // /**
  15279. // * Resolves a relative URI against an absolute base URI.
  15280. // * Convenience method.
  15281. // * @param {String} uri the relative URI to resolve
  15282. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  15283. // */
  15284. // URI.resolve = function(sURI, sBaseURI) {
  15285. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  15286. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  15287. // return uri.resolve(baseURI).toString();
  15288. // };
  15289. // var cache = {};
  15290. /**
  15291. * Serialises the URI to a string.
  15292. */
  15293. URI.prototype.toString = function() {
  15294. var result = '';
  15295. if (this.scheme)
  15296. result += this.scheme + ':';
  15297. if (this.authority)
  15298. result += '//' + this.authority;
  15299. result += this.path;
  15300. if (this.query)
  15301. result += '?' + this.query;
  15302. if (this.fragment)
  15303. result += '#' + this.fragment;
  15304. return result;
  15305. };
  15306. return URI;
  15307. });
  15308. /*global define*/
  15309. define('Core/TrustedServers',[
  15310. '../ThirdParty/Uri',
  15311. './defined',
  15312. './DeveloperError'
  15313. ], function(
  15314. Uri,
  15315. defined,
  15316. DeveloperError) {
  15317. 'use strict';
  15318. /**
  15319. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  15320. * any requests to these servers.
  15321. *
  15322. * @exports TrustedServers
  15323. *
  15324. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  15325. */
  15326. var TrustedServers = {};
  15327. var _servers = {};
  15328. /**
  15329. * Adds a trusted server to the registry
  15330. *
  15331. * @param {String} host The host to be added.
  15332. * @param {Number} port The port used to access the host.
  15333. *
  15334. * @example
  15335. * // Add a trusted server
  15336. * TrustedServers.add('my.server.com', 80);
  15337. */
  15338. TrustedServers.add = function(host, port) {
  15339. if (!defined(host)) {
  15340. throw new DeveloperError('host is required.');
  15341. }
  15342. if (!defined(port) || port <= 0) {
  15343. throw new DeveloperError('port is required to be greater than 0.');
  15344. }
  15345. var authority = host.toLowerCase() + ':' + port;
  15346. if (!defined(_servers[authority])) {
  15347. _servers[authority] = true;
  15348. }
  15349. };
  15350. /**
  15351. * Removes a trusted server from the registry
  15352. *
  15353. * @param {String} host The host to be removed.
  15354. * @param {Number} port The port used to access the host.
  15355. *
  15356. * @example
  15357. * // Remove a trusted server
  15358. * TrustedServers.remove('my.server.com', 80);
  15359. */
  15360. TrustedServers.remove = function(host, port) {
  15361. if (!defined(host)) {
  15362. throw new DeveloperError('host is required.');
  15363. }
  15364. if (!defined(port) || port <= 0) {
  15365. throw new DeveloperError('port is required to be greater than 0.');
  15366. }
  15367. var authority = host.toLowerCase() + ':' + port;
  15368. if (defined(_servers[authority])) {
  15369. delete _servers[authority];
  15370. }
  15371. };
  15372. function getAuthority(url) {
  15373. var uri = new Uri(url);
  15374. uri.normalize();
  15375. // Removes username:password@ so we just have host[:port]
  15376. var authority = uri.getAuthority();
  15377. if (!defined(authority)) {
  15378. return undefined; // Relative URL
  15379. }
  15380. if (authority.indexOf('@') !== -1) {
  15381. var parts = authority.split('@');
  15382. authority = parts[1];
  15383. }
  15384. // If the port is missing add one based on the scheme
  15385. if (authority.indexOf(':') === -1) {
  15386. var scheme = uri.getScheme();
  15387. if (!defined(scheme)) {
  15388. scheme = window.location.protocol;
  15389. scheme = scheme.substring(0, scheme.length-1);
  15390. }
  15391. if (scheme === 'http') {
  15392. authority += ':80';
  15393. } else if (scheme === 'https') {
  15394. authority += ':443';
  15395. } else {
  15396. return undefined;
  15397. }
  15398. }
  15399. return authority;
  15400. }
  15401. /**
  15402. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  15403. *
  15404. * @param {String} url The url to be tested against the trusted list
  15405. *
  15406. * @returns {boolean} Returns true if url is trusted, false otherwise.
  15407. *
  15408. * @example
  15409. * // Add server
  15410. * TrustedServers.add('my.server.com', 81);
  15411. *
  15412. * // Check if server is trusted
  15413. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  15414. * // my.server.com:81 is trusted
  15415. * }
  15416. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  15417. * // my.server.com isn't trusted
  15418. * }
  15419. */
  15420. TrustedServers.contains = function(url) {
  15421. if (!defined(url)) {
  15422. throw new DeveloperError('url is required.');
  15423. }
  15424. var authority = getAuthority(url);
  15425. if (defined(authority) && defined(_servers[authority])) {
  15426. return true;
  15427. }
  15428. return false;
  15429. };
  15430. /**
  15431. * Clears the registry
  15432. *
  15433. * @example
  15434. * // Remove a trusted server
  15435. * TrustedServers.clear();
  15436. */
  15437. TrustedServers.clear = function() {
  15438. _servers = {};
  15439. };
  15440. return TrustedServers;
  15441. });
  15442. /*global define*/
  15443. define('Core/loadWithXhr',[
  15444. '../ThirdParty/when',
  15445. './defaultValue',
  15446. './defined',
  15447. './DeveloperError',
  15448. './RequestErrorEvent',
  15449. './RuntimeError',
  15450. './TrustedServers'
  15451. ], function(
  15452. when,
  15453. defaultValue,
  15454. defined,
  15455. DeveloperError,
  15456. RequestErrorEvent,
  15457. RuntimeError,
  15458. TrustedServers) {
  15459. 'use strict';
  15460. /**
  15461. * Asynchronously loads the given URL. Returns a promise that will resolve to
  15462. * the result once loaded, or reject if the URL failed to load. The data is loaded
  15463. * using XMLHttpRequest, which means that in order to make requests to another origin,
  15464. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  15465. *
  15466. * @exports loadWithXhr
  15467. *
  15468. * @param {Object} options Object with the following properties:
  15469. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  15470. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  15471. * @param {String} [options.method='GET'] The HTTP method to use.
  15472. * @param {String} [options.data] The data to send with the request, if any.
  15473. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  15474. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  15475. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  15476. *
  15477. *
  15478. * @example
  15479. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  15480. * Cesium.loadWithXhr({
  15481. * url : 'some/url',
  15482. * responseType : 'blob'
  15483. * }).then(function(blob) {
  15484. * // use the data
  15485. * }).otherwise(function(error) {
  15486. * // an error occurred
  15487. * });
  15488. *
  15489. * @see loadArrayBuffer
  15490. * @see loadBlob
  15491. * @see loadJson
  15492. * @see loadText
  15493. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  15494. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  15495. */
  15496. function loadWithXhr(options) {
  15497. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  15498. if (!defined(options.url)) {
  15499. throw new DeveloperError('options.url is required.');
  15500. }
  15501. var responseType = options.responseType;
  15502. var method = defaultValue(options.method, 'GET');
  15503. var data = options.data;
  15504. var headers = options.headers;
  15505. var overrideMimeType = options.overrideMimeType;
  15506. return when(options.url, function(url) {
  15507. var deferred = when.defer();
  15508. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  15509. return deferred.promise;
  15510. });
  15511. }
  15512. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  15513. function decodeDataUriText(isBase64, data) {
  15514. var result = decodeURIComponent(data);
  15515. if (isBase64) {
  15516. return atob(result);
  15517. }
  15518. return result;
  15519. }
  15520. function decodeDataUriArrayBuffer(isBase64, data) {
  15521. var byteString = decodeDataUriText(isBase64, data);
  15522. var buffer = new ArrayBuffer(byteString.length);
  15523. var view = new Uint8Array(buffer);
  15524. for (var i = 0; i < byteString.length; i++) {
  15525. view[i] = byteString.charCodeAt(i);
  15526. }
  15527. return buffer;
  15528. }
  15529. function decodeDataUri(dataUriRegexResult, responseType) {
  15530. responseType = defaultValue(responseType, '');
  15531. var mimeType = dataUriRegexResult[1];
  15532. var isBase64 = !!dataUriRegexResult[2];
  15533. var data = dataUriRegexResult[3];
  15534. switch (responseType) {
  15535. case '':
  15536. case 'text':
  15537. return decodeDataUriText(isBase64, data);
  15538. case 'arraybuffer':
  15539. return decodeDataUriArrayBuffer(isBase64, data);
  15540. case 'blob':
  15541. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  15542. return new Blob([buffer], {
  15543. type : mimeType
  15544. });
  15545. case 'document':
  15546. var parser = new DOMParser();
  15547. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  15548. case 'json':
  15549. return JSON.parse(decodeDataUriText(isBase64, data));
  15550. default:
  15551. throw new DeveloperError('Unhandled responseType: ' + responseType);
  15552. }
  15553. }
  15554. // This is broken out into a separate function so that it can be mocked for testing purposes.
  15555. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  15556. var dataUriRegexResult = dataUriRegex.exec(url);
  15557. if (dataUriRegexResult !== null) {
  15558. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  15559. return;
  15560. }
  15561. var xhr = new XMLHttpRequest();
  15562. if (TrustedServers.contains(url)) {
  15563. xhr.withCredentials = true;
  15564. }
  15565. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  15566. xhr.overrideMimeType(overrideMimeType);
  15567. }
  15568. xhr.open(method, url, true);
  15569. if (defined(headers)) {
  15570. for (var key in headers) {
  15571. if (headers.hasOwnProperty(key)) {
  15572. xhr.setRequestHeader(key, headers[key]);
  15573. }
  15574. }
  15575. }
  15576. if (defined(responseType)) {
  15577. xhr.responseType = responseType;
  15578. }
  15579. xhr.onload = function() {
  15580. if (xhr.status < 200 || xhr.status >= 300) {
  15581. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  15582. return;
  15583. }
  15584. var response = xhr.response;
  15585. var browserResponseType = xhr.responseType;
  15586. //All modern browsers will go into either the first if block or last else block.
  15587. //Other code paths support older browsers that either do not support the supplied responseType
  15588. //or do not support the xhr.response property.
  15589. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  15590. deferred.resolve(response);
  15591. } else if ((responseType === 'json') && typeof response === 'string') {
  15592. try {
  15593. deferred.resolve(JSON.parse(response));
  15594. } catch (e) {
  15595. deferred.reject(e);
  15596. }
  15597. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  15598. deferred.resolve(xhr.responseXML);
  15599. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  15600. deferred.resolve(xhr.responseText);
  15601. } else {
  15602. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  15603. }
  15604. };
  15605. xhr.onerror = function(e) {
  15606. deferred.reject(new RequestErrorEvent());
  15607. };
  15608. xhr.send(data);
  15609. };
  15610. loadWithXhr.defaultLoad = loadWithXhr.load;
  15611. return loadWithXhr;
  15612. });
  15613. /*global define*/
  15614. define('Core/loadText',[
  15615. './loadWithXhr'
  15616. ], function(
  15617. loadWithXhr) {
  15618. 'use strict';
  15619. /**
  15620. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  15621. * a String once loaded, or reject if the URL failed to load. The data is loaded
  15622. * using XMLHttpRequest, which means that in order to make requests to another origin,
  15623. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  15624. *
  15625. * @exports loadText
  15626. *
  15627. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  15628. * @param {Object} [headers] HTTP headers to send with the request.
  15629. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  15630. *
  15631. *
  15632. * @example
  15633. * // load text from a URL, setting a custom header
  15634. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  15635. * 'X-Custom-Header' : 'some value'
  15636. * }).then(function(text) {
  15637. * // Do something with the text
  15638. * }).otherwise(function(error) {
  15639. * // an error occurred
  15640. * });
  15641. *
  15642. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  15643. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  15644. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  15645. */
  15646. function loadText(url, headers) {
  15647. return loadWithXhr({
  15648. url : url,
  15649. headers : headers
  15650. });
  15651. }
  15652. return loadText;
  15653. });
  15654. /*global define*/
  15655. define('Core/loadJson',[
  15656. './clone',
  15657. './defined',
  15658. './DeveloperError',
  15659. './loadText'
  15660. ], function(
  15661. clone,
  15662. defined,
  15663. DeveloperError,
  15664. loadText) {
  15665. 'use strict';
  15666. var defaultHeaders = {
  15667. Accept : 'application/json,*/*;q=0.01'
  15668. };
  15669. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  15670. /**
  15671. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  15672. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  15673. * using XMLHttpRequest, which means that in order to make requests to another origin,
  15674. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  15675. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  15676. * already specified.
  15677. *
  15678. * @exports loadJson
  15679. *
  15680. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  15681. * @param {Object} [headers] HTTP headers to send with the request.
  15682. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  15683. * if not specified.
  15684. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  15685. *
  15686. *
  15687. * @example
  15688. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  15689. * // Do something with the JSON object
  15690. * }).otherwise(function(error) {
  15691. * // an error occurred
  15692. * });
  15693. *
  15694. * @see loadText
  15695. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  15696. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  15697. */
  15698. function loadJson(url, headers) {
  15699. if (!defined(url)) {
  15700. throw new DeveloperError('url is required.');
  15701. }
  15702. if (!defined(headers)) {
  15703. headers = defaultHeaders;
  15704. } else if (!defined(headers.Accept)) {
  15705. // clone before adding the Accept header
  15706. headers = clone(headers);
  15707. headers.Accept = defaultHeaders.Accept;
  15708. }
  15709. return loadText(url, headers).then(function(value) {
  15710. return JSON.parse(value);
  15711. });
  15712. }
  15713. return loadJson;
  15714. });
  15715. /*global define*/
  15716. define('Core/EarthOrientationParameters',[
  15717. '../ThirdParty/when',
  15718. './binarySearch',
  15719. './defaultValue',
  15720. './defined',
  15721. './EarthOrientationParametersSample',
  15722. './freezeObject',
  15723. './JulianDate',
  15724. './LeapSecond',
  15725. './loadJson',
  15726. './RuntimeError',
  15727. './TimeConstants',
  15728. './TimeStandard'
  15729. ], function(
  15730. when,
  15731. binarySearch,
  15732. defaultValue,
  15733. defined,
  15734. EarthOrientationParametersSample,
  15735. freezeObject,
  15736. JulianDate,
  15737. LeapSecond,
  15738. loadJson,
  15739. RuntimeError,
  15740. TimeConstants,
  15741. TimeStandard) {
  15742. 'use strict';
  15743. /**
  15744. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  15745. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  15746. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  15747. * Reference Frame (ITRF).
  15748. *
  15749. * @alias EarthOrientationParameters
  15750. * @constructor
  15751. *
  15752. * @param {Object} [options] Object with the following properties:
  15753. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  15754. * parameter nor options.data is specified, all EOP values are assumed
  15755. * to be 0.0. If options.data is specified, this parameter is
  15756. * ignored.
  15757. * @param {Object} [options.data] The actual EOP data. If neither this
  15758. * parameter nor options.data is specified, all EOP values are assumed
  15759. * to be 0.0.
  15760. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  15761. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  15762. * should be added to {@link JulianDate.leapSeconds}. False if
  15763. * new leap seconds should be handled correctly in the context
  15764. * of the EOP data but otherwise ignored.
  15765. *
  15766. * @example
  15767. * // An example EOP data file, EOP.json:
  15768. * {
  15769. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  15770. * "samples" : [
  15771. * "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,
  15772. * "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,
  15773. * "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
  15774. * ]
  15775. * }
  15776. *
  15777. * @example
  15778. * // Loading the EOP data
  15779. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  15780. * Cesium.Transforms.earthOrientationParameters = eop;
  15781. *
  15782. * @private
  15783. */
  15784. function EarthOrientationParameters(options) {
  15785. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  15786. this._dates = undefined;
  15787. this._samples = undefined;
  15788. this._dateColumn = -1;
  15789. this._xPoleWanderRadiansColumn = -1;
  15790. this._yPoleWanderRadiansColumn = -1;
  15791. this._ut1MinusUtcSecondsColumn = -1;
  15792. this._xCelestialPoleOffsetRadiansColumn = -1;
  15793. this._yCelestialPoleOffsetRadiansColumn = -1;
  15794. this._taiMinusUtcSecondsColumn = -1;
  15795. this._columnCount = 0;
  15796. this._lastIndex = -1;
  15797. this._downloadPromise = undefined;
  15798. this._dataError = undefined;
  15799. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  15800. if (defined(options.data)) {
  15801. // Use supplied EOP data.
  15802. onDataReady(this, options.data);
  15803. } else if (defined(options.url)) {
  15804. // Download EOP data.
  15805. var that = this;
  15806. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  15807. onDataReady(that, eopData);
  15808. }, function() {
  15809. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  15810. });
  15811. } else {
  15812. // Use all zeros for EOP data.
  15813. onDataReady(this, {
  15814. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  15815. 'samples' : []
  15816. });
  15817. }
  15818. }
  15819. /**
  15820. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  15821. */
  15822. EarthOrientationParameters.NONE = freezeObject({
  15823. getPromiseToLoad : function() {
  15824. return when();
  15825. },
  15826. compute : function(date, result) {
  15827. if (!defined(result)) {
  15828. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  15829. } else {
  15830. result.xPoleWander = 0.0;
  15831. result.yPoleWander = 0.0;
  15832. result.xPoleOffset = 0.0;
  15833. result.yPoleOffset = 0.0;
  15834. result.ut1MinusUtc = 0.0;
  15835. }
  15836. return result;
  15837. }
  15838. });
  15839. /**
  15840. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  15841. * ready to use.
  15842. *
  15843. * @returns {Promise.<undefined>} The promise.
  15844. *
  15845. * @see when
  15846. */
  15847. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  15848. return when(this._downloadPromise);
  15849. };
  15850. /**
  15851. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  15852. * If the EOP data has not yet been download, this method returns undefined.
  15853. *
  15854. * @param {JulianDate} date The date for each to evaluate the EOP.
  15855. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  15856. * If this parameter is undefined, a new instance is created and returned.
  15857. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  15858. * undefined if the data necessary to evaluate EOP at the date has not yet been
  15859. * downloaded.
  15860. *
  15861. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  15862. *
  15863. * @see EarthOrientationParameters#getPromiseToLoad
  15864. */
  15865. EarthOrientationParameters.prototype.compute = function(date, result) {
  15866. // We cannot compute until the samples are available.
  15867. if (!defined(this._samples)) {
  15868. if (defined(this._dataError)) {
  15869. throw new RuntimeError(this._dataError);
  15870. }
  15871. return undefined;
  15872. }
  15873. if (!defined(result)) {
  15874. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  15875. }
  15876. if (this._samples.length === 0) {
  15877. result.xPoleWander = 0.0;
  15878. result.yPoleWander = 0.0;
  15879. result.xPoleOffset = 0.0;
  15880. result.yPoleOffset = 0.0;
  15881. result.ut1MinusUtc = 0.0;
  15882. return result;
  15883. }
  15884. var dates = this._dates;
  15885. var lastIndex = this._lastIndex;
  15886. var before = 0;
  15887. var after = 0;
  15888. if (defined(lastIndex)) {
  15889. var previousIndexDate = dates[lastIndex];
  15890. var nextIndexDate = dates[lastIndex + 1];
  15891. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  15892. var isAfterLastSample = !defined(nextIndexDate);
  15893. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  15894. if (isAfterPrevious && isBeforeNext) {
  15895. before = lastIndex;
  15896. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  15897. ++before;
  15898. }
  15899. after = before + 1;
  15900. interpolate(this, dates, this._samples, date, before, after, result);
  15901. return result;
  15902. }
  15903. }
  15904. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  15905. if (index >= 0) {
  15906. // If the next entry is the same date, use the later entry. This way, if two entries
  15907. // describe the same moment, one before a leap second and the other after, then we will use
  15908. // the post-leap second data.
  15909. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  15910. ++index;
  15911. }
  15912. before = index;
  15913. after = index;
  15914. } else {
  15915. after = ~index;
  15916. before = after - 1;
  15917. // Use the first entry if the date requested is before the beginning of the data.
  15918. if (before < 0) {
  15919. before = 0;
  15920. }
  15921. }
  15922. this._lastIndex = before;
  15923. interpolate(this, dates, this._samples, date, before, after, result);
  15924. return result;
  15925. };
  15926. function compareLeapSecondDates(leapSecond, dateToFind) {
  15927. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  15928. }
  15929. function onDataReady(eop, eopData) {
  15930. if (!defined(eopData.columnNames)) {
  15931. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  15932. return;
  15933. }
  15934. if (!defined(eopData.samples)) {
  15935. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  15936. return;
  15937. }
  15938. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  15939. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  15940. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  15941. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  15942. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  15943. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  15944. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  15945. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  15946. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  15947. return;
  15948. }
  15949. var samples = eop._samples = eopData.samples;
  15950. var dates = eop._dates = [];
  15951. eop._dateColumn = dateColumn;
  15952. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  15953. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  15954. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  15955. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  15956. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  15957. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  15958. eop._columnCount = eopData.columnNames.length;
  15959. eop._lastIndex = undefined;
  15960. var lastTaiMinusUtc;
  15961. var addNewLeapSeconds = eop._addNewLeapSeconds;
  15962. // Convert the ISO8601 dates to JulianDates.
  15963. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  15964. var mjd = samples[i + dateColumn];
  15965. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  15966. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  15967. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  15968. dates.push(date);
  15969. if (addNewLeapSeconds) {
  15970. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  15971. // We crossed a leap second boundary, so add the leap second
  15972. // if it does not already exist.
  15973. var leapSeconds = JulianDate.leapSeconds;
  15974. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  15975. if (leapSecondIndex < 0) {
  15976. var leapSecond = new LeapSecond(date, taiMinusUtc);
  15977. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  15978. }
  15979. }
  15980. lastTaiMinusUtc = taiMinusUtc;
  15981. }
  15982. }
  15983. }
  15984. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  15985. var start = index * columnCount;
  15986. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  15987. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  15988. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  15989. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  15990. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  15991. }
  15992. function linearInterp(dx, y1, y2) {
  15993. return y1 + dx * (y2 - y1);
  15994. }
  15995. function interpolate(eop, dates, samples, date, before, after, result) {
  15996. var columnCount = eop._columnCount;
  15997. // First check the bounds on the EOP data
  15998. // If we are after the bounds of the data, return zeros.
  15999. // The 'before' index should never be less than zero.
  16000. if (after > dates.length - 1) {
  16001. result.xPoleWander = 0;
  16002. result.yPoleWander = 0;
  16003. result.xPoleOffset = 0;
  16004. result.yPoleOffset = 0;
  16005. result.ut1MinusUtc = 0;
  16006. return result;
  16007. }
  16008. var beforeDate = dates[before];
  16009. var afterDate = dates[after];
  16010. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  16011. fillResultFromIndex(eop, samples, before, columnCount, result);
  16012. return result;
  16013. } else if (date.equals(afterDate)) {
  16014. fillResultFromIndex(eop, samples, after, columnCount, result);
  16015. return result;
  16016. }
  16017. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  16018. var startBefore = before * columnCount;
  16019. var startAfter = after * columnCount;
  16020. // Handle UT1 leap second edge case
  16021. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  16022. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  16023. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  16024. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  16025. // The absolute difference between the values is more than 0.5, so we may have
  16026. // crossed a leap second. Check if this is the case and, if so, adjust the
  16027. // afterValue to account for the leap second. This way, our interpolation will
  16028. // produce reasonable results.
  16029. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  16030. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  16031. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  16032. if (afterDate.equals(date)) {
  16033. // If we are at the end of the leap second interval, take the second value
  16034. // Otherwise, the interpolation below will yield the wrong side of the
  16035. // discontinuity
  16036. // At the end of the leap second, we need to start accounting for the jump
  16037. beforeUt1MinusUtc = afterUt1MinusUtc;
  16038. } else {
  16039. // Otherwise, remove the leap second so that the interpolation is correct
  16040. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  16041. }
  16042. }
  16043. }
  16044. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  16045. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  16046. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  16047. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  16048. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  16049. return result;
  16050. }
  16051. return EarthOrientationParameters;
  16052. });
  16053. /*global define*/
  16054. define('Core/HeadingPitchRoll',[
  16055. './defaultValue',
  16056. './defined',
  16057. './DeveloperError',
  16058. './Math'
  16059. ], function(
  16060. defaultValue,
  16061. defined,
  16062. DeveloperError,
  16063. CesiumMath) {
  16064. "use strict";
  16065. /**
  16066. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  16067. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  16068. * the positive x axis.
  16069. * @alias HeadingPitchRoll
  16070. * @constructor
  16071. *
  16072. * @param {Number} [heading=0.0] The heading component in radians.
  16073. * @param {Number} [pitch=0.0] The pitch component in radians.
  16074. * @param {Number} [roll=0.0] The roll component in radians.
  16075. */
  16076. function HeadingPitchRoll(heading, pitch, roll) {
  16077. this.heading = defaultValue(heading, 0.0);
  16078. this.pitch = defaultValue(pitch, 0.0);
  16079. this.roll = defaultValue(roll, 0.0);
  16080. }
  16081. /**
  16082. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  16083. *
  16084. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  16085. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  16086. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  16087. */
  16088. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  16089. if (!defined(quaternion)) {
  16090. throw new DeveloperError('quaternion is required');
  16091. }
  16092. if (!defined(result)) {
  16093. result = new HeadingPitchRoll();
  16094. }
  16095. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  16096. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  16097. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  16098. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  16099. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  16100. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  16101. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  16102. result.pitch = -Math.asin(test);
  16103. return result;
  16104. };
  16105. /**
  16106. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  16107. *
  16108. * @param {Number} heading the heading in degrees
  16109. * @param {Number} pitch the pitch in degrees
  16110. * @param {Number} roll the heading in degrees
  16111. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  16112. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  16113. */
  16114. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  16115. if (!defined(heading)) {
  16116. throw new DeveloperError('heading is required');
  16117. }
  16118. if (!defined(pitch)) {
  16119. throw new DeveloperError('pitch is required');
  16120. }
  16121. if (!defined(roll)) {
  16122. throw new DeveloperError('roll is required');
  16123. }
  16124. if (!defined(result)) {
  16125. result = new HeadingPitchRoll();
  16126. }
  16127. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  16128. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  16129. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  16130. return result;
  16131. };
  16132. /**
  16133. * Duplicates a HeadingPitchRoll instance.
  16134. *
  16135. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  16136. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  16137. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  16138. */
  16139. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  16140. if (!defined(headingPitchRoll)) {
  16141. return undefined;
  16142. }
  16143. if (!defined(result)) {
  16144. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  16145. }
  16146. result.heading = headingPitchRoll.heading;
  16147. result.pitch = headingPitchRoll.pitch;
  16148. result.roll = headingPitchRoll.roll;
  16149. return result;
  16150. };
  16151. /**
  16152. * Compares the provided HeadingPitchRolls componentwise and returns
  16153. * <code>true</code> if they are equal, <code>false</code> otherwise.
  16154. *
  16155. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  16156. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  16157. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  16158. */
  16159. HeadingPitchRoll.equals = function(left, right) {
  16160. return (left === right) ||
  16161. ((defined(left)) &&
  16162. (defined(right)) &&
  16163. (left.heading === right.heading) &&
  16164. (left.pitch === right.pitch) &&
  16165. (left.roll === right.roll));
  16166. };
  16167. /**
  16168. * Compares the provided HeadingPitchRolls componentwise and returns
  16169. * <code>true</code> if they pass an absolute or relative tolerance test,
  16170. * <code>false</code> otherwise.
  16171. *
  16172. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  16173. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  16174. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  16175. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  16176. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  16177. */
  16178. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  16179. return (left === right) ||
  16180. (defined(left) &&
  16181. defined(right) &&
  16182. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  16183. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  16184. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  16185. };
  16186. /**
  16187. * Duplicates this HeadingPitchRoll instance.
  16188. *
  16189. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  16190. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  16191. */
  16192. HeadingPitchRoll.prototype.clone = function(result) {
  16193. return HeadingPitchRoll.clone(this, result);
  16194. };
  16195. /**
  16196. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  16197. * <code>true</code> if they are equal, <code>false</code> otherwise.
  16198. *
  16199. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  16200. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  16201. */
  16202. HeadingPitchRoll.prototype.equals = function(right) {
  16203. return HeadingPitchRoll.equals(this, right);
  16204. };
  16205. /**
  16206. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  16207. * <code>true</code> if they pass an absolute or relative tolerance test,
  16208. * <code>false</code> otherwise.
  16209. *
  16210. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  16211. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  16212. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  16213. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  16214. */
  16215. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  16216. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  16217. };
  16218. /**
  16219. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  16220. *
  16221. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  16222. */
  16223. HeadingPitchRoll.prototype.toString = function() {
  16224. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  16225. };
  16226. return HeadingPitchRoll;
  16227. });
  16228. /*global define*/
  16229. define('Core/getAbsoluteUri',[
  16230. '../ThirdParty/Uri',
  16231. './defaultValue',
  16232. './defined',
  16233. './DeveloperError'
  16234. ], function(
  16235. Uri,
  16236. defaultValue,
  16237. defined,
  16238. DeveloperError) {
  16239. 'use strict';
  16240. /**
  16241. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  16242. * @exports getAbsoluteUri
  16243. *
  16244. * @param {String} relative The relative Uri.
  16245. * @param {String} [base] The base Uri.
  16246. * @returns {String} The absolute Uri of the given relative Uri.
  16247. *
  16248. * @example
  16249. * //absolute Uri will be "https://test.com/awesome.png";
  16250. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  16251. */
  16252. function getAbsoluteUri(relative, base) {
  16253. if (!defined(relative)) {
  16254. throw new DeveloperError('relative uri is required.');
  16255. }
  16256. base = defaultValue(base, document.location.href);
  16257. var baseUri = new Uri(base);
  16258. var relativeUri = new Uri(relative);
  16259. return relativeUri.resolve(baseUri).toString();
  16260. }
  16261. return getAbsoluteUri;
  16262. });
  16263. /*global define*/
  16264. define('Core/joinUrls',[
  16265. '../ThirdParty/Uri',
  16266. './defaultValue',
  16267. './defined',
  16268. './DeveloperError'
  16269. ], function(
  16270. Uri,
  16271. defaultValue,
  16272. defined,
  16273. DeveloperError) {
  16274. 'use strict';
  16275. /**
  16276. * Function for joining URLs in a manner that is aware of query strings and fragments.
  16277. * This is useful when the base URL has a query string that needs to be maintained
  16278. * (e.g. a presigned base URL).
  16279. * @param {String|Uri} first The base URL.
  16280. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  16281. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  16282. * @private
  16283. */
  16284. function joinUrls(first, second, appendSlash) {
  16285. if (!defined(first)) {
  16286. throw new DeveloperError('first is required');
  16287. }
  16288. if (!defined(second)) {
  16289. throw new DeveloperError('second is required');
  16290. }
  16291. appendSlash = defaultValue(appendSlash, true);
  16292. if (!(first instanceof Uri)) {
  16293. first = new Uri(first);
  16294. }
  16295. if (!(second instanceof Uri)) {
  16296. second = new Uri(second);
  16297. }
  16298. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  16299. // not a scheme, add a scheme matching the page's scheme.
  16300. if (defined(second.authority) && !defined(second.scheme)) {
  16301. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  16302. second.scheme = new Uri(document.location.href).scheme;
  16303. } else {
  16304. // Not in a browser? Use the first URL's scheme instead.
  16305. second.scheme = first.scheme;
  16306. }
  16307. }
  16308. // If the second URL is absolute, use it for the scheme, authority, and path.
  16309. var baseUri = first;
  16310. if (second.isAbsolute()) {
  16311. baseUri = second;
  16312. }
  16313. var url = '';
  16314. if (defined(baseUri.scheme)) {
  16315. url += baseUri.scheme + ':';
  16316. }
  16317. if (defined(baseUri.authority)) {
  16318. url += '//' + baseUri.authority;
  16319. if (baseUri.path !== '' && baseUri.path !== '/') {
  16320. url = url.replace(/\/?$/, '/');
  16321. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  16322. }
  16323. }
  16324. // Combine the paths (only if second is relative).
  16325. if (baseUri === first) {
  16326. if (appendSlash) {
  16327. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  16328. } else {
  16329. url += first.path + second.path;
  16330. }
  16331. } else {
  16332. url += second.path;
  16333. }
  16334. // Combine the queries and fragments.
  16335. var hasFirstQuery = defined(first.query);
  16336. var hasSecondQuery = defined(second.query);
  16337. if (hasFirstQuery && hasSecondQuery) {
  16338. url += '?' + first.query + '&' + second.query;
  16339. } else if (hasFirstQuery && !hasSecondQuery) {
  16340. url += '?' + first.query;
  16341. } else if (!hasFirstQuery && hasSecondQuery) {
  16342. url += '?' + second.query;
  16343. }
  16344. var hasSecondFragment = defined(second.fragment);
  16345. if (defined(first.fragment) && !hasSecondFragment) {
  16346. url += '#' + first.fragment;
  16347. } else if (hasSecondFragment) {
  16348. url += '#' + second.fragment;
  16349. }
  16350. return url;
  16351. }
  16352. return joinUrls;
  16353. });
  16354. /*global define*/
  16355. define('Core/buildModuleUrl',[
  16356. '../ThirdParty/Uri',
  16357. './defined',
  16358. './DeveloperError',
  16359. './getAbsoluteUri',
  16360. './joinUrls',
  16361. 'require'
  16362. ], function(
  16363. Uri,
  16364. defined,
  16365. DeveloperError,
  16366. getAbsoluteUri,
  16367. joinUrls,
  16368. require) {
  16369. 'use strict';
  16370. /*global CESIUM_BASE_URL*/
  16371. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  16372. function getBaseUrlFromCesiumScript() {
  16373. var scripts = document.getElementsByTagName('script');
  16374. for ( var i = 0, len = scripts.length; i < len; ++i) {
  16375. var src = scripts[i].getAttribute('src');
  16376. var result = cesiumScriptRegex.exec(src);
  16377. if (result !== null) {
  16378. return result[1];
  16379. }
  16380. }
  16381. return undefined;
  16382. }
  16383. var baseUrl;
  16384. function getCesiumBaseUrl() {
  16385. if (defined(baseUrl)) {
  16386. return baseUrl;
  16387. }
  16388. var baseUrlString;
  16389. if (typeof CESIUM_BASE_URL !== 'undefined') {
  16390. baseUrlString = CESIUM_BASE_URL;
  16391. } else {
  16392. baseUrlString = getBaseUrlFromCesiumScript();
  16393. }
  16394. if (!defined(baseUrlString)) {
  16395. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  16396. }
  16397. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  16398. return baseUrl;
  16399. }
  16400. function buildModuleUrlFromRequireToUrl(moduleID) {
  16401. //moduleID will be non-relative, so require it relative to this module, in Core.
  16402. return require.toUrl('../' + moduleID);
  16403. }
  16404. function buildModuleUrlFromBaseUrl(moduleID) {
  16405. return joinUrls(getCesiumBaseUrl(), moduleID);
  16406. }
  16407. var implementation;
  16408. var a;
  16409. /**
  16410. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  16411. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  16412. * the base URL of the Cesium.js script.
  16413. *
  16414. * @private
  16415. */
  16416. function buildModuleUrl(moduleID) {
  16417. if (!defined(implementation)) {
  16418. //select implementation
  16419. if (defined(require.toUrl)) {
  16420. implementation = buildModuleUrlFromRequireToUrl;
  16421. } else {
  16422. implementation = buildModuleUrlFromBaseUrl;
  16423. }
  16424. }
  16425. if (!defined(a)) {
  16426. a = document.createElement('a');
  16427. }
  16428. var url = implementation(moduleID);
  16429. a.href = url;
  16430. a.href = a.href; // IE only absolutizes href on get, not set
  16431. return a.href;
  16432. }
  16433. // exposed for testing
  16434. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  16435. /**
  16436. * Sets the base URL for resolving modules.
  16437. * @param {String} value The new base URL.
  16438. */
  16439. buildModuleUrl.setBaseUrl = function(value) {
  16440. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  16441. };
  16442. return buildModuleUrl;
  16443. });
  16444. /*global define*/
  16445. define('Core/Iau2006XysSample',[],function() {
  16446. 'use strict';
  16447. /**
  16448. * An IAU 2006 XYS value sampled at a particular time.
  16449. *
  16450. * @alias Iau2006XysSample
  16451. * @constructor
  16452. *
  16453. * @param {Number} x The X value.
  16454. * @param {Number} y The Y value.
  16455. * @param {Number} s The S value.
  16456. *
  16457. * @private
  16458. */
  16459. function Iau2006XysSample(x, y, s) {
  16460. /**
  16461. * The X value.
  16462. * @type {Number}
  16463. */
  16464. this.x = x;
  16465. /**
  16466. * The Y value.
  16467. * @type {Number}
  16468. */
  16469. this.y = y;
  16470. /**
  16471. * The S value.
  16472. * @type {Number}
  16473. */
  16474. this.s = s;
  16475. }
  16476. return Iau2006XysSample;
  16477. });
  16478. /*global define*/
  16479. define('Core/Iau2006XysData',[
  16480. '../ThirdParty/when',
  16481. './buildModuleUrl',
  16482. './defaultValue',
  16483. './defined',
  16484. './Iau2006XysSample',
  16485. './JulianDate',
  16486. './loadJson',
  16487. './TimeStandard'
  16488. ], function(
  16489. when,
  16490. buildModuleUrl,
  16491. defaultValue,
  16492. defined,
  16493. Iau2006XysSample,
  16494. JulianDate,
  16495. loadJson,
  16496. TimeStandard) {
  16497. 'use strict';
  16498. /**
  16499. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  16500. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  16501. *
  16502. * @alias Iau2006XysData
  16503. * @constructor
  16504. *
  16505. * @param {Object} [options] Object with the following properties:
  16506. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  16507. * `{0}` will be replaced with the file index.
  16508. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  16509. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  16510. * first XYS sample.
  16511. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  16512. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  16513. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  16514. *
  16515. * @private
  16516. */
  16517. function Iau2006XysData(options) {
  16518. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16519. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  16520. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  16521. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  16522. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  16523. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  16524. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  16525. this._totalSamples = defaultValue(options.totalSamples, 27426);
  16526. this._samples = new Array(this._totalSamples * 3);
  16527. this._chunkDownloadsInProgress = [];
  16528. var order = this._interpolationOrder;
  16529. // Compute denominators and X values for interpolation.
  16530. var denom = this._denominators = new Array(order + 1);
  16531. var xTable = this._xTable = new Array(order + 1);
  16532. var stepN = Math.pow(this._stepSizeDays, order);
  16533. for ( var i = 0; i <= order; ++i) {
  16534. denom[i] = stepN;
  16535. xTable[i] = i * this._stepSizeDays;
  16536. for ( var j = 0; j <= order; ++j) {
  16537. if (j !== i) {
  16538. denom[i] *= (i - j);
  16539. }
  16540. }
  16541. denom[i] = 1.0 / denom[i];
  16542. }
  16543. // Allocate scratch arrays for interpolation.
  16544. this._work = new Array(order + 1);
  16545. this._coef = new Array(order + 1);
  16546. }
  16547. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  16548. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  16549. var dateTT = julianDateScratch;
  16550. dateTT.dayNumber = dayTT;
  16551. dateTT.secondsOfDay = secondTT;
  16552. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  16553. }
  16554. /**
  16555. * Preloads XYS data for a specified date range.
  16556. *
  16557. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  16558. * the Terrestrial Time (TT) time standard.
  16559. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  16560. * the Terrestrial Time (TT) time standard.
  16561. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  16562. * the Terrestrial Time (TT) time standard.
  16563. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  16564. * the Terrestrial Time (TT) time standard.
  16565. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  16566. * preloaded.
  16567. */
  16568. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  16569. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  16570. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  16571. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  16572. if (startIndex < 0) {
  16573. startIndex = 0;
  16574. }
  16575. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  16576. if (stopIndex >= this._totalSamples) {
  16577. stopIndex = this._totalSamples - 1;
  16578. }
  16579. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  16580. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  16581. var promises = [];
  16582. for ( var i = startChunk; i <= stopChunk; ++i) {
  16583. promises.push(requestXysChunk(this, i));
  16584. }
  16585. return when.all(promises);
  16586. };
  16587. /**
  16588. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  16589. * this method will return undefined.
  16590. *
  16591. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  16592. * the Terrestrial Time (TT) time standard.
  16593. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  16594. * the Terrestrial Time (TT) time standard.
  16595. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  16596. * is undefined, a new instance is allocated and returned.
  16597. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  16598. * computation has not yet been downloaded.
  16599. *
  16600. * @see Iau2006XysData#preload
  16601. */
  16602. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  16603. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  16604. if (daysSinceEpoch < 0.0) {
  16605. // Can't evaluate prior to the epoch of the data.
  16606. return undefined;
  16607. }
  16608. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  16609. if (centerIndex >= this._totalSamples) {
  16610. // Can't evaluate after the last sample in the data.
  16611. return undefined;
  16612. }
  16613. var degree = this._interpolationOrder;
  16614. var firstIndex = centerIndex - ((degree / 2) | 0);
  16615. if (firstIndex < 0) {
  16616. firstIndex = 0;
  16617. }
  16618. var lastIndex = firstIndex + degree;
  16619. if (lastIndex >= this._totalSamples) {
  16620. lastIndex = this._totalSamples - 1;
  16621. firstIndex = lastIndex - degree;
  16622. if (firstIndex < 0) {
  16623. firstIndex = 0;
  16624. }
  16625. }
  16626. // Are all the samples we need present?
  16627. // We can assume so if the first and last are present
  16628. var isDataMissing = false;
  16629. var samples = this._samples;
  16630. if (!defined(samples[firstIndex * 3])) {
  16631. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  16632. isDataMissing = true;
  16633. }
  16634. if (!defined(samples[lastIndex * 3])) {
  16635. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  16636. isDataMissing = true;
  16637. }
  16638. if (isDataMissing) {
  16639. return undefined;
  16640. }
  16641. if (!defined(result)) {
  16642. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  16643. } else {
  16644. result.x = 0.0;
  16645. result.y = 0.0;
  16646. result.s = 0.0;
  16647. }
  16648. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  16649. var work = this._work;
  16650. var denom = this._denominators;
  16651. var coef = this._coef;
  16652. var xTable = this._xTable;
  16653. var i, j;
  16654. for (i = 0; i <= degree; ++i) {
  16655. work[i] = x - xTable[i];
  16656. }
  16657. for (i = 0; i <= degree; ++i) {
  16658. coef[i] = 1.0;
  16659. for (j = 0; j <= degree; ++j) {
  16660. if (j !== i) {
  16661. coef[i] *= work[j];
  16662. }
  16663. }
  16664. coef[i] *= denom[i];
  16665. var sampleIndex = (firstIndex + i) * 3;
  16666. result.x += coef[i] * samples[sampleIndex++];
  16667. result.y += coef[i] * samples[sampleIndex++];
  16668. result.s += coef[i] * samples[sampleIndex];
  16669. }
  16670. return result;
  16671. };
  16672. function requestXysChunk(xysData, chunkIndex) {
  16673. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  16674. // Chunk has already been requested.
  16675. return xysData._chunkDownloadsInProgress[chunkIndex];
  16676. }
  16677. var deferred = when.defer();
  16678. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  16679. var chunkUrl;
  16680. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  16681. if (defined(xysFileUrlTemplate)) {
  16682. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  16683. } else {
  16684. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  16685. }
  16686. when(loadJson(chunkUrl), function(chunk) {
  16687. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  16688. var samples = xysData._samples;
  16689. var newSamples = chunk.samples;
  16690. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  16691. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  16692. samples[startIndex + i] = newSamples[i];
  16693. }
  16694. deferred.resolve();
  16695. });
  16696. return deferred.promise;
  16697. }
  16698. return Iau2006XysData;
  16699. });
  16700. /*global define*/
  16701. define('Core/Fullscreen',[
  16702. './defined',
  16703. './defineProperties'
  16704. ], function(
  16705. defined,
  16706. defineProperties) {
  16707. 'use strict';
  16708. var _supportsFullscreen;
  16709. var _names = {
  16710. requestFullscreen : undefined,
  16711. exitFullscreen : undefined,
  16712. fullscreenEnabled : undefined,
  16713. fullscreenElement : undefined,
  16714. fullscreenchange : undefined,
  16715. fullscreenerror : undefined
  16716. };
  16717. /**
  16718. * Browser-independent functions for working with the standard fullscreen API.
  16719. *
  16720. * @exports Fullscreen
  16721. *
  16722. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  16723. */
  16724. var Fullscreen = {};
  16725. defineProperties(Fullscreen, {
  16726. /**
  16727. * The element that is currently fullscreen, if any. To simply check if the
  16728. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  16729. * @memberof Fullscreen
  16730. * @type {Object}
  16731. * @readonly
  16732. */
  16733. element : {
  16734. get : function() {
  16735. if (!Fullscreen.supportsFullscreen()) {
  16736. return undefined;
  16737. }
  16738. return document[_names.fullscreenElement];
  16739. }
  16740. },
  16741. /**
  16742. * The name of the event on the document that is fired when fullscreen is
  16743. * entered or exited. This event name is intended for use with addEventListener.
  16744. * In your event handler, to determine if the browser is in fullscreen mode or not,
  16745. * use {@link Fullscreen#fullscreen}.
  16746. * @memberof Fullscreen
  16747. * @type {String}
  16748. * @readonly
  16749. */
  16750. changeEventName : {
  16751. get : function() {
  16752. if (!Fullscreen.supportsFullscreen()) {
  16753. return undefined;
  16754. }
  16755. return _names.fullscreenchange;
  16756. }
  16757. },
  16758. /**
  16759. * The name of the event that is fired when a fullscreen error
  16760. * occurs. This event name is intended for use with addEventListener.
  16761. * @memberof Fullscreen
  16762. * @type {String}
  16763. * @readonly
  16764. */
  16765. errorEventName : {
  16766. get : function() {
  16767. if (!Fullscreen.supportsFullscreen()) {
  16768. return undefined;
  16769. }
  16770. return _names.fullscreenerror;
  16771. }
  16772. },
  16773. /**
  16774. * Determine whether the browser will allow an element to be made fullscreen, or not.
  16775. * For example, by default, iframes cannot go fullscreen unless the containing page
  16776. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  16777. * @memberof Fullscreen
  16778. * @type {Boolean}
  16779. * @readonly
  16780. */
  16781. enabled : {
  16782. get : function() {
  16783. if (!Fullscreen.supportsFullscreen()) {
  16784. return undefined;
  16785. }
  16786. return document[_names.fullscreenEnabled];
  16787. }
  16788. },
  16789. /**
  16790. * Determines if the browser is currently in fullscreen mode.
  16791. * @memberof Fullscreen
  16792. * @type {Boolean}
  16793. * @readonly
  16794. */
  16795. fullscreen : {
  16796. get : function() {
  16797. if (!Fullscreen.supportsFullscreen()) {
  16798. return undefined;
  16799. }
  16800. return Fullscreen.element !== null;
  16801. }
  16802. }
  16803. });
  16804. /**
  16805. * Detects whether the browser supports the standard fullscreen API.
  16806. *
  16807. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  16808. * <code>false</code> otherwise.
  16809. */
  16810. Fullscreen.supportsFullscreen = function() {
  16811. if (defined(_supportsFullscreen)) {
  16812. return _supportsFullscreen;
  16813. }
  16814. _supportsFullscreen = false;
  16815. var body = document.body;
  16816. if (typeof body.requestFullscreen === 'function') {
  16817. // go with the unprefixed, standard set of names
  16818. _names.requestFullscreen = 'requestFullscreen';
  16819. _names.exitFullscreen = 'exitFullscreen';
  16820. _names.fullscreenEnabled = 'fullscreenEnabled';
  16821. _names.fullscreenElement = 'fullscreenElement';
  16822. _names.fullscreenchange = 'fullscreenchange';
  16823. _names.fullscreenerror = 'fullscreenerror';
  16824. _supportsFullscreen = true;
  16825. return _supportsFullscreen;
  16826. }
  16827. //check for the correct combination of prefix plus the various names that browsers use
  16828. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  16829. var name;
  16830. for (var i = 0, len = prefixes.length; i < len; ++i) {
  16831. var prefix = prefixes[i];
  16832. // casing of Fullscreen differs across browsers
  16833. name = prefix + 'RequestFullscreen';
  16834. if (typeof body[name] === 'function') {
  16835. _names.requestFullscreen = name;
  16836. _supportsFullscreen = true;
  16837. } else {
  16838. name = prefix + 'RequestFullScreen';
  16839. if (typeof body[name] === 'function') {
  16840. _names.requestFullscreen = name;
  16841. _supportsFullscreen = true;
  16842. }
  16843. }
  16844. // disagreement about whether it's "exit" as per spec, or "cancel"
  16845. name = prefix + 'ExitFullscreen';
  16846. if (typeof document[name] === 'function') {
  16847. _names.exitFullscreen = name;
  16848. } else {
  16849. name = prefix + 'CancelFullScreen';
  16850. if (typeof document[name] === 'function') {
  16851. _names.exitFullscreen = name;
  16852. }
  16853. }
  16854. // casing of Fullscreen differs across browsers
  16855. name = prefix + 'FullscreenEnabled';
  16856. if (document[name] !== undefined) {
  16857. _names.fullscreenEnabled = name;
  16858. } else {
  16859. name = prefix + 'FullScreenEnabled';
  16860. if (document[name] !== undefined) {
  16861. _names.fullscreenEnabled = name;
  16862. }
  16863. }
  16864. // casing of Fullscreen differs across browsers
  16865. name = prefix + 'FullscreenElement';
  16866. if (document[name] !== undefined) {
  16867. _names.fullscreenElement = name;
  16868. } else {
  16869. name = prefix + 'FullScreenElement';
  16870. if (document[name] !== undefined) {
  16871. _names.fullscreenElement = name;
  16872. }
  16873. }
  16874. // thankfully, event names are all lowercase per spec
  16875. name = prefix + 'fullscreenchange';
  16876. // event names do not have 'on' in the front, but the property on the document does
  16877. if (document['on' + name] !== undefined) {
  16878. //except on IE
  16879. if (prefix === 'ms') {
  16880. name = 'MSFullscreenChange';
  16881. }
  16882. _names.fullscreenchange = name;
  16883. }
  16884. name = prefix + 'fullscreenerror';
  16885. if (document['on' + name] !== undefined) {
  16886. //except on IE
  16887. if (prefix === 'ms') {
  16888. name = 'MSFullscreenError';
  16889. }
  16890. _names.fullscreenerror = name;
  16891. }
  16892. }
  16893. return _supportsFullscreen;
  16894. };
  16895. /**
  16896. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  16897. * If fullscreen mode is not supported by the browser, does nothing.
  16898. *
  16899. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  16900. * @param {HMDVRDevice} [vrDevice] The VR device.
  16901. *
  16902. * @example
  16903. * // Put the entire page into fullscreen.
  16904. * Cesium.Fullscreen.requestFullscreen(document.body)
  16905. *
  16906. * // Place only the Cesium canvas into fullscreen.
  16907. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  16908. */
  16909. Fullscreen.requestFullscreen = function(element, vrDevice) {
  16910. if (!Fullscreen.supportsFullscreen()) {
  16911. return;
  16912. }
  16913. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  16914. };
  16915. /**
  16916. * Asynchronously exits fullscreen mode. If the browser is not currently
  16917. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  16918. */
  16919. Fullscreen.exitFullscreen = function() {
  16920. if (!Fullscreen.supportsFullscreen()) {
  16921. return;
  16922. }
  16923. document[_names.exitFullscreen]();
  16924. };
  16925. return Fullscreen;
  16926. });
  16927. /*global define*/
  16928. define('Core/FeatureDetection',[
  16929. './defaultValue',
  16930. './defined',
  16931. './Fullscreen'
  16932. ], function(
  16933. defaultValue,
  16934. defined,
  16935. Fullscreen) {
  16936. 'use strict';
  16937. var theNavigator;
  16938. if (typeof navigator !== 'undefined') {
  16939. theNavigator = navigator;
  16940. } else {
  16941. theNavigator = {};
  16942. }
  16943. function extractVersion(versionString) {
  16944. var parts = versionString.split('.');
  16945. for (var i = 0, len = parts.length; i < len; ++i) {
  16946. parts[i] = parseInt(parts[i], 10);
  16947. }
  16948. return parts;
  16949. }
  16950. var isChromeResult;
  16951. var chromeVersionResult;
  16952. function isChrome() {
  16953. if (!defined(isChromeResult)) {
  16954. isChromeResult = false;
  16955. // Edge contains Chrome in the user agent too
  16956. if (!isEdge()) {
  16957. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  16958. if (fields !== null) {
  16959. isChromeResult = true;
  16960. chromeVersionResult = extractVersion(fields[1]);
  16961. }
  16962. }
  16963. }
  16964. return isChromeResult;
  16965. }
  16966. function chromeVersion() {
  16967. return isChrome() && chromeVersionResult;
  16968. }
  16969. var isSafariResult;
  16970. var safariVersionResult;
  16971. function isSafari() {
  16972. if (!defined(isSafariResult)) {
  16973. isSafariResult = false;
  16974. // Chrome and Edge contain Safari in the user agent too
  16975. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  16976. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  16977. if (fields !== null) {
  16978. isSafariResult = true;
  16979. safariVersionResult = extractVersion(fields[1]);
  16980. }
  16981. }
  16982. }
  16983. return isSafariResult;
  16984. }
  16985. function safariVersion() {
  16986. return isSafari() && safariVersionResult;
  16987. }
  16988. var isWebkitResult;
  16989. var webkitVersionResult;
  16990. function isWebkit() {
  16991. if (!defined(isWebkitResult)) {
  16992. isWebkitResult = false;
  16993. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  16994. if (fields !== null) {
  16995. isWebkitResult = true;
  16996. webkitVersionResult = extractVersion(fields[1]);
  16997. webkitVersionResult.isNightly = !!fields[2];
  16998. }
  16999. }
  17000. return isWebkitResult;
  17001. }
  17002. function webkitVersion() {
  17003. return isWebkit() && webkitVersionResult;
  17004. }
  17005. var isInternetExplorerResult;
  17006. var internetExplorerVersionResult;
  17007. function isInternetExplorer() {
  17008. if (!defined(isInternetExplorerResult)) {
  17009. isInternetExplorerResult = false;
  17010. var fields;
  17011. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  17012. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  17013. if (fields !== null) {
  17014. isInternetExplorerResult = true;
  17015. internetExplorerVersionResult = extractVersion(fields[1]);
  17016. }
  17017. } else if (theNavigator.appName === 'Netscape') {
  17018. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  17019. if (fields !== null) {
  17020. isInternetExplorerResult = true;
  17021. internetExplorerVersionResult = extractVersion(fields[1]);
  17022. }
  17023. }
  17024. }
  17025. return isInternetExplorerResult;
  17026. }
  17027. function internetExplorerVersion() {
  17028. return isInternetExplorer() && internetExplorerVersionResult;
  17029. }
  17030. var isEdgeResult;
  17031. var edgeVersionResult;
  17032. function isEdge() {
  17033. if (!defined(isEdgeResult)) {
  17034. isEdgeResult = false;
  17035. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  17036. if (fields !== null) {
  17037. isEdgeResult = true;
  17038. edgeVersionResult = extractVersion(fields[1]);
  17039. }
  17040. }
  17041. return isEdgeResult;
  17042. }
  17043. function edgeVersion() {
  17044. return isEdge() && edgeVersionResult;
  17045. }
  17046. var isFirefoxResult;
  17047. var firefoxVersionResult;
  17048. function isFirefox() {
  17049. if (!defined(isFirefoxResult)) {
  17050. isFirefoxResult = false;
  17051. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  17052. if (fields !== null) {
  17053. isFirefoxResult = true;
  17054. firefoxVersionResult = extractVersion(fields[1]);
  17055. }
  17056. }
  17057. return isFirefoxResult;
  17058. }
  17059. var isWindowsResult;
  17060. function isWindows() {
  17061. if (!defined(isWindowsResult)) {
  17062. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  17063. }
  17064. return isWindowsResult;
  17065. }
  17066. function firefoxVersion() {
  17067. return isFirefox() && firefoxVersionResult;
  17068. }
  17069. var hasPointerEvents;
  17070. function supportsPointerEvents() {
  17071. if (!defined(hasPointerEvents)) {
  17072. //While navigator.pointerEnabled is deprecated in the W3C specification
  17073. //we still need to use it if it exists in order to support browsers
  17074. //that rely on it, such as the Windows WebBrowser control which defines
  17075. //PointerEvent but sets navigator.pointerEnabled to false.
  17076. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  17077. }
  17078. return hasPointerEvents;
  17079. }
  17080. var imageRenderingValueResult;
  17081. var supportsImageRenderingPixelatedResult;
  17082. function supportsImageRenderingPixelated() {
  17083. if (!defined(supportsImageRenderingPixelatedResult)) {
  17084. var canvas = document.createElement('canvas');
  17085. canvas.setAttribute('style',
  17086. 'image-rendering: -moz-crisp-edges;' +
  17087. 'image-rendering: pixelated;');
  17088. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  17089. var tmp = canvas.style.imageRendering;
  17090. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  17091. if (supportsImageRenderingPixelatedResult) {
  17092. imageRenderingValueResult = tmp;
  17093. }
  17094. }
  17095. return supportsImageRenderingPixelatedResult;
  17096. }
  17097. function imageRenderingValue() {
  17098. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  17099. }
  17100. /**
  17101. * A set of functions to detect whether the current browser supports
  17102. * various features.
  17103. *
  17104. * @exports FeatureDetection
  17105. */
  17106. var FeatureDetection = {
  17107. isChrome : isChrome,
  17108. chromeVersion : chromeVersion,
  17109. isSafari : isSafari,
  17110. safariVersion : safariVersion,
  17111. isWebkit : isWebkit,
  17112. webkitVersion : webkitVersion,
  17113. isInternetExplorer : isInternetExplorer,
  17114. internetExplorerVersion : internetExplorerVersion,
  17115. isEdge : isEdge,
  17116. edgeVersion : edgeVersion,
  17117. isFirefox : isFirefox,
  17118. firefoxVersion : firefoxVersion,
  17119. isWindows : isWindows,
  17120. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  17121. supportsPointerEvents : supportsPointerEvents,
  17122. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  17123. imageRenderingValue: imageRenderingValue
  17124. };
  17125. /**
  17126. * Detects whether the current browser supports the full screen standard.
  17127. *
  17128. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  17129. *
  17130. * @see Fullscreen
  17131. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  17132. */
  17133. FeatureDetection.supportsFullscreen = function() {
  17134. return Fullscreen.supportsFullscreen();
  17135. };
  17136. /**
  17137. * Detects whether the current browser supports typed arrays.
  17138. *
  17139. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  17140. *
  17141. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  17142. */
  17143. FeatureDetection.supportsTypedArrays = function() {
  17144. return typeof ArrayBuffer !== 'undefined';
  17145. };
  17146. /**
  17147. * Detects whether the current browser supports Web Workers.
  17148. *
  17149. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  17150. *
  17151. * @see {@link http://www.w3.org/TR/workers/}
  17152. */
  17153. FeatureDetection.supportsWebWorkers = function() {
  17154. return typeof Worker !== 'undefined';
  17155. };
  17156. return FeatureDetection;
  17157. });
  17158. /*global define*/
  17159. define('Core/Quaternion',[
  17160. './Cartesian3',
  17161. './defaultValue',
  17162. './defined',
  17163. './DeveloperError',
  17164. './FeatureDetection',
  17165. './freezeObject',
  17166. './Math',
  17167. './Matrix3'
  17168. ], function(
  17169. Cartesian3,
  17170. defaultValue,
  17171. defined,
  17172. DeveloperError,
  17173. FeatureDetection,
  17174. freezeObject,
  17175. CesiumMath,
  17176. Matrix3) {
  17177. 'use strict';
  17178. /**
  17179. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  17180. * @alias Quaternion
  17181. * @constructor
  17182. *
  17183. * @param {Number} [x=0.0] The X component.
  17184. * @param {Number} [y=0.0] The Y component.
  17185. * @param {Number} [z=0.0] The Z component.
  17186. * @param {Number} [w=0.0] The W component.
  17187. *
  17188. * @see PackableForInterpolation
  17189. */
  17190. function Quaternion(x, y, z, w) {
  17191. /**
  17192. * The X component.
  17193. * @type {Number}
  17194. * @default 0.0
  17195. */
  17196. this.x = defaultValue(x, 0.0);
  17197. /**
  17198. * The Y component.
  17199. * @type {Number}
  17200. * @default 0.0
  17201. */
  17202. this.y = defaultValue(y, 0.0);
  17203. /**
  17204. * The Z component.
  17205. * @type {Number}
  17206. * @default 0.0
  17207. */
  17208. this.z = defaultValue(z, 0.0);
  17209. /**
  17210. * The W component.
  17211. * @type {Number}
  17212. * @default 0.0
  17213. */
  17214. this.w = defaultValue(w, 0.0);
  17215. }
  17216. var fromAxisAngleScratch = new Cartesian3();
  17217. /**
  17218. * Computes a quaternion representing a rotation around an axis.
  17219. *
  17220. * @param {Cartesian3} axis The axis of rotation.
  17221. * @param {Number} angle The angle in radians to rotate around the axis.
  17222. * @param {Quaternion} [result] The object onto which to store the result.
  17223. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17224. */
  17225. Quaternion.fromAxisAngle = function(axis, angle, result) {
  17226. if (!defined(axis)) {
  17227. throw new DeveloperError('axis is required.');
  17228. }
  17229. if (typeof angle !== 'number') {
  17230. throw new DeveloperError('angle is required and must be a number.');
  17231. }
  17232. var halfAngle = angle / 2.0;
  17233. var s = Math.sin(halfAngle);
  17234. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  17235. var x = fromAxisAngleScratch.x * s;
  17236. var y = fromAxisAngleScratch.y * s;
  17237. var z = fromAxisAngleScratch.z * s;
  17238. var w = Math.cos(halfAngle);
  17239. if (!defined(result)) {
  17240. return new Quaternion(x, y, z, w);
  17241. }
  17242. result.x = x;
  17243. result.y = y;
  17244. result.z = z;
  17245. result.w = w;
  17246. return result;
  17247. };
  17248. var fromRotationMatrixNext = [1, 2, 0];
  17249. var fromRotationMatrixQuat = new Array(3);
  17250. /**
  17251. * Computes a Quaternion from the provided Matrix3 instance.
  17252. *
  17253. * @param {Matrix3} matrix The rotation matrix.
  17254. * @param {Quaternion} [result] The object onto which to store the result.
  17255. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17256. *
  17257. * @see Matrix3.fromQuaternion
  17258. */
  17259. Quaternion.fromRotationMatrix = function(matrix, result) {
  17260. if (!defined(matrix)) {
  17261. throw new DeveloperError('matrix is required.');
  17262. }
  17263. var root;
  17264. var x;
  17265. var y;
  17266. var z;
  17267. var w;
  17268. var m00 = matrix[Matrix3.COLUMN0ROW0];
  17269. var m11 = matrix[Matrix3.COLUMN1ROW1];
  17270. var m22 = matrix[Matrix3.COLUMN2ROW2];
  17271. var trace = m00 + m11 + m22;
  17272. if (trace > 0.0) {
  17273. // |w| > 1/2, may as well choose w > 1/2
  17274. root = Math.sqrt(trace + 1.0); // 2w
  17275. w = 0.5 * root;
  17276. root = 0.5 / root; // 1/(4w)
  17277. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  17278. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  17279. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  17280. } else {
  17281. // |w| <= 1/2
  17282. var next = fromRotationMatrixNext;
  17283. var i = 0;
  17284. if (m11 > m00) {
  17285. i = 1;
  17286. }
  17287. if (m22 > m00 && m22 > m11) {
  17288. i = 2;
  17289. }
  17290. var j = next[i];
  17291. var k = next[j];
  17292. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  17293. var quat = fromRotationMatrixQuat;
  17294. quat[i] = 0.5 * root;
  17295. root = 0.5 / root;
  17296. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  17297. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  17298. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  17299. x = -quat[0];
  17300. y = -quat[1];
  17301. z = -quat[2];
  17302. }
  17303. if (!defined(result)) {
  17304. return new Quaternion(x, y, z, w);
  17305. }
  17306. result.x = x;
  17307. result.y = y;
  17308. result.z = z;
  17309. result.w = w;
  17310. return result;
  17311. };
  17312. var scratchHPRQuaternion = new Quaternion();
  17313. /**
  17314. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  17315. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  17316. * the positive x axis.
  17317. *
  17318. * @param {Number} heading The heading angle in radians.
  17319. * @param {Number} pitch The pitch angle in radians.
  17320. * @param {Number} roll The roll angle in radians.
  17321. * @param {Quaternion} [result] The object onto which to store the result.
  17322. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  17323. */
  17324. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  17325. if (!defined(heading)) {
  17326. throw new DeveloperError('heading is required.');
  17327. }
  17328. if (!defined(pitch)) {
  17329. throw new DeveloperError('pitch is required.');
  17330. }
  17331. if (!defined(roll)) {
  17332. throw new DeveloperError('roll is required.');
  17333. }
  17334. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  17335. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  17336. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  17337. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  17338. return Quaternion.multiply(headingQuaternion, result, result);
  17339. };
  17340. var sampledQuaternionAxis = new Cartesian3();
  17341. var sampledQuaternionRotation = new Cartesian3();
  17342. var sampledQuaternionTempQuaternion = new Quaternion();
  17343. var sampledQuaternionQuaternion0 = new Quaternion();
  17344. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  17345. /**
  17346. * The number of elements used to pack the object into an array.
  17347. * @type {Number}
  17348. */
  17349. Quaternion.packedLength = 4;
  17350. /**
  17351. * Stores the provided instance into the provided array.
  17352. *
  17353. * @param {Quaternion} value The value to pack.
  17354. * @param {Number[]} array The array to pack into.
  17355. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  17356. *
  17357. * @returns {Number[]} The array that was packed into
  17358. */
  17359. Quaternion.pack = function(value, array, startingIndex) {
  17360. if (!defined(value)) {
  17361. throw new DeveloperError('value is required');
  17362. }
  17363. if (!defined(array)) {
  17364. throw new DeveloperError('array is required');
  17365. }
  17366. startingIndex = defaultValue(startingIndex, 0);
  17367. array[startingIndex++] = value.x;
  17368. array[startingIndex++] = value.y;
  17369. array[startingIndex++] = value.z;
  17370. array[startingIndex] = value.w;
  17371. return array;
  17372. };
  17373. /**
  17374. * Retrieves an instance from a packed array.
  17375. *
  17376. * @param {Number[]} array The packed array.
  17377. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  17378. * @param {Quaternion} [result] The object into which to store the result.
  17379. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17380. */
  17381. Quaternion.unpack = function(array, startingIndex, result) {
  17382. if (!defined(array)) {
  17383. throw new DeveloperError('array is required');
  17384. }
  17385. startingIndex = defaultValue(startingIndex, 0);
  17386. if (!defined(result)) {
  17387. result = new Quaternion();
  17388. }
  17389. result.x = array[startingIndex];
  17390. result.y = array[startingIndex + 1];
  17391. result.z = array[startingIndex + 2];
  17392. result.w = array[startingIndex + 3];
  17393. return result;
  17394. };
  17395. /**
  17396. * The number of elements used to store the object into an array in its interpolatable form.
  17397. * @type {Number}
  17398. */
  17399. Quaternion.packedInterpolationLength = 3;
  17400. /**
  17401. * Converts a packed array into a form suitable for interpolation.
  17402. *
  17403. * @param {Number[]} packedArray The packed array.
  17404. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  17405. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  17406. * @param {Number[]} result The object into which to store the result.
  17407. */
  17408. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  17409. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  17410. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  17411. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  17412. var offset = i * 3;
  17413. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  17414. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  17415. if (sampledQuaternionTempQuaternion.w < 0) {
  17416. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  17417. }
  17418. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  17419. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  17420. result[offset] = sampledQuaternionAxis.x * angle;
  17421. result[offset + 1] = sampledQuaternionAxis.y * angle;
  17422. result[offset + 2] = sampledQuaternionAxis.z * angle;
  17423. }
  17424. };
  17425. /**
  17426. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  17427. *
  17428. * @param {Number[]} array The array previously packed for interpolation.
  17429. * @param {Number[]} sourceArray The original packed array.
  17430. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  17431. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  17432. * @param {Quaternion} [result] The object into which to store the result.
  17433. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17434. */
  17435. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  17436. if (!defined(result)) {
  17437. result = new Quaternion();
  17438. }
  17439. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  17440. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  17441. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  17442. if (magnitude === 0) {
  17443. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  17444. } else {
  17445. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  17446. }
  17447. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  17448. };
  17449. /**
  17450. * Duplicates a Quaternion instance.
  17451. *
  17452. * @param {Quaternion} quaternion The quaternion to duplicate.
  17453. * @param {Quaternion} [result] The object onto which to store the result.
  17454. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  17455. */
  17456. Quaternion.clone = function(quaternion, result) {
  17457. if (!defined(quaternion)) {
  17458. return undefined;
  17459. }
  17460. if (!defined(result)) {
  17461. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  17462. }
  17463. result.x = quaternion.x;
  17464. result.y = quaternion.y;
  17465. result.z = quaternion.z;
  17466. result.w = quaternion.w;
  17467. return result;
  17468. };
  17469. /**
  17470. * Computes the conjugate of the provided quaternion.
  17471. *
  17472. * @param {Quaternion} quaternion The quaternion to conjugate.
  17473. * @param {Quaternion} result The object onto which to store the result.
  17474. * @returns {Quaternion} The modified result parameter.
  17475. */
  17476. Quaternion.conjugate = function(quaternion, result) {
  17477. if (!defined(quaternion)) {
  17478. throw new DeveloperError('quaternion is required');
  17479. }
  17480. if (!defined(result)) {
  17481. throw new DeveloperError('result is required');
  17482. }
  17483. result.x = -quaternion.x;
  17484. result.y = -quaternion.y;
  17485. result.z = -quaternion.z;
  17486. result.w = quaternion.w;
  17487. return result;
  17488. };
  17489. /**
  17490. * Computes magnitude squared for the provided quaternion.
  17491. *
  17492. * @param {Quaternion} quaternion The quaternion to conjugate.
  17493. * @returns {Number} The magnitude squared.
  17494. */
  17495. Quaternion.magnitudeSquared = function(quaternion) {
  17496. if (!defined(quaternion)) {
  17497. throw new DeveloperError('quaternion is required');
  17498. }
  17499. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  17500. };
  17501. /**
  17502. * Computes magnitude for the provided quaternion.
  17503. *
  17504. * @param {Quaternion} quaternion The quaternion to conjugate.
  17505. * @returns {Number} The magnitude.
  17506. */
  17507. Quaternion.magnitude = function(quaternion) {
  17508. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  17509. };
  17510. /**
  17511. * Computes the normalized form of the provided quaternion.
  17512. *
  17513. * @param {Quaternion} quaternion The quaternion to normalize.
  17514. * @param {Quaternion} result The object onto which to store the result.
  17515. * @returns {Quaternion} The modified result parameter.
  17516. */
  17517. Quaternion.normalize = function(quaternion, result) {
  17518. if (!defined(result)) {
  17519. throw new DeveloperError('result is required');
  17520. }
  17521. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  17522. var x = quaternion.x * inverseMagnitude;
  17523. var y = quaternion.y * inverseMagnitude;
  17524. var z = quaternion.z * inverseMagnitude;
  17525. var w = quaternion.w * inverseMagnitude;
  17526. result.x = x;
  17527. result.y = y;
  17528. result.z = z;
  17529. result.w = w;
  17530. return result;
  17531. };
  17532. /**
  17533. * Computes the inverse of the provided quaternion.
  17534. *
  17535. * @param {Quaternion} quaternion The quaternion to normalize.
  17536. * @param {Quaternion} result The object onto which to store the result.
  17537. * @returns {Quaternion} The modified result parameter.
  17538. */
  17539. Quaternion.inverse = function(quaternion, result) {
  17540. if (!defined(result)) {
  17541. throw new DeveloperError('result is required');
  17542. }
  17543. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  17544. result = Quaternion.conjugate(quaternion, result);
  17545. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  17546. };
  17547. /**
  17548. * Computes the componentwise sum of two quaternions.
  17549. *
  17550. * @param {Quaternion} left The first quaternion.
  17551. * @param {Quaternion} right The second quaternion.
  17552. * @param {Quaternion} result The object onto which to store the result.
  17553. * @returns {Quaternion} The modified result parameter.
  17554. */
  17555. Quaternion.add = function(left, right, result) {
  17556. if (!defined(left)) {
  17557. throw new DeveloperError('left is required');
  17558. }
  17559. if (!defined(right)) {
  17560. throw new DeveloperError('right is required');
  17561. }
  17562. if (!defined(result)) {
  17563. throw new DeveloperError('result is required');
  17564. }
  17565. result.x = left.x + right.x;
  17566. result.y = left.y + right.y;
  17567. result.z = left.z + right.z;
  17568. result.w = left.w + right.w;
  17569. return result;
  17570. };
  17571. /**
  17572. * Computes the componentwise difference of two quaternions.
  17573. *
  17574. * @param {Quaternion} left The first quaternion.
  17575. * @param {Quaternion} right The second quaternion.
  17576. * @param {Quaternion} result The object onto which to store the result.
  17577. * @returns {Quaternion} The modified result parameter.
  17578. */
  17579. Quaternion.subtract = function(left, right, result) {
  17580. if (!defined(left)) {
  17581. throw new DeveloperError('left is required');
  17582. }
  17583. if (!defined(right)) {
  17584. throw new DeveloperError('right is required');
  17585. }
  17586. if (!defined(result)) {
  17587. throw new DeveloperError('result is required');
  17588. }
  17589. result.x = left.x - right.x;
  17590. result.y = left.y - right.y;
  17591. result.z = left.z - right.z;
  17592. result.w = left.w - right.w;
  17593. return result;
  17594. };
  17595. /**
  17596. * Negates the provided quaternion.
  17597. *
  17598. * @param {Quaternion} quaternion The quaternion to be negated.
  17599. * @param {Quaternion} result The object onto which to store the result.
  17600. * @returns {Quaternion} The modified result parameter.
  17601. */
  17602. Quaternion.negate = function(quaternion, result) {
  17603. if (!defined(quaternion)) {
  17604. throw new DeveloperError('quaternion is required');
  17605. }
  17606. if (!defined(result)) {
  17607. throw new DeveloperError('result is required');
  17608. }
  17609. result.x = -quaternion.x;
  17610. result.y = -quaternion.y;
  17611. result.z = -quaternion.z;
  17612. result.w = -quaternion.w;
  17613. return result;
  17614. };
  17615. /**
  17616. * Computes the dot (scalar) product of two quaternions.
  17617. *
  17618. * @param {Quaternion} left The first quaternion.
  17619. * @param {Quaternion} right The second quaternion.
  17620. * @returns {Number} The dot product.
  17621. */
  17622. Quaternion.dot = function(left, right) {
  17623. if (!defined(left)) {
  17624. throw new DeveloperError('left is required');
  17625. }
  17626. if (!defined(right)) {
  17627. throw new DeveloperError('right is required');
  17628. }
  17629. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  17630. };
  17631. /**
  17632. * Computes the product of two quaternions.
  17633. *
  17634. * @param {Quaternion} left The first quaternion.
  17635. * @param {Quaternion} right The second quaternion.
  17636. * @param {Quaternion} result The object onto which to store the result.
  17637. * @returns {Quaternion} The modified result parameter.
  17638. */
  17639. Quaternion.multiply = function(left, right, result) {
  17640. if (!defined(left)) {
  17641. throw new DeveloperError('left is required');
  17642. }
  17643. if (!defined(right)) {
  17644. throw new DeveloperError('right is required');
  17645. }
  17646. if (!defined(result)) {
  17647. throw new DeveloperError('result is required');
  17648. }
  17649. var leftX = left.x;
  17650. var leftY = left.y;
  17651. var leftZ = left.z;
  17652. var leftW = left.w;
  17653. var rightX = right.x;
  17654. var rightY = right.y;
  17655. var rightZ = right.z;
  17656. var rightW = right.w;
  17657. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  17658. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  17659. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  17660. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  17661. result.x = x;
  17662. result.y = y;
  17663. result.z = z;
  17664. result.w = w;
  17665. return result;
  17666. };
  17667. /**
  17668. * Multiplies the provided quaternion componentwise by the provided scalar.
  17669. *
  17670. * @param {Quaternion} quaternion The quaternion to be scaled.
  17671. * @param {Number} scalar The scalar to multiply with.
  17672. * @param {Quaternion} result The object onto which to store the result.
  17673. * @returns {Quaternion} The modified result parameter.
  17674. */
  17675. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  17676. if (!defined(quaternion)) {
  17677. throw new DeveloperError('quaternion is required');
  17678. }
  17679. if (typeof scalar !== 'number') {
  17680. throw new DeveloperError('scalar is required and must be a number.');
  17681. }
  17682. if (!defined(result)) {
  17683. throw new DeveloperError('result is required');
  17684. }
  17685. result.x = quaternion.x * scalar;
  17686. result.y = quaternion.y * scalar;
  17687. result.z = quaternion.z * scalar;
  17688. result.w = quaternion.w * scalar;
  17689. return result;
  17690. };
  17691. /**
  17692. * Divides the provided quaternion componentwise by the provided scalar.
  17693. *
  17694. * @param {Quaternion} quaternion The quaternion to be divided.
  17695. * @param {Number} scalar The scalar to divide by.
  17696. * @param {Quaternion} result The object onto which to store the result.
  17697. * @returns {Quaternion} The modified result parameter.
  17698. */
  17699. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  17700. if (!defined(quaternion)) {
  17701. throw new DeveloperError('quaternion is required');
  17702. }
  17703. if (typeof scalar !== 'number') {
  17704. throw new DeveloperError('scalar is required and must be a number.');
  17705. }
  17706. if (!defined(result)) {
  17707. throw new DeveloperError('result is required');
  17708. }
  17709. result.x = quaternion.x / scalar;
  17710. result.y = quaternion.y / scalar;
  17711. result.z = quaternion.z / scalar;
  17712. result.w = quaternion.w / scalar;
  17713. return result;
  17714. };
  17715. /**
  17716. * Computes the axis of rotation of the provided quaternion.
  17717. *
  17718. * @param {Quaternion} quaternion The quaternion to use.
  17719. * @param {Cartesian3} result The object onto which to store the result.
  17720. * @returns {Cartesian3} The modified result parameter.
  17721. */
  17722. Quaternion.computeAxis = function(quaternion, result) {
  17723. if (!defined(quaternion)) {
  17724. throw new DeveloperError('quaternion is required');
  17725. }
  17726. if (!defined(result)) {
  17727. throw new DeveloperError('result is required');
  17728. }
  17729. var w = quaternion.w;
  17730. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  17731. result.x = result.y = result.z = 0;
  17732. return result;
  17733. }
  17734. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  17735. result.x = quaternion.x * scalar;
  17736. result.y = quaternion.y * scalar;
  17737. result.z = quaternion.z * scalar;
  17738. return result;
  17739. };
  17740. /**
  17741. * Computes the angle of rotation of the provided quaternion.
  17742. *
  17743. * @param {Quaternion} quaternion The quaternion to use.
  17744. * @returns {Number} The angle of rotation.
  17745. */
  17746. Quaternion.computeAngle = function(quaternion) {
  17747. if (!defined(quaternion)) {
  17748. throw new DeveloperError('quaternion is required');
  17749. }
  17750. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  17751. return 0.0;
  17752. }
  17753. return 2.0 * Math.acos(quaternion.w);
  17754. };
  17755. var lerpScratch = new Quaternion();
  17756. /**
  17757. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  17758. *
  17759. * @param {Quaternion} start The value corresponding to t at 0.0.
  17760. * @param {Quaternion} end The value corresponding to t at 1.0.
  17761. * @param {Number} t The point along t at which to interpolate.
  17762. * @param {Quaternion} result The object onto which to store the result.
  17763. * @returns {Quaternion} The modified result parameter.
  17764. */
  17765. Quaternion.lerp = function(start, end, t, result) {
  17766. if (!defined(start)) {
  17767. throw new DeveloperError('start is required.');
  17768. }
  17769. if (!defined(end)) {
  17770. throw new DeveloperError('end is required.');
  17771. }
  17772. if (typeof t !== 'number') {
  17773. throw new DeveloperError('t is required and must be a number.');
  17774. }
  17775. if (!defined(result)) {
  17776. throw new DeveloperError('result is required');
  17777. }
  17778. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  17779. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  17780. return Quaternion.add(lerpScratch, result, result);
  17781. };
  17782. var slerpEndNegated = new Quaternion();
  17783. var slerpScaledP = new Quaternion();
  17784. var slerpScaledR = new Quaternion();
  17785. /**
  17786. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  17787. *
  17788. * @param {Quaternion} start The value corresponding to t at 0.0.
  17789. * @param {Quaternion} end The value corresponding to t at 1.0.
  17790. * @param {Number} t The point along t at which to interpolate.
  17791. * @param {Quaternion} result The object onto which to store the result.
  17792. * @returns {Quaternion} The modified result parameter.
  17793. *
  17794. * @see Quaternion#fastSlerp
  17795. */
  17796. Quaternion.slerp = function(start, end, t, result) {
  17797. if (!defined(start)) {
  17798. throw new DeveloperError('start is required.');
  17799. }
  17800. if (!defined(end)) {
  17801. throw new DeveloperError('end is required.');
  17802. }
  17803. if (typeof t !== 'number') {
  17804. throw new DeveloperError('t is required and must be a number.');
  17805. }
  17806. if (!defined(result)) {
  17807. throw new DeveloperError('result is required');
  17808. }
  17809. var dot = Quaternion.dot(start, end);
  17810. // The angle between start must be acute. Since q and -q represent
  17811. // the same rotation, negate q to get the acute angle.
  17812. var r = end;
  17813. if (dot < 0.0) {
  17814. dot = -dot;
  17815. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  17816. }
  17817. // dot > 0, as the dot product approaches 1, the angle between the
  17818. // quaternions vanishes. use linear interpolation.
  17819. if (1.0 - dot < CesiumMath.EPSILON6) {
  17820. return Quaternion.lerp(start, r, t, result);
  17821. }
  17822. var theta = Math.acos(dot);
  17823. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  17824. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  17825. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  17826. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  17827. };
  17828. /**
  17829. * The logarithmic quaternion function.
  17830. *
  17831. * @param {Quaternion} quaternion The unit quaternion.
  17832. * @param {Cartesian3} result The object onto which to store the result.
  17833. * @returns {Cartesian3} The modified result parameter.
  17834. */
  17835. Quaternion.log = function(quaternion, result) {
  17836. if (!defined(quaternion)) {
  17837. throw new DeveloperError('quaternion is required.');
  17838. }
  17839. if (!defined(result)) {
  17840. throw new DeveloperError('result is required');
  17841. }
  17842. var theta = CesiumMath.acosClamped(quaternion.w);
  17843. var thetaOverSinTheta = 0.0;
  17844. if (theta !== 0.0) {
  17845. thetaOverSinTheta = theta / Math.sin(theta);
  17846. }
  17847. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  17848. };
  17849. /**
  17850. * The exponential quaternion function.
  17851. *
  17852. * @param {Cartesian3} cartesian The cartesian.
  17853. * @param {Quaternion} result The object onto which to store the result.
  17854. * @returns {Quaternion} The modified result parameter.
  17855. */
  17856. Quaternion.exp = function(cartesian, result) {
  17857. if (!defined(cartesian)) {
  17858. throw new DeveloperError('cartesian is required.');
  17859. }
  17860. if (!defined(result)) {
  17861. throw new DeveloperError('result is required');
  17862. }
  17863. var theta = Cartesian3.magnitude(cartesian);
  17864. var sinThetaOverTheta = 0.0;
  17865. if (theta !== 0.0) {
  17866. sinThetaOverTheta = Math.sin(theta) / theta;
  17867. }
  17868. result.x = cartesian.x * sinThetaOverTheta;
  17869. result.y = cartesian.y * sinThetaOverTheta;
  17870. result.z = cartesian.z * sinThetaOverTheta;
  17871. result.w = Math.cos(theta);
  17872. return result;
  17873. };
  17874. var squadScratchCartesian0 = new Cartesian3();
  17875. var squadScratchCartesian1 = new Cartesian3();
  17876. var squadScratchQuaternion0 = new Quaternion();
  17877. var squadScratchQuaternion1 = new Quaternion();
  17878. /**
  17879. * Computes an inner quadrangle point.
  17880. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  17881. *
  17882. * @param {Quaternion} q0 The first quaternion.
  17883. * @param {Quaternion} q1 The second quaternion.
  17884. * @param {Quaternion} q2 The third quaternion.
  17885. * @param {Quaternion} result The object onto which to store the result.
  17886. * @returns {Quaternion} The modified result parameter.
  17887. *
  17888. * @see Quaternion#squad
  17889. */
  17890. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  17891. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  17892. throw new DeveloperError('q0, q1, and q2 are required.');
  17893. }
  17894. if (!defined(result)) {
  17895. throw new DeveloperError('result is required');
  17896. }
  17897. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  17898. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  17899. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  17900. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  17901. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  17902. Cartesian3.add(cart0, cart1, cart0);
  17903. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  17904. Cartesian3.negate(cart0, cart0);
  17905. Quaternion.exp(cart0, squadScratchQuaternion0);
  17906. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  17907. };
  17908. /**
  17909. * Computes the spherical quadrangle interpolation between quaternions.
  17910. *
  17911. * @param {Quaternion} q0 The first quaternion.
  17912. * @param {Quaternion} q1 The second quaternion.
  17913. * @param {Quaternion} s0 The first inner quadrangle.
  17914. * @param {Quaternion} s1 The second inner quadrangle.
  17915. * @param {Number} t The time in [0,1] used to interpolate.
  17916. * @param {Quaternion} result The object onto which to store the result.
  17917. * @returns {Quaternion} The modified result parameter.
  17918. *
  17919. *
  17920. * @example
  17921. * // 1. compute the squad interpolation between two quaternions on a curve
  17922. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  17923. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  17924. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  17925. *
  17926. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  17927. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  17928. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  17929. *
  17930. * @see Quaternion#computeInnerQuadrangle
  17931. */
  17932. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  17933. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  17934. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  17935. }
  17936. if (typeof t !== 'number') {
  17937. throw new DeveloperError('t is required and must be a number.');
  17938. }
  17939. if (!defined(result)) {
  17940. throw new DeveloperError('result is required');
  17941. }
  17942. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  17943. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  17944. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  17945. };
  17946. var fastSlerpScratchQuaternion = new Quaternion();
  17947. var opmu = 1.90110745351730037;
  17948. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  17949. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  17950. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  17951. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  17952. for (var i = 0; i < 7; ++i) {
  17953. var s = i + 1.0;
  17954. var t = 2.0 * s + 1.0;
  17955. u[i] = 1.0 / (s * t);
  17956. v[i] = s / t;
  17957. }
  17958. u[7] = opmu / (8.0 * 17.0);
  17959. v[7] = opmu * 8.0 / 17.0;
  17960. /**
  17961. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  17962. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  17963. *
  17964. * @param {Quaternion} start The value corresponding to t at 0.0.
  17965. * @param {Quaternion} end The value corresponding to t at 1.0.
  17966. * @param {Number} t The point along t at which to interpolate.
  17967. * @param {Quaternion} result The object onto which to store the result.
  17968. * @returns {Quaternion} The modified result parameter.
  17969. *
  17970. * @see Quaternion#slerp
  17971. */
  17972. Quaternion.fastSlerp = function(start, end, t, result) {
  17973. if (!defined(start)) {
  17974. throw new DeveloperError('start is required.');
  17975. }
  17976. if (!defined(end)) {
  17977. throw new DeveloperError('end is required.');
  17978. }
  17979. if (typeof t !== 'number') {
  17980. throw new DeveloperError('t is required and must be a number.');
  17981. }
  17982. if (!defined(result)) {
  17983. throw new DeveloperError('result is required');
  17984. }
  17985. var x = Quaternion.dot(start, end);
  17986. var sign;
  17987. if (x >= 0) {
  17988. sign = 1.0;
  17989. } else {
  17990. sign = -1.0;
  17991. x = -x;
  17992. }
  17993. var xm1 = x - 1.0;
  17994. var d = 1.0 - t;
  17995. var sqrT = t * t;
  17996. var sqrD = d * d;
  17997. for (var i = 7; i >= 0; --i) {
  17998. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  17999. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  18000. }
  18001. var cT = sign * t * (
  18002. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  18003. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  18004. var cD = d * (
  18005. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  18006. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  18007. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  18008. Quaternion.multiplyByScalar(end, cT, result);
  18009. return Quaternion.add(temp, result, result);
  18010. };
  18011. /**
  18012. * Computes the spherical quadrangle interpolation between quaternions.
  18013. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  18014. *
  18015. * @param {Quaternion} q0 The first quaternion.
  18016. * @param {Quaternion} q1 The second quaternion.
  18017. * @param {Quaternion} s0 The first inner quadrangle.
  18018. * @param {Quaternion} s1 The second inner quadrangle.
  18019. * @param {Number} t The time in [0,1] used to interpolate.
  18020. * @param {Quaternion} result The object onto which to store the result.
  18021. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  18022. *
  18023. * @see Quaternion#squad
  18024. */
  18025. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  18026. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18027. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18028. }
  18029. if (typeof t !== 'number') {
  18030. throw new DeveloperError('t is required and must be a number.');
  18031. }
  18032. if (!defined(result)) {
  18033. throw new DeveloperError('result is required');
  18034. }
  18035. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  18036. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  18037. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18038. };
  18039. /**
  18040. * Compares the provided quaternions componentwise and returns
  18041. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18042. *
  18043. * @param {Quaternion} [left] The first quaternion.
  18044. * @param {Quaternion} [right] The second quaternion.
  18045. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18046. */
  18047. Quaternion.equals = function(left, right) {
  18048. return (left === right) ||
  18049. ((defined(left)) &&
  18050. (defined(right)) &&
  18051. (left.x === right.x) &&
  18052. (left.y === right.y) &&
  18053. (left.z === right.z) &&
  18054. (left.w === right.w));
  18055. };
  18056. /**
  18057. * Compares the provided quaternions componentwise and returns
  18058. * <code>true</code> if they are within the provided epsilon,
  18059. * <code>false</code> otherwise.
  18060. *
  18061. * @param {Quaternion} [left] The first quaternion.
  18062. * @param {Quaternion} [right] The second quaternion.
  18063. * @param {Number} epsilon The epsilon to use for equality testing.
  18064. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18065. */
  18066. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  18067. if (typeof epsilon !== 'number') {
  18068. throw new DeveloperError('epsilon is required and must be a number.');
  18069. }
  18070. return (left === right) ||
  18071. ((defined(left)) &&
  18072. (defined(right)) &&
  18073. (Math.abs(left.x - right.x) <= epsilon) &&
  18074. (Math.abs(left.y - right.y) <= epsilon) &&
  18075. (Math.abs(left.z - right.z) <= epsilon) &&
  18076. (Math.abs(left.w - right.w) <= epsilon));
  18077. };
  18078. /**
  18079. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  18080. *
  18081. * @type {Quaternion}
  18082. * @constant
  18083. */
  18084. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  18085. /**
  18086. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  18087. *
  18088. * @type {Quaternion}
  18089. * @constant
  18090. */
  18091. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  18092. /**
  18093. * Duplicates this Quaternion instance.
  18094. *
  18095. * @param {Quaternion} [result] The object onto which to store the result.
  18096. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18097. */
  18098. Quaternion.prototype.clone = function(result) {
  18099. return Quaternion.clone(this, result);
  18100. };
  18101. /**
  18102. * Compares this and the provided quaternion componentwise and returns
  18103. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18104. *
  18105. * @param {Quaternion} [right] The right hand side quaternion.
  18106. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18107. */
  18108. Quaternion.prototype.equals = function(right) {
  18109. return Quaternion.equals(this, right);
  18110. };
  18111. /**
  18112. * Compares this and the provided quaternion componentwise and returns
  18113. * <code>true</code> if they are within the provided epsilon,
  18114. * <code>false</code> otherwise.
  18115. *
  18116. * @param {Quaternion} [right] The right hand side quaternion.
  18117. * @param {Number} epsilon The epsilon to use for equality testing.
  18118. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18119. */
  18120. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  18121. return Quaternion.equalsEpsilon(this, right, epsilon);
  18122. };
  18123. /**
  18124. * Returns a string representing this quaternion in the format (x, y, z, w).
  18125. *
  18126. * @returns {String} A string representing this Quaternion.
  18127. */
  18128. Quaternion.prototype.toString = function() {
  18129. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  18130. };
  18131. return Quaternion;
  18132. });
  18133. /*global define*/
  18134. define('Core/Transforms',[
  18135. '../ThirdParty/when',
  18136. './Cartesian2',
  18137. './Cartesian3',
  18138. './Cartesian4',
  18139. './Cartographic',
  18140. './defaultValue',
  18141. './defined',
  18142. './deprecationWarning',
  18143. './DeveloperError',
  18144. './EarthOrientationParameters',
  18145. './EarthOrientationParametersSample',
  18146. './Ellipsoid',
  18147. './HeadingPitchRoll',
  18148. './Iau2006XysData',
  18149. './Iau2006XysSample',
  18150. './JulianDate',
  18151. './Math',
  18152. './Matrix3',
  18153. './Matrix4',
  18154. './Quaternion',
  18155. './TimeConstants'
  18156. ], function(
  18157. when,
  18158. Cartesian2,
  18159. Cartesian3,
  18160. Cartesian4,
  18161. Cartographic,
  18162. defaultValue,
  18163. defined,
  18164. deprecationWarning,
  18165. DeveloperError,
  18166. EarthOrientationParameters,
  18167. EarthOrientationParametersSample,
  18168. Ellipsoid,
  18169. HeadingPitchRoll,
  18170. Iau2006XysData,
  18171. Iau2006XysSample,
  18172. JulianDate,
  18173. CesiumMath,
  18174. Matrix3,
  18175. Matrix4,
  18176. Quaternion,
  18177. TimeConstants) {
  18178. 'use strict';
  18179. /**
  18180. * Contains functions for transforming positions to various reference frames.
  18181. *
  18182. * @exports Transforms
  18183. */
  18184. var Transforms = {};
  18185. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  18186. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  18187. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  18188. /**
  18189. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  18190. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18191. * The local axes are defined as:
  18192. * <ul>
  18193. * <li>The <code>x</code> axis points in the local east direction.</li>
  18194. * <li>The <code>y</code> axis points in the local north direction.</li>
  18195. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  18196. * </ul>
  18197. *
  18198. * @param {Cartesian3} origin The center point of the local reference frame.
  18199. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18200. * @param {Matrix4} [result] The object onto which to store the result.
  18201. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18202. *
  18203. * @example
  18204. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  18205. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18206. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  18207. */
  18208. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  18209. if (!defined(origin)) {
  18210. throw new DeveloperError('origin is required.');
  18211. }
  18212. // If x and y are zero, assume origin is at a pole, which is a special case.
  18213. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18214. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18215. var sign = CesiumMath.sign(origin.z);
  18216. if (!defined(result)) {
  18217. return new Matrix4(
  18218. 0.0, -sign, 0.0, origin.x,
  18219. 1.0, 0.0, 0.0, origin.y,
  18220. 0.0, 0.0, sign, origin.z,
  18221. 0.0, 0.0, 0.0, 1.0);
  18222. }
  18223. result[0] = 0.0;
  18224. result[1] = 1.0;
  18225. result[2] = 0.0;
  18226. result[3] = 0.0;
  18227. result[4] = -sign;
  18228. result[5] = 0.0;
  18229. result[6] = 0.0;
  18230. result[7] = 0.0;
  18231. result[8] = 0.0;
  18232. result[9] = 0.0;
  18233. result[10] = sign;
  18234. result[11] = 0.0;
  18235. result[12] = origin.x;
  18236. result[13] = origin.y;
  18237. result[14] = origin.z;
  18238. result[15] = 1.0;
  18239. return result;
  18240. }
  18241. var normal = eastNorthUpToFixedFrameNormal;
  18242. var tangent = eastNorthUpToFixedFrameTangent;
  18243. var bitangent = eastNorthUpToFixedFrameBitangent;
  18244. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18245. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18246. tangent.x = -origin.y;
  18247. tangent.y = origin.x;
  18248. tangent.z = 0.0;
  18249. Cartesian3.normalize(tangent, tangent);
  18250. Cartesian3.cross(normal, tangent, bitangent);
  18251. if (!defined(result)) {
  18252. return new Matrix4(
  18253. tangent.x, bitangent.x, normal.x, origin.x,
  18254. tangent.y, bitangent.y, normal.y, origin.y,
  18255. tangent.z, bitangent.z, normal.z, origin.z,
  18256. 0.0, 0.0, 0.0, 1.0);
  18257. }
  18258. result[0] = tangent.x;
  18259. result[1] = tangent.y;
  18260. result[2] = tangent.z;
  18261. result[3] = 0.0;
  18262. result[4] = bitangent.x;
  18263. result[5] = bitangent.y;
  18264. result[6] = bitangent.z;
  18265. result[7] = 0.0;
  18266. result[8] = normal.x;
  18267. result[9] = normal.y;
  18268. result[10] = normal.z;
  18269. result[11] = 0.0;
  18270. result[12] = origin.x;
  18271. result[13] = origin.y;
  18272. result[14] = origin.z;
  18273. result[15] = 1.0;
  18274. return result;
  18275. };
  18276. var northEastDownToFixedFrameNormal = new Cartesian3();
  18277. var northEastDownToFixedFrameTangent = new Cartesian3();
  18278. var northEastDownToFixedFrameBitangent = new Cartesian3();
  18279. /**
  18280. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  18281. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18282. * The local axes are defined as:
  18283. * <ul>
  18284. * <li>The <code>x</code> axis points in the local north direction.</li>
  18285. * <li>The <code>y</code> axis points in the local east direction.</li>
  18286. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  18287. * </ul>
  18288. *
  18289. * @param {Cartesian3} origin The center point of the local reference frame.
  18290. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18291. * @param {Matrix4} [result] The object onto which to store the result.
  18292. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18293. *
  18294. * @example
  18295. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  18296. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18297. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  18298. */
  18299. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  18300. if (!defined(origin)) {
  18301. throw new DeveloperError('origin is required.');
  18302. }
  18303. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18304. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18305. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  18306. var sign = CesiumMath.sign(origin.z);
  18307. if (!defined(result)) {
  18308. return new Matrix4(
  18309. -sign, 0.0, 0.0, origin.x,
  18310. 0.0, 1.0, 0.0, origin.y,
  18311. 0.0, 0.0, -sign, origin.z,
  18312. 0.0, 0.0, 0.0, 1.0);
  18313. }
  18314. result[0] = -sign;
  18315. result[1] = 0.0;
  18316. result[2] = 0.0;
  18317. result[3] = 0.0;
  18318. result[4] = 0.0;
  18319. result[5] = 1.0;
  18320. result[6] = 0.0;
  18321. result[7] = 0.0;
  18322. result[8] = 0.0;
  18323. result[9] = 0.0;
  18324. result[10] = -sign;
  18325. result[11] = 0.0;
  18326. result[12] = origin.x;
  18327. result[13] = origin.y;
  18328. result[14] = origin.z;
  18329. result[15] = 1.0;
  18330. return result;
  18331. }
  18332. var normal = northEastDownToFixedFrameNormal;
  18333. var tangent = northEastDownToFixedFrameTangent;
  18334. var bitangent = northEastDownToFixedFrameBitangent;
  18335. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18336. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18337. tangent.x = -origin.y;
  18338. tangent.y = origin.x;
  18339. tangent.z = 0.0;
  18340. Cartesian3.normalize(tangent, tangent);
  18341. Cartesian3.cross(normal, tangent, bitangent);
  18342. if (!defined(result)) {
  18343. return new Matrix4(
  18344. bitangent.x, tangent.x, -normal.x, origin.x,
  18345. bitangent.y, tangent.y, -normal.y, origin.y,
  18346. bitangent.z, tangent.z, -normal.z, origin.z,
  18347. 0.0, 0.0, 0.0, 1.0);
  18348. }
  18349. result[0] = bitangent.x;
  18350. result[1] = bitangent.y;
  18351. result[2] = bitangent.z;
  18352. result[3] = 0.0;
  18353. result[4] = tangent.x;
  18354. result[5] = tangent.y;
  18355. result[6] = tangent.z;
  18356. result[7] = 0.0;
  18357. result[8] = -normal.x;
  18358. result[9] = -normal.y;
  18359. result[10] = -normal.z;
  18360. result[11] = 0.0;
  18361. result[12] = origin.x;
  18362. result[13] = origin.y;
  18363. result[14] = origin.z;
  18364. result[15] = 1.0;
  18365. return result;
  18366. };
  18367. /**
  18368. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  18369. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18370. * The local axes are defined as:
  18371. * <ul>
  18372. * <li>The <code>x</code> axis points in the local north direction.</li>
  18373. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  18374. * <li>The <code>z</code> axis points in the local east direction.</li>
  18375. * </ul>
  18376. *
  18377. * @param {Cartesian3} origin The center point of the local reference frame.
  18378. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18379. * @param {Matrix4} [result] The object onto which to store the result.
  18380. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18381. *
  18382. * @example
  18383. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  18384. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18385. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  18386. */
  18387. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  18388. if (!defined(origin)) {
  18389. throw new DeveloperError('origin is required.');
  18390. }
  18391. // If x and y are zero, assume origin is at a pole, which is a special case.
  18392. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18393. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18394. var sign = CesiumMath.sign(origin.z);
  18395. if (!defined(result)) {
  18396. return new Matrix4(
  18397. -sign, 0.0, 0.0, origin.x,
  18398. 0.0, 0.0, 1.0, origin.y,
  18399. 0.0, sign, 0.0, origin.z,
  18400. 0.0, 0.0, 0.0, 1.0);
  18401. }
  18402. result[0] = -sign;
  18403. result[1] = 0.0;
  18404. result[2] = 0.0;
  18405. result[3] = 0.0;
  18406. result[4] = 0.0;
  18407. result[5] = 0.0;
  18408. result[6] = sign;
  18409. result[7] = 0.0;
  18410. result[8] = 0.0;
  18411. result[9] = 1.0;
  18412. result[10] = 0.0;
  18413. result[11] = 0.0;
  18414. result[12] = origin.x;
  18415. result[13] = origin.y;
  18416. result[14] = origin.z;
  18417. result[15] = 1.0;
  18418. return result;
  18419. }
  18420. var normal = eastNorthUpToFixedFrameNormal;
  18421. var tangent = eastNorthUpToFixedFrameTangent;
  18422. var bitangent = eastNorthUpToFixedFrameBitangent;
  18423. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18424. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18425. tangent.x = -origin.y;
  18426. tangent.y = origin.x;
  18427. tangent.z = 0.0;
  18428. Cartesian3.normalize(tangent, tangent);
  18429. Cartesian3.cross(normal, tangent, bitangent);
  18430. if (!defined(result)) {
  18431. return new Matrix4(
  18432. bitangent.x, normal.x, tangent.x, origin.x,
  18433. bitangent.y, normal.y, tangent.y, origin.y,
  18434. bitangent.z, normal.z, tangent.z, origin.z,
  18435. 0.0, 0.0, 0.0, 1.0);
  18436. }
  18437. result[0] = bitangent.x;
  18438. result[1] = bitangent.y;
  18439. result[2] = bitangent.z;
  18440. result[3] = 0.0;
  18441. result[4] = normal.x;
  18442. result[5] = normal.y;
  18443. result[6] = normal.z;
  18444. result[7] = 0.0;
  18445. result[8] = tangent.x;
  18446. result[9] = tangent.y;
  18447. result[10] = tangent.z;
  18448. result[11] = 0.0;
  18449. result[12] = origin.x;
  18450. result[13] = origin.y;
  18451. result[14] = origin.z;
  18452. result[15] = 1.0;
  18453. return result;
  18454. };
  18455. /**
  18456. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  18457. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18458. * The local axes are defined as:
  18459. * <ul>
  18460. * <li>The <code>x</code> axis points in the local north direction.</li>
  18461. * <li>The <code>y</code> axis points in the local west direction.</li>
  18462. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  18463. * </ul>
  18464. *
  18465. * @param {Cartesian3} origin The center point of the local reference frame.
  18466. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18467. * @param {Matrix4} [result] The object onto which to store the result.
  18468. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18469. *
  18470. * @example
  18471. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  18472. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18473. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  18474. */
  18475. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  18476. if (!defined(origin)) {
  18477. throw new DeveloperError('origin is required.');
  18478. }
  18479. // If x and y are zero, assume origin is at a pole, which is a special case.
  18480. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18481. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18482. var sign = CesiumMath.sign(origin.z);
  18483. if (!defined(result)) {
  18484. return new Matrix4(
  18485. -sign, 0.0, 0.0, origin.x,
  18486. 0.0, -1.0, 0.0, origin.y,
  18487. 0.0, 0.0, sign, origin.z,
  18488. 0.0, 0.0, 0.0, 1.0);
  18489. }
  18490. result[0] = -sign;
  18491. result[1] = 0.0;
  18492. result[2] = 0.0;
  18493. result[3] = 0.0;
  18494. result[4] = 0.0;
  18495. result[5] = -1.0;
  18496. result[6] = 0.0;
  18497. result[7] = 0.0;
  18498. result[8] = 0.0;
  18499. result[9] = 0.0;
  18500. result[10] = sign;
  18501. result[11] = 0.0;
  18502. result[12] = origin.x;
  18503. result[13] = origin.y;
  18504. result[14] = origin.z;
  18505. result[15] = 1.0;
  18506. return result;
  18507. }
  18508. var normal = eastNorthUpToFixedFrameNormal;//Up
  18509. var tangent = eastNorthUpToFixedFrameTangent;//East
  18510. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  18511. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18512. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18513. tangent.x = -origin.y;
  18514. tangent.y = origin.x;
  18515. tangent.z = 0.0;
  18516. Cartesian3.normalize(tangent, tangent);
  18517. Cartesian3.cross(normal, tangent, bitangent);
  18518. if (!defined(result)) {
  18519. return new Matrix4(
  18520. bitangent.x, -tangent.x, normal.x, origin.x,
  18521. bitangent.y, -tangent.y, normal.y, origin.y,
  18522. bitangent.z, -tangent.z, normal.z, origin.z,
  18523. 0.0, 0.0, 0.0, 1.0);
  18524. }
  18525. result[0] = bitangent.x;
  18526. result[1] = bitangent.y;
  18527. result[2] = bitangent.z;
  18528. result[3] = 0.0;
  18529. result[4] = -tangent.x;
  18530. result[5] = -tangent.y;
  18531. result[6] = -tangent.z;
  18532. result[7] = 0.0;
  18533. result[8] = normal.x;
  18534. result[9] = normal.y;
  18535. result[10] = normal.z;
  18536. result[11] = 0.0;
  18537. result[12] = origin.x;
  18538. result[13] = origin.y;
  18539. result[14] = origin.z;
  18540. result[15] = 1.0;
  18541. return result;
  18542. };
  18543. var scratchHPRQuaternion = new Quaternion();
  18544. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  18545. var scratchHPRMatrix4 = new Matrix4();
  18546. /**
  18547. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  18548. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  18549. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  18550. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  18551. *
  18552. * @param {Cartesian3} origin The center point of the local reference frame.
  18553. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  18554. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18555. * @param {Matrix4} [result] The object onto which to store the result.
  18556. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18557. *
  18558. * @example
  18559. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  18560. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18561. * var heading = -Cesium.Math.PI_OVER_TWO;
  18562. * var pitch = Cesium.Math.PI_OVER_FOUR;
  18563. * var roll = 0.0;
  18564. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  18565. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  18566. */
  18567. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  18568. var heading;
  18569. if (typeof headingPitchRoll === 'object') {
  18570. // Shift arguments using assignments to encourage JIT optimization.
  18571. ellipsoid = pitch;
  18572. result = roll;
  18573. heading = headingPitchRoll.heading;
  18574. pitch = headingPitchRoll.pitch;
  18575. roll = headingPitchRoll.roll;
  18576. } else {
  18577. 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.');
  18578. heading = headingPitchRoll;
  18579. }
  18580. // checks for required parameters happen in the called functions
  18581. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  18582. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  18583. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  18584. return Matrix4.multiply(result, hprMatrix, result);
  18585. };
  18586. var scratchHPR = new HeadingPitchRoll();
  18587. var scratchENUMatrix4 = new Matrix4();
  18588. var scratchHPRMatrix3 = new Matrix3();
  18589. /**
  18590. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  18591. * centered at the provided origin. Heading is the rotation from the local north
  18592. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  18593. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  18594. *
  18595. * @param {Cartesian3} origin The center point of the local reference frame.
  18596. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  18597. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18598. * @param {Quaternion} [result] The object onto which to store the result.
  18599. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  18600. *
  18601. * @example
  18602. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  18603. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18604. * var heading = -Cesium.Math.PI_OVER_TWO;
  18605. * var pitch = Cesium.Math.PI_OVER_FOUR;
  18606. * var roll = 0.0;
  18607. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  18608. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  18609. */
  18610. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  18611. var hpr;
  18612. if (typeof headingPitchRoll === 'object') {
  18613. // Shift arguments using assignment to encourage JIT optimization.
  18614. hpr = headingPitchRoll;
  18615. ellipsoid = pitch;
  18616. result = roll;
  18617. } else {
  18618. 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.');
  18619. scratchHPR.heading = headingPitchRoll;
  18620. scratchHPR.pitch = pitch;
  18621. scratchHPR.roll = roll;
  18622. hpr = scratchHPR;
  18623. }
  18624. // checks for required parameters happen in the called functions
  18625. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  18626. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  18627. return Quaternion.fromRotationMatrix(rotation, result);
  18628. };
  18629. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  18630. var gmstConstant1 = 8640184.812866;
  18631. var gmstConstant2 = 0.093104;
  18632. var gmstConstant3 = -6.2E-6;
  18633. var rateCoef = 1.1772758384668e-19;
  18634. var wgs84WRPrecessing = 7.2921158553E-5;
  18635. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  18636. var dateInUtc = new JulianDate();
  18637. /**
  18638. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  18639. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  18640. *
  18641. * @param {JulianDate} date The time at which to compute the rotation matrix.
  18642. * @param {Matrix3} [result] The object onto which to store the result.
  18643. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  18644. *
  18645. * @example
  18646. * //Set the view to in the inertial frame.
  18647. * scene.preRender.addEventListener(function(scene, time) {
  18648. * var now = Cesium.JulianDate.now();
  18649. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  18650. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  18651. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  18652. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  18653. * camera.lookAtTransform(transform, offset);
  18654. * });
  18655. */
  18656. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  18657. if (!defined(date)) {
  18658. throw new DeveloperError('date is required.');
  18659. }
  18660. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  18661. // We do not want to use the function like convertTaiToUtc in JulianDate because
  18662. // we explicitly do not want to fail when inside the leap second.
  18663. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  18664. var utcDayNumber = dateInUtc.dayNumber;
  18665. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  18666. var t;
  18667. var diffDays = utcDayNumber - 2451545;
  18668. if (utcSecondsIntoDay >= 43200.0) {
  18669. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  18670. } else {
  18671. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  18672. }
  18673. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  18674. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  18675. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  18676. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  18677. var gha = angle + (ratio * secondsSinceMidnight);
  18678. var cosGha = Math.cos(gha);
  18679. var sinGha = Math.sin(gha);
  18680. if (!defined(result)) {
  18681. return new Matrix3(cosGha, sinGha, 0.0,
  18682. -sinGha, cosGha, 0.0,
  18683. 0.0, 0.0, 1.0);
  18684. }
  18685. result[0] = cosGha;
  18686. result[1] = -sinGha;
  18687. result[2] = 0.0;
  18688. result[3] = sinGha;
  18689. result[4] = cosGha;
  18690. result[5] = 0.0;
  18691. result[6] = 0.0;
  18692. result[7] = 0.0;
  18693. result[8] = 1.0;
  18694. return result;
  18695. };
  18696. /**
  18697. * The source of IAU 2006 XYS data, used for computing the transformation between the
  18698. * Fixed and ICRF axes.
  18699. * @type {Iau2006XysData}
  18700. *
  18701. * @see Transforms.computeIcrfToFixedMatrix
  18702. * @see Transforms.computeFixedToIcrfMatrix
  18703. *
  18704. * @private
  18705. */
  18706. Transforms.iau2006XysData = new Iau2006XysData();
  18707. /**
  18708. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  18709. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  18710. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  18711. * @type {EarthOrientationParameters}
  18712. *
  18713. * @see Transforms.computeIcrfToFixedMatrix
  18714. * @see Transforms.computeFixedToIcrfMatrix
  18715. *
  18716. * @private
  18717. */
  18718. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  18719. var ttMinusTai = 32.184;
  18720. var j2000ttDays = 2451545.0;
  18721. /**
  18722. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  18723. * direction, over a given interval. This function returns a promise that, when resolved,
  18724. * indicates that the preload has completed.
  18725. *
  18726. * @param {TimeInterval} timeInterval The interval to preload.
  18727. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  18728. * and evaluation of the transformation between the fixed and ICRF axes will
  18729. * no longer return undefined for a time inside the interval.
  18730. *
  18731. *
  18732. * @example
  18733. * var interval = new Cesium.TimeInterval(...);
  18734. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  18735. * // the data is now loaded
  18736. * });
  18737. *
  18738. * @see Transforms.computeIcrfToFixedMatrix
  18739. * @see Transforms.computeFixedToIcrfMatrix
  18740. * @see when
  18741. */
  18742. Transforms.preloadIcrfFixed = function(timeInterval) {
  18743. var startDayTT = timeInterval.start.dayNumber;
  18744. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  18745. var stopDayTT = timeInterval.stop.dayNumber;
  18746. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  18747. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  18748. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  18749. return when.all([xysPromise, eopPromise]);
  18750. };
  18751. /**
  18752. * Computes a rotation matrix to transform a point or vector from the International Celestial
  18753. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  18754. * at a given time. This function may return undefined if the data necessary to
  18755. * do the transformation is not yet loaded.
  18756. *
  18757. * @param {JulianDate} date The time at which to compute the rotation matrix.
  18758. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  18759. * not specified, a new instance is created and returned.
  18760. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  18761. * transformation is not yet loaded.
  18762. *
  18763. *
  18764. * @example
  18765. * scene.preRender.addEventListener(function(scene, time) {
  18766. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  18767. * if (Cesium.defined(icrfToFixed)) {
  18768. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  18769. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  18770. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  18771. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  18772. * camera.lookAtTransform(transform, offset);
  18773. * }
  18774. * });
  18775. *
  18776. * @see Transforms.preloadIcrfFixed
  18777. */
  18778. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  18779. if (!defined(date)) {
  18780. throw new DeveloperError('date is required.');
  18781. }
  18782. if (!defined(result)) {
  18783. result = new Matrix3();
  18784. }
  18785. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  18786. if (!defined(fixedToIcrfMtx)) {
  18787. return undefined;
  18788. }
  18789. return Matrix3.transpose(fixedToIcrfMtx, result);
  18790. };
  18791. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  18792. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  18793. var rotation1Scratch = new Matrix3();
  18794. var rotation2Scratch = new Matrix3();
  18795. /**
  18796. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  18797. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  18798. * at a given time. This function may return undefined if the data necessary to
  18799. * do the transformation is not yet loaded.
  18800. *
  18801. * @param {JulianDate} date The time at which to compute the rotation matrix.
  18802. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  18803. * not specified, a new instance is created and returned.
  18804. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  18805. * transformation is not yet loaded.
  18806. *
  18807. *
  18808. * @example
  18809. * // Transform a point from the ICRF axes to the Fixed axes.
  18810. * var now = Cesium.JulianDate.now();
  18811. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18812. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  18813. * var pointInInertial = new Cesium.Cartesian3();
  18814. * if (Cesium.defined(fixedToIcrf)) {
  18815. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  18816. * }
  18817. *
  18818. * @see Transforms.preloadIcrfFixed
  18819. */
  18820. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  18821. if (!defined(date)) {
  18822. throw new DeveloperError('date is required.');
  18823. }
  18824. if (!defined(result)) {
  18825. result = new Matrix3();
  18826. }
  18827. // Compute pole wander
  18828. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  18829. if (!defined(eop)) {
  18830. return undefined;
  18831. }
  18832. // There is no external conversion to Terrestrial Time (TT).
  18833. // So use International Atomic Time (TAI) and convert using offsets.
  18834. // Here we are assuming that dayTT and secondTT are positive
  18835. var dayTT = date.dayNumber;
  18836. // It's possible here that secondTT could roll over 86400
  18837. // This does not seem to affect the precision (unit tests check for this)
  18838. var secondTT = date.secondsOfDay + ttMinusTai;
  18839. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  18840. if (!defined(xys)) {
  18841. return undefined;
  18842. }
  18843. var x = xys.x + eop.xPoleOffset;
  18844. var y = xys.y + eop.yPoleOffset;
  18845. // Compute XYS rotation
  18846. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  18847. var rotation1 = rotation1Scratch;
  18848. rotation1[0] = 1.0 - a * x * x;
  18849. rotation1[3] = -a * x * y;
  18850. rotation1[6] = x;
  18851. rotation1[1] = -a * x * y;
  18852. rotation1[4] = 1 - a * y * y;
  18853. rotation1[7] = y;
  18854. rotation1[2] = -x;
  18855. rotation1[5] = -y;
  18856. rotation1[8] = 1 - a * (x * x + y * y);
  18857. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  18858. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  18859. // Similar to TT conversions above
  18860. // It's possible here that secondTT could roll over 86400
  18861. // This does not seem to affect the precision (unit tests check for this)
  18862. var dateUt1day = date.dayNumber;
  18863. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  18864. // Compute Earth rotation angle
  18865. // The IERS standard for era is
  18866. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  18867. // where
  18868. // Tu = JulianDateInUt1 - 2451545.0
  18869. // However, you get much more precision if you make the following simplification
  18870. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  18871. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  18872. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  18873. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  18874. var daysSinceJ2000 = dateUt1day - 2451545;
  18875. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  18876. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  18877. era = (era % 1.0) * CesiumMath.TWO_PI;
  18878. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  18879. // pseudoFixed to ICRF
  18880. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  18881. // Compute pole wander matrix
  18882. var cosxp = Math.cos(eop.xPoleWander);
  18883. var cosyp = Math.cos(eop.yPoleWander);
  18884. var sinxp = Math.sin(eop.xPoleWander);
  18885. var sinyp = Math.sin(eop.yPoleWander);
  18886. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  18887. ttt /= 36525.0;
  18888. // approximate sp value in rad
  18889. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  18890. var cossp = Math.cos(sp);
  18891. var sinsp = Math.sin(sp);
  18892. var fToPfMtx = rotation2Scratch;
  18893. fToPfMtx[0] = cosxp * cossp;
  18894. fToPfMtx[1] = cosxp * sinsp;
  18895. fToPfMtx[2] = sinxp;
  18896. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  18897. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  18898. fToPfMtx[5] = -sinyp * cosxp;
  18899. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  18900. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  18901. fToPfMtx[8] = cosyp * cosxp;
  18902. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  18903. };
  18904. var pointToWindowCoordinatesTemp = new Cartesian4();
  18905. /**
  18906. * Transform a point from model coordinates to window coordinates.
  18907. *
  18908. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  18909. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  18910. * @param {Cartesian3} point The point to transform.
  18911. * @param {Cartesian2} [result] The object onto which to store the result.
  18912. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  18913. */
  18914. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  18915. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  18916. result.y = 2.0 * viewportTransformation[5] - result.y;
  18917. return result;
  18918. };
  18919. /**
  18920. * @private
  18921. */
  18922. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  18923. if (!defined(modelViewProjectionMatrix)) {
  18924. throw new DeveloperError('modelViewProjectionMatrix is required.');
  18925. }
  18926. if (!defined(viewportTransformation)) {
  18927. throw new DeveloperError('viewportTransformation is required.');
  18928. }
  18929. if (!defined(point)) {
  18930. throw new DeveloperError('point is required.');
  18931. }
  18932. if (!defined(result)) {
  18933. result = new Cartesian2();
  18934. }
  18935. var tmp = pointToWindowCoordinatesTemp;
  18936. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  18937. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  18938. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  18939. return Cartesian2.fromCartesian4(tmp, result);
  18940. };
  18941. var normalScratch = new Cartesian3();
  18942. var rightScratch = new Cartesian3();
  18943. var upScratch = new Cartesian3();
  18944. /**
  18945. * @private
  18946. */
  18947. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  18948. if (!defined(position)) {
  18949. throw new DeveloperError('position is required.');
  18950. }
  18951. if (!defined(velocity)) {
  18952. throw new DeveloperError('velocity is required.');
  18953. }
  18954. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  18955. var right = Cartesian3.cross(velocity, normal, rightScratch);
  18956. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  18957. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  18958. }
  18959. var up = Cartesian3.cross(right, velocity, upScratch);
  18960. Cartesian3.cross(velocity, up, right);
  18961. Cartesian3.negate(right, right);
  18962. if (!defined(result)) {
  18963. result = new Matrix3();
  18964. }
  18965. result[0] = velocity.x;
  18966. result[1] = velocity.y;
  18967. result[2] = velocity.z;
  18968. result[3] = right.x;
  18969. result[4] = right.y;
  18970. result[5] = right.z;
  18971. result[6] = up.x;
  18972. result[7] = up.y;
  18973. result[8] = up.z;
  18974. return result;
  18975. };
  18976. var scratchCartographic = new Cartographic();
  18977. var scratchCartesian3Projection = new Cartesian3();
  18978. var scratchCartesian3 = new Cartesian3();
  18979. var scratchCartesian4Origin = new Cartesian4();
  18980. var scratchCartesian4NewOrigin = new Cartesian4();
  18981. var scratchCartesian4NewXAxis = new Cartesian4();
  18982. var scratchCartesian4NewYAxis = new Cartesian4();
  18983. var scratchCartesian4NewZAxis = new Cartesian4();
  18984. var scratchFromENU = new Matrix4();
  18985. var scratchToENU = new Matrix4();
  18986. /**
  18987. * @private
  18988. */
  18989. Transforms.basisTo2D = function(projection, matrix, result) {
  18990. if (!defined(projection)) {
  18991. throw new DeveloperError('projection is required.');
  18992. }
  18993. if (!defined(matrix)) {
  18994. throw new DeveloperError('matrix is required.');
  18995. }
  18996. if (!defined(result)) {
  18997. throw new DeveloperError('result is required.');
  18998. }
  18999. var ellipsoid = projection.ellipsoid;
  19000. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  19001. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  19002. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  19003. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  19004. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  19005. var newOrigin = scratchCartesian4NewOrigin;
  19006. newOrigin.x = projectedPosition.z;
  19007. newOrigin.y = projectedPosition.x;
  19008. newOrigin.z = projectedPosition.y;
  19009. newOrigin.w = 1.0;
  19010. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  19011. var xScale = Cartesian3.magnitude(xAxis);
  19012. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  19013. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  19014. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  19015. var yScale = Cartesian3.magnitude(yAxis);
  19016. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  19017. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  19018. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  19019. var zScale = Cartesian3.magnitude(zAxis);
  19020. var newZAxis = scratchCartesian4NewZAxis;
  19021. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  19022. Cartesian3.normalize(newZAxis, newZAxis);
  19023. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  19024. Cartesian3.normalize(newXAxis, newXAxis);
  19025. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  19026. Cartesian3.normalize(newYAxis, newYAxis);
  19027. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  19028. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  19029. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  19030. Matrix4.setColumn(result, 0, newXAxis, result);
  19031. Matrix4.setColumn(result, 1, newYAxis, result);
  19032. Matrix4.setColumn(result, 2, newZAxis, result);
  19033. Matrix4.setColumn(result, 3, newOrigin, result);
  19034. return result;
  19035. };
  19036. return Transforms;
  19037. });
  19038. /*global define*/
  19039. define('Core/EllipsoidTangentPlane',[
  19040. './AxisAlignedBoundingBox',
  19041. './Cartesian2',
  19042. './Cartesian3',
  19043. './Cartesian4',
  19044. './defaultValue',
  19045. './defined',
  19046. './defineProperties',
  19047. './DeveloperError',
  19048. './Ellipsoid',
  19049. './IntersectionTests',
  19050. './Matrix4',
  19051. './Plane',
  19052. './Ray',
  19053. './Transforms'
  19054. ], function(
  19055. AxisAlignedBoundingBox,
  19056. Cartesian2,
  19057. Cartesian3,
  19058. Cartesian4,
  19059. defaultValue,
  19060. defined,
  19061. defineProperties,
  19062. DeveloperError,
  19063. Ellipsoid,
  19064. IntersectionTests,
  19065. Matrix4,
  19066. Plane,
  19067. Ray,
  19068. Transforms) {
  19069. 'use strict';
  19070. var scratchCart4 = new Cartesian4();
  19071. /**
  19072. * A plane tangent to the provided ellipsoid at the provided origin.
  19073. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  19074. * If origin is at the center of the ellipsoid, an exception will be thrown.
  19075. * @alias EllipsoidTangentPlane
  19076. * @constructor
  19077. *
  19078. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  19079. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  19080. *
  19081. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  19082. */
  19083. function EllipsoidTangentPlane(origin, ellipsoid) {
  19084. if (!defined(origin)) {
  19085. throw new DeveloperError('origin is required.');
  19086. }
  19087. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19088. origin = ellipsoid.scaleToGeodeticSurface(origin);
  19089. if (!defined(origin)) {
  19090. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  19091. }
  19092. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  19093. this._ellipsoid = ellipsoid;
  19094. this._origin = origin;
  19095. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  19096. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  19097. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  19098. this._plane = Plane.fromPointNormal(origin, normal);
  19099. }
  19100. defineProperties(EllipsoidTangentPlane.prototype, {
  19101. /**
  19102. * Gets the ellipsoid.
  19103. * @memberof EllipsoidTangentPlane.prototype
  19104. * @type {Ellipsoid}
  19105. */
  19106. ellipsoid : {
  19107. get : function() {
  19108. return this._ellipsoid;
  19109. }
  19110. },
  19111. /**
  19112. * Gets the origin.
  19113. * @memberof EllipsoidTangentPlane.prototype
  19114. * @type {Cartesian3}
  19115. */
  19116. origin : {
  19117. get : function() {
  19118. return this._origin;
  19119. }
  19120. },
  19121. /**
  19122. * Gets the plane which is tangent to the ellipsoid.
  19123. * @memberof EllipsoidTangentPlane.prototype
  19124. * @readonly
  19125. * @type {Plane}
  19126. */
  19127. plane : {
  19128. get : function() {
  19129. return this._plane;
  19130. }
  19131. },
  19132. /**
  19133. * Gets the local X-axis (east) of the tangent plane.
  19134. * @memberof EllipsoidTangentPlane.prototype
  19135. * @readonly
  19136. * @type {Cartesian3}
  19137. */
  19138. xAxis : {
  19139. get : function() {
  19140. return this._xAxis;
  19141. }
  19142. },
  19143. /**
  19144. * Gets the local Y-axis (north) of the tangent plane.
  19145. * @memberof EllipsoidTangentPlane.prototype
  19146. * @readonly
  19147. * @type {Cartesian3}
  19148. */
  19149. yAxis : {
  19150. get : function() {
  19151. return this._yAxis;
  19152. }
  19153. },
  19154. /**
  19155. * Gets the local Z-axis (up) of the tangent plane.
  19156. * @member EllipsoidTangentPlane.prototype
  19157. * @readonly
  19158. * @type {Cartesian3}
  19159. */
  19160. zAxis : {
  19161. get : function() {
  19162. return this._plane.normal;
  19163. }
  19164. }
  19165. });
  19166. var tmp = new AxisAlignedBoundingBox();
  19167. /**
  19168. * Creates a new instance from the provided ellipsoid and the center
  19169. * point of the provided Cartesians.
  19170. *
  19171. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  19172. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  19173. */
  19174. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  19175. if (!defined(cartesians)) {
  19176. throw new DeveloperError('cartesians is required.');
  19177. }
  19178. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  19179. return new EllipsoidTangentPlane(box.center, ellipsoid);
  19180. };
  19181. var scratchProjectPointOntoPlaneRay = new Ray();
  19182. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  19183. /**
  19184. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  19185. *
  19186. * @param {Cartesian3} cartesian The point to project.
  19187. * @param {Cartesian2} [result] The object onto which to store the result.
  19188. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  19189. */
  19190. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  19191. if (!defined(cartesian)) {
  19192. throw new DeveloperError('cartesian is required.');
  19193. }
  19194. var ray = scratchProjectPointOntoPlaneRay;
  19195. ray.origin = cartesian;
  19196. Cartesian3.normalize(cartesian, ray.direction);
  19197. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19198. if (!defined(intersectionPoint)) {
  19199. Cartesian3.negate(ray.direction, ray.direction);
  19200. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19201. }
  19202. if (defined(intersectionPoint)) {
  19203. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19204. var x = Cartesian3.dot(this._xAxis, v);
  19205. var y = Cartesian3.dot(this._yAxis, v);
  19206. if (!defined(result)) {
  19207. return new Cartesian2(x, y);
  19208. }
  19209. result.x = x;
  19210. result.y = y;
  19211. return result;
  19212. }
  19213. return undefined;
  19214. };
  19215. /**
  19216. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  19217. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  19218. *
  19219. * @see EllipsoidTangentPlane.projectPointOntoPlane
  19220. *
  19221. * @param {Cartesian3[]} cartesians The array of points to project.
  19222. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19223. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  19224. */
  19225. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  19226. if (!defined(cartesians)) {
  19227. throw new DeveloperError('cartesians is required.');
  19228. }
  19229. if (!defined(result)) {
  19230. result = [];
  19231. }
  19232. var count = 0;
  19233. var length = cartesians.length;
  19234. for ( var i = 0; i < length; i++) {
  19235. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  19236. if (defined(p)) {
  19237. result[count] = p;
  19238. count++;
  19239. }
  19240. }
  19241. result.length = count;
  19242. return result;
  19243. };
  19244. /**
  19245. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  19246. *
  19247. * @param {Cartesian3} cartesian The point to project.
  19248. * @param {Cartesian2} [result] The object onto which to store the result.
  19249. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19250. */
  19251. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  19252. if (!defined(cartesian)) {
  19253. throw new DeveloperError('cartesian is required.');
  19254. }
  19255. if (!defined(result)) {
  19256. result = new Cartesian2();
  19257. }
  19258. var ray = scratchProjectPointOntoPlaneRay;
  19259. ray.origin = cartesian;
  19260. Cartesian3.clone(this._plane.normal, ray.direction);
  19261. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19262. if (!defined(intersectionPoint)) {
  19263. Cartesian3.negate(ray.direction, ray.direction);
  19264. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19265. }
  19266. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19267. var x = Cartesian3.dot(this._xAxis, v);
  19268. var y = Cartesian3.dot(this._yAxis, v);
  19269. result.x = x;
  19270. result.y = y;
  19271. return result;
  19272. };
  19273. /**
  19274. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  19275. *
  19276. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  19277. *
  19278. * @param {Cartesian3[]} cartesians The array of points to project.
  19279. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19280. * @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>.
  19281. */
  19282. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  19283. if (!defined(cartesians)) {
  19284. throw new DeveloperError('cartesians is required.');
  19285. }
  19286. if (!defined(result)) {
  19287. result = [];
  19288. }
  19289. var length = cartesians.length;
  19290. result.length = length;
  19291. for (var i = 0; i < length; i++) {
  19292. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  19293. }
  19294. return result;
  19295. };
  19296. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  19297. /**
  19298. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  19299. *
  19300. * @param {Cartesian2[]} cartesians The array of points to project.
  19301. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  19302. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  19303. */
  19304. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  19305. if (!defined(cartesians)) {
  19306. throw new DeveloperError('cartesians is required.');
  19307. }
  19308. var length = cartesians.length;
  19309. if (!defined(result)) {
  19310. result = new Array(length);
  19311. } else {
  19312. result.length = length;
  19313. }
  19314. var ellipsoid = this._ellipsoid;
  19315. var origin = this._origin;
  19316. var xAxis = this._xAxis;
  19317. var yAxis = this._yAxis;
  19318. var tmp = projectPointsOntoEllipsoidScratch;
  19319. for ( var i = 0; i < length; ++i) {
  19320. var position = cartesians[i];
  19321. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  19322. if (!defined(result[i])) {
  19323. result[i] = new Cartesian3();
  19324. }
  19325. var point = Cartesian3.add(origin, tmp, result[i]);
  19326. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  19327. Cartesian3.add(point, tmp, point);
  19328. ellipsoid.scaleToGeocentricSurface(point, point);
  19329. }
  19330. return result;
  19331. };
  19332. return EllipsoidTangentPlane;
  19333. });
  19334. /*global define*/
  19335. define('Core/OrientedBoundingBox',[
  19336. './BoundingSphere',
  19337. './Cartesian2',
  19338. './Cartesian3',
  19339. './Cartographic',
  19340. './defaultValue',
  19341. './defined',
  19342. './DeveloperError',
  19343. './Ellipsoid',
  19344. './EllipsoidTangentPlane',
  19345. './Intersect',
  19346. './Interval',
  19347. './Math',
  19348. './Matrix3',
  19349. './Plane',
  19350. './Rectangle'
  19351. ], function(
  19352. BoundingSphere,
  19353. Cartesian2,
  19354. Cartesian3,
  19355. Cartographic,
  19356. defaultValue,
  19357. defined,
  19358. DeveloperError,
  19359. Ellipsoid,
  19360. EllipsoidTangentPlane,
  19361. Intersect,
  19362. Interval,
  19363. CesiumMath,
  19364. Matrix3,
  19365. Plane,
  19366. Rectangle) {
  19367. 'use strict';
  19368. /**
  19369. * Creates an instance of an OrientedBoundingBox.
  19370. * An OrientedBoundingBox of some object is a closed and convex cuboid. It can provide a tighter bounding volume than {@link BoundingSphere} or {@link AxisAlignedBoundingBox} in many cases.
  19371. * @alias OrientedBoundingBox
  19372. * @constructor
  19373. *
  19374. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the box.
  19375. * @param {Matrix3} [halfAxes=Matrix3.ZERO] The three orthogonal half-axes of the bounding box.
  19376. * Equivalently, the transformation matrix, to rotate and scale a 2x2x2
  19377. * cube centered at the origin.
  19378. *
  19379. *
  19380. * @example
  19381. * // Create an OrientedBoundingBox using a transformation matrix, a position where the box will be translated, and a scale.
  19382. * var center = new Cesium.Cartesian3(1.0, 0.0, 0.0);
  19383. * var halfAxes = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(1.0, 3.0, 2.0), new Cesium.Matrix3());
  19384. *
  19385. * var obb = new Cesium.OrientedBoundingBox(center, halfAxes);
  19386. *
  19387. * @see BoundingSphere
  19388. * @see BoundingRectangle
  19389. */
  19390. function OrientedBoundingBox(center, halfAxes) {
  19391. /**
  19392. * The center of the box.
  19393. * @type {Cartesian3}
  19394. * @default {@link Cartesian3.ZERO}
  19395. */
  19396. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  19397. /**
  19398. * The transformation matrix, to rotate the box to the right position.
  19399. * @type {Matrix3}
  19400. * @default {@link Matrix3.IDENTITY}
  19401. */
  19402. this.halfAxes = Matrix3.clone(defaultValue(halfAxes, Matrix3.ZERO));
  19403. }
  19404. var scratchCartesian1 = new Cartesian3();
  19405. var scratchCartesian2 = new Cartesian3();
  19406. var scratchCartesian3 = new Cartesian3();
  19407. var scratchCartesian4 = new Cartesian3();
  19408. var scratchCartesian5 = new Cartesian3();
  19409. var scratchCartesian6 = new Cartesian3();
  19410. var scratchCovarianceResult = new Matrix3();
  19411. var scratchEigenResult = {
  19412. unitary : new Matrix3(),
  19413. diagonal : new Matrix3()
  19414. };
  19415. /**
  19416. * Computes an instance of an OrientedBoundingBox of the given positions.
  19417. * This is an implementation of Stefan Gottschalk's Collision Queries using Oriented Bounding Boxes solution (PHD thesis).
  19418. * Reference: http://gamma.cs.unc.edu/users/gottschalk/main.pdf
  19419. *
  19420. * @param {Cartesian3[]} positions List of {@link Cartesian3} points that the bounding box will enclose.
  19421. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  19422. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  19423. *
  19424. * @example
  19425. * // Compute an object oriented bounding box enclosing two points.
  19426. * var box = Cesium.OrientedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  19427. */
  19428. OrientedBoundingBox.fromPoints = function(positions, result) {
  19429. if (!defined(result)) {
  19430. result = new OrientedBoundingBox();
  19431. }
  19432. if (!defined(positions) || positions.length === 0) {
  19433. result.halfAxes = Matrix3.ZERO;
  19434. result.center = Cartesian3.ZERO;
  19435. return result;
  19436. }
  19437. var i;
  19438. var length = positions.length;
  19439. var meanPoint = Cartesian3.clone(positions[0], scratchCartesian1);
  19440. for (i = 1; i < length; i++) {
  19441. Cartesian3.add(meanPoint, positions[i], meanPoint);
  19442. }
  19443. var invLength = 1.0 / length;
  19444. Cartesian3.multiplyByScalar(meanPoint, invLength, meanPoint);
  19445. var exx = 0.0;
  19446. var exy = 0.0;
  19447. var exz = 0.0;
  19448. var eyy = 0.0;
  19449. var eyz = 0.0;
  19450. var ezz = 0.0;
  19451. var p;
  19452. for (i = 0; i < length; i++) {
  19453. p = Cartesian3.subtract(positions[i], meanPoint, scratchCartesian2);
  19454. exx += p.x * p.x;
  19455. exy += p.x * p.y;
  19456. exz += p.x * p.z;
  19457. eyy += p.y * p.y;
  19458. eyz += p.y * p.z;
  19459. ezz += p.z * p.z;
  19460. }
  19461. exx *= invLength;
  19462. exy *= invLength;
  19463. exz *= invLength;
  19464. eyy *= invLength;
  19465. eyz *= invLength;
  19466. ezz *= invLength;
  19467. var covarianceMatrix = scratchCovarianceResult;
  19468. covarianceMatrix[0] = exx;
  19469. covarianceMatrix[1] = exy;
  19470. covarianceMatrix[2] = exz;
  19471. covarianceMatrix[3] = exy;
  19472. covarianceMatrix[4] = eyy;
  19473. covarianceMatrix[5] = eyz;
  19474. covarianceMatrix[6] = exz;
  19475. covarianceMatrix[7] = eyz;
  19476. covarianceMatrix[8] = ezz;
  19477. var eigenDecomposition = Matrix3.computeEigenDecomposition(covarianceMatrix, scratchEigenResult);
  19478. var rotation = Matrix3.clone(eigenDecomposition.unitary, result.halfAxes);
  19479. var v1 = Matrix3.getColumn(rotation, 0, scratchCartesian4);
  19480. var v2 = Matrix3.getColumn(rotation, 1, scratchCartesian5);
  19481. var v3 = Matrix3.getColumn(rotation, 2, scratchCartesian6);
  19482. var u1 = -Number.MAX_VALUE;
  19483. var u2 = -Number.MAX_VALUE;
  19484. var u3 = -Number.MAX_VALUE;
  19485. var l1 = Number.MAX_VALUE;
  19486. var l2 = Number.MAX_VALUE;
  19487. var l3 = Number.MAX_VALUE;
  19488. for (i = 0; i < length; i++) {
  19489. p = positions[i];
  19490. u1 = Math.max(Cartesian3.dot(v1, p), u1);
  19491. u2 = Math.max(Cartesian3.dot(v2, p), u2);
  19492. u3 = Math.max(Cartesian3.dot(v3, p), u3);
  19493. l1 = Math.min(Cartesian3.dot(v1, p), l1);
  19494. l2 = Math.min(Cartesian3.dot(v2, p), l2);
  19495. l3 = Math.min(Cartesian3.dot(v3, p), l3);
  19496. }
  19497. v1 = Cartesian3.multiplyByScalar(v1, 0.5 * (l1 + u1), v1);
  19498. v2 = Cartesian3.multiplyByScalar(v2, 0.5 * (l2 + u2), v2);
  19499. v3 = Cartesian3.multiplyByScalar(v3, 0.5 * (l3 + u3), v3);
  19500. var center = Cartesian3.add(v1, v2, result.center);
  19501. center = Cartesian3.add(center, v3, center);
  19502. var scale = scratchCartesian3;
  19503. scale.x = u1 - l1;
  19504. scale.y = u2 - l2;
  19505. scale.z = u3 - l3;
  19506. Cartesian3.multiplyByScalar(scale, 0.5, scale);
  19507. Matrix3.multiplyByScale(result.halfAxes, scale, result.halfAxes);
  19508. return result;
  19509. };
  19510. var scratchOffset = new Cartesian3();
  19511. var scratchScale = new Cartesian3();
  19512. /**
  19513. * Computes an OrientedBoundingBox given extents in the east-north-up space of the tangent plane.
  19514. *
  19515. * @param {Number} minimumX Minimum X extent in tangent plane space.
  19516. * @param {Number} maximumX Maximum X extent in tangent plane space.
  19517. * @param {Number} minimumY Minimum Y extent in tangent plane space.
  19518. * @param {Number} maximumY Maximum Y extent in tangent plane space.
  19519. * @param {Number} minimumZ Minimum Z extent in tangent plane space.
  19520. * @param {Number} maximumZ Maximum Z extent in tangent plane space.
  19521. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  19522. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  19523. */
  19524. function fromTangentPlaneExtents(tangentPlane, minimumX, maximumX, minimumY, maximumY, minimumZ, maximumZ, result) {
  19525. if (!defined(minimumX) ||
  19526. !defined(maximumX) ||
  19527. !defined(minimumY) ||
  19528. !defined(maximumY) ||
  19529. !defined(minimumZ) ||
  19530. !defined(maximumZ)) {
  19531. throw new DeveloperError('all extents (minimum/maximum X/Y/Z) are required.');
  19532. }
  19533. if (!defined(result)) {
  19534. result = new OrientedBoundingBox();
  19535. }
  19536. var halfAxes = result.halfAxes;
  19537. Matrix3.setColumn(halfAxes, 0, tangentPlane.xAxis, halfAxes);
  19538. Matrix3.setColumn(halfAxes, 1, tangentPlane.yAxis, halfAxes);
  19539. Matrix3.setColumn(halfAxes, 2, tangentPlane.zAxis, halfAxes);
  19540. var centerOffset = scratchOffset;
  19541. centerOffset.x = (minimumX + maximumX) / 2.0;
  19542. centerOffset.y = (minimumY + maximumY) / 2.0;
  19543. centerOffset.z = (minimumZ + maximumZ) / 2.0;
  19544. var scale = scratchScale;
  19545. scale.x = (maximumX - minimumX) / 2.0;
  19546. scale.y = (maximumY - minimumY) / 2.0;
  19547. scale.z = (maximumZ - minimumZ) / 2.0;
  19548. var center = result.center;
  19549. centerOffset = Matrix3.multiplyByVector(halfAxes, centerOffset, centerOffset);
  19550. Cartesian3.add(tangentPlane.origin, centerOffset, center);
  19551. Matrix3.multiplyByScale(halfAxes, scale, halfAxes);
  19552. return result;
  19553. }
  19554. var scratchRectangleCenterCartographic = new Cartographic();
  19555. var scratchRectangleCenter = new Cartesian3();
  19556. var perimeterCartographicScratch = [new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic()];
  19557. var perimeterCartesianScratch = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
  19558. var perimeterProjectedScratch = [new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2(), new Cartesian2()];
  19559. /**
  19560. * Computes an OrientedBoundingBox that bounds a {@link Rectangle} on the surface of an {@link Ellipsoid}.
  19561. * There are no guarantees about the orientation of the bounding box.
  19562. *
  19563. * @param {Rectangle} rectangle The cartographic rectangle on the surface of the ellipsoid.
  19564. * @param {Number} [minimumHeight=0.0] The minimum height (elevation) within the tile.
  19565. * @param {Number} [maximumHeight=0.0] The maximum height (elevation) within the tile.
  19566. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the rectangle is defined.
  19567. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  19568. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided.
  19569. *
  19570. * @exception {DeveloperError} rectangle.width must be between 0 and pi.
  19571. * @exception {DeveloperError} rectangle.height must be between 0 and pi.
  19572. * @exception {DeveloperError} ellipsoid must be an ellipsoid of revolution (<code>radii.x == radii.y</code>)
  19573. */
  19574. OrientedBoundingBox.fromRectangle = function(rectangle, minimumHeight, maximumHeight, ellipsoid, result) {
  19575. if (!defined(rectangle)) {
  19576. throw new DeveloperError('rectangle is required');
  19577. }
  19578. if (rectangle.width < 0.0 || rectangle.width > CesiumMath.PI) {
  19579. throw new DeveloperError('Rectangle width must be between 0 and pi');
  19580. }
  19581. if (rectangle.height < 0.0 || rectangle.height > CesiumMath.PI) {
  19582. throw new DeveloperError('Rectangle height must be between 0 and pi');
  19583. }
  19584. if (defined(ellipsoid) && !CesiumMath.equalsEpsilon(ellipsoid.radii.x, ellipsoid.radii.y, CesiumMath.EPSILON15)) {
  19585. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  19586. }
  19587. minimumHeight = defaultValue(minimumHeight, 0.0);
  19588. maximumHeight = defaultValue(maximumHeight, 0.0);
  19589. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19590. // The bounding box will be aligned with the tangent plane at the center of the rectangle.
  19591. var tangentPointCartographic = Rectangle.center(rectangle, scratchRectangleCenterCartographic);
  19592. var tangentPoint = ellipsoid.cartographicToCartesian(tangentPointCartographic, scratchRectangleCenter);
  19593. var tangentPlane = new EllipsoidTangentPlane(tangentPoint, ellipsoid);
  19594. var plane = tangentPlane.plane;
  19595. // Corner arrangement:
  19596. // N/+y
  19597. // [0] [1] [2]
  19598. // W/-x [7] [3] E/+x
  19599. // [6] [5] [4]
  19600. // S/-y
  19601. // "C" refers to the central lat/long, which by default aligns with the tangent point (above).
  19602. // If the rectangle spans the equator, CW and CE are instead aligned with the equator.
  19603. var perimeterNW = perimeterCartographicScratch[0];
  19604. var perimeterNC = perimeterCartographicScratch[1];
  19605. var perimeterNE = perimeterCartographicScratch[2];
  19606. var perimeterCE = perimeterCartographicScratch[3];
  19607. var perimeterSE = perimeterCartographicScratch[4];
  19608. var perimeterSC = perimeterCartographicScratch[5];
  19609. var perimeterSW = perimeterCartographicScratch[6];
  19610. var perimeterCW = perimeterCartographicScratch[7];
  19611. var lonCenter = tangentPointCartographic.longitude;
  19612. var latCenter = (rectangle.south < 0.0 && rectangle.north > 0.0) ? 0.0 : tangentPointCartographic.latitude;
  19613. perimeterSW.latitude = perimeterSC.latitude = perimeterSE.latitude = rectangle.south;
  19614. perimeterCW.latitude = perimeterCE.latitude = latCenter;
  19615. perimeterNW.latitude = perimeterNC.latitude = perimeterNE.latitude = rectangle.north;
  19616. perimeterSW.longitude = perimeterCW.longitude = perimeterNW.longitude = rectangle.west;
  19617. perimeterSC.longitude = perimeterNC.longitude = lonCenter;
  19618. perimeterSE.longitude = perimeterCE.longitude = perimeterNE.longitude = rectangle.east;
  19619. // Compute XY extents using the rectangle at maximum height
  19620. perimeterNE.height = perimeterNC.height = perimeterNW.height = perimeterCW.height = perimeterSW.height = perimeterSC.height = perimeterSE.height = perimeterCE.height = maximumHeight;
  19621. ellipsoid.cartographicArrayToCartesianArray(perimeterCartographicScratch, perimeterCartesianScratch);
  19622. tangentPlane.projectPointsToNearestOnPlane(perimeterCartesianScratch, perimeterProjectedScratch);
  19623. // See the `perimeterXX` definitions above for what these are
  19624. var minX = Math.min(perimeterProjectedScratch[6].x, perimeterProjectedScratch[7].x, perimeterProjectedScratch[0].x);
  19625. var maxX = Math.max(perimeterProjectedScratch[2].x, perimeterProjectedScratch[3].x, perimeterProjectedScratch[4].x);
  19626. var minY = Math.min(perimeterProjectedScratch[4].y, perimeterProjectedScratch[5].y, perimeterProjectedScratch[6].y);
  19627. var maxY = Math.max(perimeterProjectedScratch[0].y, perimeterProjectedScratch[1].y, perimeterProjectedScratch[2].y);
  19628. // Compute minimum Z using the rectangle at minimum height
  19629. perimeterNE.height = perimeterNW.height = perimeterSE.height = perimeterSW.height = minimumHeight;
  19630. ellipsoid.cartographicArrayToCartesianArray(perimeterCartographicScratch, perimeterCartesianScratch);
  19631. var minZ = Math.min(Plane.getPointDistance(plane, perimeterCartesianScratch[0]),
  19632. Plane.getPointDistance(plane, perimeterCartesianScratch[2]),
  19633. Plane.getPointDistance(plane, perimeterCartesianScratch[4]),
  19634. Plane.getPointDistance(plane, perimeterCartesianScratch[6]));
  19635. var maxZ = maximumHeight; // Since the tangent plane touches the surface at height = 0, this is okay
  19636. return fromTangentPlaneExtents(tangentPlane, minX, maxX, minY, maxY, minZ, maxZ, result);
  19637. };
  19638. /**
  19639. * Duplicates a OrientedBoundingBox instance.
  19640. *
  19641. * @param {OrientedBoundingBox} box The bounding box to duplicate.
  19642. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  19643. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  19644. */
  19645. OrientedBoundingBox.clone = function(box, result) {
  19646. if (!defined(box)) {
  19647. return undefined;
  19648. }
  19649. if (!defined(result)) {
  19650. return new OrientedBoundingBox(box.center, box.halfAxes);
  19651. }
  19652. Cartesian3.clone(box.center, result.center);
  19653. Matrix3.clone(box.halfAxes, result.halfAxes);
  19654. return result;
  19655. };
  19656. /**
  19657. * Determines which side of a plane the oriented bounding box is located.
  19658. *
  19659. * @param {OrientedBoundingBox} box The oriented bounding box to test.
  19660. * @param {Plane} plane The plane to test against.
  19661. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  19662. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  19663. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  19664. * intersects the plane.
  19665. */
  19666. OrientedBoundingBox.intersectPlane = function(box, plane) {
  19667. if (!defined(box)) {
  19668. throw new DeveloperError('box is required.');
  19669. }
  19670. if (!defined(plane)) {
  19671. throw new DeveloperError('plane is required.');
  19672. }
  19673. var center = box.center;
  19674. var normal = plane.normal;
  19675. var halfAxes = box.halfAxes;
  19676. var normalX = normal.x, normalY = normal.y, normalZ = normal.z;
  19677. // plane is used as if it is its normal; the first three components are assumed to be normalized
  19678. var radEffective = Math.abs(normalX * halfAxes[Matrix3.COLUMN0ROW0] + normalY * halfAxes[Matrix3.COLUMN0ROW1] + normalZ * halfAxes[Matrix3.COLUMN0ROW2]) +
  19679. Math.abs(normalX * halfAxes[Matrix3.COLUMN1ROW0] + normalY * halfAxes[Matrix3.COLUMN1ROW1] + normalZ * halfAxes[Matrix3.COLUMN1ROW2]) +
  19680. Math.abs(normalX * halfAxes[Matrix3.COLUMN2ROW0] + normalY * halfAxes[Matrix3.COLUMN2ROW1] + normalZ * halfAxes[Matrix3.COLUMN2ROW2]);
  19681. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  19682. if (distanceToPlane <= -radEffective) {
  19683. // The entire box is on the negative side of the plane normal
  19684. return Intersect.OUTSIDE;
  19685. } else if (distanceToPlane >= radEffective) {
  19686. // The entire box is on the positive side of the plane normal
  19687. return Intersect.INSIDE;
  19688. }
  19689. return Intersect.INTERSECTING;
  19690. };
  19691. var scratchCartesianU = new Cartesian3();
  19692. var scratchCartesianV = new Cartesian3();
  19693. var scratchCartesianW = new Cartesian3();
  19694. var scratchPPrime = new Cartesian3();
  19695. /**
  19696. * Computes the estimated distance squared from the closest point on a bounding box to a point.
  19697. *
  19698. * @param {OrientedBoundingBox} box The box.
  19699. * @param {Cartesian3} cartesian The point
  19700. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  19701. *
  19702. * @example
  19703. * // Sort bounding boxes from back to front
  19704. * boxes.sort(function(a, b) {
  19705. * return Cesium.OrientedBoundingBox.distanceSquaredTo(b, camera.positionWC) - Cesium.OrientedBoundingBox.distanceSquaredTo(a, camera.positionWC);
  19706. * });
  19707. */
  19708. OrientedBoundingBox.distanceSquaredTo = function(box, cartesian) {
  19709. // See Geometric Tools for Computer Graphics 10.4.2
  19710. if (!defined(box)) {
  19711. throw new DeveloperError('box is required.');
  19712. }
  19713. if (!defined(cartesian)) {
  19714. throw new DeveloperError('cartesian is required.');
  19715. }
  19716. var offset = Cartesian3.subtract(cartesian, box.center, scratchOffset);
  19717. var halfAxes = box.halfAxes;
  19718. var u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
  19719. var v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
  19720. var w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);
  19721. var uHalf = Cartesian3.magnitude(u);
  19722. var vHalf = Cartesian3.magnitude(v);
  19723. var wHalf = Cartesian3.magnitude(w);
  19724. Cartesian3.normalize(u, u);
  19725. Cartesian3.normalize(v, v);
  19726. Cartesian3.normalize(w, w);
  19727. var pPrime = scratchPPrime;
  19728. pPrime.x = Cartesian3.dot(offset, u);
  19729. pPrime.y = Cartesian3.dot(offset, v);
  19730. pPrime.z = Cartesian3.dot(offset, w);
  19731. var distanceSquared = 0.0;
  19732. var d;
  19733. if (pPrime.x < -uHalf) {
  19734. d = pPrime.x + uHalf;
  19735. distanceSquared += d * d;
  19736. } else if (pPrime.x > uHalf) {
  19737. d = pPrime.x - uHalf;
  19738. distanceSquared += d * d;
  19739. }
  19740. if (pPrime.y < -vHalf) {
  19741. d = pPrime.y + vHalf;
  19742. distanceSquared += d * d;
  19743. } else if (pPrime.y > vHalf) {
  19744. d = pPrime.y - vHalf;
  19745. distanceSquared += d * d;
  19746. }
  19747. if (pPrime.z < -wHalf) {
  19748. d = pPrime.z + wHalf;
  19749. distanceSquared += d * d;
  19750. } else if (pPrime.z > wHalf) {
  19751. d = pPrime.z - wHalf;
  19752. distanceSquared += d * d;
  19753. }
  19754. return distanceSquared;
  19755. };
  19756. var scratchCorner = new Cartesian3();
  19757. var scratchToCenter = new Cartesian3();
  19758. /**
  19759. * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
  19760. * <br>
  19761. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  19762. * closest and farthest planes from position that intersect the bounding box.
  19763. *
  19764. * @param {OrientedBoundingBox} box The bounding box to calculate the distance to.
  19765. * @param {Cartesian3} position The position to calculate the distance from.
  19766. * @param {Cartesian3} direction The direction from position.
  19767. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  19768. * @returns {Interval} The nearest and farthest distances on the bounding box from position in direction.
  19769. */
  19770. OrientedBoundingBox.computePlaneDistances = function(box, position, direction, result) {
  19771. if (!defined(box)) {
  19772. throw new DeveloperError('box is required.');
  19773. }
  19774. if (!defined(position)) {
  19775. throw new DeveloperError('position is required.');
  19776. }
  19777. if (!defined(direction)) {
  19778. throw new DeveloperError('direction is required.');
  19779. }
  19780. if (!defined(result)) {
  19781. result = new Interval();
  19782. }
  19783. var minDist = Number.POSITIVE_INFINITY;
  19784. var maxDist = Number.NEGATIVE_INFINITY;
  19785. var center = box.center;
  19786. var halfAxes = box.halfAxes;
  19787. var u = Matrix3.getColumn(halfAxes, 0, scratchCartesianU);
  19788. var v = Matrix3.getColumn(halfAxes, 1, scratchCartesianV);
  19789. var w = Matrix3.getColumn(halfAxes, 2, scratchCartesianW);
  19790. // project first corner
  19791. var corner = Cartesian3.add(u, v, scratchCorner);
  19792. Cartesian3.add(corner, w, corner);
  19793. Cartesian3.add(corner, center, corner);
  19794. var toCenter = Cartesian3.subtract(corner, position, scratchToCenter);
  19795. var mag = Cartesian3.dot(direction, toCenter);
  19796. minDist = Math.min(mag, minDist);
  19797. maxDist = Math.max(mag, maxDist);
  19798. // project second corner
  19799. Cartesian3.add(center, u, corner);
  19800. Cartesian3.add(corner, v, corner);
  19801. Cartesian3.subtract(corner, w, corner);
  19802. Cartesian3.subtract(corner, position, toCenter);
  19803. mag = Cartesian3.dot(direction, toCenter);
  19804. minDist = Math.min(mag, minDist);
  19805. maxDist = Math.max(mag, maxDist);
  19806. // project third corner
  19807. Cartesian3.add(center, u, corner);
  19808. Cartesian3.subtract(corner, v, corner);
  19809. Cartesian3.add(corner, w, corner);
  19810. Cartesian3.subtract(corner, position, toCenter);
  19811. mag = Cartesian3.dot(direction, toCenter);
  19812. minDist = Math.min(mag, minDist);
  19813. maxDist = Math.max(mag, maxDist);
  19814. // project fourth corner
  19815. Cartesian3.add(center, u, corner);
  19816. Cartesian3.subtract(corner, v, corner);
  19817. Cartesian3.subtract(corner, w, corner);
  19818. Cartesian3.subtract(corner, position, toCenter);
  19819. mag = Cartesian3.dot(direction, toCenter);
  19820. minDist = Math.min(mag, minDist);
  19821. maxDist = Math.max(mag, maxDist);
  19822. // project fifth corner
  19823. Cartesian3.subtract(center, u, corner);
  19824. Cartesian3.add(corner, v, corner);
  19825. Cartesian3.add(corner, w, corner);
  19826. Cartesian3.subtract(corner, position, toCenter);
  19827. mag = Cartesian3.dot(direction, toCenter);
  19828. minDist = Math.min(mag, minDist);
  19829. maxDist = Math.max(mag, maxDist);
  19830. // project sixth corner
  19831. Cartesian3.subtract(center, u, corner);
  19832. Cartesian3.add(corner, v, corner);
  19833. Cartesian3.subtract(corner, w, corner);
  19834. Cartesian3.subtract(corner, position, toCenter);
  19835. mag = Cartesian3.dot(direction, toCenter);
  19836. minDist = Math.min(mag, minDist);
  19837. maxDist = Math.max(mag, maxDist);
  19838. // project seventh corner
  19839. Cartesian3.subtract(center, u, corner);
  19840. Cartesian3.subtract(corner, v, corner);
  19841. Cartesian3.add(corner, w, corner);
  19842. Cartesian3.subtract(corner, position, toCenter);
  19843. mag = Cartesian3.dot(direction, toCenter);
  19844. minDist = Math.min(mag, minDist);
  19845. maxDist = Math.max(mag, maxDist);
  19846. // project eighth corner
  19847. Cartesian3.subtract(center, u, corner);
  19848. Cartesian3.subtract(corner, v, corner);
  19849. Cartesian3.subtract(corner, w, corner);
  19850. Cartesian3.subtract(corner, position, toCenter);
  19851. mag = Cartesian3.dot(direction, toCenter);
  19852. minDist = Math.min(mag, minDist);
  19853. maxDist = Math.max(mag, maxDist);
  19854. result.start = minDist;
  19855. result.stop = maxDist;
  19856. return result;
  19857. };
  19858. var scratchBoundingSphere = new BoundingSphere();
  19859. /**
  19860. * Determines whether or not a bounding box is hidden from view by the occluder.
  19861. *
  19862. * @param {OrientedBoundingBox} box The bounding box surrounding the occludee object.
  19863. * @param {Occluder} occluder The occluder.
  19864. * @returns {Boolean} <code>true</code> if the box is not visible; otherwise <code>false</code>.
  19865. */
  19866. OrientedBoundingBox.isOccluded = function(box, occluder) {
  19867. if (!defined(box)) {
  19868. throw new DeveloperError('box is required.');
  19869. }
  19870. if (!defined(occluder)) {
  19871. throw new DeveloperError('occluder is required.');
  19872. }
  19873. var sphere = BoundingSphere.fromOrientedBoundingBox(box, scratchBoundingSphere);
  19874. return !occluder.isBoundingSphereVisible(sphere);
  19875. };
  19876. /**
  19877. * Determines which side of a plane the oriented bounding box is located.
  19878. *
  19879. * @param {Plane} plane The plane to test against.
  19880. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  19881. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  19882. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  19883. * intersects the plane.
  19884. */
  19885. OrientedBoundingBox.prototype.intersectPlane = function(plane) {
  19886. return OrientedBoundingBox.intersectPlane(this, plane);
  19887. };
  19888. /**
  19889. * Computes the estimated distance squared from the closest point on a bounding box to a point.
  19890. *
  19891. * @param {Cartesian3} cartesian The point
  19892. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  19893. *
  19894. * @example
  19895. * // Sort bounding boxes from back to front
  19896. * boxes.sort(function(a, b) {
  19897. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  19898. * });
  19899. */
  19900. OrientedBoundingBox.prototype.distanceSquaredTo = function(cartesian) {
  19901. return OrientedBoundingBox.distanceSquaredTo(this, cartesian);
  19902. };
  19903. /**
  19904. * The distances calculated by the vector from the center of the bounding box to position projected onto direction.
  19905. * <br>
  19906. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  19907. * closest and farthest planes from position that intersect the bounding box.
  19908. *
  19909. * @param {Cartesian3} position The position to calculate the distance from.
  19910. * @param {Cartesian3} direction The direction from position.
  19911. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  19912. * @returns {Interval} The nearest and farthest distances on the bounding box from position in direction.
  19913. */
  19914. OrientedBoundingBox.prototype.computePlaneDistances = function(position, direction, result) {
  19915. return OrientedBoundingBox.computePlaneDistances(this, position, direction, result);
  19916. };
  19917. /**
  19918. * Determines whether or not a bounding box is hidden from view by the occluder.
  19919. *
  19920. * @param {Occluder} occluder The occluder.
  19921. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  19922. */
  19923. OrientedBoundingBox.prototype.isOccluded = function(occluder) {
  19924. return OrientedBoundingBox.isOccluded(this, occluder);
  19925. };
  19926. /**
  19927. * Compares the provided OrientedBoundingBox componentwise and returns
  19928. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19929. *
  19930. * @param {OrientedBoundingBox} left The first OrientedBoundingBox.
  19931. * @param {OrientedBoundingBox} right The second OrientedBoundingBox.
  19932. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  19933. */
  19934. OrientedBoundingBox.equals = function(left, right) {
  19935. return (left === right) ||
  19936. ((defined(left)) &&
  19937. (defined(right)) &&
  19938. Cartesian3.equals(left.center, right.center) &&
  19939. Matrix3.equals(left.halfAxes, right.halfAxes));
  19940. };
  19941. /**
  19942. * Duplicates this OrientedBoundingBox instance.
  19943. *
  19944. * @param {OrientedBoundingBox} [result] The object onto which to store the result.
  19945. * @returns {OrientedBoundingBox} The modified result parameter or a new OrientedBoundingBox instance if one was not provided.
  19946. */
  19947. OrientedBoundingBox.prototype.clone = function(result) {
  19948. return OrientedBoundingBox.clone(this, result);
  19949. };
  19950. /**
  19951. * Compares this OrientedBoundingBox against the provided OrientedBoundingBox componentwise and returns
  19952. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19953. *
  19954. * @param {OrientedBoundingBox} [right] The right hand side OrientedBoundingBox.
  19955. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  19956. */
  19957. OrientedBoundingBox.prototype.equals = function(right) {
  19958. return OrientedBoundingBox.equals(this, right);
  19959. };
  19960. return OrientedBoundingBox;
  19961. });
  19962. /*global define*/
  19963. define('Core/AttributeCompression',[
  19964. './Cartesian2',
  19965. './Cartesian3',
  19966. './defined',
  19967. './DeveloperError',
  19968. './Math'
  19969. ], function(
  19970. Cartesian2,
  19971. Cartesian3,
  19972. defined,
  19973. DeveloperError,
  19974. CesiumMath) {
  19975. 'use strict';
  19976. /**
  19977. * Attribute compression and decompression functions.
  19978. *
  19979. * @exports AttributeCompression
  19980. *
  19981. * @private
  19982. */
  19983. var AttributeCompression = {};
  19984. /**
  19985. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  19986. *
  19987. * Oct encoding is a compact representation of unit length vectors.
  19988. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  19989. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  19990. *
  19991. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  19992. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  19993. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  19994. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  19995. *
  19996. * @exception {DeveloperError} vector must be normalized.
  19997. *
  19998. * @see AttributeCompression.octDecodeInRange
  19999. */
  20000. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  20001. if (!defined(vector)) {
  20002. throw new DeveloperError('vector is required.');
  20003. }
  20004. if (!defined(result)) {
  20005. throw new DeveloperError('result is required.');
  20006. }
  20007. var magSquared = Cartesian3.magnitudeSquared(vector);
  20008. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  20009. throw new DeveloperError('vector must be normalized.');
  20010. }
  20011. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20012. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20013. if (vector.z < 0) {
  20014. var x = result.x;
  20015. var y = result.y;
  20016. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  20017. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  20018. }
  20019. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  20020. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  20021. return result;
  20022. };
  20023. /**
  20024. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  20025. *
  20026. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20027. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  20028. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  20029. *
  20030. * @exception {DeveloperError} vector must be normalized.
  20031. *
  20032. * @see AttributeCompression.octEncodeInRange
  20033. * @see AttributeCompression.octDecode
  20034. */
  20035. AttributeCompression.octEncode = function(vector, result) {
  20036. return AttributeCompression.octEncodeInRange(vector, 255, result);
  20037. };
  20038. /**
  20039. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  20040. *
  20041. * @param {Number} x The x component of the oct-encoded unit length vector.
  20042. * @param {Number} y The y component of the oct-encoded unit length vector.
  20043. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  20044. * @param {Cartesian3} result The decoded and normalized vector
  20045. * @returns {Cartesian3} The decoded and normalized vector.
  20046. *
  20047. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  20048. *
  20049. * @see AttributeCompression.octEncodeInRange
  20050. */
  20051. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  20052. if (!defined(result)) {
  20053. throw new DeveloperError('result is required.');
  20054. }
  20055. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  20056. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  20057. }
  20058. result.x = CesiumMath.fromSNorm(x, rangeMax);
  20059. result.y = CesiumMath.fromSNorm(y, rangeMax);
  20060. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  20061. if (result.z < 0.0)
  20062. {
  20063. var oldVX = result.x;
  20064. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  20065. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  20066. }
  20067. return Cartesian3.normalize(result, result);
  20068. };
  20069. /**
  20070. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  20071. *
  20072. * @param {Number} x The x component of the oct-encoded unit length vector.
  20073. * @param {Number} y The y component of the oct-encoded unit length vector.
  20074. * @param {Cartesian3} result The decoded and normalized vector.
  20075. * @returns {Cartesian3} The decoded and normalized vector.
  20076. *
  20077. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  20078. *
  20079. * @see AttributeCompression.octDecodeInRange
  20080. */
  20081. AttributeCompression.octDecode = function(x, y, result) {
  20082. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  20083. };
  20084. /**
  20085. * Packs an oct encoded vector into a single floating-point number.
  20086. *
  20087. * @param {Cartesian2} encoded The oct encoded vector.
  20088. * @returns {Number} The oct encoded vector packed into a single float.
  20089. *
  20090. */
  20091. AttributeCompression.octPackFloat = function(encoded) {
  20092. if (!defined(encoded)) {
  20093. throw new DeveloperError('encoded is required.');
  20094. }
  20095. return 256.0 * encoded.x + encoded.y;
  20096. };
  20097. var scratchEncodeCart2 = new Cartesian2();
  20098. /**
  20099. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  20100. * stores those values in a single float-point number.
  20101. *
  20102. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20103. * @returns {Number} The 2 byte oct-encoded unit length vector.
  20104. *
  20105. * @exception {DeveloperError} vector must be normalized.
  20106. */
  20107. AttributeCompression.octEncodeFloat = function(vector) {
  20108. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  20109. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  20110. };
  20111. /**
  20112. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  20113. *
  20114. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  20115. * @param {Cartesian3} result The decoded and normalized vector
  20116. * @returns {Cartesian3} The decoded and normalized vector.
  20117. *
  20118. */
  20119. AttributeCompression.octDecodeFloat = function(value, result) {
  20120. if (!defined(value)) {
  20121. throw new DeveloperError('value is required.');
  20122. }
  20123. var temp = value / 256.0;
  20124. var x = Math.floor(temp);
  20125. var y = (temp - x) * 256.0;
  20126. return AttributeCompression.octDecode(x, y, result);
  20127. };
  20128. /**
  20129. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  20130. * packs those into two floating-point numbers.
  20131. *
  20132. * @param {Cartesian3} v1 A normalized vector to be compressed.
  20133. * @param {Cartesian3} v2 A normalized vector to be compressed.
  20134. * @param {Cartesian3} v3 A normalized vector to be compressed.
  20135. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  20136. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  20137. *
  20138. */
  20139. AttributeCompression.octPack = function(v1, v2, v3, result) {
  20140. if (!defined(v1)) {
  20141. throw new DeveloperError('v1 is required.');
  20142. }
  20143. if (!defined(v2)) {
  20144. throw new DeveloperError('v2 is required.');
  20145. }
  20146. if (!defined(v3)) {
  20147. throw new DeveloperError('v3 is required.');
  20148. }
  20149. if (!defined(result)) {
  20150. throw new DeveloperError('result is required.');
  20151. }
  20152. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  20153. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  20154. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  20155. result.x = 65536.0 * encoded3.x + encoded1;
  20156. result.y = 65536.0 * encoded3.y + encoded2;
  20157. return result;
  20158. };
  20159. /**
  20160. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  20161. *
  20162. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  20163. * @param {Cartesian3} v1 One decoded and normalized vector.
  20164. * @param {Cartesian3} v2 One decoded and normalized vector.
  20165. * @param {Cartesian3} v3 One decoded and normalized vector.
  20166. */
  20167. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  20168. if (!defined(packed)) {
  20169. throw new DeveloperError('packed is required.');
  20170. }
  20171. if (!defined(v1)) {
  20172. throw new DeveloperError('v1 is required.');
  20173. }
  20174. if (!defined(v2)) {
  20175. throw new DeveloperError('v2 is required.');
  20176. }
  20177. if (!defined(v3)) {
  20178. throw new DeveloperError('v3 is required.');
  20179. }
  20180. var temp = packed.x / 65536.0;
  20181. var x = Math.floor(temp);
  20182. var encodedFloat1 = (temp - x) * 65536.0;
  20183. temp = packed.y / 65536.0;
  20184. var y = Math.floor(temp);
  20185. var encodedFloat2 = (temp - y) * 65536.0;
  20186. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  20187. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  20188. AttributeCompression.octDecode(x, y, v3);
  20189. };
  20190. /**
  20191. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  20192. *
  20193. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  20194. * @returns {Number} The packed texture coordinates.
  20195. *
  20196. */
  20197. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  20198. if (!defined(textureCoordinates)) {
  20199. throw new DeveloperError('textureCoordinates is required.');
  20200. }
  20201. // Move x and y to the range 0-4095;
  20202. var x = (textureCoordinates.x * 4095.0) | 0;
  20203. var y = (textureCoordinates.y * 4095.0) | 0;
  20204. return 4096.0 * x + y;
  20205. };
  20206. /**
  20207. * Decompresses texture coordinates that were packed into a single float.
  20208. *
  20209. * @param {Number} compressed The compressed texture coordinates.
  20210. * @param {Cartesian2} result The decompressed texture coordinates.
  20211. * @returns {Cartesian2} The modified result parameter.
  20212. *
  20213. */
  20214. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  20215. if (!defined(compressed)) {
  20216. throw new DeveloperError('compressed is required.');
  20217. }
  20218. if (!defined(result)) {
  20219. throw new DeveloperError('result is required.');
  20220. }
  20221. var temp = compressed / 4096.0;
  20222. var xZeroTo4095 = Math.floor(temp);
  20223. result.x = xZeroTo4095 / 4095.0;
  20224. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  20225. return result;
  20226. };
  20227. return AttributeCompression;
  20228. });
  20229. /*global define*/
  20230. define('Core/WebGLConstants',[
  20231. './freezeObject'
  20232. ], function(
  20233. freezeObject) {
  20234. 'use strict';
  20235. /**
  20236. * Enum containing WebGL Constant values by name.
  20237. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  20238. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  20239. *
  20240. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  20241. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  20242. * specifications.
  20243. *
  20244. * @exports WebGLConstants
  20245. */
  20246. var WebGLConstants = {
  20247. DEPTH_BUFFER_BIT : 0x00000100,
  20248. STENCIL_BUFFER_BIT : 0x00000400,
  20249. COLOR_BUFFER_BIT : 0x00004000,
  20250. POINTS : 0x0000,
  20251. LINES : 0x0001,
  20252. LINE_LOOP : 0x0002,
  20253. LINE_STRIP : 0x0003,
  20254. TRIANGLES : 0x0004,
  20255. TRIANGLE_STRIP : 0x0005,
  20256. TRIANGLE_FAN : 0x0006,
  20257. ZERO : 0,
  20258. ONE : 1,
  20259. SRC_COLOR : 0x0300,
  20260. ONE_MINUS_SRC_COLOR : 0x0301,
  20261. SRC_ALPHA : 0x0302,
  20262. ONE_MINUS_SRC_ALPHA : 0x0303,
  20263. DST_ALPHA : 0x0304,
  20264. ONE_MINUS_DST_ALPHA : 0x0305,
  20265. DST_COLOR : 0x0306,
  20266. ONE_MINUS_DST_COLOR : 0x0307,
  20267. SRC_ALPHA_SATURATE : 0x0308,
  20268. FUNC_ADD : 0x8006,
  20269. BLEND_EQUATION : 0x8009,
  20270. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  20271. BLEND_EQUATION_ALPHA : 0x883D,
  20272. FUNC_SUBTRACT : 0x800A,
  20273. FUNC_REVERSE_SUBTRACT : 0x800B,
  20274. BLEND_DST_RGB : 0x80C8,
  20275. BLEND_SRC_RGB : 0x80C9,
  20276. BLEND_DST_ALPHA : 0x80CA,
  20277. BLEND_SRC_ALPHA : 0x80CB,
  20278. CONSTANT_COLOR : 0x8001,
  20279. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  20280. CONSTANT_ALPHA : 0x8003,
  20281. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  20282. BLEND_COLOR : 0x8005,
  20283. ARRAY_BUFFER : 0x8892,
  20284. ELEMENT_ARRAY_BUFFER : 0x8893,
  20285. ARRAY_BUFFER_BINDING : 0x8894,
  20286. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  20287. STREAM_DRAW : 0x88E0,
  20288. STATIC_DRAW : 0x88E4,
  20289. DYNAMIC_DRAW : 0x88E8,
  20290. BUFFER_SIZE : 0x8764,
  20291. BUFFER_USAGE : 0x8765,
  20292. CURRENT_VERTEX_ATTRIB : 0x8626,
  20293. FRONT : 0x0404,
  20294. BACK : 0x0405,
  20295. FRONT_AND_BACK : 0x0408,
  20296. CULL_FACE : 0x0B44,
  20297. BLEND : 0x0BE2,
  20298. DITHER : 0x0BD0,
  20299. STENCIL_TEST : 0x0B90,
  20300. DEPTH_TEST : 0x0B71,
  20301. SCISSOR_TEST : 0x0C11,
  20302. POLYGON_OFFSET_FILL : 0x8037,
  20303. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  20304. SAMPLE_COVERAGE : 0x80A0,
  20305. NO_ERROR : 0,
  20306. INVALID_ENUM : 0x0500,
  20307. INVALID_VALUE : 0x0501,
  20308. INVALID_OPERATION : 0x0502,
  20309. OUT_OF_MEMORY : 0x0505,
  20310. CW : 0x0900,
  20311. CCW : 0x0901,
  20312. LINE_WIDTH : 0x0B21,
  20313. ALIASED_POINT_SIZE_RANGE : 0x846D,
  20314. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  20315. CULL_FACE_MODE : 0x0B45,
  20316. FRONT_FACE : 0x0B46,
  20317. DEPTH_RANGE : 0x0B70,
  20318. DEPTH_WRITEMASK : 0x0B72,
  20319. DEPTH_CLEAR_VALUE : 0x0B73,
  20320. DEPTH_FUNC : 0x0B74,
  20321. STENCIL_CLEAR_VALUE : 0x0B91,
  20322. STENCIL_FUNC : 0x0B92,
  20323. STENCIL_FAIL : 0x0B94,
  20324. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  20325. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  20326. STENCIL_REF : 0x0B97,
  20327. STENCIL_VALUE_MASK : 0x0B93,
  20328. STENCIL_WRITEMASK : 0x0B98,
  20329. STENCIL_BACK_FUNC : 0x8800,
  20330. STENCIL_BACK_FAIL : 0x8801,
  20331. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  20332. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  20333. STENCIL_BACK_REF : 0x8CA3,
  20334. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  20335. STENCIL_BACK_WRITEMASK : 0x8CA5,
  20336. VIEWPORT : 0x0BA2,
  20337. SCISSOR_BOX : 0x0C10,
  20338. COLOR_CLEAR_VALUE : 0x0C22,
  20339. COLOR_WRITEMASK : 0x0C23,
  20340. UNPACK_ALIGNMENT : 0x0CF5,
  20341. PACK_ALIGNMENT : 0x0D05,
  20342. MAX_TEXTURE_SIZE : 0x0D33,
  20343. MAX_VIEWPORT_DIMS : 0x0D3A,
  20344. SUBPIXEL_BITS : 0x0D50,
  20345. RED_BITS : 0x0D52,
  20346. GREEN_BITS : 0x0D53,
  20347. BLUE_BITS : 0x0D54,
  20348. ALPHA_BITS : 0x0D55,
  20349. DEPTH_BITS : 0x0D56,
  20350. STENCIL_BITS : 0x0D57,
  20351. POLYGON_OFFSET_UNITS : 0x2A00,
  20352. POLYGON_OFFSET_FACTOR : 0x8038,
  20353. TEXTURE_BINDING_2D : 0x8069,
  20354. SAMPLE_BUFFERS : 0x80A8,
  20355. SAMPLES : 0x80A9,
  20356. SAMPLE_COVERAGE_VALUE : 0x80AA,
  20357. SAMPLE_COVERAGE_INVERT : 0x80AB,
  20358. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  20359. DONT_CARE : 0x1100,
  20360. FASTEST : 0x1101,
  20361. NICEST : 0x1102,
  20362. GENERATE_MIPMAP_HINT : 0x8192,
  20363. BYTE : 0x1400,
  20364. UNSIGNED_BYTE : 0x1401,
  20365. SHORT : 0x1402,
  20366. UNSIGNED_SHORT : 0x1403,
  20367. INT : 0x1404,
  20368. UNSIGNED_INT : 0x1405,
  20369. FLOAT : 0x1406,
  20370. DEPTH_COMPONENT : 0x1902,
  20371. ALPHA : 0x1906,
  20372. RGB : 0x1907,
  20373. RGBA : 0x1908,
  20374. LUMINANCE : 0x1909,
  20375. LUMINANCE_ALPHA : 0x190A,
  20376. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  20377. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  20378. UNSIGNED_SHORT_5_6_5 : 0x8363,
  20379. FRAGMENT_SHADER : 0x8B30,
  20380. VERTEX_SHADER : 0x8B31,
  20381. MAX_VERTEX_ATTRIBS : 0x8869,
  20382. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  20383. MAX_VARYING_VECTORS : 0x8DFC,
  20384. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  20385. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  20386. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  20387. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  20388. SHADER_TYPE : 0x8B4F,
  20389. DELETE_STATUS : 0x8B80,
  20390. LINK_STATUS : 0x8B82,
  20391. VALIDATE_STATUS : 0x8B83,
  20392. ATTACHED_SHADERS : 0x8B85,
  20393. ACTIVE_UNIFORMS : 0x8B86,
  20394. ACTIVE_ATTRIBUTES : 0x8B89,
  20395. SHADING_LANGUAGE_VERSION : 0x8B8C,
  20396. CURRENT_PROGRAM : 0x8B8D,
  20397. NEVER : 0x0200,
  20398. LESS : 0x0201,
  20399. EQUAL : 0x0202,
  20400. LEQUAL : 0x0203,
  20401. GREATER : 0x0204,
  20402. NOTEQUAL : 0x0205,
  20403. GEQUAL : 0x0206,
  20404. ALWAYS : 0x0207,
  20405. KEEP : 0x1E00,
  20406. REPLACE : 0x1E01,
  20407. INCR : 0x1E02,
  20408. DECR : 0x1E03,
  20409. INVERT : 0x150A,
  20410. INCR_WRAP : 0x8507,
  20411. DECR_WRAP : 0x8508,
  20412. VENDOR : 0x1F00,
  20413. RENDERER : 0x1F01,
  20414. VERSION : 0x1F02,
  20415. NEAREST : 0x2600,
  20416. LINEAR : 0x2601,
  20417. NEAREST_MIPMAP_NEAREST : 0x2700,
  20418. LINEAR_MIPMAP_NEAREST : 0x2701,
  20419. NEAREST_MIPMAP_LINEAR : 0x2702,
  20420. LINEAR_MIPMAP_LINEAR : 0x2703,
  20421. TEXTURE_MAG_FILTER : 0x2800,
  20422. TEXTURE_MIN_FILTER : 0x2801,
  20423. TEXTURE_WRAP_S : 0x2802,
  20424. TEXTURE_WRAP_T : 0x2803,
  20425. TEXTURE_2D : 0x0DE1,
  20426. TEXTURE : 0x1702,
  20427. TEXTURE_CUBE_MAP : 0x8513,
  20428. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  20429. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  20430. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  20431. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  20432. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  20433. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  20434. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  20435. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  20436. TEXTURE0 : 0x84C0,
  20437. TEXTURE1 : 0x84C1,
  20438. TEXTURE2 : 0x84C2,
  20439. TEXTURE3 : 0x84C3,
  20440. TEXTURE4 : 0x84C4,
  20441. TEXTURE5 : 0x84C5,
  20442. TEXTURE6 : 0x84C6,
  20443. TEXTURE7 : 0x84C7,
  20444. TEXTURE8 : 0x84C8,
  20445. TEXTURE9 : 0x84C9,
  20446. TEXTURE10 : 0x84CA,
  20447. TEXTURE11 : 0x84CB,
  20448. TEXTURE12 : 0x84CC,
  20449. TEXTURE13 : 0x84CD,
  20450. TEXTURE14 : 0x84CE,
  20451. TEXTURE15 : 0x84CF,
  20452. TEXTURE16 : 0x84D0,
  20453. TEXTURE17 : 0x84D1,
  20454. TEXTURE18 : 0x84D2,
  20455. TEXTURE19 : 0x84D3,
  20456. TEXTURE20 : 0x84D4,
  20457. TEXTURE21 : 0x84D5,
  20458. TEXTURE22 : 0x84D6,
  20459. TEXTURE23 : 0x84D7,
  20460. TEXTURE24 : 0x84D8,
  20461. TEXTURE25 : 0x84D9,
  20462. TEXTURE26 : 0x84DA,
  20463. TEXTURE27 : 0x84DB,
  20464. TEXTURE28 : 0x84DC,
  20465. TEXTURE29 : 0x84DD,
  20466. TEXTURE30 : 0x84DE,
  20467. TEXTURE31 : 0x84DF,
  20468. ACTIVE_TEXTURE : 0x84E0,
  20469. REPEAT : 0x2901,
  20470. CLAMP_TO_EDGE : 0x812F,
  20471. MIRRORED_REPEAT : 0x8370,
  20472. FLOAT_VEC2 : 0x8B50,
  20473. FLOAT_VEC3 : 0x8B51,
  20474. FLOAT_VEC4 : 0x8B52,
  20475. INT_VEC2 : 0x8B53,
  20476. INT_VEC3 : 0x8B54,
  20477. INT_VEC4 : 0x8B55,
  20478. BOOL : 0x8B56,
  20479. BOOL_VEC2 : 0x8B57,
  20480. BOOL_VEC3 : 0x8B58,
  20481. BOOL_VEC4 : 0x8B59,
  20482. FLOAT_MAT2 : 0x8B5A,
  20483. FLOAT_MAT3 : 0x8B5B,
  20484. FLOAT_MAT4 : 0x8B5C,
  20485. SAMPLER_2D : 0x8B5E,
  20486. SAMPLER_CUBE : 0x8B60,
  20487. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  20488. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  20489. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  20490. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  20491. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  20492. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  20493. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  20494. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  20495. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  20496. COMPILE_STATUS : 0x8B81,
  20497. LOW_FLOAT : 0x8DF0,
  20498. MEDIUM_FLOAT : 0x8DF1,
  20499. HIGH_FLOAT : 0x8DF2,
  20500. LOW_INT : 0x8DF3,
  20501. MEDIUM_INT : 0x8DF4,
  20502. HIGH_INT : 0x8DF5,
  20503. FRAMEBUFFER : 0x8D40,
  20504. RENDERBUFFER : 0x8D41,
  20505. RGBA4 : 0x8056,
  20506. RGB5_A1 : 0x8057,
  20507. RGB565 : 0x8D62,
  20508. DEPTH_COMPONENT16 : 0x81A5,
  20509. STENCIL_INDEX : 0x1901,
  20510. STENCIL_INDEX8 : 0x8D48,
  20511. DEPTH_STENCIL : 0x84F9,
  20512. RENDERBUFFER_WIDTH : 0x8D42,
  20513. RENDERBUFFER_HEIGHT : 0x8D43,
  20514. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  20515. RENDERBUFFER_RED_SIZE : 0x8D50,
  20516. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  20517. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  20518. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  20519. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  20520. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  20521. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  20522. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  20523. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  20524. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  20525. COLOR_ATTACHMENT0 : 0x8CE0,
  20526. DEPTH_ATTACHMENT : 0x8D00,
  20527. STENCIL_ATTACHMENT : 0x8D20,
  20528. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  20529. NONE : 0,
  20530. FRAMEBUFFER_COMPLETE : 0x8CD5,
  20531. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  20532. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  20533. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  20534. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  20535. FRAMEBUFFER_BINDING : 0x8CA6,
  20536. RENDERBUFFER_BINDING : 0x8CA7,
  20537. MAX_RENDERBUFFER_SIZE : 0x84E8,
  20538. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  20539. UNPACK_FLIP_Y_WEBGL : 0x9240,
  20540. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  20541. CONTEXT_LOST_WEBGL : 0x9242,
  20542. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  20543. BROWSER_DEFAULT_WEBGL : 0x9244,
  20544. // Desktop OpenGL
  20545. DOUBLE : 0x140A,
  20546. // WebGL 2
  20547. READ_BUFFER : 0x0C02,
  20548. UNPACK_ROW_LENGTH : 0x0CF2,
  20549. UNPACK_SKIP_ROWS : 0x0CF3,
  20550. UNPACK_SKIP_PIXELS : 0x0CF4,
  20551. PACK_ROW_LENGTH : 0x0D02,
  20552. PACK_SKIP_ROWS : 0x0D03,
  20553. PACK_SKIP_PIXELS : 0x0D04,
  20554. COLOR : 0x1800,
  20555. DEPTH : 0x1801,
  20556. STENCIL : 0x1802,
  20557. RED : 0x1903,
  20558. RGB8 : 0x8051,
  20559. RGBA8 : 0x8058,
  20560. RGB10_A2 : 0x8059,
  20561. TEXTURE_BINDING_3D : 0x806A,
  20562. UNPACK_SKIP_IMAGES : 0x806D,
  20563. UNPACK_IMAGE_HEIGHT : 0x806E,
  20564. TEXTURE_3D : 0x806F,
  20565. TEXTURE_WRAP_R : 0x8072,
  20566. MAX_3D_TEXTURE_SIZE : 0x8073,
  20567. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  20568. MAX_ELEMENTS_VERTICES : 0x80E8,
  20569. MAX_ELEMENTS_INDICES : 0x80E9,
  20570. TEXTURE_MIN_LOD : 0x813A,
  20571. TEXTURE_MAX_LOD : 0x813B,
  20572. TEXTURE_BASE_LEVEL : 0x813C,
  20573. TEXTURE_MAX_LEVEL : 0x813D,
  20574. MIN : 0x8007,
  20575. MAX : 0x8008,
  20576. DEPTH_COMPONENT24 : 0x81A6,
  20577. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  20578. TEXTURE_COMPARE_MODE : 0x884C,
  20579. TEXTURE_COMPARE_FUNC : 0x884D,
  20580. CURRENT_QUERY : 0x8865,
  20581. QUERY_RESULT : 0x8866,
  20582. QUERY_RESULT_AVAILABLE : 0x8867,
  20583. STREAM_READ : 0x88E1,
  20584. STREAM_COPY : 0x88E2,
  20585. STATIC_READ : 0x88E5,
  20586. STATIC_COPY : 0x88E6,
  20587. DYNAMIC_READ : 0x88E9,
  20588. DYNAMIC_COPY : 0x88EA,
  20589. MAX_DRAW_BUFFERS : 0x8824,
  20590. DRAW_BUFFER0 : 0x8825,
  20591. DRAW_BUFFER1 : 0x8826,
  20592. DRAW_BUFFER2 : 0x8827,
  20593. DRAW_BUFFER3 : 0x8828,
  20594. DRAW_BUFFER4 : 0x8829,
  20595. DRAW_BUFFER5 : 0x882A,
  20596. DRAW_BUFFER6 : 0x882B,
  20597. DRAW_BUFFER7 : 0x882C,
  20598. DRAW_BUFFER8 : 0x882D,
  20599. DRAW_BUFFER9 : 0x882E,
  20600. DRAW_BUFFER10 : 0x882F,
  20601. DRAW_BUFFER11 : 0x8830,
  20602. DRAW_BUFFER12 : 0x8831,
  20603. DRAW_BUFFER13 : 0x8832,
  20604. DRAW_BUFFER14 : 0x8833,
  20605. DRAW_BUFFER15 : 0x8834,
  20606. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  20607. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  20608. SAMPLER_3D : 0x8B5F,
  20609. SAMPLER_2D_SHADOW : 0x8B62,
  20610. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  20611. PIXEL_PACK_BUFFER : 0x88EB,
  20612. PIXEL_UNPACK_BUFFER : 0x88EC,
  20613. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  20614. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  20615. FLOAT_MAT2x3 : 0x8B65,
  20616. FLOAT_MAT2x4 : 0x8B66,
  20617. FLOAT_MAT3x2 : 0x8B67,
  20618. FLOAT_MAT3x4 : 0x8B68,
  20619. FLOAT_MAT4x2 : 0x8B69,
  20620. FLOAT_MAT4x3 : 0x8B6A,
  20621. SRGB : 0x8C40,
  20622. SRGB8 : 0x8C41,
  20623. SRGB8_ALPHA8 : 0x8C43,
  20624. COMPARE_REF_TO_TEXTURE : 0x884E,
  20625. RGBA32F : 0x8814,
  20626. RGB32F : 0x8815,
  20627. RGBA16F : 0x881A,
  20628. RGB16F : 0x881B,
  20629. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  20630. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  20631. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  20632. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  20633. MAX_VARYING_COMPONENTS : 0x8B4B,
  20634. TEXTURE_2D_ARRAY : 0x8C1A,
  20635. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  20636. R11F_G11F_B10F : 0x8C3A,
  20637. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  20638. RGB9_E5 : 0x8C3D,
  20639. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  20640. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  20641. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  20642. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  20643. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  20644. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  20645. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  20646. RASTERIZER_DISCARD : 0x8C89,
  20647. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  20648. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  20649. INTERLEAVED_ATTRIBS : 0x8C8C,
  20650. SEPARATE_ATTRIBS : 0x8C8D,
  20651. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  20652. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  20653. RGBA32UI : 0x8D70,
  20654. RGB32UI : 0x8D71,
  20655. RGBA16UI : 0x8D76,
  20656. RGB16UI : 0x8D77,
  20657. RGBA8UI : 0x8D7C,
  20658. RGB8UI : 0x8D7D,
  20659. RGBA32I : 0x8D82,
  20660. RGB32I : 0x8D83,
  20661. RGBA16I : 0x8D88,
  20662. RGB16I : 0x8D89,
  20663. RGBA8I : 0x8D8E,
  20664. RGB8I : 0x8D8F,
  20665. RED_INTEGER : 0x8D94,
  20666. RGB_INTEGER : 0x8D98,
  20667. RGBA_INTEGER : 0x8D99,
  20668. SAMPLER_2D_ARRAY : 0x8DC1,
  20669. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  20670. SAMPLER_CUBE_SHADOW : 0x8DC5,
  20671. UNSIGNED_INT_VEC2 : 0x8DC6,
  20672. UNSIGNED_INT_VEC3 : 0x8DC7,
  20673. UNSIGNED_INT_VEC4 : 0x8DC8,
  20674. INT_SAMPLER_2D : 0x8DCA,
  20675. INT_SAMPLER_3D : 0x8DCB,
  20676. INT_SAMPLER_CUBE : 0x8DCC,
  20677. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  20678. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  20679. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  20680. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  20681. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  20682. DEPTH_COMPONENT32F : 0x8CAC,
  20683. DEPTH32F_STENCIL8 : 0x8CAD,
  20684. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  20685. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  20686. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  20687. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  20688. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  20689. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  20690. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  20691. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  20692. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  20693. FRAMEBUFFER_DEFAULT : 0x8218,
  20694. UNSIGNED_INT_24_8 : 0x84FA,
  20695. DEPTH24_STENCIL8 : 0x88F0,
  20696. UNSIGNED_NORMALIZED : 0x8C17,
  20697. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  20698. READ_FRAMEBUFFER : 0x8CA8,
  20699. DRAW_FRAMEBUFFER : 0x8CA9,
  20700. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  20701. RENDERBUFFER_SAMPLES : 0x8CAB,
  20702. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  20703. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  20704. COLOR_ATTACHMENT1 : 0x8CE1,
  20705. COLOR_ATTACHMENT2 : 0x8CE2,
  20706. COLOR_ATTACHMENT3 : 0x8CE3,
  20707. COLOR_ATTACHMENT4 : 0x8CE4,
  20708. COLOR_ATTACHMENT5 : 0x8CE5,
  20709. COLOR_ATTACHMENT6 : 0x8CE6,
  20710. COLOR_ATTACHMENT7 : 0x8CE7,
  20711. COLOR_ATTACHMENT8 : 0x8CE8,
  20712. COLOR_ATTACHMENT9 : 0x8CE9,
  20713. COLOR_ATTACHMENT10 : 0x8CEA,
  20714. COLOR_ATTACHMENT11 : 0x8CEB,
  20715. COLOR_ATTACHMENT12 : 0x8CEC,
  20716. COLOR_ATTACHMENT13 : 0x8CED,
  20717. COLOR_ATTACHMENT14 : 0x8CEE,
  20718. COLOR_ATTACHMENT15 : 0x8CEF,
  20719. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  20720. MAX_SAMPLES : 0x8D57,
  20721. HALF_FLOAT : 0x140B,
  20722. RG : 0x8227,
  20723. RG_INTEGER : 0x8228,
  20724. R8 : 0x8229,
  20725. RG8 : 0x822B,
  20726. R16F : 0x822D,
  20727. R32F : 0x822E,
  20728. RG16F : 0x822F,
  20729. RG32F : 0x8230,
  20730. R8I : 0x8231,
  20731. R8UI : 0x8232,
  20732. R16I : 0x8233,
  20733. R16UI : 0x8234,
  20734. R32I : 0x8235,
  20735. R32UI : 0x8236,
  20736. RG8I : 0x8237,
  20737. RG8UI : 0x8238,
  20738. RG16I : 0x8239,
  20739. RG16UI : 0x823A,
  20740. RG32I : 0x823B,
  20741. RG32UI : 0x823C,
  20742. VERTEX_ARRAY_BINDING : 0x85B5,
  20743. R8_SNORM : 0x8F94,
  20744. RG8_SNORM : 0x8F95,
  20745. RGB8_SNORM : 0x8F96,
  20746. RGBA8_SNORM : 0x8F97,
  20747. SIGNED_NORMALIZED : 0x8F9C,
  20748. COPY_READ_BUFFER : 0x8F36,
  20749. COPY_WRITE_BUFFER : 0x8F37,
  20750. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  20751. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  20752. UNIFORM_BUFFER : 0x8A11,
  20753. UNIFORM_BUFFER_BINDING : 0x8A28,
  20754. UNIFORM_BUFFER_START : 0x8A29,
  20755. UNIFORM_BUFFER_SIZE : 0x8A2A,
  20756. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  20757. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  20758. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  20759. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  20760. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  20761. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  20762. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  20763. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  20764. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  20765. UNIFORM_TYPE : 0x8A37,
  20766. UNIFORM_SIZE : 0x8A38,
  20767. UNIFORM_BLOCK_INDEX : 0x8A3A,
  20768. UNIFORM_OFFSET : 0x8A3B,
  20769. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  20770. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  20771. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  20772. UNIFORM_BLOCK_BINDING : 0x8A3F,
  20773. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  20774. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  20775. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  20776. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  20777. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  20778. INVALID_INDEX : 0xFFFFFFFF,
  20779. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  20780. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  20781. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  20782. OBJECT_TYPE : 0x9112,
  20783. SYNC_CONDITION : 0x9113,
  20784. SYNC_STATUS : 0x9114,
  20785. SYNC_FLAGS : 0x9115,
  20786. SYNC_FENCE : 0x9116,
  20787. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  20788. UNSIGNALED : 0x9118,
  20789. SIGNALED : 0x9119,
  20790. ALREADY_SIGNALED : 0x911A,
  20791. TIMEOUT_EXPIRED : 0x911B,
  20792. CONDITION_SATISFIED : 0x911C,
  20793. WAIT_FAILED : 0x911D,
  20794. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  20795. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  20796. ANY_SAMPLES_PASSED : 0x8C2F,
  20797. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  20798. SAMPLER_BINDING : 0x8919,
  20799. RGB10_A2UI : 0x906F,
  20800. INT_2_10_10_10_REV : 0x8D9F,
  20801. TRANSFORM_FEEDBACK : 0x8E22,
  20802. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  20803. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  20804. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  20805. COMPRESSED_R11_EAC : 0x9270,
  20806. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  20807. COMPRESSED_RG11_EAC : 0x9272,
  20808. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  20809. COMPRESSED_RGB8_ETC2 : 0x9274,
  20810. COMPRESSED_SRGB8_ETC2 : 0x9275,
  20811. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  20812. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  20813. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  20814. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  20815. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  20816. MAX_ELEMENT_INDEX : 0x8D6B,
  20817. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  20818. };
  20819. return freezeObject(WebGLConstants);
  20820. });
  20821. /*global define*/
  20822. define('Core/ComponentDatatype',[
  20823. './defaultValue',
  20824. './defined',
  20825. './DeveloperError',
  20826. './FeatureDetection',
  20827. './freezeObject',
  20828. './WebGLConstants'
  20829. ], function(
  20830. defaultValue,
  20831. defined,
  20832. DeveloperError,
  20833. FeatureDetection,
  20834. freezeObject,
  20835. WebGLConstants) {
  20836. 'use strict';
  20837. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  20838. // from failing, since we won't be able to create a WebGL context anyway.
  20839. if (!FeatureDetection.supportsTypedArrays()) {
  20840. return {};
  20841. }
  20842. /**
  20843. * WebGL component datatypes. Components are intrinsics,
  20844. * which form attributes, which form vertices.
  20845. *
  20846. * @exports ComponentDatatype
  20847. */
  20848. var ComponentDatatype = {
  20849. /**
  20850. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  20851. * of an element in <code>Int8Array</code>.
  20852. *
  20853. * @type {Number}
  20854. * @constant
  20855. */
  20856. BYTE : WebGLConstants.BYTE,
  20857. /**
  20858. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  20859. * of an element in <code>Uint8Array</code>.
  20860. *
  20861. * @type {Number}
  20862. * @constant
  20863. */
  20864. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  20865. /**
  20866. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  20867. * of an element in <code>Int16Array</code>.
  20868. *
  20869. * @type {Number}
  20870. * @constant
  20871. */
  20872. SHORT : WebGLConstants.SHORT,
  20873. /**
  20874. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  20875. * of an element in <code>Uint16Array</code>.
  20876. *
  20877. * @type {Number}
  20878. * @constant
  20879. */
  20880. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  20881. /**
  20882. * 32-bit signed int corresponding to <code>INT</code> and the type
  20883. * of an element in <code>Int32Array</code>.
  20884. *
  20885. * @memberOf ComponentDatatype
  20886. *
  20887. * @type {Number}
  20888. * @constant
  20889. */
  20890. INT : WebGLConstants.INT,
  20891. /**
  20892. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  20893. * of an element in <code>Uint32Array</code>.
  20894. *
  20895. * @memberOf ComponentDatatype
  20896. *
  20897. * @type {Number}
  20898. * @constant
  20899. */
  20900. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  20901. /**
  20902. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  20903. * of an element in <code>Float32Array</code>.
  20904. *
  20905. * @type {Number}
  20906. * @constant
  20907. */
  20908. FLOAT : WebGLConstants.FLOAT,
  20909. /**
  20910. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  20911. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  20912. * and the type of an element in <code>Float64Array</code>.
  20913. *
  20914. * @memberOf ComponentDatatype
  20915. *
  20916. * @type {Number}
  20917. * @constant
  20918. * @default 0x140A
  20919. */
  20920. DOUBLE : WebGLConstants.DOUBLE
  20921. };
  20922. /**
  20923. * Returns the size, in bytes, of the corresponding datatype.
  20924. *
  20925. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  20926. * @returns {Number} The size in bytes.
  20927. *
  20928. * @exception {DeveloperError} componentDatatype is not a valid value.
  20929. *
  20930. * @example
  20931. * // Returns Int8Array.BYTES_PER_ELEMENT
  20932. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  20933. */
  20934. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  20935. if (!defined(componentDatatype)) {
  20936. throw new DeveloperError('value is required.');
  20937. }
  20938. switch (componentDatatype) {
  20939. case ComponentDatatype.BYTE:
  20940. return Int8Array.BYTES_PER_ELEMENT;
  20941. case ComponentDatatype.UNSIGNED_BYTE:
  20942. return Uint8Array.BYTES_PER_ELEMENT;
  20943. case ComponentDatatype.SHORT:
  20944. return Int16Array.BYTES_PER_ELEMENT;
  20945. case ComponentDatatype.UNSIGNED_SHORT:
  20946. return Uint16Array.BYTES_PER_ELEMENT;
  20947. case ComponentDatatype.INT:
  20948. return Int32Array.BYTES_PER_ELEMENT;
  20949. case ComponentDatatype.UNSIGNED_INT:
  20950. return Uint32Array.BYTES_PER_ELEMENT;
  20951. case ComponentDatatype.FLOAT:
  20952. return Float32Array.BYTES_PER_ELEMENT;
  20953. case ComponentDatatype.DOUBLE:
  20954. return Float64Array.BYTES_PER_ELEMENT;
  20955. default:
  20956. throw new DeveloperError('componentDatatype is not a valid value.');
  20957. }
  20958. };
  20959. /**
  20960. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  20961. *
  20962. * @param {TypedArray} array The typed array.
  20963. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  20964. */
  20965. ComponentDatatype.fromTypedArray = function(array) {
  20966. if (array instanceof Int8Array) {
  20967. return ComponentDatatype.BYTE;
  20968. }
  20969. if (array instanceof Uint8Array) {
  20970. return ComponentDatatype.UNSIGNED_BYTE;
  20971. }
  20972. if (array instanceof Int16Array) {
  20973. return ComponentDatatype.SHORT;
  20974. }
  20975. if (array instanceof Uint16Array) {
  20976. return ComponentDatatype.UNSIGNED_SHORT;
  20977. }
  20978. if (array instanceof Int32Array) {
  20979. return ComponentDatatype.INT;
  20980. }
  20981. if (array instanceof Uint32Array) {
  20982. return ComponentDatatype.UNSIGNED_INT;
  20983. }
  20984. if (array instanceof Float32Array) {
  20985. return ComponentDatatype.FLOAT;
  20986. }
  20987. if (array instanceof Float64Array) {
  20988. return ComponentDatatype.DOUBLE;
  20989. }
  20990. };
  20991. /**
  20992. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  20993. *
  20994. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  20995. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  20996. *
  20997. * @example
  20998. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  20999. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  21000. * }
  21001. */
  21002. ComponentDatatype.validate = function(componentDatatype) {
  21003. return defined(componentDatatype) &&
  21004. (componentDatatype === ComponentDatatype.BYTE ||
  21005. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  21006. componentDatatype === ComponentDatatype.SHORT ||
  21007. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  21008. componentDatatype === ComponentDatatype.INT ||
  21009. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  21010. componentDatatype === ComponentDatatype.FLOAT ||
  21011. componentDatatype === ComponentDatatype.DOUBLE);
  21012. };
  21013. /**
  21014. * Creates a typed array corresponding to component data type.
  21015. *
  21016. * @param {ComponentDatatype} componentDatatype The component data type.
  21017. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  21018. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  21019. *
  21020. * @exception {DeveloperError} componentDatatype is not a valid value.
  21021. *
  21022. * @example
  21023. * // creates a Float32Array with length of 100
  21024. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  21025. */
  21026. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  21027. if (!defined(componentDatatype)) {
  21028. throw new DeveloperError('componentDatatype is required.');
  21029. }
  21030. if (!defined(valuesOrLength)) {
  21031. throw new DeveloperError('valuesOrLength is required.');
  21032. }
  21033. switch (componentDatatype) {
  21034. case ComponentDatatype.BYTE:
  21035. return new Int8Array(valuesOrLength);
  21036. case ComponentDatatype.UNSIGNED_BYTE:
  21037. return new Uint8Array(valuesOrLength);
  21038. case ComponentDatatype.SHORT:
  21039. return new Int16Array(valuesOrLength);
  21040. case ComponentDatatype.UNSIGNED_SHORT:
  21041. return new Uint16Array(valuesOrLength);
  21042. case ComponentDatatype.INT:
  21043. return new Int32Array(valuesOrLength);
  21044. case ComponentDatatype.UNSIGNED_INT:
  21045. return new Uint32Array(valuesOrLength);
  21046. case ComponentDatatype.FLOAT:
  21047. return new Float32Array(valuesOrLength);
  21048. case ComponentDatatype.DOUBLE:
  21049. return new Float64Array(valuesOrLength);
  21050. default:
  21051. throw new DeveloperError('componentDatatype is not a valid value.');
  21052. }
  21053. };
  21054. /**
  21055. * Creates a typed view of an array of bytes.
  21056. *
  21057. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  21058. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  21059. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  21060. * @param {Number} [length] The number of elements in the view.
  21061. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  21062. *
  21063. * @exception {DeveloperError} componentDatatype is not a valid value.
  21064. */
  21065. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  21066. if (!defined(componentDatatype)) {
  21067. throw new DeveloperError('componentDatatype is required.');
  21068. }
  21069. if (!defined(buffer)) {
  21070. throw new DeveloperError('buffer is required.');
  21071. }
  21072. byteOffset = defaultValue(byteOffset, 0);
  21073. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  21074. switch (componentDatatype) {
  21075. case ComponentDatatype.BYTE:
  21076. return new Int8Array(buffer, byteOffset, length);
  21077. case ComponentDatatype.UNSIGNED_BYTE:
  21078. return new Uint8Array(buffer, byteOffset, length);
  21079. case ComponentDatatype.SHORT:
  21080. return new Int16Array(buffer, byteOffset, length);
  21081. case ComponentDatatype.UNSIGNED_SHORT:
  21082. return new Uint16Array(buffer, byteOffset, length);
  21083. case ComponentDatatype.INT:
  21084. return new Int32Array(buffer, byteOffset, length);
  21085. case ComponentDatatype.UNSIGNED_INT:
  21086. return new Uint32Array(buffer, byteOffset, length);
  21087. case ComponentDatatype.FLOAT:
  21088. return new Float32Array(buffer, byteOffset, length);
  21089. case ComponentDatatype.DOUBLE:
  21090. return new Float64Array(buffer, byteOffset, length);
  21091. default:
  21092. throw new DeveloperError('componentDatatype is not a valid value.');
  21093. }
  21094. };
  21095. /**
  21096. * Get the ComponentDatatype from its name.
  21097. *
  21098. * @param {String} name The name of the ComponentDatatype.
  21099. * @returns {ComponentDatatype} The ComponentDatatype.
  21100. *
  21101. * @exception {DeveloperError} name is not a valid value.
  21102. */
  21103. ComponentDatatype.fromName = function(name) {
  21104. switch (name) {
  21105. case 'BYTE':
  21106. return ComponentDatatype.BYTE;
  21107. case 'UNSIGNED_BYTE':
  21108. return ComponentDatatype.UNSIGNED_BYTE;
  21109. case 'SHORT':
  21110. return ComponentDatatype.SHORT;
  21111. case 'UNSIGNED_SHORT':
  21112. return ComponentDatatype.UNSIGNED_SHORT;
  21113. case 'INT':
  21114. return ComponentDatatype.INT;
  21115. case 'UNSIGNED_INT':
  21116. return ComponentDatatype.UNSIGNED_INT;
  21117. case 'FLOAT':
  21118. return ComponentDatatype.FLOAT;
  21119. case 'DOUBLE':
  21120. return ComponentDatatype.DOUBLE;
  21121. default:
  21122. throw new DeveloperError('name is not a valid value.');
  21123. }
  21124. };
  21125. return freezeObject(ComponentDatatype);
  21126. });
  21127. /*global define*/
  21128. define('Core/TerrainQuantization',[
  21129. './freezeObject'
  21130. ], function(
  21131. freezeObject) {
  21132. 'use strict';
  21133. /**
  21134. * This enumerated type is used to determine how the vertices of the terrain mesh are compressed.
  21135. *
  21136. * @exports TerrainQuantization
  21137. *
  21138. * @private
  21139. */
  21140. var TerrainQuantization = {
  21141. /**
  21142. * The vertices are not compressed.
  21143. *
  21144. * @type {Number}
  21145. * @constant
  21146. */
  21147. NONE : 0,
  21148. /**
  21149. * The vertices are compressed to 12 bits.
  21150. *
  21151. * @type {Number}
  21152. * @constant
  21153. */
  21154. BITS12 : 1
  21155. };
  21156. return freezeObject(TerrainQuantization);
  21157. });
  21158. /*global define*/
  21159. define('Core/TerrainEncoding',[
  21160. './AttributeCompression',
  21161. './Cartesian2',
  21162. './Cartesian3',
  21163. './ComponentDatatype',
  21164. './defaultValue',
  21165. './defined',
  21166. './Math',
  21167. './Matrix4',
  21168. './TerrainQuantization'
  21169. ], function(
  21170. AttributeCompression,
  21171. Cartesian2,
  21172. Cartesian3,
  21173. ComponentDatatype,
  21174. defaultValue,
  21175. defined,
  21176. CesiumMath,
  21177. Matrix4,
  21178. TerrainQuantization) {
  21179. 'use strict';
  21180. var cartesian3Scratch = new Cartesian3();
  21181. var cartesian3DimScratch = new Cartesian3();
  21182. var cartesian2Scratch = new Cartesian2();
  21183. var matrix4Scratch = new Matrix4();
  21184. var matrix4Scratch2 = new Matrix4();
  21185. var SHIFT_LEFT_12 = Math.pow(2.0, 12.0);
  21186. /**
  21187. * Data used to quantize and pack the terrain mesh. The position can be unpacked for picking and all attributes
  21188. * are unpacked in the vertex shader.
  21189. *
  21190. * @alias TerrainEncoding
  21191. * @constructor
  21192. *
  21193. * @param {AxisAlignedBoundingBox} axisAlignedBoundingBox The bounds of the tile in the east-north-up coordinates at the tiles center.
  21194. * @param {Number} minimumHeight The minimum height.
  21195. * @param {Number} maximumHeight The maximum height.
  21196. * @param {Matrix4} fromENU The east-north-up to fixed frame matrix at the center of the terrain mesh.
  21197. * @param {Boolean} hasVertexNormals If the mesh has vertex normals.
  21198. * @param {Boolean} [hasWebMercatorT=false] true if the terrain data includes a Web Mercator texture coordinate; otherwise, false.
  21199. *
  21200. * @private
  21201. */
  21202. function TerrainEncoding(axisAlignedBoundingBox, minimumHeight, maximumHeight, fromENU, hasVertexNormals, hasWebMercatorT) {
  21203. var quantization;
  21204. var center;
  21205. var toENU;
  21206. var matrix;
  21207. if (defined(axisAlignedBoundingBox) && defined(minimumHeight) && defined(maximumHeight) && defined(fromENU)) {
  21208. var minimum = axisAlignedBoundingBox.minimum;
  21209. var maximum = axisAlignedBoundingBox.maximum;
  21210. var dimensions = Cartesian3.subtract(maximum, minimum, cartesian3DimScratch);
  21211. var hDim = maximumHeight - minimumHeight;
  21212. var maxDim = Math.max(Cartesian3.maximumComponent(dimensions), hDim);
  21213. if (maxDim < SHIFT_LEFT_12 - 1.0) {
  21214. quantization = TerrainQuantization.BITS12;
  21215. } else {
  21216. quantization = TerrainQuantization.NONE;
  21217. }
  21218. center = axisAlignedBoundingBox.center;
  21219. toENU = Matrix4.inverseTransformation(fromENU, new Matrix4());
  21220. var translation = Cartesian3.negate(minimum, cartesian3Scratch);
  21221. Matrix4.multiply(Matrix4.fromTranslation(translation, matrix4Scratch), toENU, toENU);
  21222. var scale = cartesian3Scratch;
  21223. scale.x = 1.0 / dimensions.x;
  21224. scale.y = 1.0 / dimensions.y;
  21225. scale.z = 1.0 / dimensions.z;
  21226. Matrix4.multiply(Matrix4.fromScale(scale, matrix4Scratch), toENU, toENU);
  21227. matrix = Matrix4.clone(fromENU);
  21228. Matrix4.setTranslation(matrix, Cartesian3.ZERO, matrix);
  21229. fromENU = Matrix4.clone(fromENU, new Matrix4());
  21230. var translationMatrix = Matrix4.fromTranslation(minimum, matrix4Scratch);
  21231. var scaleMatrix = Matrix4.fromScale(dimensions, matrix4Scratch2);
  21232. var st = Matrix4.multiply(translationMatrix, scaleMatrix,matrix4Scratch);
  21233. Matrix4.multiply(fromENU, st, fromENU);
  21234. Matrix4.multiply(matrix, st, matrix);
  21235. }
  21236. /**
  21237. * How the vertices of the mesh were compressed.
  21238. * @type {TerrainQuantization}
  21239. */
  21240. this.quantization = quantization;
  21241. /**
  21242. * The minimum height of the tile including the skirts.
  21243. * @type {Number}
  21244. */
  21245. this.minimumHeight = minimumHeight;
  21246. /**
  21247. * The maximum height of the tile.
  21248. * @type {Number}
  21249. */
  21250. this.maximumHeight = maximumHeight;
  21251. /**
  21252. * The center of the tile.
  21253. * @type {Cartesian3}
  21254. */
  21255. this.center = center;
  21256. /**
  21257. * A matrix that takes a vertex from the tile, transforms it to east-north-up at the center and scales
  21258. * it so each component is in the [0, 1] range.
  21259. * @type {Matrix4}
  21260. */
  21261. this.toScaledENU = toENU;
  21262. /**
  21263. * A matrix that restores a vertex transformed with toScaledENU back to the earth fixed reference frame
  21264. * @type {Matrix4}
  21265. */
  21266. this.fromScaledENU = fromENU;
  21267. /**
  21268. * The matrix used to decompress the terrain vertices in the shader for RTE rendering.
  21269. * @type {Matrix4}
  21270. */
  21271. this.matrix = matrix;
  21272. /**
  21273. * The terrain mesh contains normals.
  21274. * @type {Boolean}
  21275. */
  21276. this.hasVertexNormals = hasVertexNormals;
  21277. /**
  21278. * The terrain mesh contains a vertical texture coordinate following the Web Mercator projection.
  21279. * @type {Boolean}
  21280. */
  21281. this.hasWebMercatorT = defaultValue(hasWebMercatorT, false);
  21282. }
  21283. TerrainEncoding.prototype.encode = function(vertexBuffer, bufferIndex, position, uv, height, normalToPack, webMercatorT) {
  21284. var u = uv.x;
  21285. var v = uv.y;
  21286. if (this.quantization === TerrainQuantization.BITS12) {
  21287. position = Matrix4.multiplyByPoint(this.toScaledENU, position, cartesian3Scratch);
  21288. position.x = CesiumMath.clamp(position.x, 0.0, 1.0);
  21289. position.y = CesiumMath.clamp(position.y, 0.0, 1.0);
  21290. position.z = CesiumMath.clamp(position.z, 0.0, 1.0);
  21291. var hDim = this.maximumHeight - this.minimumHeight;
  21292. var h = CesiumMath.clamp((height - this.minimumHeight) / hDim, 0.0, 1.0);
  21293. Cartesian2.fromElements(position.x, position.y, cartesian2Scratch);
  21294. var compressed0 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21295. Cartesian2.fromElements(position.z, h, cartesian2Scratch);
  21296. var compressed1 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21297. Cartesian2.fromElements(u, v, cartesian2Scratch);
  21298. var compressed2 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21299. vertexBuffer[bufferIndex++] = compressed0;
  21300. vertexBuffer[bufferIndex++] = compressed1;
  21301. vertexBuffer[bufferIndex++] = compressed2;
  21302. if (this.hasWebMercatorT) {
  21303. Cartesian2.fromElements(webMercatorT, 0.0, cartesian2Scratch);
  21304. var compressed3 = AttributeCompression.compressTextureCoordinates(cartesian2Scratch);
  21305. vertexBuffer[bufferIndex++] = compressed3;
  21306. }
  21307. } else {
  21308. Cartesian3.subtract(position, this.center, cartesian3Scratch);
  21309. vertexBuffer[bufferIndex++] = cartesian3Scratch.x;
  21310. vertexBuffer[bufferIndex++] = cartesian3Scratch.y;
  21311. vertexBuffer[bufferIndex++] = cartesian3Scratch.z;
  21312. vertexBuffer[bufferIndex++] = height;
  21313. vertexBuffer[bufferIndex++] = u;
  21314. vertexBuffer[bufferIndex++] = v;
  21315. if (this.hasWebMercatorT) {
  21316. vertexBuffer[bufferIndex++] = webMercatorT;
  21317. }
  21318. }
  21319. if (this.hasVertexNormals) {
  21320. vertexBuffer[bufferIndex++] = AttributeCompression.octPackFloat(normalToPack);
  21321. }
  21322. return bufferIndex;
  21323. };
  21324. TerrainEncoding.prototype.decodePosition = function(buffer, index, result) {
  21325. if (!defined(result)) {
  21326. result = new Cartesian3();
  21327. }
  21328. index *= this.getStride();
  21329. if (this.quantization === TerrainQuantization.BITS12) {
  21330. var xy = AttributeCompression.decompressTextureCoordinates(buffer[index], cartesian2Scratch);
  21331. result.x = xy.x;
  21332. result.y = xy.y;
  21333. var zh = AttributeCompression.decompressTextureCoordinates(buffer[index + 1], cartesian2Scratch);
  21334. result.z = zh.x;
  21335. return Matrix4.multiplyByPoint(this.fromScaledENU, result, result);
  21336. }
  21337. result.x = buffer[index];
  21338. result.y = buffer[index + 1];
  21339. result.z = buffer[index + 2];
  21340. return Cartesian3.add(result, this.center, result);
  21341. };
  21342. TerrainEncoding.prototype.decodeTextureCoordinates = function(buffer, index, result) {
  21343. if (!defined(result)) {
  21344. result = new Cartesian2();
  21345. }
  21346. index *= this.getStride();
  21347. if (this.quantization === TerrainQuantization.BITS12) {
  21348. return AttributeCompression.decompressTextureCoordinates(buffer[index + 2], result);
  21349. }
  21350. return Cartesian2.fromElements(buffer[index + 4], buffer[index + 5], result);
  21351. };
  21352. TerrainEncoding.prototype.decodeHeight = function(buffer, index) {
  21353. index *= this.getStride();
  21354. if (this.quantization === TerrainQuantization.BITS12) {
  21355. var zh = AttributeCompression.decompressTextureCoordinates(buffer[index + 1], cartesian2Scratch);
  21356. return zh.y * (this.maximumHeight - this.minimumHeight) + this.minimumHeight;
  21357. }
  21358. return buffer[index + 3];
  21359. };
  21360. TerrainEncoding.prototype.getOctEncodedNormal = function(buffer, index, result) {
  21361. var stride = this.getStride();
  21362. index = (index + 1) * stride - 1;
  21363. var temp = buffer[index] / 256.0;
  21364. var x = Math.floor(temp);
  21365. var y = (temp - x) * 256.0;
  21366. return Cartesian2.fromElements(x, y, result);
  21367. };
  21368. TerrainEncoding.prototype.getStride = function() {
  21369. var vertexStride;
  21370. switch (this.quantization) {
  21371. case TerrainQuantization.BITS12:
  21372. vertexStride = 3;
  21373. break;
  21374. default:
  21375. vertexStride = 6;
  21376. }
  21377. if (this.hasWebMercatorT) {
  21378. ++vertexStride;
  21379. }
  21380. if (this.hasVertexNormals) {
  21381. ++vertexStride;
  21382. }
  21383. return vertexStride;
  21384. };
  21385. var attributesNone = {
  21386. position3DAndHeight : 0,
  21387. textureCoordAndEncodedNormals : 1
  21388. };
  21389. var attributes = {
  21390. compressed0 : 0,
  21391. compressed1 : 1
  21392. };
  21393. TerrainEncoding.prototype.getAttributes = function(buffer) {
  21394. var datatype = ComponentDatatype.FLOAT;
  21395. var sizeInBytes = ComponentDatatype.getSizeInBytes(datatype);
  21396. var stride;
  21397. if (this.quantization === TerrainQuantization.NONE) {
  21398. var position3DAndHeightLength = 4;
  21399. var numTexCoordComponents = 2;
  21400. if (this.hasWebMercatorT) {
  21401. ++numTexCoordComponents;
  21402. }
  21403. if (this.hasVertexNormals) {
  21404. ++numTexCoordComponents;
  21405. }
  21406. stride = (position3DAndHeightLength + numTexCoordComponents) * sizeInBytes;
  21407. return [{
  21408. index : attributesNone.position3DAndHeight,
  21409. vertexBuffer : buffer,
  21410. componentDatatype : datatype,
  21411. componentsPerAttribute : position3DAndHeightLength,
  21412. offsetInBytes : 0,
  21413. strideInBytes : stride
  21414. }, {
  21415. index : attributesNone.textureCoordAndEncodedNormals,
  21416. vertexBuffer : buffer,
  21417. componentDatatype : datatype,
  21418. componentsPerAttribute : numTexCoordComponents,
  21419. offsetInBytes : position3DAndHeightLength * sizeInBytes,
  21420. strideInBytes : stride
  21421. }];
  21422. }
  21423. var numCompressed0 = 3;
  21424. var numCompressed1 = 0;
  21425. if (this.hasWebMercatorT || this.hasVertexNormals) {
  21426. ++numCompressed0;
  21427. }
  21428. if (this.hasWebMercatorT && this.hasVertexNormals) {
  21429. ++numCompressed1;
  21430. stride = (numCompressed0 + numCompressed1) * sizeInBytes;
  21431. return [{
  21432. index : attributes.compressed0,
  21433. vertexBuffer : buffer,
  21434. componentDatatype : datatype,
  21435. componentsPerAttribute : numCompressed0,
  21436. offsetInBytes : 0,
  21437. strideInBytes : stride
  21438. }, {
  21439. index : attributes.compressed1,
  21440. vertexBuffer : buffer,
  21441. componentDatatype : datatype,
  21442. componentsPerAttribute : numCompressed1,
  21443. offsetInBytes : numCompressed0 * sizeInBytes,
  21444. strideInBytes : stride
  21445. }];
  21446. } else {
  21447. return [{
  21448. index : attributes.compressed0,
  21449. vertexBuffer : buffer,
  21450. componentDatatype : datatype,
  21451. componentsPerAttribute : numCompressed0
  21452. }];
  21453. }
  21454. };
  21455. TerrainEncoding.prototype.getAttributeLocations = function() {
  21456. if (this.quantization === TerrainQuantization.NONE) {
  21457. return attributesNone;
  21458. } else {
  21459. return attributes;
  21460. }
  21461. };
  21462. TerrainEncoding.clone = function(encoding, result) {
  21463. if (!defined(result)) {
  21464. result = new TerrainEncoding();
  21465. }
  21466. result.quantization = encoding.quantization;
  21467. result.minimumHeight = encoding.minimumHeight;
  21468. result.maximumHeight = encoding.maximumHeight;
  21469. result.center = Cartesian3.clone(encoding.center);
  21470. result.toScaledENU = Matrix4.clone(encoding.toScaledENU);
  21471. result.fromScaledENU = Matrix4.clone(encoding.fromScaledENU);
  21472. result.matrix = Matrix4.clone(encoding.matrix);
  21473. result.hasVertexNormals = encoding.hasVertexNormals;
  21474. result.hasWebMercatorT = encoding.hasWebMercatorT;
  21475. return result;
  21476. };
  21477. return TerrainEncoding;
  21478. });
  21479. /*global define*/
  21480. define('Core/WebMercatorProjection',[
  21481. './Cartesian3',
  21482. './Cartographic',
  21483. './defaultValue',
  21484. './defined',
  21485. './defineProperties',
  21486. './DeveloperError',
  21487. './Ellipsoid',
  21488. './Math'
  21489. ], function(
  21490. Cartesian3,
  21491. Cartographic,
  21492. defaultValue,
  21493. defined,
  21494. defineProperties,
  21495. DeveloperError,
  21496. Ellipsoid,
  21497. CesiumMath) {
  21498. 'use strict';
  21499. /**
  21500. * The map projection used by Google Maps, Bing Maps, and most of ArcGIS Online, EPSG:3857. This
  21501. * projection use longitude and latitude expressed with the WGS84 and transforms them to Mercator using
  21502. * the spherical (rather than ellipsoidal) equations.
  21503. *
  21504. * @alias WebMercatorProjection
  21505. * @constructor
  21506. *
  21507. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  21508. *
  21509. * @see GeographicProjection
  21510. */
  21511. function WebMercatorProjection(ellipsoid) {
  21512. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  21513. this._semimajorAxis = this._ellipsoid.maximumRadius;
  21514. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  21515. }
  21516. defineProperties(WebMercatorProjection.prototype, {
  21517. /**
  21518. * Gets the {@link Ellipsoid}.
  21519. *
  21520. * @memberof WebMercatorProjection.prototype
  21521. *
  21522. * @type {Ellipsoid}
  21523. * @readonly
  21524. */
  21525. ellipsoid : {
  21526. get : function() {
  21527. return this._ellipsoid;
  21528. }
  21529. }
  21530. });
  21531. /**
  21532. * Converts a Mercator angle, in the range -PI to PI, to a geodetic latitude
  21533. * in the range -PI/2 to PI/2.
  21534. *
  21535. * @param {Number} mercatorAngle The angle to convert.
  21536. * @returns {Number} The geodetic latitude in radians.
  21537. */
  21538. WebMercatorProjection.mercatorAngleToGeodeticLatitude = function(mercatorAngle) {
  21539. return CesiumMath.PI_OVER_TWO - (2.0 * Math.atan(Math.exp(-mercatorAngle)));
  21540. };
  21541. /**
  21542. * Converts a geodetic latitude in radians, in the range -PI/2 to PI/2, to a Mercator
  21543. * angle in the range -PI to PI.
  21544. *
  21545. * @param {Number} latitude The geodetic latitude in radians.
  21546. * @returns {Number} The Mercator angle.
  21547. */
  21548. WebMercatorProjection.geodeticLatitudeToMercatorAngle = function(latitude) {
  21549. // Clamp the latitude coordinate to the valid Mercator bounds.
  21550. if (latitude > WebMercatorProjection.MaximumLatitude) {
  21551. latitude = WebMercatorProjection.MaximumLatitude;
  21552. } else if (latitude < -WebMercatorProjection.MaximumLatitude) {
  21553. latitude = -WebMercatorProjection.MaximumLatitude;
  21554. }
  21555. var sinLatitude = Math.sin(latitude);
  21556. return 0.5 * Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude));
  21557. };
  21558. /**
  21559. * The maximum latitude (both North and South) supported by a Web Mercator
  21560. * (EPSG:3857) projection. Technically, the Mercator projection is defined
  21561. * for any latitude up to (but not including) 90 degrees, but it makes sense
  21562. * to cut it off sooner because it grows exponentially with increasing latitude.
  21563. * The logic behind this particular cutoff value, which is the one used by
  21564. * Google Maps, Bing Maps, and Esri, is that it makes the projection
  21565. * square. That is, the rectangle is equal in the X and Y directions.
  21566. *
  21567. * The constant value is computed by calling:
  21568. * WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI)
  21569. *
  21570. * @type {Number}
  21571. */
  21572. WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI);
  21573. /**
  21574. * Converts geodetic ellipsoid coordinates, in radians, to the equivalent Web Mercator
  21575. * X, Y, Z coordinates expressed in meters and returned in a {@link Cartesian3}. The height
  21576. * is copied unmodified to the Z coordinate.
  21577. *
  21578. * @param {Cartographic} cartographic The cartographic coordinates in radians.
  21579. * @param {Cartesian3} [result] The instance to which to copy the result, or undefined if a
  21580. * new instance should be created.
  21581. * @returns {Cartesian3} The equivalent web mercator X, Y, Z coordinates, in meters.
  21582. */
  21583. WebMercatorProjection.prototype.project = function(cartographic, result) {
  21584. var semimajorAxis = this._semimajorAxis;
  21585. var x = cartographic.longitude * semimajorAxis;
  21586. var y = WebMercatorProjection.geodeticLatitudeToMercatorAngle(cartographic.latitude) * semimajorAxis;
  21587. var z = cartographic.height;
  21588. if (!defined(result)) {
  21589. return new Cartesian3(x, y, z);
  21590. }
  21591. result.x = x;
  21592. result.y = y;
  21593. result.z = z;
  21594. return result;
  21595. };
  21596. /**
  21597. * Converts Web Mercator X, Y coordinates, expressed in meters, to a {@link Cartographic}
  21598. * containing geodetic ellipsoid coordinates. The Z coordinate is copied unmodified to the
  21599. * height.
  21600. *
  21601. * @param {Cartesian3} cartesian The web mercator Cartesian position to unrproject with height (z) in meters.
  21602. * @param {Cartographic} [result] The instance to which to copy the result, or undefined if a
  21603. * new instance should be created.
  21604. * @returns {Cartographic} The equivalent cartographic coordinates.
  21605. */
  21606. WebMercatorProjection.prototype.unproject = function(cartesian, result) {
  21607. if (!defined(cartesian)) {
  21608. throw new DeveloperError('cartesian is required');
  21609. }
  21610. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  21611. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  21612. var latitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(cartesian.y * oneOverEarthSemimajorAxis);
  21613. var height = cartesian.z;
  21614. if (!defined(result)) {
  21615. return new Cartographic(longitude, latitude, height);
  21616. }
  21617. result.longitude = longitude;
  21618. result.latitude = latitude;
  21619. result.height = height;
  21620. return result;
  21621. };
  21622. return WebMercatorProjection;
  21623. });
  21624. /*global define*/
  21625. define('Core/HeightmapTessellator',[
  21626. './AxisAlignedBoundingBox',
  21627. './BoundingSphere',
  21628. './Cartesian2',
  21629. './Cartesian3',
  21630. './defaultValue',
  21631. './defined',
  21632. './DeveloperError',
  21633. './Ellipsoid',
  21634. './EllipsoidalOccluder',
  21635. './freezeObject',
  21636. './Math',
  21637. './Matrix4',
  21638. './OrientedBoundingBox',
  21639. './Rectangle',
  21640. './TerrainEncoding',
  21641. './Transforms',
  21642. './WebMercatorProjection'
  21643. ], function(
  21644. AxisAlignedBoundingBox,
  21645. BoundingSphere,
  21646. Cartesian2,
  21647. Cartesian3,
  21648. defaultValue,
  21649. defined,
  21650. DeveloperError,
  21651. Ellipsoid,
  21652. EllipsoidalOccluder,
  21653. freezeObject,
  21654. CesiumMath,
  21655. Matrix4,
  21656. OrientedBoundingBox,
  21657. Rectangle,
  21658. TerrainEncoding,
  21659. Transforms,
  21660. WebMercatorProjection) {
  21661. 'use strict';
  21662. /**
  21663. * Contains functions to create a mesh from a heightmap image.
  21664. *
  21665. * @exports HeightmapTessellator
  21666. *
  21667. * @private
  21668. */
  21669. var HeightmapTessellator = {};
  21670. /**
  21671. * The default structure of a heightmap, as given to {@link HeightmapTessellator.computeVertices}.
  21672. *
  21673. * @constant
  21674. */
  21675. HeightmapTessellator.DEFAULT_STRUCTURE = freezeObject({
  21676. heightScale : 1.0,
  21677. heightOffset : 0.0,
  21678. elementsPerHeight : 1,
  21679. stride : 1,
  21680. elementMultiplier : 256.0,
  21681. isBigEndian : false
  21682. });
  21683. var cartesian3Scratch = new Cartesian3();
  21684. var matrix4Scratch = new Matrix4();
  21685. var minimumScratch = new Cartesian3();
  21686. var maximumScratch = new Cartesian3();
  21687. /**
  21688. * Fills an array of vertices from a heightmap image.
  21689. *
  21690. * @param {Object} options Object with the following properties:
  21691. * @param {TypedArray} options.heightmap The heightmap to tessellate.
  21692. * @param {Number} options.width The width of the heightmap, in height samples.
  21693. * @param {Number} options.height The height of the heightmap, in height samples.
  21694. * @param {Number} options.skirtHeight The height of skirts to drape at the edges of the heightmap.
  21695. * @param {Rectangle} options.nativeRectangle An rectangle in the native coordinates of the heightmap's projection. For
  21696. * a heightmap with a geographic projection, this is degrees. For the web mercator
  21697. * projection, this is meters.
  21698. * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
  21699. * @param {Rectangle} [options.rectangle] The rectangle covered by the heightmap, in geodetic coordinates with north, south, east and
  21700. * west properties in radians. Either rectangle or nativeRectangle must be provided. If both
  21701. * are provided, they're assumed to be consistent.
  21702. * @param {Boolean} [options.isGeographic=true] True if the heightmap uses a {@link GeographicProjection}, or false if it uses
  21703. * a {@link WebMercatorProjection}.
  21704. * @param {Cartesian3} [options.relativeToCenter=Cartesian3.ZERO] The positions will be computed as <code>Cartesian3.subtract(worldPosition, relativeToCenter)</code>.
  21705. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to which the heightmap applies.
  21706. * @param {Object} [options.structure] An object describing the structure of the height data.
  21707. * @param {Number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
  21708. * the height above the heightOffset, in meters. The heightOffset is added to the resulting
  21709. * height after multiplying by the scale.
  21710. * @param {Number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
  21711. * height in meters. The offset is added after the height sample is multiplied by the
  21712. * heightScale.
  21713. * @param {Number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
  21714. * sample. This is usually 1, indicating that each element is a separate height sample. If
  21715. * it is greater than 1, that number of elements together form the height sample, which is
  21716. * computed according to the structure.elementMultiplier and structure.isBigEndian properties.
  21717. * @param {Number} [options.structure.stride=1] The number of elements to skip to get from the first element of
  21718. * one height to the first element of the next height.
  21719. * @param {Number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
  21720. * stride property is greater than 1. For example, if the stride is 4 and the strideMultiplier
  21721. * is 256, the height is computed as follows:
  21722. * `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
  21723. * This is assuming that the isBigEndian property is false. If it is true, the order of the
  21724. * elements is reversed.
  21725. * @param {Number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer. Any heights that are lower
  21726. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  21727. * buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers. If this parameter is
  21728. * not specified, no minimum value is enforced.
  21729. * @param {Number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer. Any heights that are higher
  21730. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  21731. * buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
  21732. * than 65535. If this parameter is not specified, no maximum value is enforced.
  21733. * @param {Boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
  21734. * stride property is greater than 1. If this property is false, the first element is the
  21735. * low-order element. If it is true, the first element is the high-order element.
  21736. *
  21737. * @example
  21738. * var width = 5;
  21739. * var height = 5;
  21740. * var statistics = Cesium.HeightmapTessellator.computeVertices({
  21741. * heightmap : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
  21742. * width : width,
  21743. * height : height,
  21744. * skirtHeight : 0.0,
  21745. * nativeRectangle : {
  21746. * west : 10.0,
  21747. * east : 20.0,
  21748. * south : 30.0,
  21749. * north : 40.0
  21750. * }
  21751. * });
  21752. *
  21753. * var encoding = statistics.encoding;
  21754. * var position = encoding.decodePosition(statistics.vertices, index * encoding.getStride());
  21755. */
  21756. HeightmapTessellator.computeVertices = function(options) {
  21757. if (!defined(options) || !defined(options.heightmap)) {
  21758. throw new DeveloperError('options.heightmap is required.');
  21759. }
  21760. if (!defined(options.width) || !defined(options.height)) {
  21761. throw new DeveloperError('options.width and options.height are required.');
  21762. }
  21763. if (!defined(options.nativeRectangle)) {
  21764. throw new DeveloperError('options.nativeRectangle is required.');
  21765. }
  21766. if (!defined(options.skirtHeight)) {
  21767. throw new DeveloperError('options.skirtHeight is required.');
  21768. }
  21769. // This function tends to be a performance hotspot for terrain rendering,
  21770. // so it employs a lot of inlining and unrolling as an optimization.
  21771. // In particular, the functionality of Ellipsoid.cartographicToCartesian
  21772. // is inlined.
  21773. var cos = Math.cos;
  21774. var sin = Math.sin;
  21775. var sqrt = Math.sqrt;
  21776. var atan = Math.atan;
  21777. var exp = Math.exp;
  21778. var piOverTwo = CesiumMath.PI_OVER_TWO;
  21779. var toRadians = CesiumMath.toRadians;
  21780. var heightmap = options.heightmap;
  21781. var width = options.width;
  21782. var height = options.height;
  21783. var skirtHeight = options.skirtHeight;
  21784. var isGeographic = defaultValue(options.isGeographic, true);
  21785. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  21786. var oneOverGlobeSemimajorAxis = 1.0 / ellipsoid.maximumRadius;
  21787. var nativeRectangle = options.nativeRectangle;
  21788. var geographicWest;
  21789. var geographicSouth;
  21790. var geographicEast;
  21791. var geographicNorth;
  21792. var rectangle = options.rectangle;
  21793. if (!defined(rectangle)) {
  21794. if (isGeographic) {
  21795. geographicWest = toRadians(nativeRectangle.west);
  21796. geographicSouth = toRadians(nativeRectangle.south);
  21797. geographicEast = toRadians(nativeRectangle.east);
  21798. geographicNorth = toRadians(nativeRectangle.north);
  21799. } else {
  21800. geographicWest = nativeRectangle.west * oneOverGlobeSemimajorAxis;
  21801. geographicSouth = piOverTwo - (2.0 * atan(exp(-nativeRectangle.south * oneOverGlobeSemimajorAxis)));
  21802. geographicEast = nativeRectangle.east * oneOverGlobeSemimajorAxis;
  21803. geographicNorth = piOverTwo - (2.0 * atan(exp(-nativeRectangle.north * oneOverGlobeSemimajorAxis)));
  21804. }
  21805. } else {
  21806. geographicWest = rectangle.west;
  21807. geographicSouth = rectangle.south;
  21808. geographicEast = rectangle.east;
  21809. geographicNorth = rectangle.north;
  21810. }
  21811. var relativeToCenter = options.relativeToCenter;
  21812. var hasRelativeToCenter = defined(relativeToCenter);
  21813. relativeToCenter = hasRelativeToCenter ? relativeToCenter : Cartesian3.ZERO;
  21814. var exaggeration = defaultValue(options.exaggeration, 1.0);
  21815. var includeWebMercatorT = defaultValue(options.includeWebMercatorT, false);
  21816. var structure = defaultValue(options.structure, HeightmapTessellator.DEFAULT_STRUCTURE);
  21817. var heightScale = defaultValue(structure.heightScale, HeightmapTessellator.DEFAULT_STRUCTURE.heightScale);
  21818. var heightOffset = defaultValue(structure.heightOffset, HeightmapTessellator.DEFAULT_STRUCTURE.heightOffset);
  21819. var elementsPerHeight = defaultValue(structure.elementsPerHeight, HeightmapTessellator.DEFAULT_STRUCTURE.elementsPerHeight);
  21820. var stride = defaultValue(structure.stride, HeightmapTessellator.DEFAULT_STRUCTURE.stride);
  21821. var elementMultiplier = defaultValue(structure.elementMultiplier, HeightmapTessellator.DEFAULT_STRUCTURE.elementMultiplier);
  21822. var isBigEndian = defaultValue(structure.isBigEndian, HeightmapTessellator.DEFAULT_STRUCTURE.isBigEndian);
  21823. var granularityX = Rectangle.computeWidth(nativeRectangle) / (width - 1);
  21824. var granularityY = Rectangle.computeHeight(nativeRectangle) / (height - 1);
  21825. var radiiSquared = ellipsoid.radiiSquared;
  21826. var radiiSquaredX = radiiSquared.x;
  21827. var radiiSquaredY = radiiSquared.y;
  21828. var radiiSquaredZ = radiiSquared.z;
  21829. var minimumHeight = 65536.0;
  21830. var maximumHeight = -65536.0;
  21831. var fromENU = Transforms.eastNorthUpToFixedFrame(relativeToCenter, ellipsoid);
  21832. var toENU = Matrix4.inverseTransformation(fromENU, matrix4Scratch);
  21833. var southMercatorY;
  21834. var oneOverMercatorHeight;
  21835. if (includeWebMercatorT) {
  21836. southMercatorY = WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicSouth);
  21837. oneOverMercatorHeight = 1.0 / (WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicNorth) - southMercatorY);
  21838. }
  21839. var minimum = minimumScratch;
  21840. minimum.x = Number.POSITIVE_INFINITY;
  21841. minimum.y = Number.POSITIVE_INFINITY;
  21842. minimum.z = Number.POSITIVE_INFINITY;
  21843. var maximum = maximumScratch;
  21844. maximum.x = Number.NEGATIVE_INFINITY;
  21845. maximum.y = Number.NEGATIVE_INFINITY;
  21846. maximum.z = Number.NEGATIVE_INFINITY;
  21847. var hMin = Number.POSITIVE_INFINITY;
  21848. var arrayWidth = width + (skirtHeight > 0.0 ? 2.0 : 0.0);
  21849. var arrayHeight = height + (skirtHeight > 0.0 ? 2.0 : 0.0);
  21850. var size = arrayWidth * arrayHeight;
  21851. var positions = new Array(size);
  21852. var heights = new Array(size);
  21853. var uvs = new Array(size);
  21854. var webMercatorTs = includeWebMercatorT ? new Array(size) : [];
  21855. var startRow = 0;
  21856. var endRow = height;
  21857. var startCol = 0;
  21858. var endCol = width;
  21859. if (skirtHeight > 0) {
  21860. --startRow;
  21861. ++endRow;
  21862. --startCol;
  21863. ++endCol;
  21864. }
  21865. var index = 0;
  21866. for (var rowIndex = startRow; rowIndex < endRow; ++rowIndex) {
  21867. var row = rowIndex;
  21868. if (row < 0) {
  21869. row = 0;
  21870. }
  21871. if (row >= height) {
  21872. row = height - 1;
  21873. }
  21874. var latitude = nativeRectangle.north - granularityY * row;
  21875. if (!isGeographic) {
  21876. latitude = piOverTwo - (2.0 * atan(exp(-latitude * oneOverGlobeSemimajorAxis)));
  21877. } else {
  21878. latitude = toRadians(latitude);
  21879. }
  21880. var cosLatitude = cos(latitude);
  21881. var nZ = sin(latitude);
  21882. var kZ = radiiSquaredZ * nZ;
  21883. var v = (latitude - geographicSouth) / (geographicNorth - geographicSouth);
  21884. v = CesiumMath.clamp(v, 0.0, 1.0);
  21885. var webMercatorT;
  21886. if (includeWebMercatorT) {
  21887. webMercatorT = (WebMercatorProjection.geodeticLatitudeToMercatorAngle(latitude) - southMercatorY) * oneOverMercatorHeight;
  21888. }
  21889. for (var colIndex = startCol; colIndex < endCol; ++colIndex) {
  21890. var col = colIndex;
  21891. if (col < 0) {
  21892. col = 0;
  21893. }
  21894. if (col >= width) {
  21895. col = width - 1;
  21896. }
  21897. var longitude = nativeRectangle.west + granularityX * col;
  21898. if (!isGeographic) {
  21899. longitude = longitude * oneOverGlobeSemimajorAxis;
  21900. } else {
  21901. longitude = toRadians(longitude);
  21902. }
  21903. var terrainOffset = row * (width * stride) + col * stride;
  21904. var heightSample;
  21905. if (elementsPerHeight === 1) {
  21906. heightSample = heightmap[terrainOffset];
  21907. } else {
  21908. heightSample = 0;
  21909. var elementOffset;
  21910. if (isBigEndian) {
  21911. for (elementOffset = 0; elementOffset < elementsPerHeight; ++elementOffset) {
  21912. heightSample = (heightSample * elementMultiplier) + heightmap[terrainOffset + elementOffset];
  21913. }
  21914. } else {
  21915. for (elementOffset = elementsPerHeight - 1; elementOffset >= 0; --elementOffset) {
  21916. heightSample = (heightSample * elementMultiplier) + heightmap[terrainOffset + elementOffset];
  21917. }
  21918. }
  21919. }
  21920. heightSample = (heightSample * heightScale + heightOffset) * exaggeration;
  21921. maximumHeight = Math.max(maximumHeight, heightSample);
  21922. minimumHeight = Math.min(minimumHeight, heightSample);
  21923. if (colIndex !== col || rowIndex !== row) {
  21924. heightSample -= skirtHeight;
  21925. }
  21926. var nX = cosLatitude * cos(longitude);
  21927. var nY = cosLatitude * sin(longitude);
  21928. var kX = radiiSquaredX * nX;
  21929. var kY = radiiSquaredY * nY;
  21930. var gamma = sqrt((kX * nX) + (kY * nY) + (kZ * nZ));
  21931. var oneOverGamma = 1.0 / gamma;
  21932. var rSurfaceX = kX * oneOverGamma;
  21933. var rSurfaceY = kY * oneOverGamma;
  21934. var rSurfaceZ = kZ * oneOverGamma;
  21935. var position = new Cartesian3();
  21936. position.x = rSurfaceX + nX * heightSample;
  21937. position.y = rSurfaceY + nY * heightSample;
  21938. position.z = rSurfaceZ + nZ * heightSample;
  21939. positions[index] = position;
  21940. heights[index] = heightSample;
  21941. var u = (longitude - geographicWest) / (geographicEast - geographicWest);
  21942. u = CesiumMath.clamp(u, 0.0, 1.0);
  21943. uvs[index] = new Cartesian2(u, v);
  21944. if (includeWebMercatorT) {
  21945. webMercatorTs[index] = webMercatorT;
  21946. }
  21947. index++;
  21948. Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch);
  21949. Cartesian3.minimumByComponent(cartesian3Scratch, minimum, minimum);
  21950. Cartesian3.maximumByComponent(cartesian3Scratch, maximum, maximum);
  21951. hMin = Math.min(hMin, heightSample);
  21952. }
  21953. }
  21954. var boundingSphere3D = BoundingSphere.fromPoints(positions);
  21955. var orientedBoundingBox;
  21956. if (defined(rectangle) && rectangle.width < CesiumMath.PI_OVER_TWO + CesiumMath.EPSILON5) {
  21957. // Here, rectangle.width < pi/2, and rectangle.height < pi
  21958. // (though it would still work with rectangle.width up to pi)
  21959. orientedBoundingBox = OrientedBoundingBox.fromRectangle(rectangle, minimumHeight, maximumHeight, ellipsoid);
  21960. }
  21961. var occludeePointInScaledSpace;
  21962. if (hasRelativeToCenter) {
  21963. var occluder = new EllipsoidalOccluder(ellipsoid);
  21964. occludeePointInScaledSpace = occluder.computeHorizonCullingPoint(relativeToCenter, positions);
  21965. }
  21966. var aaBox = new AxisAlignedBoundingBox(minimum, maximum, relativeToCenter);
  21967. var encoding = new TerrainEncoding(aaBox, hMin, maximumHeight, fromENU, false, includeWebMercatorT);
  21968. var vertices = new Float32Array(size * encoding.getStride());
  21969. var bufferIndex = 0;
  21970. for (var j = 0; j < size; ++j) {
  21971. bufferIndex = encoding.encode(vertices, bufferIndex, positions[j], uvs[j], heights[j], undefined, webMercatorTs[j]);
  21972. }
  21973. return {
  21974. vertices : vertices,
  21975. maximumHeight : maximumHeight,
  21976. minimumHeight : minimumHeight,
  21977. encoding : encoding,
  21978. boundingSphere3D : boundingSphere3D,
  21979. orientedBoundingBox : orientedBoundingBox,
  21980. occludeePointInScaledSpace : occludeePointInScaledSpace
  21981. };
  21982. };
  21983. return HeightmapTessellator;
  21984. });
  21985. /*global define*/
  21986. define('Core/formatError',[
  21987. './defined'
  21988. ], function(
  21989. defined) {
  21990. 'use strict';
  21991. /**
  21992. * Formats an error object into a String. If available, uses name, message, and stack
  21993. * properties, otherwise, falls back on toString().
  21994. *
  21995. * @exports formatError
  21996. *
  21997. * @param {Object} object The item to find in the array.
  21998. * @returns {String} A string containing the formatted error.
  21999. */
  22000. function formatError(object) {
  22001. var result;
  22002. var name = object.name;
  22003. var message = object.message;
  22004. if (defined(name) && defined(message)) {
  22005. result = name + ': ' + message;
  22006. } else {
  22007. result = object.toString();
  22008. }
  22009. var stack = object.stack;
  22010. if (defined(stack)) {
  22011. result += '\n' + stack;
  22012. }
  22013. return result;
  22014. }
  22015. return formatError;
  22016. });
  22017. /*global define*/
  22018. define('Workers/createTaskProcessorWorker',[
  22019. '../Core/defaultValue',
  22020. '../Core/defined',
  22021. '../Core/formatError'
  22022. ], function(
  22023. defaultValue,
  22024. defined,
  22025. formatError) {
  22026. 'use strict';
  22027. /**
  22028. * Creates an adapter function to allow a calculation function to operate as a Web Worker,
  22029. * paired with TaskProcessor, to receive tasks and return results.
  22030. *
  22031. * @exports createTaskProcessorWorker
  22032. *
  22033. * @param {createTaskProcessorWorker~WorkerFunction} workerFunction The calculation function,
  22034. * which takes parameters and returns a result.
  22035. * @returns {createTaskProcessorWorker~TaskProcessorWorkerFunction} A function that adapts the
  22036. * calculation function to work as a Web Worker onmessage listener with TaskProcessor.
  22037. *
  22038. *
  22039. * @example
  22040. * function doCalculation(parameters, transferableObjects) {
  22041. * // calculate some result using the inputs in parameters
  22042. * return result;
  22043. * }
  22044. *
  22045. * return Cesium.createTaskProcessorWorker(doCalculation);
  22046. * // the resulting function is compatible with TaskProcessor
  22047. *
  22048. * @see TaskProcessor
  22049. * @see {@link http://www.w3.org/TR/workers/|Web Workers}
  22050. * @see {@link http://www.w3.org/TR/html5/common-dom-interfaces.html#transferable-objects|Transferable objects}
  22051. */
  22052. function createTaskProcessorWorker(workerFunction) {
  22053. var postMessage;
  22054. var transferableObjects = [];
  22055. var responseMessage = {
  22056. id : undefined,
  22057. result : undefined,
  22058. error : undefined
  22059. };
  22060. return function(event) {
  22061. /*global self*/
  22062. var data = event.data;
  22063. transferableObjects.length = 0;
  22064. responseMessage.id = data.id;
  22065. responseMessage.error = undefined;
  22066. responseMessage.result = undefined;
  22067. try {
  22068. responseMessage.result = workerFunction(data.parameters, transferableObjects);
  22069. } catch (e) {
  22070. if (e instanceof Error) {
  22071. // Errors can't be posted in a message, copy the properties
  22072. responseMessage.error = {
  22073. name : e.name,
  22074. message : e.message,
  22075. stack : e.stack
  22076. };
  22077. } else {
  22078. responseMessage.error = e;
  22079. }
  22080. }
  22081. if (!defined(postMessage)) {
  22082. postMessage = defaultValue(self.webkitPostMessage, self.postMessage);
  22083. }
  22084. if (!data.canTransferArrayBuffer) {
  22085. transferableObjects.length = 0;
  22086. }
  22087. try {
  22088. postMessage(responseMessage, transferableObjects);
  22089. } catch (e) {
  22090. // something went wrong trying to post the message, post a simpler
  22091. // error that we can be sure will be cloneable
  22092. responseMessage.result = undefined;
  22093. responseMessage.error = 'postMessage failed with error: ' + formatError(e) + '\n with responseMessage: ' + JSON.stringify(responseMessage);
  22094. postMessage(responseMessage);
  22095. }
  22096. };
  22097. }
  22098. /**
  22099. * A function that performs a calculation in a Web Worker.
  22100. * @callback createTaskProcessorWorker~WorkerFunction
  22101. *
  22102. * @param {Object} parameters Parameters to the calculation.
  22103. * @param {Array} transferableObjects An array that should be filled with references to objects inside
  22104. * the result that should be transferred back to the main document instead of copied.
  22105. * @returns {Object} The result of the calculation.
  22106. *
  22107. * @example
  22108. * function calculate(parameters, transferableObjects) {
  22109. * // perform whatever calculation is necessary.
  22110. * var typedArray = new Float32Array(0);
  22111. *
  22112. * // typed arrays are transferable
  22113. * transferableObjects.push(typedArray)
  22114. *
  22115. * return {
  22116. * typedArray : typedArray
  22117. * };
  22118. * }
  22119. */
  22120. /**
  22121. * A Web Worker message event handler function that handles the interaction with TaskProcessor,
  22122. * specifically, task ID management and posting a response message containing the result.
  22123. * @callback createTaskProcessorWorker~TaskProcessorWorkerFunction
  22124. *
  22125. * @param {Object} event The onmessage event object.
  22126. */
  22127. return createTaskProcessorWorker;
  22128. });
  22129. /*global define*/
  22130. define('Workers/createVerticesFromHeightmap',[
  22131. '../Core/Ellipsoid',
  22132. '../Core/HeightmapTessellator',
  22133. '../Core/Rectangle',
  22134. './createTaskProcessorWorker'
  22135. ], function(
  22136. Ellipsoid,
  22137. HeightmapTessellator,
  22138. Rectangle,
  22139. createTaskProcessorWorker) {
  22140. 'use strict';
  22141. function createVerticesFromHeightmap(parameters, transferableObjects) {
  22142. var arrayWidth = parameters.width;
  22143. var arrayHeight = parameters.height;
  22144. if (parameters.skirtHeight > 0.0) {
  22145. arrayWidth += 2;
  22146. arrayHeight += 2;
  22147. }
  22148. parameters.ellipsoid = Ellipsoid.clone(parameters.ellipsoid);
  22149. parameters.rectangle = Rectangle.clone(parameters.rectangle);
  22150. var statistics = HeightmapTessellator.computeVertices(parameters);
  22151. var vertices = statistics.vertices;
  22152. transferableObjects.push(vertices.buffer);
  22153. return {
  22154. vertices : vertices.buffer,
  22155. numberOfAttributes : statistics.encoding.getStride(),
  22156. minimumHeight : statistics.minimumHeight,
  22157. maximumHeight : statistics.maximumHeight,
  22158. gridWidth : arrayWidth,
  22159. gridHeight : arrayHeight,
  22160. boundingSphere3D : statistics.boundingSphere3D,
  22161. orientedBoundingBox : statistics.orientedBoundingBox,
  22162. occludeePointInScaledSpace : statistics.occludeePointInScaledSpace,
  22163. encoding : statistics.encoding
  22164. };
  22165. }
  22166. return createTaskProcessorWorker(createVerticesFromHeightmap);
  22167. });
  22168. }());