aframe-extras.js 337 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440
  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. 'use strict';
  3. require('./');
  4. },{"./":2}],2:[function(require,module,exports){
  5. 'use strict';
  6. require('./src/controls');
  7. require('./src/loaders');
  8. require('./src/misc');
  9. require('./src/pathfinding');
  10. require('./src/primitives');
  11. },{"./src/controls":14,"./src/loaders":23,"./src/misc":28,"./src/pathfinding":34,"./src/primitives":42}],3:[function(require,module,exports){
  12. 'use strict';
  13. /**
  14. * @author mrdoob / http://mrdoob.com/
  15. * @author Mugen87 / https://github.com/Mugen87
  16. */
  17. module.exports = THREE.ColladaLoader = function (manager) {
  18. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  19. };
  20. THREE.ColladaLoader.prototype = {
  21. constructor: THREE.ColladaLoader,
  22. crossOrigin: 'anonymous',
  23. load: function load(url, onLoad, onProgress, onError) {
  24. var scope = this;
  25. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase(url) : scope.path;
  26. var loader = new THREE.FileLoader(scope.manager);
  27. loader.setPath(scope.path);
  28. loader.load(url, function (text) {
  29. onLoad(scope.parse(text, path));
  30. }, onProgress, onError);
  31. },
  32. setPath: function setPath(value) {
  33. this.path = value;
  34. return this;
  35. },
  36. setResourcePath: function setResourcePath(value) {
  37. this.resourcePath = value;
  38. return this;
  39. },
  40. options: {
  41. set convertUpAxis(value) {
  42. console.warn('THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.');
  43. }
  44. },
  45. setCrossOrigin: function setCrossOrigin(value) {
  46. this.crossOrigin = value;
  47. return this;
  48. },
  49. parse: function parse(text, path) {
  50. function getElementsByTagName(xml, name) {
  51. // Non recursive xml.getElementsByTagName() ...
  52. var array = [];
  53. var childNodes = xml.childNodes;
  54. for (var i = 0, l = childNodes.length; i < l; i++) {
  55. var child = childNodes[i];
  56. if (child.nodeName === name) {
  57. array.push(child);
  58. }
  59. }
  60. return array;
  61. }
  62. function parseStrings(text) {
  63. if (text.length === 0) return [];
  64. var parts = text.trim().split(/\s+/);
  65. var array = new Array(parts.length);
  66. for (var i = 0, l = parts.length; i < l; i++) {
  67. array[i] = parts[i];
  68. }
  69. return array;
  70. }
  71. function parseFloats(text) {
  72. if (text.length === 0) return [];
  73. var parts = text.trim().split(/\s+/);
  74. var array = new Array(parts.length);
  75. for (var i = 0, l = parts.length; i < l; i++) {
  76. array[i] = parseFloat(parts[i]);
  77. }
  78. return array;
  79. }
  80. function parseInts(text) {
  81. if (text.length === 0) return [];
  82. var parts = text.trim().split(/\s+/);
  83. var array = new Array(parts.length);
  84. for (var i = 0, l = parts.length; i < l; i++) {
  85. array[i] = parseInt(parts[i]);
  86. }
  87. return array;
  88. }
  89. function parseId(text) {
  90. return text.substring(1);
  91. }
  92. function generateId() {
  93. return 'three_default_' + count++;
  94. }
  95. function isEmpty(object) {
  96. return Object.keys(object).length === 0;
  97. }
  98. // asset
  99. function parseAsset(xml) {
  100. return {
  101. unit: parseAssetUnit(getElementsByTagName(xml, 'unit')[0]),
  102. upAxis: parseAssetUpAxis(getElementsByTagName(xml, 'up_axis')[0])
  103. };
  104. }
  105. function parseAssetUnit(xml) {
  106. if (xml !== undefined && xml.hasAttribute('meter') === true) {
  107. return parseFloat(xml.getAttribute('meter'));
  108. } else {
  109. return 1; // default 1 meter
  110. }
  111. }
  112. function parseAssetUpAxis(xml) {
  113. return xml !== undefined ? xml.textContent : 'Y_UP';
  114. }
  115. // library
  116. function parseLibrary(xml, libraryName, nodeName, parser) {
  117. var library = getElementsByTagName(xml, libraryName)[0];
  118. if (library !== undefined) {
  119. var elements = getElementsByTagName(library, nodeName);
  120. for (var i = 0; i < elements.length; i++) {
  121. parser(elements[i]);
  122. }
  123. }
  124. }
  125. function buildLibrary(data, builder) {
  126. for (var name in data) {
  127. var object = data[name];
  128. object.build = builder(data[name]);
  129. }
  130. }
  131. // get
  132. function getBuild(data, builder) {
  133. if (data.build !== undefined) return data.build;
  134. data.build = builder(data);
  135. return data.build;
  136. }
  137. // animation
  138. function parseAnimation(xml) {
  139. var data = {
  140. sources: {},
  141. samplers: {},
  142. channels: {}
  143. };
  144. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  145. var child = xml.childNodes[i];
  146. if (child.nodeType !== 1) continue;
  147. var id;
  148. switch (child.nodeName) {
  149. case 'source':
  150. id = child.getAttribute('id');
  151. data.sources[id] = parseSource(child);
  152. break;
  153. case 'sampler':
  154. id = child.getAttribute('id');
  155. data.samplers[id] = parseAnimationSampler(child);
  156. break;
  157. case 'channel':
  158. id = child.getAttribute('target');
  159. data.channels[id] = parseAnimationChannel(child);
  160. break;
  161. default:
  162. console.log(child);
  163. }
  164. }
  165. library.animations[xml.getAttribute('id')] = data;
  166. }
  167. function parseAnimationSampler(xml) {
  168. var data = {
  169. inputs: {}
  170. };
  171. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  172. var child = xml.childNodes[i];
  173. if (child.nodeType !== 1) continue;
  174. switch (child.nodeName) {
  175. case 'input':
  176. var id = parseId(child.getAttribute('source'));
  177. var semantic = child.getAttribute('semantic');
  178. data.inputs[semantic] = id;
  179. break;
  180. }
  181. }
  182. return data;
  183. }
  184. function parseAnimationChannel(xml) {
  185. var data = {};
  186. var target = xml.getAttribute('target');
  187. // parsing SID Addressing Syntax
  188. var parts = target.split('/');
  189. var id = parts.shift();
  190. var sid = parts.shift();
  191. // check selection syntax
  192. var arraySyntax = sid.indexOf('(') !== -1;
  193. var memberSyntax = sid.indexOf('.') !== -1;
  194. if (memberSyntax) {
  195. // member selection access
  196. parts = sid.split('.');
  197. sid = parts.shift();
  198. data.member = parts.shift();
  199. } else if (arraySyntax) {
  200. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  201. var indices = sid.split('(');
  202. sid = indices.shift();
  203. for (var i = 0; i < indices.length; i++) {
  204. indices[i] = parseInt(indices[i].replace(/\)/, ''));
  205. }
  206. data.indices = indices;
  207. }
  208. data.id = id;
  209. data.sid = sid;
  210. data.arraySyntax = arraySyntax;
  211. data.memberSyntax = memberSyntax;
  212. data.sampler = parseId(xml.getAttribute('source'));
  213. return data;
  214. }
  215. function buildAnimation(data) {
  216. var tracks = [];
  217. var channels = data.channels;
  218. var samplers = data.samplers;
  219. var sources = data.sources;
  220. for (var target in channels) {
  221. if (channels.hasOwnProperty(target)) {
  222. var channel = channels[target];
  223. var sampler = samplers[channel.sampler];
  224. var inputId = sampler.inputs.INPUT;
  225. var outputId = sampler.inputs.OUTPUT;
  226. var inputSource = sources[inputId];
  227. var outputSource = sources[outputId];
  228. var animation = buildAnimationChannel(channel, inputSource, outputSource);
  229. createKeyframeTracks(animation, tracks);
  230. }
  231. }
  232. return tracks;
  233. }
  234. function getAnimation(id) {
  235. return getBuild(library.animations[id], buildAnimation);
  236. }
  237. function buildAnimationChannel(channel, inputSource, outputSource) {
  238. var node = library.nodes[channel.id];
  239. var object3D = getNode(node.id);
  240. var transform = node.transforms[channel.sid];
  241. var defaultMatrix = node.matrix.clone().transpose();
  242. var time, stride;
  243. var i, il, j, jl;
  244. var data = {};
  245. // the collada spec allows the animation of data in various ways.
  246. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  247. switch (transform) {
  248. case 'matrix':
  249. for (i = 0, il = inputSource.array.length; i < il; i++) {
  250. time = inputSource.array[i];
  251. stride = i * outputSource.stride;
  252. if (data[time] === undefined) data[time] = {};
  253. if (channel.arraySyntax === true) {
  254. var value = outputSource.array[stride];
  255. var index = channel.indices[0] + 4 * channel.indices[1];
  256. data[time][index] = value;
  257. } else {
  258. for (j = 0, jl = outputSource.stride; j < jl; j++) {
  259. data[time][j] = outputSource.array[stride + j];
  260. }
  261. }
  262. }
  263. break;
  264. case 'translate':
  265. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  266. break;
  267. case 'rotate':
  268. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  269. break;
  270. case 'scale':
  271. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  272. break;
  273. }
  274. var keyframes = prepareAnimationData(data, defaultMatrix);
  275. var animation = {
  276. name: object3D.uuid,
  277. keyframes: keyframes
  278. };
  279. return animation;
  280. }
  281. function prepareAnimationData(data, defaultMatrix) {
  282. var keyframes = [];
  283. // transfer data into a sortable array
  284. for (var time in data) {
  285. keyframes.push({ time: parseFloat(time), value: data[time] });
  286. }
  287. // ensure keyframes are sorted by time
  288. keyframes.sort(ascending);
  289. // now we clean up all animation data, so we can use them for keyframe tracks
  290. for (var i = 0; i < 16; i++) {
  291. transformAnimationData(keyframes, i, defaultMatrix.elements[i]);
  292. }
  293. return keyframes;
  294. // array sort function
  295. function ascending(a, b) {
  296. return a.time - b.time;
  297. }
  298. }
  299. var position = new THREE.Vector3();
  300. var scale = new THREE.Vector3();
  301. var quaternion = new THREE.Quaternion();
  302. function createKeyframeTracks(animation, tracks) {
  303. var keyframes = animation.keyframes;
  304. var name = animation.name;
  305. var times = [];
  306. var positionData = [];
  307. var quaternionData = [];
  308. var scaleData = [];
  309. for (var i = 0, l = keyframes.length; i < l; i++) {
  310. var keyframe = keyframes[i];
  311. var time = keyframe.time;
  312. var value = keyframe.value;
  313. matrix.fromArray(value).transpose();
  314. matrix.decompose(position, quaternion, scale);
  315. times.push(time);
  316. positionData.push(position.x, position.y, position.z);
  317. quaternionData.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  318. scaleData.push(scale.x, scale.y, scale.z);
  319. }
  320. if (positionData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.position', times, positionData));
  321. if (quaternionData.length > 0) tracks.push(new THREE.QuaternionKeyframeTrack(name + '.quaternion', times, quaternionData));
  322. if (scaleData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.scale', times, scaleData));
  323. return tracks;
  324. }
  325. function transformAnimationData(keyframes, property, defaultValue) {
  326. var keyframe;
  327. var empty = true;
  328. var i, l;
  329. // check, if values of a property are missing in our keyframes
  330. for (i = 0, l = keyframes.length; i < l; i++) {
  331. keyframe = keyframes[i];
  332. if (keyframe.value[property] === undefined) {
  333. keyframe.value[property] = null; // mark as missing
  334. } else {
  335. empty = false;
  336. }
  337. }
  338. if (empty === true) {
  339. // no values at all, so we set a default value
  340. for (i = 0, l = keyframes.length; i < l; i++) {
  341. keyframe = keyframes[i];
  342. keyframe.value[property] = defaultValue;
  343. }
  344. } else {
  345. // filling gaps
  346. createMissingKeyframes(keyframes, property);
  347. }
  348. }
  349. function createMissingKeyframes(keyframes, property) {
  350. var prev, next;
  351. for (var i = 0, l = keyframes.length; i < l; i++) {
  352. var keyframe = keyframes[i];
  353. if (keyframe.value[property] === null) {
  354. prev = getPrev(keyframes, i, property);
  355. next = getNext(keyframes, i, property);
  356. if (prev === null) {
  357. keyframe.value[property] = next.value[property];
  358. continue;
  359. }
  360. if (next === null) {
  361. keyframe.value[property] = prev.value[property];
  362. continue;
  363. }
  364. interpolate(keyframe, prev, next, property);
  365. }
  366. }
  367. }
  368. function getPrev(keyframes, i, property) {
  369. while (i >= 0) {
  370. var keyframe = keyframes[i];
  371. if (keyframe.value[property] !== null) return keyframe;
  372. i--;
  373. }
  374. return null;
  375. }
  376. function getNext(keyframes, i, property) {
  377. while (i < keyframes.length) {
  378. var keyframe = keyframes[i];
  379. if (keyframe.value[property] !== null) return keyframe;
  380. i++;
  381. }
  382. return null;
  383. }
  384. function interpolate(key, prev, next, property) {
  385. if (next.time - prev.time === 0) {
  386. key.value[property] = prev.value[property];
  387. return;
  388. }
  389. key.value[property] = (key.time - prev.time) * (next.value[property] - prev.value[property]) / (next.time - prev.time) + prev.value[property];
  390. }
  391. // animation clips
  392. function parseAnimationClip(xml) {
  393. var data = {
  394. name: xml.getAttribute('id') || 'default',
  395. start: parseFloat(xml.getAttribute('start') || 0),
  396. end: parseFloat(xml.getAttribute('end') || 0),
  397. animations: []
  398. };
  399. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  400. var child = xml.childNodes[i];
  401. if (child.nodeType !== 1) continue;
  402. switch (child.nodeName) {
  403. case 'instance_animation':
  404. data.animations.push(parseId(child.getAttribute('url')));
  405. break;
  406. }
  407. }
  408. library.clips[xml.getAttribute('id')] = data;
  409. }
  410. function buildAnimationClip(data) {
  411. var tracks = [];
  412. var name = data.name;
  413. var duration = data.end - data.start || -1;
  414. var animations = data.animations;
  415. for (var i = 0, il = animations.length; i < il; i++) {
  416. var animationTracks = getAnimation(animations[i]);
  417. for (var j = 0, jl = animationTracks.length; j < jl; j++) {
  418. tracks.push(animationTracks[j]);
  419. }
  420. }
  421. return new THREE.AnimationClip(name, duration, tracks);
  422. }
  423. function getAnimationClip(id) {
  424. return getBuild(library.clips[id], buildAnimationClip);
  425. }
  426. // controller
  427. function parseController(xml) {
  428. var data = {};
  429. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  430. var child = xml.childNodes[i];
  431. if (child.nodeType !== 1) continue;
  432. switch (child.nodeName) {
  433. case 'skin':
  434. // there is exactly one skin per controller
  435. data.id = parseId(child.getAttribute('source'));
  436. data.skin = parseSkin(child);
  437. break;
  438. case 'morph':
  439. data.id = parseId(child.getAttribute('source'));
  440. console.warn('THREE.ColladaLoader: Morph target animation not supported yet.');
  441. break;
  442. }
  443. }
  444. library.controllers[xml.getAttribute('id')] = data;
  445. }
  446. function parseSkin(xml) {
  447. var data = {
  448. sources: {}
  449. };
  450. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  451. var child = xml.childNodes[i];
  452. if (child.nodeType !== 1) continue;
  453. switch (child.nodeName) {
  454. case 'bind_shape_matrix':
  455. data.bindShapeMatrix = parseFloats(child.textContent);
  456. break;
  457. case 'source':
  458. var id = child.getAttribute('id');
  459. data.sources[id] = parseSource(child);
  460. break;
  461. case 'joints':
  462. data.joints = parseJoints(child);
  463. break;
  464. case 'vertex_weights':
  465. data.vertexWeights = parseVertexWeights(child);
  466. break;
  467. }
  468. }
  469. return data;
  470. }
  471. function parseJoints(xml) {
  472. var data = {
  473. inputs: {}
  474. };
  475. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  476. var child = xml.childNodes[i];
  477. if (child.nodeType !== 1) continue;
  478. switch (child.nodeName) {
  479. case 'input':
  480. var semantic = child.getAttribute('semantic');
  481. var id = parseId(child.getAttribute('source'));
  482. data.inputs[semantic] = id;
  483. break;
  484. }
  485. }
  486. return data;
  487. }
  488. function parseVertexWeights(xml) {
  489. var data = {
  490. inputs: {}
  491. };
  492. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  493. var child = xml.childNodes[i];
  494. if (child.nodeType !== 1) continue;
  495. switch (child.nodeName) {
  496. case 'input':
  497. var semantic = child.getAttribute('semantic');
  498. var id = parseId(child.getAttribute('source'));
  499. var offset = parseInt(child.getAttribute('offset'));
  500. data.inputs[semantic] = { id: id, offset: offset };
  501. break;
  502. case 'vcount':
  503. data.vcount = parseInts(child.textContent);
  504. break;
  505. case 'v':
  506. data.v = parseInts(child.textContent);
  507. break;
  508. }
  509. }
  510. return data;
  511. }
  512. function buildController(data) {
  513. var build = {
  514. id: data.id
  515. };
  516. var geometry = library.geometries[build.id];
  517. if (data.skin !== undefined) {
  518. build.skin = buildSkin(data.skin);
  519. // we enhance the 'sources' property of the corresponding geometry with our skin data
  520. geometry.sources.skinIndices = build.skin.indices;
  521. geometry.sources.skinWeights = build.skin.weights;
  522. }
  523. return build;
  524. }
  525. function buildSkin(data) {
  526. var BONE_LIMIT = 4;
  527. var build = {
  528. joints: [], // this must be an array to preserve the joint order
  529. indices: {
  530. array: [],
  531. stride: BONE_LIMIT
  532. },
  533. weights: {
  534. array: [],
  535. stride: BONE_LIMIT
  536. }
  537. };
  538. var sources = data.sources;
  539. var vertexWeights = data.vertexWeights;
  540. var vcount = vertexWeights.vcount;
  541. var v = vertexWeights.v;
  542. var jointOffset = vertexWeights.inputs.JOINT.offset;
  543. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  544. var jointSource = data.sources[data.joints.inputs.JOINT];
  545. var inverseSource = data.sources[data.joints.inputs.INV_BIND_MATRIX];
  546. var weights = sources[vertexWeights.inputs.WEIGHT.id].array;
  547. var stride = 0;
  548. var i, j, l;
  549. // procces skin data for each vertex
  550. for (i = 0, l = vcount.length; i < l; i++) {
  551. var jointCount = vcount[i]; // this is the amount of joints that affect a single vertex
  552. var vertexSkinData = [];
  553. for (j = 0; j < jointCount; j++) {
  554. var skinIndex = v[stride + jointOffset];
  555. var weightId = v[stride + weightOffset];
  556. var skinWeight = weights[weightId];
  557. vertexSkinData.push({ index: skinIndex, weight: skinWeight });
  558. stride += 2;
  559. }
  560. // we sort the joints in descending order based on the weights.
  561. // this ensures, we only procced the most important joints of the vertex
  562. vertexSkinData.sort(descending);
  563. // now we provide for each vertex a set of four index and weight values.
  564. // the order of the skin data matches the order of vertices
  565. for (j = 0; j < BONE_LIMIT; j++) {
  566. var d = vertexSkinData[j];
  567. if (d !== undefined) {
  568. build.indices.array.push(d.index);
  569. build.weights.array.push(d.weight);
  570. } else {
  571. build.indices.array.push(0);
  572. build.weights.array.push(0);
  573. }
  574. }
  575. }
  576. // setup bind matrix
  577. if (data.bindShapeMatrix) {
  578. build.bindMatrix = new THREE.Matrix4().fromArray(data.bindShapeMatrix).transpose();
  579. } else {
  580. build.bindMatrix = new THREE.Matrix4().identity();
  581. }
  582. // process bones and inverse bind matrix data
  583. for (i = 0, l = jointSource.array.length; i < l; i++) {
  584. var name = jointSource.array[i];
  585. var boneInverse = new THREE.Matrix4().fromArray(inverseSource.array, i * inverseSource.stride).transpose();
  586. build.joints.push({ name: name, boneInverse: boneInverse });
  587. }
  588. return build;
  589. // array sort function
  590. function descending(a, b) {
  591. return b.weight - a.weight;
  592. }
  593. }
  594. function getController(id) {
  595. return getBuild(library.controllers[id], buildController);
  596. }
  597. // image
  598. function parseImage(xml) {
  599. var data = {
  600. init_from: getElementsByTagName(xml, 'init_from')[0].textContent
  601. };
  602. library.images[xml.getAttribute('id')] = data;
  603. }
  604. function buildImage(data) {
  605. if (data.build !== undefined) return data.build;
  606. return data.init_from;
  607. }
  608. function getImage(id) {
  609. var data = library.images[id];
  610. if (data !== undefined) {
  611. return getBuild(data, buildImage);
  612. }
  613. console.warn('THREE.ColladaLoader: Couldn\'t find image with ID:', id);
  614. return null;
  615. }
  616. // effect
  617. function parseEffect(xml) {
  618. var data = {};
  619. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  620. var child = xml.childNodes[i];
  621. if (child.nodeType !== 1) continue;
  622. switch (child.nodeName) {
  623. case 'profile_COMMON':
  624. data.profile = parseEffectProfileCOMMON(child);
  625. break;
  626. }
  627. }
  628. library.effects[xml.getAttribute('id')] = data;
  629. }
  630. function parseEffectProfileCOMMON(xml) {
  631. var data = {
  632. surfaces: {},
  633. samplers: {}
  634. };
  635. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  636. var child = xml.childNodes[i];
  637. if (child.nodeType !== 1) continue;
  638. switch (child.nodeName) {
  639. case 'newparam':
  640. parseEffectNewparam(child, data);
  641. break;
  642. case 'technique':
  643. data.technique = parseEffectTechnique(child);
  644. break;
  645. case 'extra':
  646. data.extra = parseEffectExtra(child);
  647. break;
  648. }
  649. }
  650. return data;
  651. }
  652. function parseEffectNewparam(xml, data) {
  653. var sid = xml.getAttribute('sid');
  654. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  655. var child = xml.childNodes[i];
  656. if (child.nodeType !== 1) continue;
  657. switch (child.nodeName) {
  658. case 'surface':
  659. data.surfaces[sid] = parseEffectSurface(child);
  660. break;
  661. case 'sampler2D':
  662. data.samplers[sid] = parseEffectSampler(child);
  663. break;
  664. }
  665. }
  666. }
  667. function parseEffectSurface(xml) {
  668. var data = {};
  669. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  670. var child = xml.childNodes[i];
  671. if (child.nodeType !== 1) continue;
  672. switch (child.nodeName) {
  673. case 'init_from':
  674. data.init_from = child.textContent;
  675. break;
  676. }
  677. }
  678. return data;
  679. }
  680. function parseEffectSampler(xml) {
  681. var data = {};
  682. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  683. var child = xml.childNodes[i];
  684. if (child.nodeType !== 1) continue;
  685. switch (child.nodeName) {
  686. case 'source':
  687. data.source = child.textContent;
  688. break;
  689. }
  690. }
  691. return data;
  692. }
  693. function parseEffectTechnique(xml) {
  694. var data = {};
  695. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  696. var child = xml.childNodes[i];
  697. if (child.nodeType !== 1) continue;
  698. switch (child.nodeName) {
  699. case 'constant':
  700. case 'lambert':
  701. case 'blinn':
  702. case 'phong':
  703. data.type = child.nodeName;
  704. data.parameters = parseEffectParameters(child);
  705. break;
  706. }
  707. }
  708. return data;
  709. }
  710. function parseEffectParameters(xml) {
  711. var data = {};
  712. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  713. var child = xml.childNodes[i];
  714. if (child.nodeType !== 1) continue;
  715. switch (child.nodeName) {
  716. case 'emission':
  717. case 'diffuse':
  718. case 'specular':
  719. case 'bump':
  720. case 'ambient':
  721. case 'shininess':
  722. case 'transparency':
  723. data[child.nodeName] = parseEffectParameter(child);
  724. break;
  725. case 'transparent':
  726. data[child.nodeName] = {
  727. opaque: child.getAttribute('opaque'),
  728. data: parseEffectParameter(child)
  729. };
  730. break;
  731. }
  732. }
  733. return data;
  734. }
  735. function parseEffectParameter(xml) {
  736. var data = {};
  737. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  738. var child = xml.childNodes[i];
  739. if (child.nodeType !== 1) continue;
  740. switch (child.nodeName) {
  741. case 'color':
  742. data[child.nodeName] = parseFloats(child.textContent);
  743. break;
  744. case 'float':
  745. data[child.nodeName] = parseFloat(child.textContent);
  746. break;
  747. case 'texture':
  748. data[child.nodeName] = { id: child.getAttribute('texture'), extra: parseEffectParameterTexture(child) };
  749. break;
  750. }
  751. }
  752. return data;
  753. }
  754. function parseEffectParameterTexture(xml) {
  755. var data = {
  756. technique: {}
  757. };
  758. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  759. var child = xml.childNodes[i];
  760. if (child.nodeType !== 1) continue;
  761. switch (child.nodeName) {
  762. case 'extra':
  763. parseEffectParameterTextureExtra(child, data);
  764. break;
  765. }
  766. }
  767. return data;
  768. }
  769. function parseEffectParameterTextureExtra(xml, data) {
  770. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  771. var child = xml.childNodes[i];
  772. if (child.nodeType !== 1) continue;
  773. switch (child.nodeName) {
  774. case 'technique':
  775. parseEffectParameterTextureExtraTechnique(child, data);
  776. break;
  777. }
  778. }
  779. }
  780. function parseEffectParameterTextureExtraTechnique(xml, data) {
  781. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  782. var child = xml.childNodes[i];
  783. if (child.nodeType !== 1) continue;
  784. switch (child.nodeName) {
  785. case 'repeatU':
  786. case 'repeatV':
  787. case 'offsetU':
  788. case 'offsetV':
  789. data.technique[child.nodeName] = parseFloat(child.textContent);
  790. break;
  791. case 'wrapU':
  792. case 'wrapV':
  793. // some files have values for wrapU/wrapV which become NaN via parseInt
  794. if (child.textContent.toUpperCase() === 'TRUE') {
  795. data.technique[child.nodeName] = 1;
  796. } else if (child.textContent.toUpperCase() === 'FALSE') {
  797. data.technique[child.nodeName] = 0;
  798. } else {
  799. data.technique[child.nodeName] = parseInt(child.textContent);
  800. }
  801. break;
  802. }
  803. }
  804. }
  805. function parseEffectExtra(xml) {
  806. var data = {};
  807. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  808. var child = xml.childNodes[i];
  809. if (child.nodeType !== 1) continue;
  810. switch (child.nodeName) {
  811. case 'technique':
  812. data.technique = parseEffectExtraTechnique(child);
  813. break;
  814. }
  815. }
  816. return data;
  817. }
  818. function parseEffectExtraTechnique(xml) {
  819. var data = {};
  820. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  821. var child = xml.childNodes[i];
  822. if (child.nodeType !== 1) continue;
  823. switch (child.nodeName) {
  824. case 'double_sided':
  825. data[child.nodeName] = parseInt(child.textContent);
  826. break;
  827. }
  828. }
  829. return data;
  830. }
  831. function buildEffect(data) {
  832. return data;
  833. }
  834. function getEffect(id) {
  835. return getBuild(library.effects[id], buildEffect);
  836. }
  837. // material
  838. function parseMaterial(xml) {
  839. var data = {
  840. name: xml.getAttribute('name')
  841. };
  842. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  843. var child = xml.childNodes[i];
  844. if (child.nodeType !== 1) continue;
  845. switch (child.nodeName) {
  846. case 'instance_effect':
  847. data.url = parseId(child.getAttribute('url'));
  848. break;
  849. }
  850. }
  851. library.materials[xml.getAttribute('id')] = data;
  852. }
  853. function getTextureLoader(image) {
  854. var loader;
  855. var extension = image.slice((image.lastIndexOf('.') - 1 >>> 0) + 2); // http://www.jstips.co/en/javascript/get-file-extension/
  856. extension = extension.toLowerCase();
  857. switch (extension) {
  858. case 'tga':
  859. loader = tgaLoader;
  860. break;
  861. default:
  862. loader = textureLoader;
  863. }
  864. return loader;
  865. }
  866. function buildMaterial(data) {
  867. var effect = getEffect(data.url);
  868. var technique = effect.profile.technique;
  869. var extra = effect.profile.extra;
  870. var material;
  871. switch (technique.type) {
  872. case 'phong':
  873. case 'blinn':
  874. material = new THREE.MeshPhongMaterial();
  875. break;
  876. case 'lambert':
  877. material = new THREE.MeshLambertMaterial();
  878. break;
  879. default:
  880. material = new THREE.MeshBasicMaterial();
  881. break;
  882. }
  883. material.name = data.name;
  884. function getTexture(textureObject) {
  885. var sampler = effect.profile.samplers[textureObject.id];
  886. var image = null;
  887. // get image
  888. if (sampler !== undefined) {
  889. var surface = effect.profile.surfaces[sampler.source];
  890. image = getImage(surface.init_from);
  891. } else {
  892. console.warn('THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).');
  893. image = getImage(textureObject.id);
  894. }
  895. // create texture if image is avaiable
  896. if (image !== null) {
  897. var loader = getTextureLoader(image);
  898. if (loader !== undefined) {
  899. var texture = loader.load(image);
  900. var extra = textureObject.extra;
  901. if (extra !== undefined && extra.technique !== undefined && isEmpty(extra.technique) === false) {
  902. var technique = extra.technique;
  903. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  904. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  905. texture.offset.set(technique.offsetU || 0, technique.offsetV || 0);
  906. texture.repeat.set(technique.repeatU || 1, technique.repeatV || 1);
  907. } else {
  908. texture.wrapS = THREE.RepeatWrapping;
  909. texture.wrapT = THREE.RepeatWrapping;
  910. }
  911. return texture;
  912. } else {
  913. console.warn('THREE.ColladaLoader: Loader for texture %s not found.', image);
  914. return null;
  915. }
  916. } else {
  917. console.warn('THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id);
  918. return null;
  919. }
  920. }
  921. var parameters = technique.parameters;
  922. for (var key in parameters) {
  923. var parameter = parameters[key];
  924. switch (key) {
  925. case 'diffuse':
  926. if (parameter.color) material.color.fromArray(parameter.color);
  927. if (parameter.texture) material.map = getTexture(parameter.texture);
  928. break;
  929. case 'specular':
  930. if (parameter.color && material.specular) material.specular.fromArray(parameter.color);
  931. if (parameter.texture) material.specularMap = getTexture(parameter.texture);
  932. break;
  933. case 'bump':
  934. if (parameter.texture) material.normalMap = getTexture(parameter.texture);
  935. break;
  936. case 'ambient':
  937. if (parameter.texture) material.lightMap = getTexture(parameter.texture);
  938. break;
  939. case 'shininess':
  940. if (parameter.float && material.shininess) material.shininess = parameter.float;
  941. break;
  942. case 'emission':
  943. if (parameter.color && material.emissive) material.emissive.fromArray(parameter.color);
  944. if (parameter.texture) material.emissiveMap = getTexture(parameter.texture);
  945. break;
  946. }
  947. }
  948. //
  949. var transparent = parameters['transparent'];
  950. var transparency = parameters['transparency'];
  951. // <transparency> does not exist but <transparent>
  952. if (transparency === undefined && transparent) {
  953. transparency = {
  954. float: 1
  955. };
  956. }
  957. // <transparent> does not exist but <transparency>
  958. if (transparent === undefined && transparency) {
  959. transparent = {
  960. opaque: 'A_ONE',
  961. data: {
  962. color: [1, 1, 1, 1]
  963. } };
  964. }
  965. if (transparent && transparency) {
  966. // handle case if a texture exists but no color
  967. if (transparent.data.texture) {
  968. // we do not set an alpha map (see #13792)
  969. material.transparent = true;
  970. } else {
  971. var color = transparent.data.color;
  972. switch (transparent.opaque) {
  973. case 'A_ONE':
  974. material.opacity = color[3] * transparency.float;
  975. break;
  976. case 'RGB_ZERO':
  977. material.opacity = 1 - color[0] * transparency.float;
  978. break;
  979. case 'A_ZERO':
  980. material.opacity = 1 - color[3] * transparency.float;
  981. break;
  982. case 'RGB_ONE':
  983. material.opacity = color[0] * transparency.float;
  984. break;
  985. default:
  986. console.warn('THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque);
  987. }
  988. if (material.opacity < 1) material.transparent = true;
  989. }
  990. }
  991. //
  992. if (extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1) {
  993. material.side = THREE.DoubleSide;
  994. }
  995. return material;
  996. }
  997. function getMaterial(id) {
  998. return getBuild(library.materials[id], buildMaterial);
  999. }
  1000. // camera
  1001. function parseCamera(xml) {
  1002. var data = {
  1003. name: xml.getAttribute('name')
  1004. };
  1005. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1006. var child = xml.childNodes[i];
  1007. if (child.nodeType !== 1) continue;
  1008. switch (child.nodeName) {
  1009. case 'optics':
  1010. data.optics = parseCameraOptics(child);
  1011. break;
  1012. }
  1013. }
  1014. library.cameras[xml.getAttribute('id')] = data;
  1015. }
  1016. function parseCameraOptics(xml) {
  1017. for (var i = 0; i < xml.childNodes.length; i++) {
  1018. var child = xml.childNodes[i];
  1019. switch (child.nodeName) {
  1020. case 'technique_common':
  1021. return parseCameraTechnique(child);
  1022. }
  1023. }
  1024. return {};
  1025. }
  1026. function parseCameraTechnique(xml) {
  1027. var data = {};
  1028. for (var i = 0; i < xml.childNodes.length; i++) {
  1029. var child = xml.childNodes[i];
  1030. switch (child.nodeName) {
  1031. case 'perspective':
  1032. case 'orthographic':
  1033. data.technique = child.nodeName;
  1034. data.parameters = parseCameraParameters(child);
  1035. break;
  1036. }
  1037. }
  1038. return data;
  1039. }
  1040. function parseCameraParameters(xml) {
  1041. var data = {};
  1042. for (var i = 0; i < xml.childNodes.length; i++) {
  1043. var child = xml.childNodes[i];
  1044. switch (child.nodeName) {
  1045. case 'xfov':
  1046. case 'yfov':
  1047. case 'xmag':
  1048. case 'ymag':
  1049. case 'znear':
  1050. case 'zfar':
  1051. case 'aspect_ratio':
  1052. data[child.nodeName] = parseFloat(child.textContent);
  1053. break;
  1054. }
  1055. }
  1056. return data;
  1057. }
  1058. function buildCamera(data) {
  1059. var camera;
  1060. switch (data.optics.technique) {
  1061. case 'perspective':
  1062. camera = new THREE.PerspectiveCamera(data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar);
  1063. break;
  1064. case 'orthographic':
  1065. var ymag = data.optics.parameters.ymag;
  1066. var xmag = data.optics.parameters.xmag;
  1067. var aspectRatio = data.optics.parameters.aspect_ratio;
  1068. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1069. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1070. xmag *= 0.5;
  1071. ymag *= 0.5;
  1072. camera = new THREE.OrthographicCamera(-xmag, xmag, ymag, -ymag, // left, right, top, bottom
  1073. data.optics.parameters.znear, data.optics.parameters.zfar);
  1074. break;
  1075. default:
  1076. camera = new THREE.PerspectiveCamera();
  1077. break;
  1078. }
  1079. camera.name = data.name;
  1080. return camera;
  1081. }
  1082. function getCamera(id) {
  1083. var data = library.cameras[id];
  1084. if (data !== undefined) {
  1085. return getBuild(data, buildCamera);
  1086. }
  1087. console.warn('THREE.ColladaLoader: Couldn\'t find camera with ID:', id);
  1088. return null;
  1089. }
  1090. // light
  1091. function parseLight(xml) {
  1092. var data = {};
  1093. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1094. var child = xml.childNodes[i];
  1095. if (child.nodeType !== 1) continue;
  1096. switch (child.nodeName) {
  1097. case 'technique_common':
  1098. data = parseLightTechnique(child);
  1099. break;
  1100. }
  1101. }
  1102. library.lights[xml.getAttribute('id')] = data;
  1103. }
  1104. function parseLightTechnique(xml) {
  1105. var data = {};
  1106. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1107. var child = xml.childNodes[i];
  1108. if (child.nodeType !== 1) continue;
  1109. switch (child.nodeName) {
  1110. case 'directional':
  1111. case 'point':
  1112. case 'spot':
  1113. case 'ambient':
  1114. data.technique = child.nodeName;
  1115. data.parameters = parseLightParameters(child);
  1116. }
  1117. }
  1118. return data;
  1119. }
  1120. function parseLightParameters(xml) {
  1121. var data = {};
  1122. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1123. var child = xml.childNodes[i];
  1124. if (child.nodeType !== 1) continue;
  1125. switch (child.nodeName) {
  1126. case 'color':
  1127. var array = parseFloats(child.textContent);
  1128. data.color = new THREE.Color().fromArray(array);
  1129. break;
  1130. case 'falloff_angle':
  1131. data.falloffAngle = parseFloat(child.textContent);
  1132. break;
  1133. case 'quadratic_attenuation':
  1134. var f = parseFloat(child.textContent);
  1135. data.distance = f ? Math.sqrt(1 / f) : 0;
  1136. break;
  1137. }
  1138. }
  1139. return data;
  1140. }
  1141. function buildLight(data) {
  1142. var light;
  1143. switch (data.technique) {
  1144. case 'directional':
  1145. light = new THREE.DirectionalLight();
  1146. break;
  1147. case 'point':
  1148. light = new THREE.PointLight();
  1149. break;
  1150. case 'spot':
  1151. light = new THREE.SpotLight();
  1152. break;
  1153. case 'ambient':
  1154. light = new THREE.AmbientLight();
  1155. break;
  1156. }
  1157. if (data.parameters.color) light.color.copy(data.parameters.color);
  1158. if (data.parameters.distance) light.distance = data.parameters.distance;
  1159. return light;
  1160. }
  1161. function getLight(id) {
  1162. var data = library.lights[id];
  1163. if (data !== undefined) {
  1164. return getBuild(data, buildLight);
  1165. }
  1166. console.warn('THREE.ColladaLoader: Couldn\'t find light with ID:', id);
  1167. return null;
  1168. }
  1169. // geometry
  1170. function parseGeometry(xml) {
  1171. var data = {
  1172. name: xml.getAttribute('name'),
  1173. sources: {},
  1174. vertices: {},
  1175. primitives: []
  1176. };
  1177. var mesh = getElementsByTagName(xml, 'mesh')[0];
  1178. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1179. if (mesh === undefined) return;
  1180. for (var i = 0; i < mesh.childNodes.length; i++) {
  1181. var child = mesh.childNodes[i];
  1182. if (child.nodeType !== 1) continue;
  1183. var id = child.getAttribute('id');
  1184. switch (child.nodeName) {
  1185. case 'source':
  1186. data.sources[id] = parseSource(child);
  1187. break;
  1188. case 'vertices':
  1189. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1190. data.vertices = parseGeometryVertices(child);
  1191. break;
  1192. case 'polygons':
  1193. console.warn('THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName);
  1194. break;
  1195. case 'lines':
  1196. case 'linestrips':
  1197. case 'polylist':
  1198. case 'triangles':
  1199. data.primitives.push(parseGeometryPrimitive(child));
  1200. break;
  1201. default:
  1202. console.log(child);
  1203. }
  1204. }
  1205. library.geometries[xml.getAttribute('id')] = data;
  1206. }
  1207. function parseSource(xml) {
  1208. var data = {
  1209. array: [],
  1210. stride: 3
  1211. };
  1212. for (var i = 0; i < xml.childNodes.length; i++) {
  1213. var child = xml.childNodes[i];
  1214. if (child.nodeType !== 1) continue;
  1215. switch (child.nodeName) {
  1216. case 'float_array':
  1217. data.array = parseFloats(child.textContent);
  1218. break;
  1219. case 'Name_array':
  1220. data.array = parseStrings(child.textContent);
  1221. break;
  1222. case 'technique_common':
  1223. var accessor = getElementsByTagName(child, 'accessor')[0];
  1224. if (accessor !== undefined) {
  1225. data.stride = parseInt(accessor.getAttribute('stride'));
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. return data;
  1231. }
  1232. function parseGeometryVertices(xml) {
  1233. var data = {};
  1234. for (var i = 0; i < xml.childNodes.length; i++) {
  1235. var child = xml.childNodes[i];
  1236. if (child.nodeType !== 1) continue;
  1237. data[child.getAttribute('semantic')] = parseId(child.getAttribute('source'));
  1238. }
  1239. return data;
  1240. }
  1241. function parseGeometryPrimitive(xml) {
  1242. var primitive = {
  1243. type: xml.nodeName,
  1244. material: xml.getAttribute('material'),
  1245. count: parseInt(xml.getAttribute('count')),
  1246. inputs: {},
  1247. stride: 0,
  1248. hasUV: false
  1249. };
  1250. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1251. var child = xml.childNodes[i];
  1252. if (child.nodeType !== 1) continue;
  1253. switch (child.nodeName) {
  1254. case 'input':
  1255. var id = parseId(child.getAttribute('source'));
  1256. var semantic = child.getAttribute('semantic');
  1257. var offset = parseInt(child.getAttribute('offset'));
  1258. var set = parseInt(child.getAttribute('set'));
  1259. var inputname = set > 0 ? semantic + set : semantic;
  1260. primitive.inputs[inputname] = { id: id, offset: offset };
  1261. primitive.stride = Math.max(primitive.stride, offset + 1);
  1262. if (semantic === 'TEXCOORD') primitive.hasUV = true;
  1263. break;
  1264. case 'vcount':
  1265. primitive.vcount = parseInts(child.textContent);
  1266. break;
  1267. case 'p':
  1268. primitive.p = parseInts(child.textContent);
  1269. break;
  1270. }
  1271. }
  1272. return primitive;
  1273. }
  1274. function groupPrimitives(primitives) {
  1275. var build = {};
  1276. for (var i = 0; i < primitives.length; i++) {
  1277. var primitive = primitives[i];
  1278. if (build[primitive.type] === undefined) build[primitive.type] = [];
  1279. build[primitive.type].push(primitive);
  1280. }
  1281. return build;
  1282. }
  1283. function checkUVCoordinates(primitives) {
  1284. var count = 0;
  1285. for (var i = 0, l = primitives.length; i < l; i++) {
  1286. var primitive = primitives[i];
  1287. if (primitive.hasUV === true) {
  1288. count++;
  1289. }
  1290. }
  1291. if (count > 0 && count < primitives.length) {
  1292. primitives.uvsNeedsFix = true;
  1293. }
  1294. }
  1295. function buildGeometry(data) {
  1296. var build = {};
  1297. var sources = data.sources;
  1298. var vertices = data.vertices;
  1299. var primitives = data.primitives;
  1300. if (primitives.length === 0) return {};
  1301. // our goal is to create one buffer geometry for a single type of primitives
  1302. // first, we group all primitives by their type
  1303. var groupedPrimitives = groupPrimitives(primitives);
  1304. for (var type in groupedPrimitives) {
  1305. var primitiveType = groupedPrimitives[type];
  1306. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1307. checkUVCoordinates(primitiveType);
  1308. // third, create a buffer geometry for each type of primitives
  1309. build[type] = buildGeometryType(primitiveType, sources, vertices);
  1310. }
  1311. return build;
  1312. }
  1313. function buildGeometryType(primitives, sources, vertices) {
  1314. var build = {};
  1315. var position = { array: [], stride: 0 };
  1316. var normal = { array: [], stride: 0 };
  1317. var uv = { array: [], stride: 0 };
  1318. var uv2 = { array: [], stride: 0 };
  1319. var color = { array: [], stride: 0 };
  1320. var skinIndex = { array: [], stride: 4 };
  1321. var skinWeight = { array: [], stride: 4 };
  1322. var geometry = new THREE.BufferGeometry();
  1323. var materialKeys = [];
  1324. var start = 0;
  1325. for (var p = 0; p < primitives.length; p++) {
  1326. var primitive = primitives[p];
  1327. var inputs = primitive.inputs;
  1328. // groups
  1329. var count = 0;
  1330. switch (primitive.type) {
  1331. case 'lines':
  1332. case 'linestrips':
  1333. count = primitive.count * 2;
  1334. break;
  1335. case 'triangles':
  1336. count = primitive.count * 3;
  1337. break;
  1338. case 'polylist':
  1339. for (var g = 0; g < primitive.count; g++) {
  1340. var vc = primitive.vcount[g];
  1341. switch (vc) {
  1342. case 3:
  1343. count += 3; // single triangle
  1344. break;
  1345. case 4:
  1346. count += 6; // quad, subdivided into two triangles
  1347. break;
  1348. default:
  1349. count += (vc - 2) * 3; // polylist with more than four vertices
  1350. break;
  1351. }
  1352. }
  1353. break;
  1354. default:
  1355. console.warn('THREE.ColladaLoader: Unknow primitive type:', primitive.type);
  1356. }
  1357. geometry.addGroup(start, count, p);
  1358. start += count;
  1359. // material
  1360. if (primitive.material) {
  1361. materialKeys.push(primitive.material);
  1362. }
  1363. // geometry data
  1364. for (var name in inputs) {
  1365. var input = inputs[name];
  1366. switch (name) {
  1367. case 'VERTEX':
  1368. for (var key in vertices) {
  1369. var id = vertices[key];
  1370. switch (key) {
  1371. case 'POSITION':
  1372. var prevLength = position.array.length;
  1373. buildGeometryData(primitive, sources[id], input.offset, position.array);
  1374. position.stride = sources[id].stride;
  1375. if (sources.skinWeights && sources.skinIndices) {
  1376. buildGeometryData(primitive, sources.skinIndices, input.offset, skinIndex.array);
  1377. buildGeometryData(primitive, sources.skinWeights, input.offset, skinWeight.array);
  1378. }
  1379. // see #3803
  1380. if (primitive.hasUV === false && primitives.uvsNeedsFix === true) {
  1381. var count = (position.array.length - prevLength) / position.stride;
  1382. for (var i = 0; i < count; i++) {
  1383. // fill missing uv coordinates
  1384. uv.array.push(0, 0);
  1385. }
  1386. }
  1387. break;
  1388. case 'NORMAL':
  1389. buildGeometryData(primitive, sources[id], input.offset, normal.array);
  1390. normal.stride = sources[id].stride;
  1391. break;
  1392. case 'COLOR':
  1393. buildGeometryData(primitive, sources[id], input.offset, color.array);
  1394. color.stride = sources[id].stride;
  1395. break;
  1396. case 'TEXCOORD':
  1397. buildGeometryData(primitive, sources[id], input.offset, uv.array);
  1398. uv.stride = sources[id].stride;
  1399. break;
  1400. case 'TEXCOORD1':
  1401. buildGeometryData(primitive, sources[id], input.offset, uv2.array);
  1402. uv.stride = sources[id].stride;
  1403. break;
  1404. default:
  1405. console.warn('THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key);
  1406. }
  1407. }
  1408. break;
  1409. case 'NORMAL':
  1410. buildGeometryData(primitive, sources[input.id], input.offset, normal.array);
  1411. normal.stride = sources[input.id].stride;
  1412. break;
  1413. case 'COLOR':
  1414. buildGeometryData(primitive, sources[input.id], input.offset, color.array);
  1415. color.stride = sources[input.id].stride;
  1416. break;
  1417. case 'TEXCOORD':
  1418. buildGeometryData(primitive, sources[input.id], input.offset, uv.array);
  1419. uv.stride = sources[input.id].stride;
  1420. break;
  1421. case 'TEXCOORD1':
  1422. buildGeometryData(primitive, sources[input.id], input.offset, uv2.array);
  1423. uv2.stride = sources[input.id].stride;
  1424. break;
  1425. }
  1426. }
  1427. }
  1428. // build geometry
  1429. if (position.array.length > 0) geometry.addAttribute('position', new THREE.Float32BufferAttribute(position.array, position.stride));
  1430. if (normal.array.length > 0) geometry.addAttribute('normal', new THREE.Float32BufferAttribute(normal.array, normal.stride));
  1431. if (color.array.length > 0) geometry.addAttribute('color', new THREE.Float32BufferAttribute(color.array, color.stride));
  1432. if (uv.array.length > 0) geometry.addAttribute('uv', new THREE.Float32BufferAttribute(uv.array, uv.stride));
  1433. if (uv2.array.length > 0) geometry.addAttribute('uv2', new THREE.Float32BufferAttribute(uv2.array, uv2.stride));
  1434. if (skinIndex.array.length > 0) geometry.addAttribute('skinIndex', new THREE.Float32BufferAttribute(skinIndex.array, skinIndex.stride));
  1435. if (skinWeight.array.length > 0) geometry.addAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeight.array, skinWeight.stride));
  1436. build.data = geometry;
  1437. build.type = primitives[0].type;
  1438. build.materialKeys = materialKeys;
  1439. return build;
  1440. }
  1441. function buildGeometryData(primitive, source, offset, array) {
  1442. var indices = primitive.p;
  1443. var stride = primitive.stride;
  1444. var vcount = primitive.vcount;
  1445. function pushVector(i) {
  1446. var index = indices[i + offset] * sourceStride;
  1447. var length = index + sourceStride;
  1448. for (; index < length; index++) {
  1449. array.push(sourceArray[index]);
  1450. }
  1451. }
  1452. var sourceArray = source.array;
  1453. var sourceStride = source.stride;
  1454. if (primitive.vcount !== undefined) {
  1455. var index = 0;
  1456. for (var i = 0, l = vcount.length; i < l; i++) {
  1457. var count = vcount[i];
  1458. if (count === 4) {
  1459. var a = index + stride * 0;
  1460. var b = index + stride * 1;
  1461. var c = index + stride * 2;
  1462. var d = index + stride * 3;
  1463. pushVector(a);pushVector(b);pushVector(d);
  1464. pushVector(b);pushVector(c);pushVector(d);
  1465. } else if (count === 3) {
  1466. var a = index + stride * 0;
  1467. var b = index + stride * 1;
  1468. var c = index + stride * 2;
  1469. pushVector(a);pushVector(b);pushVector(c);
  1470. } else if (count > 4) {
  1471. for (var k = 1, kl = count - 2; k <= kl; k++) {
  1472. var a = index + stride * 0;
  1473. var b = index + stride * k;
  1474. var c = index + stride * (k + 1);
  1475. pushVector(a);pushVector(b);pushVector(c);
  1476. }
  1477. }
  1478. index += stride * count;
  1479. }
  1480. } else {
  1481. for (var i = 0, l = indices.length; i < l; i += stride) {
  1482. pushVector(i);
  1483. }
  1484. }
  1485. }
  1486. function getGeometry(id) {
  1487. return getBuild(library.geometries[id], buildGeometry);
  1488. }
  1489. // kinematics
  1490. function parseKinematicsModel(xml) {
  1491. var data = {
  1492. name: xml.getAttribute('name') || '',
  1493. joints: {},
  1494. links: []
  1495. };
  1496. for (var i = 0; i < xml.childNodes.length; i++) {
  1497. var child = xml.childNodes[i];
  1498. if (child.nodeType !== 1) continue;
  1499. switch (child.nodeName) {
  1500. case 'technique_common':
  1501. parseKinematicsTechniqueCommon(child, data);
  1502. break;
  1503. }
  1504. }
  1505. library.kinematicsModels[xml.getAttribute('id')] = data;
  1506. }
  1507. function buildKinematicsModel(data) {
  1508. if (data.build !== undefined) return data.build;
  1509. return data;
  1510. }
  1511. function getKinematicsModel(id) {
  1512. return getBuild(library.kinematicsModels[id], buildKinematicsModel);
  1513. }
  1514. function parseKinematicsTechniqueCommon(xml, data) {
  1515. for (var i = 0; i < xml.childNodes.length; i++) {
  1516. var child = xml.childNodes[i];
  1517. if (child.nodeType !== 1) continue;
  1518. switch (child.nodeName) {
  1519. case 'joint':
  1520. data.joints[child.getAttribute('sid')] = parseKinematicsJoint(child);
  1521. break;
  1522. case 'link':
  1523. data.links.push(parseKinematicsLink(child));
  1524. break;
  1525. }
  1526. }
  1527. }
  1528. function parseKinematicsJoint(xml) {
  1529. var data;
  1530. for (var i = 0; i < xml.childNodes.length; i++) {
  1531. var child = xml.childNodes[i];
  1532. if (child.nodeType !== 1) continue;
  1533. switch (child.nodeName) {
  1534. case 'prismatic':
  1535. case 'revolute':
  1536. data = parseKinematicsJointParameter(child);
  1537. break;
  1538. }
  1539. }
  1540. return data;
  1541. }
  1542. function parseKinematicsJointParameter(xml, data) {
  1543. var data = {
  1544. sid: xml.getAttribute('sid'),
  1545. name: xml.getAttribute('name') || '',
  1546. axis: new THREE.Vector3(),
  1547. limits: {
  1548. min: 0,
  1549. max: 0
  1550. },
  1551. type: xml.nodeName,
  1552. static: false,
  1553. zeroPosition: 0,
  1554. middlePosition: 0
  1555. };
  1556. for (var i = 0; i < xml.childNodes.length; i++) {
  1557. var child = xml.childNodes[i];
  1558. if (child.nodeType !== 1) continue;
  1559. switch (child.nodeName) {
  1560. case 'axis':
  1561. var array = parseFloats(child.textContent);
  1562. data.axis.fromArray(array);
  1563. break;
  1564. case 'limits':
  1565. var max = child.getElementsByTagName('max')[0];
  1566. var min = child.getElementsByTagName('min')[0];
  1567. data.limits.max = parseFloat(max.textContent);
  1568. data.limits.min = parseFloat(min.textContent);
  1569. break;
  1570. }
  1571. }
  1572. // if min is equal to or greater than max, consider the joint static
  1573. if (data.limits.min >= data.limits.max) {
  1574. data.static = true;
  1575. }
  1576. // calculate middle position
  1577. data.middlePosition = (data.limits.min + data.limits.max) / 2.0;
  1578. return data;
  1579. }
  1580. function parseKinematicsLink(xml) {
  1581. var data = {
  1582. sid: xml.getAttribute('sid'),
  1583. name: xml.getAttribute('name') || '',
  1584. attachments: [],
  1585. transforms: []
  1586. };
  1587. for (var i = 0; i < xml.childNodes.length; i++) {
  1588. var child = xml.childNodes[i];
  1589. if (child.nodeType !== 1) continue;
  1590. switch (child.nodeName) {
  1591. case 'attachment_full':
  1592. data.attachments.push(parseKinematicsAttachment(child));
  1593. break;
  1594. case 'matrix':
  1595. case 'translate':
  1596. case 'rotate':
  1597. data.transforms.push(parseKinematicsTransform(child));
  1598. break;
  1599. }
  1600. }
  1601. return data;
  1602. }
  1603. function parseKinematicsAttachment(xml) {
  1604. var data = {
  1605. joint: xml.getAttribute('joint').split('/').pop(),
  1606. transforms: [],
  1607. links: []
  1608. };
  1609. for (var i = 0; i < xml.childNodes.length; i++) {
  1610. var child = xml.childNodes[i];
  1611. if (child.nodeType !== 1) continue;
  1612. switch (child.nodeName) {
  1613. case 'link':
  1614. data.links.push(parseKinematicsLink(child));
  1615. break;
  1616. case 'matrix':
  1617. case 'translate':
  1618. case 'rotate':
  1619. data.transforms.push(parseKinematicsTransform(child));
  1620. break;
  1621. }
  1622. }
  1623. return data;
  1624. }
  1625. function parseKinematicsTransform(xml) {
  1626. var data = {
  1627. type: xml.nodeName
  1628. };
  1629. var array = parseFloats(xml.textContent);
  1630. switch (data.type) {
  1631. case 'matrix':
  1632. data.obj = new THREE.Matrix4();
  1633. data.obj.fromArray(array).transpose();
  1634. break;
  1635. case 'translate':
  1636. data.obj = new THREE.Vector3();
  1637. data.obj.fromArray(array);
  1638. break;
  1639. case 'rotate':
  1640. data.obj = new THREE.Vector3();
  1641. data.obj.fromArray(array);
  1642. data.angle = THREE.Math.degToRad(array[3]);
  1643. break;
  1644. }
  1645. return data;
  1646. }
  1647. // physics
  1648. function parsePhysicsModel(xml) {
  1649. var data = {
  1650. name: xml.getAttribute('name') || '',
  1651. rigidBodies: {}
  1652. };
  1653. for (var i = 0; i < xml.childNodes.length; i++) {
  1654. var child = xml.childNodes[i];
  1655. if (child.nodeType !== 1) continue;
  1656. switch (child.nodeName) {
  1657. case 'rigid_body':
  1658. data.rigidBodies[child.getAttribute('name')] = {};
  1659. parsePhysicsRigidBody(child, data.rigidBodies[child.getAttribute('name')]);
  1660. break;
  1661. }
  1662. }
  1663. library.physicsModels[xml.getAttribute('id')] = data;
  1664. }
  1665. function parsePhysicsRigidBody(xml, data) {
  1666. for (var i = 0; i < xml.childNodes.length; i++) {
  1667. var child = xml.childNodes[i];
  1668. if (child.nodeType !== 1) continue;
  1669. switch (child.nodeName) {
  1670. case 'technique_common':
  1671. parsePhysicsTechniqueCommon(child, data);
  1672. break;
  1673. }
  1674. }
  1675. }
  1676. function parsePhysicsTechniqueCommon(xml, data) {
  1677. for (var i = 0; i < xml.childNodes.length; i++) {
  1678. var child = xml.childNodes[i];
  1679. if (child.nodeType !== 1) continue;
  1680. switch (child.nodeName) {
  1681. case 'inertia':
  1682. data.inertia = parseFloats(child.textContent);
  1683. break;
  1684. case 'mass':
  1685. data.mass = parseFloats(child.textContent)[0];
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. // scene
  1691. function parseKinematicsScene(xml) {
  1692. var data = {
  1693. bindJointAxis: []
  1694. };
  1695. for (var i = 0; i < xml.childNodes.length; i++) {
  1696. var child = xml.childNodes[i];
  1697. if (child.nodeType !== 1) continue;
  1698. switch (child.nodeName) {
  1699. case 'bind_joint_axis':
  1700. data.bindJointAxis.push(parseKinematicsBindJointAxis(child));
  1701. break;
  1702. }
  1703. }
  1704. library.kinematicsScenes[parseId(xml.getAttribute('url'))] = data;
  1705. }
  1706. function parseKinematicsBindJointAxis(xml) {
  1707. var data = {
  1708. target: xml.getAttribute('target').split('/').pop()
  1709. };
  1710. for (var i = 0; i < xml.childNodes.length; i++) {
  1711. var child = xml.childNodes[i];
  1712. if (child.nodeType !== 1) continue;
  1713. switch (child.nodeName) {
  1714. case 'axis':
  1715. var param = child.getElementsByTagName('param')[0];
  1716. data.axis = param.textContent;
  1717. var tmpJointIndex = data.axis.split('inst_').pop().split('axis')[0];
  1718. data.jointIndex = tmpJointIndex.substr(0, tmpJointIndex.length - 1);
  1719. break;
  1720. }
  1721. }
  1722. return data;
  1723. }
  1724. function buildKinematicsScene(data) {
  1725. if (data.build !== undefined) return data.build;
  1726. return data;
  1727. }
  1728. function getKinematicsScene(id) {
  1729. return getBuild(library.kinematicsScenes[id], buildKinematicsScene);
  1730. }
  1731. function setupKinematics() {
  1732. var kinematicsModelId = Object.keys(library.kinematicsModels)[0];
  1733. var kinematicsSceneId = Object.keys(library.kinematicsScenes)[0];
  1734. var visualSceneId = Object.keys(library.visualScenes)[0];
  1735. if (kinematicsModelId === undefined || kinematicsSceneId === undefined) return;
  1736. var kinematicsModel = getKinematicsModel(kinematicsModelId);
  1737. var kinematicsScene = getKinematicsScene(kinematicsSceneId);
  1738. var visualScene = getVisualScene(visualSceneId);
  1739. var bindJointAxis = kinematicsScene.bindJointAxis;
  1740. var jointMap = {};
  1741. for (var i = 0, l = bindJointAxis.length; i < l; i++) {
  1742. var axis = bindJointAxis[i];
  1743. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1744. var targetElement = collada.querySelector('[sid="' + axis.target + '"]');
  1745. if (targetElement) {
  1746. // get the parent of the transfrom element
  1747. var parentVisualElement = targetElement.parentElement;
  1748. // connect the joint of the kinematics model with the element in the visual scene
  1749. connect(axis.jointIndex, parentVisualElement);
  1750. }
  1751. }
  1752. function connect(jointIndex, visualElement) {
  1753. var visualElementName = visualElement.getAttribute('name');
  1754. var joint = kinematicsModel.joints[jointIndex];
  1755. visualScene.traverse(function (object) {
  1756. if (object.name === visualElementName) {
  1757. jointMap[jointIndex] = {
  1758. object: object,
  1759. transforms: buildTransformList(visualElement),
  1760. joint: joint,
  1761. position: joint.zeroPosition
  1762. };
  1763. }
  1764. });
  1765. }
  1766. var m0 = new THREE.Matrix4();
  1767. kinematics = {
  1768. joints: kinematicsModel && kinematicsModel.joints,
  1769. getJointValue: function getJointValue(jointIndex) {
  1770. var jointData = jointMap[jointIndex];
  1771. if (jointData) {
  1772. return jointData.position;
  1773. } else {
  1774. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.');
  1775. }
  1776. },
  1777. setJointValue: function setJointValue(jointIndex, value) {
  1778. var jointData = jointMap[jointIndex];
  1779. if (jointData) {
  1780. var joint = jointData.joint;
  1781. if (value > joint.limits.max || value < joint.limits.min) {
  1782. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').');
  1783. } else if (joint.static) {
  1784. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' is static.');
  1785. } else {
  1786. var object = jointData.object;
  1787. var axis = joint.axis;
  1788. var transforms = jointData.transforms;
  1789. matrix.identity();
  1790. // each update, we have to apply all transforms in the correct order
  1791. for (var i = 0; i < transforms.length; i++) {
  1792. var transform = transforms[i];
  1793. // if there is a connection of the transform node with a joint, apply the joint value
  1794. if (transform.sid && transform.sid.indexOf(jointIndex) !== -1) {
  1795. switch (joint.type) {
  1796. case 'revolute':
  1797. matrix.multiply(m0.makeRotationAxis(axis, THREE.Math.degToRad(value)));
  1798. break;
  1799. case 'prismatic':
  1800. matrix.multiply(m0.makeTranslation(axis.x * value, axis.y * value, axis.z * value));
  1801. break;
  1802. default:
  1803. console.warn('THREE.ColladaLoader: Unknown joint type: ' + joint.type);
  1804. break;
  1805. }
  1806. } else {
  1807. switch (transform.type) {
  1808. case 'matrix':
  1809. matrix.multiply(transform.obj);
  1810. break;
  1811. case 'translate':
  1812. matrix.multiply(m0.makeTranslation(transform.obj.x, transform.obj.y, transform.obj.z));
  1813. break;
  1814. case 'scale':
  1815. matrix.scale(transform.obj);
  1816. break;
  1817. case 'rotate':
  1818. matrix.multiply(m0.makeRotationAxis(transform.obj, transform.angle));
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. object.matrix.copy(matrix);
  1824. object.matrix.decompose(object.position, object.quaternion, object.scale);
  1825. jointMap[jointIndex].position = value;
  1826. }
  1827. } else {
  1828. console.log('THREE.ColladaLoader: ' + jointIndex + ' does not exist.');
  1829. }
  1830. }
  1831. };
  1832. }
  1833. function buildTransformList(node) {
  1834. var transforms = [];
  1835. var xml = collada.querySelector('[id="' + node.id + '"]');
  1836. for (var i = 0; i < xml.childNodes.length; i++) {
  1837. var child = xml.childNodes[i];
  1838. if (child.nodeType !== 1) continue;
  1839. switch (child.nodeName) {
  1840. case 'matrix':
  1841. var array = parseFloats(child.textContent);
  1842. var matrix = new THREE.Matrix4().fromArray(array).transpose();
  1843. transforms.push({
  1844. sid: child.getAttribute('sid'),
  1845. type: child.nodeName,
  1846. obj: matrix
  1847. });
  1848. break;
  1849. case 'translate':
  1850. case 'scale':
  1851. var array = parseFloats(child.textContent);
  1852. var vector = new THREE.Vector3().fromArray(array);
  1853. transforms.push({
  1854. sid: child.getAttribute('sid'),
  1855. type: child.nodeName,
  1856. obj: vector
  1857. });
  1858. break;
  1859. case 'rotate':
  1860. var array = parseFloats(child.textContent);
  1861. var vector = new THREE.Vector3().fromArray(array);
  1862. var angle = THREE.Math.degToRad(array[3]);
  1863. transforms.push({
  1864. sid: child.getAttribute('sid'),
  1865. type: child.nodeName,
  1866. obj: vector,
  1867. angle: angle
  1868. });
  1869. break;
  1870. }
  1871. }
  1872. return transforms;
  1873. }
  1874. // nodes
  1875. function prepareNodes(xml) {
  1876. var elements = xml.getElementsByTagName('node');
  1877. // ensure all node elements have id attributes
  1878. for (var i = 0; i < elements.length; i++) {
  1879. var element = elements[i];
  1880. if (element.hasAttribute('id') === false) {
  1881. element.setAttribute('id', generateId());
  1882. }
  1883. }
  1884. }
  1885. var matrix = new THREE.Matrix4();
  1886. var vector = new THREE.Vector3();
  1887. function parseNode(xml) {
  1888. var data = {
  1889. name: xml.getAttribute('name') || '',
  1890. type: xml.getAttribute('type'),
  1891. id: xml.getAttribute('id'),
  1892. sid: xml.getAttribute('sid'),
  1893. matrix: new THREE.Matrix4(),
  1894. nodes: [],
  1895. instanceCameras: [],
  1896. instanceControllers: [],
  1897. instanceLights: [],
  1898. instanceGeometries: [],
  1899. instanceNodes: [],
  1900. transforms: {}
  1901. };
  1902. for (var i = 0; i < xml.childNodes.length; i++) {
  1903. var child = xml.childNodes[i];
  1904. if (child.nodeType !== 1) continue;
  1905. switch (child.nodeName) {
  1906. case 'node':
  1907. data.nodes.push(child.getAttribute('id'));
  1908. parseNode(child);
  1909. break;
  1910. case 'instance_camera':
  1911. data.instanceCameras.push(parseId(child.getAttribute('url')));
  1912. break;
  1913. case 'instance_controller':
  1914. data.instanceControllers.push(parseNodeInstance(child));
  1915. break;
  1916. case 'instance_light':
  1917. data.instanceLights.push(parseId(child.getAttribute('url')));
  1918. break;
  1919. case 'instance_geometry':
  1920. data.instanceGeometries.push(parseNodeInstance(child));
  1921. break;
  1922. case 'instance_node':
  1923. data.instanceNodes.push(parseId(child.getAttribute('url')));
  1924. break;
  1925. case 'matrix':
  1926. var array = parseFloats(child.textContent);
  1927. data.matrix.multiply(matrix.fromArray(array).transpose());
  1928. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1929. break;
  1930. case 'translate':
  1931. var array = parseFloats(child.textContent);
  1932. vector.fromArray(array);
  1933. data.matrix.multiply(matrix.makeTranslation(vector.x, vector.y, vector.z));
  1934. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1935. break;
  1936. case 'rotate':
  1937. var array = parseFloats(child.textContent);
  1938. var angle = THREE.Math.degToRad(array[3]);
  1939. data.matrix.multiply(matrix.makeRotationAxis(vector.fromArray(array), angle));
  1940. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1941. break;
  1942. case 'scale':
  1943. var array = parseFloats(child.textContent);
  1944. data.matrix.scale(vector.fromArray(array));
  1945. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1946. break;
  1947. case 'extra':
  1948. break;
  1949. default:
  1950. console.log(child);
  1951. }
  1952. }
  1953. if (hasNode(data.id)) {
  1954. console.warn('THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id);
  1955. } else {
  1956. library.nodes[data.id] = data;
  1957. }
  1958. return data;
  1959. }
  1960. function parseNodeInstance(xml) {
  1961. var data = {
  1962. id: parseId(xml.getAttribute('url')),
  1963. materials: {},
  1964. skeletons: []
  1965. };
  1966. for (var i = 0; i < xml.childNodes.length; i++) {
  1967. var child = xml.childNodes[i];
  1968. switch (child.nodeName) {
  1969. case 'bind_material':
  1970. var instances = child.getElementsByTagName('instance_material');
  1971. for (var j = 0; j < instances.length; j++) {
  1972. var instance = instances[j];
  1973. var symbol = instance.getAttribute('symbol');
  1974. var target = instance.getAttribute('target');
  1975. data.materials[symbol] = parseId(target);
  1976. }
  1977. break;
  1978. case 'skeleton':
  1979. data.skeletons.push(parseId(child.textContent));
  1980. break;
  1981. default:
  1982. break;
  1983. }
  1984. }
  1985. return data;
  1986. }
  1987. function buildSkeleton(skeletons, joints) {
  1988. var boneData = [];
  1989. var sortedBoneData = [];
  1990. var i, j, data;
  1991. // a skeleton can have multiple root bones. collada expresses this
  1992. // situtation with multiple "skeleton" tags per controller instance
  1993. for (i = 0; i < skeletons.length; i++) {
  1994. var skeleton = skeletons[i];
  1995. var root;
  1996. if (hasNode(skeleton)) {
  1997. root = getNode(skeleton);
  1998. buildBoneHierarchy(root, joints, boneData);
  1999. } else if (hasVisualScene(skeleton)) {
  2000. // handle case where the skeleton refers to the visual scene (#13335)
  2001. var visualScene = library.visualScenes[skeleton];
  2002. var children = visualScene.children;
  2003. for (var j = 0; j < children.length; j++) {
  2004. var child = children[j];
  2005. if (child.type === 'JOINT') {
  2006. var root = getNode(child.id);
  2007. buildBoneHierarchy(root, joints, boneData);
  2008. }
  2009. }
  2010. } else {
  2011. console.error('THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton);
  2012. }
  2013. }
  2014. // sort bone data (the order is defined in the corresponding controller)
  2015. for (i = 0; i < joints.length; i++) {
  2016. for (j = 0; j < boneData.length; j++) {
  2017. data = boneData[j];
  2018. if (data.bone.name === joints[i].name) {
  2019. sortedBoneData[i] = data;
  2020. data.processed = true;
  2021. break;
  2022. }
  2023. }
  2024. }
  2025. // add unprocessed bone data at the end of the list
  2026. for (i = 0; i < boneData.length; i++) {
  2027. data = boneData[i];
  2028. if (data.processed === false) {
  2029. sortedBoneData.push(data);
  2030. data.processed = true;
  2031. }
  2032. }
  2033. // setup arrays for skeleton creation
  2034. var bones = [];
  2035. var boneInverses = [];
  2036. for (i = 0; i < sortedBoneData.length; i++) {
  2037. data = sortedBoneData[i];
  2038. bones.push(data.bone);
  2039. boneInverses.push(data.boneInverse);
  2040. }
  2041. return new THREE.Skeleton(bones, boneInverses);
  2042. }
  2043. function buildBoneHierarchy(root, joints, boneData) {
  2044. // setup bone data from visual scene
  2045. root.traverse(function (object) {
  2046. if (object.isBone === true) {
  2047. var boneInverse;
  2048. // retrieve the boneInverse from the controller data
  2049. for (var i = 0; i < joints.length; i++) {
  2050. var joint = joints[i];
  2051. if (joint.name === object.name) {
  2052. boneInverse = joint.boneInverse;
  2053. break;
  2054. }
  2055. }
  2056. if (boneInverse === undefined) {
  2057. // Unfortunately, there can be joints in the visual scene that are not part of the
  2058. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2059. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2060. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2061. // ensure a correct animation of the model.
  2062. boneInverse = new THREE.Matrix4();
  2063. }
  2064. boneData.push({ bone: object, boneInverse: boneInverse, processed: false });
  2065. }
  2066. });
  2067. }
  2068. function buildNode(data) {
  2069. var objects = [];
  2070. var matrix = data.matrix;
  2071. var nodes = data.nodes;
  2072. var type = data.type;
  2073. var instanceCameras = data.instanceCameras;
  2074. var instanceControllers = data.instanceControllers;
  2075. var instanceLights = data.instanceLights;
  2076. var instanceGeometries = data.instanceGeometries;
  2077. var instanceNodes = data.instanceNodes;
  2078. // nodes
  2079. for (var i = 0, l = nodes.length; i < l; i++) {
  2080. objects.push(getNode(nodes[i]));
  2081. }
  2082. // instance cameras
  2083. for (var i = 0, l = instanceCameras.length; i < l; i++) {
  2084. var instanceCamera = getCamera(instanceCameras[i]);
  2085. if (instanceCamera !== null) {
  2086. objects.push(instanceCamera.clone());
  2087. }
  2088. }
  2089. // instance controllers
  2090. for (var i = 0, l = instanceControllers.length; i < l; i++) {
  2091. var instance = instanceControllers[i];
  2092. var controller = getController(instance.id);
  2093. var geometries = getGeometry(controller.id);
  2094. var newObjects = buildObjects(geometries, instance.materials);
  2095. var skeletons = instance.skeletons;
  2096. var joints = controller.skin.joints;
  2097. var skeleton = buildSkeleton(skeletons, joints);
  2098. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2099. var object = newObjects[j];
  2100. if (object.isSkinnedMesh) {
  2101. object.bind(skeleton, controller.skin.bindMatrix);
  2102. object.normalizeSkinWeights();
  2103. }
  2104. objects.push(object);
  2105. }
  2106. }
  2107. // instance lights
  2108. for (var i = 0, l = instanceLights.length; i < l; i++) {
  2109. var instanceLight = getLight(instanceLights[i]);
  2110. if (instanceLight !== null) {
  2111. objects.push(instanceLight.clone());
  2112. }
  2113. }
  2114. // instance geometries
  2115. for (var i = 0, l = instanceGeometries.length; i < l; i++) {
  2116. var instance = instanceGeometries[i];
  2117. // a single geometry instance in collada can lead to multiple object3Ds.
  2118. // this is the case when primitives are combined like triangles and lines
  2119. var geometries = getGeometry(instance.id);
  2120. var newObjects = buildObjects(geometries, instance.materials);
  2121. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2122. objects.push(newObjects[j]);
  2123. }
  2124. }
  2125. // instance nodes
  2126. for (var i = 0, l = instanceNodes.length; i < l; i++) {
  2127. objects.push(getNode(instanceNodes[i]).clone());
  2128. }
  2129. var object;
  2130. if (nodes.length === 0 && objects.length === 1) {
  2131. object = objects[0];
  2132. } else {
  2133. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2134. for (var i = 0; i < objects.length; i++) {
  2135. object.add(objects[i]);
  2136. }
  2137. }
  2138. if (object.name === '') {
  2139. object.name = type === 'JOINT' ? data.sid : data.name;
  2140. }
  2141. object.matrix.copy(matrix);
  2142. object.matrix.decompose(object.position, object.quaternion, object.scale);
  2143. return object;
  2144. }
  2145. var fallbackMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff });
  2146. function resolveMaterialBinding(keys, instanceMaterials) {
  2147. var materials = [];
  2148. for (var i = 0, l = keys.length; i < l; i++) {
  2149. var id = instanceMaterials[keys[i]];
  2150. if (id === undefined) {
  2151. console.warn('THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[i]);
  2152. materials.push(fallbackMaterial);
  2153. } else {
  2154. materials.push(getMaterial(id));
  2155. }
  2156. }
  2157. return materials;
  2158. }
  2159. function buildObjects(geometries, instanceMaterials) {
  2160. var objects = [];
  2161. for (var type in geometries) {
  2162. var geometry = geometries[type];
  2163. var materials = resolveMaterialBinding(geometry.materialKeys, instanceMaterials);
  2164. // handle case if no materials are defined
  2165. if (materials.length === 0) {
  2166. if (type === 'lines' || type === 'linestrips') {
  2167. materials.push(new THREE.LineBasicMaterial());
  2168. } else {
  2169. materials.push(new THREE.MeshPhongMaterial());
  2170. }
  2171. }
  2172. // regard skinning
  2173. var skinning = geometry.data.attributes.skinIndex !== undefined;
  2174. if (skinning) {
  2175. for (var i = 0, l = materials.length; i < l; i++) {
  2176. materials[i].skinning = true;
  2177. }
  2178. }
  2179. // choose between a single or multi materials (material array)
  2180. var material = materials.length === 1 ? materials[0] : materials;
  2181. // now create a specific 3D object
  2182. var object;
  2183. switch (type) {
  2184. case 'lines':
  2185. object = new THREE.LineSegments(geometry.data, material);
  2186. break;
  2187. case 'linestrips':
  2188. object = new THREE.Line(geometry.data, material);
  2189. break;
  2190. case 'triangles':
  2191. case 'polylist':
  2192. if (skinning) {
  2193. object = new THREE.SkinnedMesh(geometry.data, material);
  2194. } else {
  2195. object = new THREE.Mesh(geometry.data, material);
  2196. }
  2197. break;
  2198. }
  2199. objects.push(object);
  2200. }
  2201. return objects;
  2202. }
  2203. function hasNode(id) {
  2204. return library.nodes[id] !== undefined;
  2205. }
  2206. function getNode(id) {
  2207. return getBuild(library.nodes[id], buildNode);
  2208. }
  2209. // visual scenes
  2210. function parseVisualScene(xml) {
  2211. var data = {
  2212. name: xml.getAttribute('name'),
  2213. children: []
  2214. };
  2215. prepareNodes(xml);
  2216. var elements = getElementsByTagName(xml, 'node');
  2217. for (var i = 0; i < elements.length; i++) {
  2218. data.children.push(parseNode(elements[i]));
  2219. }
  2220. library.visualScenes[xml.getAttribute('id')] = data;
  2221. }
  2222. function buildVisualScene(data) {
  2223. var group = new THREE.Group();
  2224. group.name = data.name;
  2225. var children = data.children;
  2226. for (var i = 0; i < children.length; i++) {
  2227. var child = children[i];
  2228. group.add(getNode(child.id));
  2229. }
  2230. return group;
  2231. }
  2232. function hasVisualScene(id) {
  2233. return library.visualScenes[id] !== undefined;
  2234. }
  2235. function getVisualScene(id) {
  2236. return getBuild(library.visualScenes[id], buildVisualScene);
  2237. }
  2238. // scenes
  2239. function parseScene(xml) {
  2240. var instance = getElementsByTagName(xml, 'instance_visual_scene')[0];
  2241. return getVisualScene(parseId(instance.getAttribute('url')));
  2242. }
  2243. function setupAnimations() {
  2244. var clips = library.clips;
  2245. if (isEmpty(clips) === true) {
  2246. if (isEmpty(library.animations) === false) {
  2247. // if there are animations but no clips, we create a default clip for playback
  2248. var tracks = [];
  2249. for (var id in library.animations) {
  2250. var animationTracks = getAnimation(id);
  2251. for (var i = 0, l = animationTracks.length; i < l; i++) {
  2252. tracks.push(animationTracks[i]);
  2253. }
  2254. }
  2255. animations.push(new THREE.AnimationClip('default', -1, tracks));
  2256. }
  2257. } else {
  2258. for (var id in clips) {
  2259. animations.push(getAnimationClip(id));
  2260. }
  2261. }
  2262. }
  2263. if (text.length === 0) {
  2264. return { scene: new THREE.Scene() };
  2265. }
  2266. var xml = new DOMParser().parseFromString(text, 'application/xml');
  2267. var collada = getElementsByTagName(xml, 'COLLADA')[0];
  2268. // metadata
  2269. var version = collada.getAttribute('version');
  2270. console.log('THREE.ColladaLoader: File version', version);
  2271. var asset = parseAsset(getElementsByTagName(collada, 'asset')[0]);
  2272. var textureLoader = new THREE.TextureLoader(this.manager);
  2273. textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
  2274. var tgaLoader;
  2275. if (THREE.TGALoader) {
  2276. tgaLoader = new THREE.TGALoader(this.manager);
  2277. tgaLoader.setPath(this.resourcePath || path);
  2278. }
  2279. //
  2280. var animations = [];
  2281. var kinematics = {};
  2282. var count = 0;
  2283. //
  2284. var library = {
  2285. animations: {},
  2286. clips: {},
  2287. controllers: {},
  2288. images: {},
  2289. effects: {},
  2290. materials: {},
  2291. cameras: {},
  2292. lights: {},
  2293. geometries: {},
  2294. nodes: {},
  2295. visualScenes: {},
  2296. kinematicsModels: {},
  2297. physicsModels: {},
  2298. kinematicsScenes: {}
  2299. };
  2300. parseLibrary(collada, 'library_animations', 'animation', parseAnimation);
  2301. parseLibrary(collada, 'library_animation_clips', 'animation_clip', parseAnimationClip);
  2302. parseLibrary(collada, 'library_controllers', 'controller', parseController);
  2303. parseLibrary(collada, 'library_images', 'image', parseImage);
  2304. parseLibrary(collada, 'library_effects', 'effect', parseEffect);
  2305. parseLibrary(collada, 'library_materials', 'material', parseMaterial);
  2306. parseLibrary(collada, 'library_cameras', 'camera', parseCamera);
  2307. parseLibrary(collada, 'library_lights', 'light', parseLight);
  2308. parseLibrary(collada, 'library_geometries', 'geometry', parseGeometry);
  2309. parseLibrary(collada, 'library_nodes', 'node', parseNode);
  2310. parseLibrary(collada, 'library_visual_scenes', 'visual_scene', parseVisualScene);
  2311. parseLibrary(collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel);
  2312. parseLibrary(collada, 'library_physics_models', 'physics_model', parsePhysicsModel);
  2313. parseLibrary(collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene);
  2314. buildLibrary(library.animations, buildAnimation);
  2315. buildLibrary(library.clips, buildAnimationClip);
  2316. buildLibrary(library.controllers, buildController);
  2317. buildLibrary(library.images, buildImage);
  2318. buildLibrary(library.effects, buildEffect);
  2319. buildLibrary(library.materials, buildMaterial);
  2320. buildLibrary(library.cameras, buildCamera);
  2321. buildLibrary(library.lights, buildLight);
  2322. buildLibrary(library.geometries, buildGeometry);
  2323. buildLibrary(library.visualScenes, buildVisualScene);
  2324. setupAnimations();
  2325. setupKinematics();
  2326. var scene = parseScene(getElementsByTagName(collada, 'scene')[0]);
  2327. if (asset.upAxis === 'Z_UP') {
  2328. scene.quaternion.setFromEuler(new THREE.Euler(-Math.PI / 2, 0, 0));
  2329. }
  2330. scene.scale.multiplyScalar(asset.unit);
  2331. return {
  2332. animations: animations,
  2333. kinematics: kinematics,
  2334. library: library,
  2335. scene: scene
  2336. };
  2337. }
  2338. };
  2339. },{}],4:[function(require,module,exports){
  2340. 'use strict';
  2341. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2342. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  2343. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2344. } : function (obj) {
  2345. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2346. };
  2347. /**
  2348. * @author Kyle-Larson https://github.com/Kyle-Larson
  2349. * @author Takahiro https://github.com/takahirox
  2350. * @author Lewy Blue https://github.com/looeee
  2351. *
  2352. * Loader loads FBX file and generates Group representing FBX scene.
  2353. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  2354. * Versions lower than this may load but will probably have errors
  2355. *
  2356. * Needs Support:
  2357. * Morph normals / blend shape normals
  2358. *
  2359. * FBX format references:
  2360. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  2361. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  2362. *
  2363. * Binary format specification:
  2364. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  2365. */
  2366. module.exports = THREE.FBXLoader = function () {
  2367. var fbxTree;
  2368. var connections;
  2369. var sceneGraph;
  2370. function FBXLoader(manager) {
  2371. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  2372. }
  2373. FBXLoader.prototype = {
  2374. constructor: FBXLoader,
  2375. crossOrigin: 'anonymous',
  2376. load: function load(url, onLoad, onProgress, onError) {
  2377. var self = this;
  2378. var resourceDirectory = THREE.LoaderUtils.extractUrlBase(url);
  2379. var loader = new THREE.FileLoader(this.manager);
  2380. loader.setResponseType('arraybuffer');
  2381. loader.load(url, function (buffer) {
  2382. try {
  2383. var scene = self.parse(buffer, resourceDirectory);
  2384. onLoad(scene);
  2385. } catch (error) {
  2386. setTimeout(function () {
  2387. if (onError) onError(error);
  2388. self.manager.itemError(url);
  2389. }, 0);
  2390. }
  2391. }, onProgress, onError);
  2392. },
  2393. setCrossOrigin: function setCrossOrigin(value) {
  2394. this.crossOrigin = value;
  2395. return this;
  2396. },
  2397. parse: function parse(FBXBuffer, resourceDirectory) {
  2398. if (isFbxFormatBinary(FBXBuffer)) {
  2399. fbxTree = new BinaryParser().parse(FBXBuffer);
  2400. } else {
  2401. var FBXText = convertArrayBufferToString(FBXBuffer);
  2402. if (!isFbxFormatASCII(FBXText)) {
  2403. throw new Error('THREE.FBXLoader: Unknown format.');
  2404. }
  2405. if (getFbxVersion(FBXText) < 7000) {
  2406. throw new Error('THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion(FBXText));
  2407. }
  2408. fbxTree = new TextParser().parse(FBXText);
  2409. }
  2410. //console.log( FBXTree );
  2411. var textureLoader = new THREE.TextureLoader(this.manager).setPath(resourceDirectory).setCrossOrigin(this.crossOrigin);
  2412. return new FBXTreeParser(textureLoader).parse(fbxTree);
  2413. }
  2414. };
  2415. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  2416. function FBXTreeParser(textureLoader) {
  2417. this.textureLoader = textureLoader;
  2418. }
  2419. FBXTreeParser.prototype = {
  2420. constructor: FBXTreeParser,
  2421. parse: function parse() {
  2422. connections = this.parseConnections();
  2423. var images = this.parseImages();
  2424. var textures = this.parseTextures(images);
  2425. var materials = this.parseMaterials(textures);
  2426. var deformers = this.parseDeformers();
  2427. var geometryMap = new GeometryParser().parse(deformers);
  2428. this.parseScene(deformers, geometryMap, materials);
  2429. return sceneGraph;
  2430. },
  2431. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  2432. // and details the connection type
  2433. parseConnections: function parseConnections() {
  2434. var connectionMap = new Map();
  2435. if ('Connections' in fbxTree) {
  2436. var rawConnections = fbxTree.Connections.connections;
  2437. rawConnections.forEach(function (rawConnection) {
  2438. var fromID = rawConnection[0];
  2439. var toID = rawConnection[1];
  2440. var relationship = rawConnection[2];
  2441. if (!connectionMap.has(fromID)) {
  2442. connectionMap.set(fromID, {
  2443. parents: [],
  2444. children: []
  2445. });
  2446. }
  2447. var parentRelationship = { ID: toID, relationship: relationship };
  2448. connectionMap.get(fromID).parents.push(parentRelationship);
  2449. if (!connectionMap.has(toID)) {
  2450. connectionMap.set(toID, {
  2451. parents: [],
  2452. children: []
  2453. });
  2454. }
  2455. var childRelationship = { ID: fromID, relationship: relationship };
  2456. connectionMap.get(toID).children.push(childRelationship);
  2457. });
  2458. }
  2459. return connectionMap;
  2460. },
  2461. // Parse FBXTree.Objects.Video for embedded image data
  2462. // These images are connected to textures in FBXTree.Objects.Textures
  2463. // via FBXTree.Connections.
  2464. parseImages: function parseImages() {
  2465. var images = {};
  2466. var blobs = {};
  2467. if ('Video' in fbxTree.Objects) {
  2468. var videoNodes = fbxTree.Objects.Video;
  2469. for (var nodeID in videoNodes) {
  2470. var videoNode = videoNodes[nodeID];
  2471. var id = parseInt(nodeID);
  2472. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  2473. // raw image data is in videoNode.Content
  2474. if ('Content' in videoNode) {
  2475. var arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  2476. var base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  2477. if (arrayBufferContent || base64Content) {
  2478. var image = this.parseImage(videoNodes[nodeID]);
  2479. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  2480. }
  2481. }
  2482. }
  2483. }
  2484. for (var id in images) {
  2485. var filename = images[id];
  2486. if (blobs[filename] !== undefined) images[id] = blobs[filename];else images[id] = images[id].split('\\').pop();
  2487. }
  2488. return images;
  2489. },
  2490. // Parse embedded image data in FBXTree.Video.Content
  2491. parseImage: function parseImage(videoNode) {
  2492. var content = videoNode.Content;
  2493. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  2494. var extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
  2495. var type;
  2496. switch (extension) {
  2497. case 'bmp':
  2498. type = 'image/bmp';
  2499. break;
  2500. case 'jpg':
  2501. case 'jpeg':
  2502. type = 'image/jpeg';
  2503. break;
  2504. case 'png':
  2505. type = 'image/png';
  2506. break;
  2507. case 'tif':
  2508. type = 'image/tiff';
  2509. break;
  2510. case 'tga':
  2511. if (typeof THREE.TGALoader !== 'function') {
  2512. console.warn('FBXLoader: THREE.TGALoader is required to load TGA textures');
  2513. return;
  2514. } else {
  2515. if (THREE.Loader.Handlers.get('.tga') === null) {
  2516. THREE.Loader.Handlers.add(/\.tga$/i, new THREE.TGALoader());
  2517. }
  2518. type = 'image/tga';
  2519. break;
  2520. }
  2521. default:
  2522. console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
  2523. return;
  2524. }
  2525. if (typeof content === 'string') {
  2526. // ASCII format
  2527. return 'data:' + type + ';base64,' + content;
  2528. } else {
  2529. // Binary Format
  2530. var array = new Uint8Array(content);
  2531. return window.URL.createObjectURL(new Blob([array], { type: type }));
  2532. }
  2533. },
  2534. // Parse nodes in FBXTree.Objects.Texture
  2535. // These contain details such as UV scaling, cropping, rotation etc and are connected
  2536. // to images in FBXTree.Objects.Video
  2537. parseTextures: function parseTextures(images) {
  2538. var textureMap = new Map();
  2539. if ('Texture' in fbxTree.Objects) {
  2540. var textureNodes = fbxTree.Objects.Texture;
  2541. for (var nodeID in textureNodes) {
  2542. var texture = this.parseTexture(textureNodes[nodeID], images);
  2543. textureMap.set(parseInt(nodeID), texture);
  2544. }
  2545. }
  2546. return textureMap;
  2547. },
  2548. // Parse individual node in FBXTree.Objects.Texture
  2549. parseTexture: function parseTexture(textureNode, images) {
  2550. var texture = this.loadTexture(textureNode, images);
  2551. texture.ID = textureNode.id;
  2552. texture.name = textureNode.attrName;
  2553. var wrapModeU = textureNode.WrapModeU;
  2554. var wrapModeV = textureNode.WrapModeV;
  2555. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  2556. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  2557. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  2558. // 0: repeat(default), 1: clamp
  2559. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2560. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2561. if ('Scaling' in textureNode) {
  2562. var values = textureNode.Scaling.value;
  2563. texture.repeat.x = values[0];
  2564. texture.repeat.y = values[1];
  2565. }
  2566. return texture;
  2567. },
  2568. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  2569. loadTexture: function loadTexture(textureNode, images) {
  2570. var fileName;
  2571. var currentPath = this.textureLoader.path;
  2572. var children = connections.get(textureNode.id).children;
  2573. if (children !== undefined && children.length > 0 && images[children[0].ID] !== undefined) {
  2574. fileName = images[children[0].ID];
  2575. if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {
  2576. this.textureLoader.setPath(undefined);
  2577. }
  2578. }
  2579. var texture;
  2580. var extension = textureNode.FileName.slice(-3).toLowerCase();
  2581. if (extension === 'tga') {
  2582. var loader = THREE.Loader.Handlers.get('.tga');
  2583. if (loader === null) {
  2584. console.warn('FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName);
  2585. texture = new THREE.Texture();
  2586. } else {
  2587. texture = loader.load(fileName);
  2588. }
  2589. } else if (extension === 'psd') {
  2590. console.warn('FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName);
  2591. texture = new THREE.Texture();
  2592. } else {
  2593. texture = this.textureLoader.load(fileName);
  2594. }
  2595. this.textureLoader.setPath(currentPath);
  2596. return texture;
  2597. },
  2598. // Parse nodes in FBXTree.Objects.Material
  2599. parseMaterials: function parseMaterials(textureMap) {
  2600. var materialMap = new Map();
  2601. if ('Material' in fbxTree.Objects) {
  2602. var materialNodes = fbxTree.Objects.Material;
  2603. for (var nodeID in materialNodes) {
  2604. var material = this.parseMaterial(materialNodes[nodeID], textureMap);
  2605. if (material !== null) materialMap.set(parseInt(nodeID), material);
  2606. }
  2607. }
  2608. return materialMap;
  2609. },
  2610. // Parse single node in FBXTree.Objects.Material
  2611. // Materials are connected to texture maps in FBXTree.Objects.Textures
  2612. // FBX format currently only supports Lambert and Phong shading models
  2613. parseMaterial: function parseMaterial(materialNode, textureMap) {
  2614. var ID = materialNode.id;
  2615. var name = materialNode.attrName;
  2616. var type = materialNode.ShadingModel;
  2617. // Case where FBX wraps shading model in property object.
  2618. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
  2619. type = type.value;
  2620. }
  2621. // Ignore unused materials which don't have any connections.
  2622. if (!connections.has(ID)) return null;
  2623. var parameters = this.parseParameters(materialNode, textureMap, ID);
  2624. var material;
  2625. switch (type.toLowerCase()) {
  2626. case 'phong':
  2627. material = new THREE.MeshPhongMaterial();
  2628. break;
  2629. case 'lambert':
  2630. material = new THREE.MeshLambertMaterial();
  2631. break;
  2632. default:
  2633. console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
  2634. material = new THREE.MeshPhongMaterial({ color: 0x3300ff });
  2635. break;
  2636. }
  2637. material.setValues(parameters);
  2638. material.name = name;
  2639. return material;
  2640. },
  2641. // Parse FBX material and return parameters suitable for a three.js material
  2642. // Also parse the texture map and return any textures associated with the material
  2643. parseParameters: function parseParameters(materialNode, textureMap, ID) {
  2644. var parameters = {};
  2645. if (materialNode.BumpFactor) {
  2646. parameters.bumpScale = materialNode.BumpFactor.value;
  2647. }
  2648. if (materialNode.Diffuse) {
  2649. parameters.color = new THREE.Color().fromArray(materialNode.Diffuse.value);
  2650. } else if (materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color') {
  2651. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  2652. parameters.color = new THREE.Color().fromArray(materialNode.DiffuseColor.value);
  2653. }
  2654. if (materialNode.DisplacementFactor) {
  2655. parameters.displacementScale = materialNode.DisplacementFactor.value;
  2656. }
  2657. if (materialNode.Emissive) {
  2658. parameters.emissive = new THREE.Color().fromArray(materialNode.Emissive.value);
  2659. } else if (materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color') {
  2660. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  2661. parameters.emissive = new THREE.Color().fromArray(materialNode.EmissiveColor.value);
  2662. }
  2663. if (materialNode.EmissiveFactor) {
  2664. parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
  2665. }
  2666. if (materialNode.Opacity) {
  2667. parameters.opacity = parseFloat(materialNode.Opacity.value);
  2668. }
  2669. if (parameters.opacity < 1.0) {
  2670. parameters.transparent = true;
  2671. }
  2672. if (materialNode.ReflectionFactor) {
  2673. parameters.reflectivity = materialNode.ReflectionFactor.value;
  2674. }
  2675. if (materialNode.Shininess) {
  2676. parameters.shininess = materialNode.Shininess.value;
  2677. }
  2678. if (materialNode.Specular) {
  2679. parameters.specular = new THREE.Color().fromArray(materialNode.Specular.value);
  2680. } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color') {
  2681. // The blender exporter exports specular color here instead of in materialNode.Specular
  2682. parameters.specular = new THREE.Color().fromArray(materialNode.SpecularColor.value);
  2683. }
  2684. var self = this;
  2685. connections.get(ID).children.forEach(function (child) {
  2686. var type = child.relationship;
  2687. switch (type) {
  2688. case 'Bump':
  2689. parameters.bumpMap = self.getTexture(textureMap, child.ID);
  2690. break;
  2691. case 'DiffuseColor':
  2692. parameters.map = self.getTexture(textureMap, child.ID);
  2693. break;
  2694. case 'DisplacementColor':
  2695. parameters.displacementMap = self.getTexture(textureMap, child.ID);
  2696. break;
  2697. case 'EmissiveColor':
  2698. parameters.emissiveMap = self.getTexture(textureMap, child.ID);
  2699. break;
  2700. case 'NormalMap':
  2701. parameters.normalMap = self.getTexture(textureMap, child.ID);
  2702. break;
  2703. case 'ReflectionColor':
  2704. parameters.envMap = self.getTexture(textureMap, child.ID);
  2705. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  2706. break;
  2707. case 'SpecularColor':
  2708. parameters.specularMap = self.getTexture(textureMap, child.ID);
  2709. break;
  2710. case 'TransparentColor':
  2711. parameters.alphaMap = self.getTexture(textureMap, child.ID);
  2712. parameters.transparent = true;
  2713. break;
  2714. case 'AmbientColor':
  2715. case 'ShininessExponent': // AKA glossiness map
  2716. case 'SpecularFactor': // AKA specularLevel
  2717. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  2718. default:
  2719. console.warn('THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type);
  2720. break;
  2721. }
  2722. });
  2723. return parameters;
  2724. },
  2725. // get a texture from the textureMap for use by a material.
  2726. getTexture: function getTexture(textureMap, id) {
  2727. // if the texture is a layered texture, just use the first layer and issue a warning
  2728. if ('LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
  2729. console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');
  2730. id = connections.get(id).children[0].ID;
  2731. }
  2732. return textureMap.get(id);
  2733. },
  2734. // Parse nodes in FBXTree.Objects.Deformer
  2735. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  2736. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  2737. parseDeformers: function parseDeformers() {
  2738. var skeletons = {};
  2739. var morphTargets = {};
  2740. if ('Deformer' in fbxTree.Objects) {
  2741. var DeformerNodes = fbxTree.Objects.Deformer;
  2742. for (var nodeID in DeformerNodes) {
  2743. var deformerNode = DeformerNodes[nodeID];
  2744. var relationships = connections.get(parseInt(nodeID));
  2745. if (deformerNode.attrType === 'Skin') {
  2746. var skeleton = this.parseSkeleton(relationships, DeformerNodes);
  2747. skeleton.ID = nodeID;
  2748. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: skeleton attached to more than one geometry is not supported.');
  2749. skeleton.geometryID = relationships.parents[0].ID;
  2750. skeletons[nodeID] = skeleton;
  2751. } else if (deformerNode.attrType === 'BlendShape') {
  2752. var morphTarget = {
  2753. id: nodeID
  2754. };
  2755. morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
  2756. morphTarget.id = nodeID;
  2757. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: morph target attached to more than one geometry is not supported.');
  2758. morphTargets[nodeID] = morphTarget;
  2759. }
  2760. }
  2761. }
  2762. return {
  2763. skeletons: skeletons,
  2764. morphTargets: morphTargets
  2765. };
  2766. },
  2767. // Parse single nodes in FBXTree.Objects.Deformer
  2768. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  2769. // Each skin node represents a skeleton and each cluster node represents a bone
  2770. parseSkeleton: function parseSkeleton(relationships, deformerNodes) {
  2771. var rawBones = [];
  2772. relationships.children.forEach(function (child) {
  2773. var boneNode = deformerNodes[child.ID];
  2774. if (boneNode.attrType !== 'Cluster') return;
  2775. var rawBone = {
  2776. ID: child.ID,
  2777. indices: [],
  2778. weights: [],
  2779. transform: new THREE.Matrix4().fromArray(boneNode.Transform.a),
  2780. transformLink: new THREE.Matrix4().fromArray(boneNode.TransformLink.a),
  2781. linkMode: boneNode.Mode
  2782. };
  2783. if ('Indexes' in boneNode) {
  2784. rawBone.indices = boneNode.Indexes.a;
  2785. rawBone.weights = boneNode.Weights.a;
  2786. }
  2787. rawBones.push(rawBone);
  2788. });
  2789. return {
  2790. rawBones: rawBones,
  2791. bones: []
  2792. };
  2793. },
  2794. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  2795. parseMorphTargets: function parseMorphTargets(relationships, deformerNodes) {
  2796. var rawMorphTargets = [];
  2797. for (var i = 0; i < relationships.children.length; i++) {
  2798. if (i === 8) {
  2799. console.warn('FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.');
  2800. break;
  2801. }
  2802. var child = relationships.children[i];
  2803. var morphTargetNode = deformerNodes[child.ID];
  2804. var rawMorphTarget = {
  2805. name: morphTargetNode.attrName,
  2806. initialWeight: morphTargetNode.DeformPercent,
  2807. id: morphTargetNode.id,
  2808. fullWeights: morphTargetNode.FullWeights.a
  2809. };
  2810. if (morphTargetNode.attrType !== 'BlendShapeChannel') return;
  2811. var targetRelationships = connections.get(parseInt(child.ID));
  2812. targetRelationships.children.forEach(function (child) {
  2813. if (child.relationship === undefined) rawMorphTarget.geoID = child.ID;
  2814. });
  2815. rawMorphTargets.push(rawMorphTarget);
  2816. }
  2817. return rawMorphTargets;
  2818. },
  2819. // create the main THREE.Group() to be returned by the loader
  2820. parseScene: function parseScene(deformers, geometryMap, materialMap) {
  2821. sceneGraph = new THREE.Group();
  2822. var modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
  2823. var modelNodes = fbxTree.Objects.Model;
  2824. var self = this;
  2825. modelMap.forEach(function (model) {
  2826. var modelNode = modelNodes[model.ID];
  2827. self.setLookAtProperties(model, modelNode);
  2828. var parentConnections = connections.get(model.ID).parents;
  2829. parentConnections.forEach(function (connection) {
  2830. var parent = modelMap.get(connection.ID);
  2831. if (parent !== undefined) parent.add(model);
  2832. });
  2833. if (model.parent === null) {
  2834. sceneGraph.add(model);
  2835. }
  2836. });
  2837. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  2838. this.createAmbientLight();
  2839. this.setupMorphMaterials();
  2840. var animations = new AnimationParser().parse();
  2841. // if all the models where already combined in a single group, just return that
  2842. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  2843. sceneGraph.children[0].animations = animations;
  2844. sceneGraph = sceneGraph.children[0];
  2845. }
  2846. sceneGraph.animations = animations;
  2847. },
  2848. // parse nodes in FBXTree.Objects.Model
  2849. parseModels: function parseModels(skeletons, geometryMap, materialMap) {
  2850. var modelMap = new Map();
  2851. var modelNodes = fbxTree.Objects.Model;
  2852. for (var nodeID in modelNodes) {
  2853. var id = parseInt(nodeID);
  2854. var node = modelNodes[nodeID];
  2855. var relationships = connections.get(id);
  2856. var model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
  2857. if (!model) {
  2858. switch (node.attrType) {
  2859. case 'Camera':
  2860. model = this.createCamera(relationships);
  2861. break;
  2862. case 'Light':
  2863. model = this.createLight(relationships);
  2864. break;
  2865. case 'Mesh':
  2866. model = this.createMesh(relationships, geometryMap, materialMap);
  2867. break;
  2868. case 'NurbsCurve':
  2869. model = this.createCurve(relationships, geometryMap);
  2870. break;
  2871. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  2872. case 'Null':
  2873. default:
  2874. model = new THREE.Group();
  2875. break;
  2876. }
  2877. model.name = THREE.PropertyBinding.sanitizeNodeName(node.attrName);
  2878. model.ID = id;
  2879. }
  2880. this.setModelTransforms(model, node);
  2881. modelMap.set(id, model);
  2882. }
  2883. return modelMap;
  2884. },
  2885. buildSkeleton: function buildSkeleton(relationships, skeletons, id, name) {
  2886. var bone = null;
  2887. relationships.parents.forEach(function (parent) {
  2888. for (var ID in skeletons) {
  2889. var skeleton = skeletons[ID];
  2890. skeleton.rawBones.forEach(function (rawBone, i) {
  2891. if (rawBone.ID === parent.ID) {
  2892. var subBone = bone;
  2893. bone = new THREE.Bone();
  2894. bone.matrixWorld.copy(rawBone.transformLink);
  2895. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  2896. bone.name = THREE.PropertyBinding.sanitizeNodeName(name);
  2897. bone.ID = id;
  2898. skeleton.bones[i] = bone;
  2899. // In cases where a bone is shared between multiple meshes
  2900. // duplicate the bone here and and it as a child of the first bone
  2901. if (subBone !== null) {
  2902. bone.add(subBone);
  2903. }
  2904. }
  2905. });
  2906. }
  2907. });
  2908. return bone;
  2909. },
  2910. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  2911. createCamera: function createCamera(relationships) {
  2912. var model;
  2913. var cameraAttribute;
  2914. relationships.children.forEach(function (child) {
  2915. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2916. if (attr !== undefined) {
  2917. cameraAttribute = attr;
  2918. }
  2919. });
  2920. if (cameraAttribute === undefined) {
  2921. model = new THREE.Object3D();
  2922. } else {
  2923. var type = 0;
  2924. if (cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1) {
  2925. type = 1;
  2926. }
  2927. var nearClippingPlane = 1;
  2928. if (cameraAttribute.NearPlane !== undefined) {
  2929. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  2930. }
  2931. var farClippingPlane = 1000;
  2932. if (cameraAttribute.FarPlane !== undefined) {
  2933. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  2934. }
  2935. var width = window.innerWidth;
  2936. var height = window.innerHeight;
  2937. if (cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined) {
  2938. width = cameraAttribute.AspectWidth.value;
  2939. height = cameraAttribute.AspectHeight.value;
  2940. }
  2941. var aspect = width / height;
  2942. var fov = 45;
  2943. if (cameraAttribute.FieldOfView !== undefined) {
  2944. fov = cameraAttribute.FieldOfView.value;
  2945. }
  2946. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  2947. switch (type) {
  2948. case 0:
  2949. // Perspective
  2950. model = new THREE.PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
  2951. if (focalLength !== null) model.setFocalLength(focalLength);
  2952. break;
  2953. case 1:
  2954. // Orthographic
  2955. model = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane);
  2956. break;
  2957. default:
  2958. console.warn('THREE.FBXLoader: Unknown camera type ' + type + '.');
  2959. model = new THREE.Object3D();
  2960. break;
  2961. }
  2962. }
  2963. return model;
  2964. },
  2965. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  2966. createLight: function createLight(relationships) {
  2967. var model;
  2968. var lightAttribute;
  2969. relationships.children.forEach(function (child) {
  2970. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2971. if (attr !== undefined) {
  2972. lightAttribute = attr;
  2973. }
  2974. });
  2975. if (lightAttribute === undefined) {
  2976. model = new THREE.Object3D();
  2977. } else {
  2978. var type;
  2979. // LightType can be undefined for Point lights
  2980. if (lightAttribute.LightType === undefined) {
  2981. type = 0;
  2982. } else {
  2983. type = lightAttribute.LightType.value;
  2984. }
  2985. var color = 0xffffff;
  2986. if (lightAttribute.Color !== undefined) {
  2987. color = new THREE.Color().fromArray(lightAttribute.Color.value);
  2988. }
  2989. var intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100;
  2990. // light disabled
  2991. if (lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0) {
  2992. intensity = 0;
  2993. }
  2994. var distance = 0;
  2995. if (lightAttribute.FarAttenuationEnd !== undefined) {
  2996. if (lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0) {
  2997. distance = 0;
  2998. } else {
  2999. distance = lightAttribute.FarAttenuationEnd.value;
  3000. }
  3001. }
  3002. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  3003. var decay = 1;
  3004. switch (type) {
  3005. case 0:
  3006. // Point
  3007. model = new THREE.PointLight(color, intensity, distance, decay);
  3008. break;
  3009. case 1:
  3010. // Directional
  3011. model = new THREE.DirectionalLight(color, intensity);
  3012. break;
  3013. case 2:
  3014. // Spot
  3015. var angle = Math.PI / 3;
  3016. if (lightAttribute.InnerAngle !== undefined) {
  3017. angle = THREE.Math.degToRad(lightAttribute.InnerAngle.value);
  3018. }
  3019. var penumbra = 0;
  3020. if (lightAttribute.OuterAngle !== undefined) {
  3021. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  3022. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  3023. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  3024. penumbra = THREE.Math.degToRad(lightAttribute.OuterAngle.value);
  3025. penumbra = Math.max(penumbra, 1);
  3026. }
  3027. model = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
  3028. break;
  3029. default:
  3030. console.warn('THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.');
  3031. model = new THREE.PointLight(color, intensity);
  3032. break;
  3033. }
  3034. if (lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1) {
  3035. model.castShadow = true;
  3036. }
  3037. }
  3038. return model;
  3039. },
  3040. createMesh: function createMesh(relationships, geometryMap, materialMap) {
  3041. var model;
  3042. var geometry = null;
  3043. var material = null;
  3044. var materials = [];
  3045. // get geometry and materials(s) from connections
  3046. relationships.children.forEach(function (child) {
  3047. if (geometryMap.has(child.ID)) {
  3048. geometry = geometryMap.get(child.ID);
  3049. }
  3050. if (materialMap.has(child.ID)) {
  3051. materials.push(materialMap.get(child.ID));
  3052. }
  3053. });
  3054. if (materials.length > 1) {
  3055. material = materials;
  3056. } else if (materials.length > 0) {
  3057. material = materials[0];
  3058. } else {
  3059. material = new THREE.MeshPhongMaterial({ color: 0xcccccc });
  3060. materials.push(material);
  3061. }
  3062. if ('color' in geometry.attributes) {
  3063. materials.forEach(function (material) {
  3064. material.vertexColors = THREE.VertexColors;
  3065. });
  3066. }
  3067. if (geometry.FBX_Deformer) {
  3068. materials.forEach(function (material) {
  3069. material.skinning = true;
  3070. });
  3071. model = new THREE.SkinnedMesh(geometry, material);
  3072. } else {
  3073. model = new THREE.Mesh(geometry, material);
  3074. }
  3075. return model;
  3076. },
  3077. createCurve: function createCurve(relationships, geometryMap) {
  3078. var geometry = relationships.children.reduce(function (geo, child) {
  3079. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  3080. return geo;
  3081. }, null);
  3082. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  3083. var material = new THREE.LineBasicMaterial({ color: 0x3300ff, linewidth: 1 });
  3084. return new THREE.Line(geometry, material);
  3085. },
  3086. // parse the model node for transform details and apply them to the model
  3087. setModelTransforms: function setModelTransforms(model, modelNode) {
  3088. var transformData = {};
  3089. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3090. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3091. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3092. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3093. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3094. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3095. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3096. var transform = generateTransform(transformData);
  3097. model.applyMatrix(transform);
  3098. },
  3099. setLookAtProperties: function setLookAtProperties(model, modelNode) {
  3100. if ('LookAtProperty' in modelNode) {
  3101. var children = connections.get(model.ID).children;
  3102. children.forEach(function (child) {
  3103. if (child.relationship === 'LookAtProperty') {
  3104. var lookAtTarget = fbxTree.Objects.Model[child.ID];
  3105. if ('Lcl_Translation' in lookAtTarget) {
  3106. var pos = lookAtTarget.Lcl_Translation.value;
  3107. // DirectionalLight, SpotLight
  3108. if (model.target !== undefined) {
  3109. model.target.position.fromArray(pos);
  3110. sceneGraph.add(model.target);
  3111. } else {
  3112. // Cameras and other Object3Ds
  3113. model.lookAt(new THREE.Vector3().fromArray(pos));
  3114. }
  3115. }
  3116. }
  3117. });
  3118. }
  3119. },
  3120. bindSkeleton: function bindSkeleton(skeletons, geometryMap, modelMap) {
  3121. var bindMatrices = this.parsePoseNodes();
  3122. for (var ID in skeletons) {
  3123. var skeleton = skeletons[ID];
  3124. var parents = connections.get(parseInt(skeleton.ID)).parents;
  3125. parents.forEach(function (parent) {
  3126. if (geometryMap.has(parent.ID)) {
  3127. var geoID = parent.ID;
  3128. var geoRelationships = connections.get(geoID);
  3129. geoRelationships.parents.forEach(function (geoConnParent) {
  3130. if (modelMap.has(geoConnParent.ID)) {
  3131. var model = modelMap.get(geoConnParent.ID);
  3132. model.bind(new THREE.Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
  3133. }
  3134. });
  3135. }
  3136. });
  3137. }
  3138. },
  3139. parsePoseNodes: function parsePoseNodes() {
  3140. var bindMatrices = {};
  3141. if ('Pose' in fbxTree.Objects) {
  3142. var BindPoseNode = fbxTree.Objects.Pose;
  3143. for (var nodeID in BindPoseNode) {
  3144. if (BindPoseNode[nodeID].attrType === 'BindPose') {
  3145. var poseNodes = BindPoseNode[nodeID].PoseNode;
  3146. if (Array.isArray(poseNodes)) {
  3147. poseNodes.forEach(function (poseNode) {
  3148. bindMatrices[poseNode.Node] = new THREE.Matrix4().fromArray(poseNode.Matrix.a);
  3149. });
  3150. } else {
  3151. bindMatrices[poseNodes.Node] = new THREE.Matrix4().fromArray(poseNodes.Matrix.a);
  3152. }
  3153. }
  3154. }
  3155. }
  3156. return bindMatrices;
  3157. },
  3158. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  3159. createAmbientLight: function createAmbientLight() {
  3160. if ('GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings) {
  3161. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  3162. var r = ambientColor[0];
  3163. var g = ambientColor[1];
  3164. var b = ambientColor[2];
  3165. if (r !== 0 || g !== 0 || b !== 0) {
  3166. var color = new THREE.Color(r, g, b);
  3167. sceneGraph.add(new THREE.AmbientLight(color, 1));
  3168. }
  3169. }
  3170. },
  3171. setupMorphMaterials: function setupMorphMaterials() {
  3172. sceneGraph.traverse(function (child) {
  3173. if (child.isMesh) {
  3174. if (child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal) {
  3175. var uuid = child.uuid;
  3176. var matUuid = child.material.uuid;
  3177. // if a geometry has morph targets, it cannot share the material with other geometries
  3178. var sharedMat = false;
  3179. sceneGraph.traverse(function (child) {
  3180. if (child.isMesh) {
  3181. if (child.material.uuid === matUuid && child.uuid !== uuid) sharedMat = true;
  3182. }
  3183. });
  3184. if (sharedMat === true) child.material = child.material.clone();
  3185. child.material.morphTargets = true;
  3186. }
  3187. }
  3188. });
  3189. }
  3190. };
  3191. // parse Geometry data from FBXTree and return map of BufferGeometries
  3192. function GeometryParser() {}
  3193. GeometryParser.prototype = {
  3194. constructor: GeometryParser,
  3195. // Parse nodes in FBXTree.Objects.Geometry
  3196. parse: function parse(deformers) {
  3197. var geometryMap = new Map();
  3198. if ('Geometry' in fbxTree.Objects) {
  3199. var geoNodes = fbxTree.Objects.Geometry;
  3200. for (var nodeID in geoNodes) {
  3201. var relationships = connections.get(parseInt(nodeID));
  3202. var geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
  3203. geometryMap.set(parseInt(nodeID), geo);
  3204. }
  3205. }
  3206. return geometryMap;
  3207. },
  3208. // Parse single node in FBXTree.Objects.Geometry
  3209. parseGeometry: function parseGeometry(relationships, geoNode, deformers) {
  3210. switch (geoNode.attrType) {
  3211. case 'Mesh':
  3212. return this.parseMeshGeometry(relationships, geoNode, deformers);
  3213. break;
  3214. case 'NurbsCurve':
  3215. return this.parseNurbsGeometry(geoNode);
  3216. break;
  3217. }
  3218. },
  3219. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  3220. parseMeshGeometry: function parseMeshGeometry(relationships, geoNode, deformers) {
  3221. var skeletons = deformers.skeletons;
  3222. var morphTargets = deformers.morphTargets;
  3223. var modelNodes = relationships.parents.map(function (parent) {
  3224. return fbxTree.Objects.Model[parent.ID];
  3225. });
  3226. // don't create geometry if it is not associated with any models
  3227. if (modelNodes.length === 0) return;
  3228. var skeleton = relationships.children.reduce(function (skeleton, child) {
  3229. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  3230. return skeleton;
  3231. }, null);
  3232. var morphTarget = relationships.children.reduce(function (morphTarget, child) {
  3233. if (morphTargets[child.ID] !== undefined) morphTarget = morphTargets[child.ID];
  3234. return morphTarget;
  3235. }, null);
  3236. // TODO: if there is more than one model associated with the geometry, AND the models have
  3237. // different geometric transforms, then this will cause problems
  3238. // if ( modelNodes.length > 1 ) { }
  3239. // For now just assume one model and get the preRotations from that
  3240. var modelNode = modelNodes[0];
  3241. var transformData = {};
  3242. if ('RotationOrder' in modelNode) transformData.eulerOrder = modelNode.RotationOrder.value;
  3243. if ('GeometricTranslation' in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
  3244. if ('GeometricRotation' in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
  3245. if ('GeometricScaling' in modelNode) transformData.scale = modelNode.GeometricScaling.value;
  3246. var transform = generateTransform(transformData);
  3247. return this.genGeometry(geoNode, skeleton, morphTarget, transform);
  3248. },
  3249. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  3250. genGeometry: function genGeometry(geoNode, skeleton, morphTarget, preTransform) {
  3251. var geo = new THREE.BufferGeometry();
  3252. if (geoNode.attrName) geo.name = geoNode.attrName;
  3253. var geoInfo = this.parseGeoNode(geoNode, skeleton);
  3254. var buffers = this.genBuffers(geoInfo);
  3255. var positionAttribute = new THREE.Float32BufferAttribute(buffers.vertex, 3);
  3256. preTransform.applyToBufferAttribute(positionAttribute);
  3257. geo.addAttribute('position', positionAttribute);
  3258. if (buffers.colors.length > 0) {
  3259. geo.addAttribute('color', new THREE.Float32BufferAttribute(buffers.colors, 3));
  3260. }
  3261. if (skeleton) {
  3262. geo.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(buffers.weightsIndices, 4));
  3263. geo.addAttribute('skinWeight', new THREE.Float32BufferAttribute(buffers.vertexWeights, 4));
  3264. // used later to bind the skeleton to the model
  3265. geo.FBX_Deformer = skeleton;
  3266. }
  3267. if (buffers.normal.length > 0) {
  3268. var normalAttribute = new THREE.Float32BufferAttribute(buffers.normal, 3);
  3269. var normalMatrix = new THREE.Matrix3().getNormalMatrix(preTransform);
  3270. normalMatrix.applyToBufferAttribute(normalAttribute);
  3271. geo.addAttribute('normal', normalAttribute);
  3272. }
  3273. buffers.uvs.forEach(function (uvBuffer, i) {
  3274. // subsequent uv buffers are called 'uv1', 'uv2', ...
  3275. var name = 'uv' + (i + 1).toString();
  3276. // the first uv buffer is just called 'uv'
  3277. if (i === 0) {
  3278. name = 'uv';
  3279. }
  3280. geo.addAttribute(name, new THREE.Float32BufferAttribute(buffers.uvs[i], 2));
  3281. });
  3282. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3283. // Convert the material indices of each vertex into rendering groups on the geometry.
  3284. var prevMaterialIndex = buffers.materialIndex[0];
  3285. var startIndex = 0;
  3286. buffers.materialIndex.forEach(function (currentIndex, i) {
  3287. if (currentIndex !== prevMaterialIndex) {
  3288. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  3289. prevMaterialIndex = currentIndex;
  3290. startIndex = i;
  3291. }
  3292. });
  3293. // the loop above doesn't add the last group, do that here.
  3294. if (geo.groups.length > 0) {
  3295. var lastGroup = geo.groups[geo.groups.length - 1];
  3296. var lastIndex = lastGroup.start + lastGroup.count;
  3297. if (lastIndex !== buffers.materialIndex.length) {
  3298. geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
  3299. }
  3300. }
  3301. // case where there are multiple materials but the whole geometry is only
  3302. // using one of them
  3303. if (geo.groups.length === 0) {
  3304. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  3305. }
  3306. }
  3307. this.addMorphTargets(geo, geoNode, morphTarget, preTransform);
  3308. return geo;
  3309. },
  3310. parseGeoNode: function parseGeoNode(geoNode, skeleton) {
  3311. var geoInfo = {};
  3312. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  3313. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  3314. if (geoNode.LayerElementColor) {
  3315. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  3316. }
  3317. if (geoNode.LayerElementMaterial) {
  3318. geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
  3319. }
  3320. if (geoNode.LayerElementNormal) {
  3321. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  3322. }
  3323. if (geoNode.LayerElementUV) {
  3324. geoInfo.uv = [];
  3325. var i = 0;
  3326. while (geoNode.LayerElementUV[i]) {
  3327. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  3328. i++;
  3329. }
  3330. }
  3331. geoInfo.weightTable = {};
  3332. if (skeleton !== null) {
  3333. geoInfo.skeleton = skeleton;
  3334. skeleton.rawBones.forEach(function (rawBone, i) {
  3335. // loop over the bone's vertex indices and weights
  3336. rawBone.indices.forEach(function (index, j) {
  3337. if (geoInfo.weightTable[index] === undefined) geoInfo.weightTable[index] = [];
  3338. geoInfo.weightTable[index].push({
  3339. id: i,
  3340. weight: rawBone.weights[j]
  3341. });
  3342. });
  3343. });
  3344. }
  3345. return geoInfo;
  3346. },
  3347. genBuffers: function genBuffers(geoInfo) {
  3348. var buffers = {
  3349. vertex: [],
  3350. normal: [],
  3351. colors: [],
  3352. uvs: [],
  3353. materialIndex: [],
  3354. vertexWeights: [],
  3355. weightsIndices: []
  3356. };
  3357. var polygonIndex = 0;
  3358. var faceLength = 0;
  3359. var displayedWeightsWarning = false;
  3360. // these will hold data for a single face
  3361. var facePositionIndexes = [];
  3362. var faceNormals = [];
  3363. var faceColors = [];
  3364. var faceUVs = [];
  3365. var faceWeights = [];
  3366. var faceWeightIndices = [];
  3367. var self = this;
  3368. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  3369. var endOfFace = false;
  3370. // Face index and vertex index arrays are combined in a single array
  3371. // A cube with quad faces looks like this:
  3372. // PolygonVertexIndex: *24 {
  3373. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  3374. // }
  3375. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  3376. // to find index of last vertex bit shift the index: ^ - 1
  3377. if (vertexIndex < 0) {
  3378. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  3379. endOfFace = true;
  3380. }
  3381. var weightIndices = [];
  3382. var weights = [];
  3383. facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
  3384. if (geoInfo.color) {
  3385. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
  3386. faceColors.push(data[0], data[1], data[2]);
  3387. }
  3388. if (geoInfo.skeleton) {
  3389. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  3390. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  3391. weights.push(wt.weight);
  3392. weightIndices.push(wt.id);
  3393. });
  3394. }
  3395. if (weights.length > 4) {
  3396. if (!displayedWeightsWarning) {
  3397. console.warn('THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.');
  3398. displayedWeightsWarning = true;
  3399. }
  3400. var wIndex = [0, 0, 0, 0];
  3401. var Weight = [0, 0, 0, 0];
  3402. weights.forEach(function (weight, weightIndex) {
  3403. var currentWeight = weight;
  3404. var currentIndex = weightIndices[weightIndex];
  3405. Weight.forEach(function (comparedWeight, comparedWeightIndex, comparedWeightArray) {
  3406. if (currentWeight > comparedWeight) {
  3407. comparedWeightArray[comparedWeightIndex] = currentWeight;
  3408. currentWeight = comparedWeight;
  3409. var tmp = wIndex[comparedWeightIndex];
  3410. wIndex[comparedWeightIndex] = currentIndex;
  3411. currentIndex = tmp;
  3412. }
  3413. });
  3414. });
  3415. weightIndices = wIndex;
  3416. weights = Weight;
  3417. }
  3418. // if the weight array is shorter than 4 pad with 0s
  3419. while (weights.length < 4) {
  3420. weights.push(0);
  3421. weightIndices.push(0);
  3422. }
  3423. for (var i = 0; i < 4; ++i) {
  3424. faceWeights.push(weights[i]);
  3425. faceWeightIndices.push(weightIndices[i]);
  3426. }
  3427. }
  3428. if (geoInfo.normal) {
  3429. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
  3430. faceNormals.push(data[0], data[1], data[2]);
  3431. }
  3432. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3433. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
  3434. }
  3435. if (geoInfo.uv) {
  3436. geoInfo.uv.forEach(function (uv, i) {
  3437. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
  3438. if (faceUVs[i] === undefined) {
  3439. faceUVs[i] = [];
  3440. }
  3441. faceUVs[i].push(data[0]);
  3442. faceUVs[i].push(data[1]);
  3443. });
  3444. }
  3445. faceLength++;
  3446. if (endOfFace) {
  3447. self.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
  3448. polygonIndex++;
  3449. faceLength = 0;
  3450. // reset arrays for the next face
  3451. facePositionIndexes = [];
  3452. faceNormals = [];
  3453. faceColors = [];
  3454. faceUVs = [];
  3455. faceWeights = [];
  3456. faceWeightIndices = [];
  3457. }
  3458. });
  3459. return buffers;
  3460. },
  3461. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  3462. genFace: function genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
  3463. for (var i = 2; i < faceLength; i++) {
  3464. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  3465. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  3466. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  3467. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]);
  3468. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]);
  3469. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]);
  3470. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  3471. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]);
  3472. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]);
  3473. if (geoInfo.skeleton) {
  3474. buffers.vertexWeights.push(faceWeights[0]);
  3475. buffers.vertexWeights.push(faceWeights[1]);
  3476. buffers.vertexWeights.push(faceWeights[2]);
  3477. buffers.vertexWeights.push(faceWeights[3]);
  3478. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  3479. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  3480. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  3481. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  3482. buffers.vertexWeights.push(faceWeights[i * 4]);
  3483. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  3484. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  3485. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  3486. buffers.weightsIndices.push(faceWeightIndices[0]);
  3487. buffers.weightsIndices.push(faceWeightIndices[1]);
  3488. buffers.weightsIndices.push(faceWeightIndices[2]);
  3489. buffers.weightsIndices.push(faceWeightIndices[3]);
  3490. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  3491. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  3492. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  3493. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  3494. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  3495. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  3496. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  3497. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  3498. }
  3499. if (geoInfo.color) {
  3500. buffers.colors.push(faceColors[0]);
  3501. buffers.colors.push(faceColors[1]);
  3502. buffers.colors.push(faceColors[2]);
  3503. buffers.colors.push(faceColors[(i - 1) * 3]);
  3504. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  3505. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  3506. buffers.colors.push(faceColors[i * 3]);
  3507. buffers.colors.push(faceColors[i * 3 + 1]);
  3508. buffers.colors.push(faceColors[i * 3 + 2]);
  3509. }
  3510. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3511. buffers.materialIndex.push(materialIndex);
  3512. buffers.materialIndex.push(materialIndex);
  3513. buffers.materialIndex.push(materialIndex);
  3514. }
  3515. if (geoInfo.normal) {
  3516. buffers.normal.push(faceNormals[0]);
  3517. buffers.normal.push(faceNormals[1]);
  3518. buffers.normal.push(faceNormals[2]);
  3519. buffers.normal.push(faceNormals[(i - 1) * 3]);
  3520. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  3521. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  3522. buffers.normal.push(faceNormals[i * 3]);
  3523. buffers.normal.push(faceNormals[i * 3 + 1]);
  3524. buffers.normal.push(faceNormals[i * 3 + 2]);
  3525. }
  3526. if (geoInfo.uv) {
  3527. geoInfo.uv.forEach(function (uv, j) {
  3528. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  3529. buffers.uvs[j].push(faceUVs[j][0]);
  3530. buffers.uvs[j].push(faceUVs[j][1]);
  3531. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  3532. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  3533. buffers.uvs[j].push(faceUVs[j][i * 2]);
  3534. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  3535. });
  3536. }
  3537. }
  3538. },
  3539. addMorphTargets: function addMorphTargets(parentGeo, parentGeoNode, morphTarget, preTransform) {
  3540. if (morphTarget === null) return;
  3541. parentGeo.morphAttributes.position = [];
  3542. parentGeo.morphAttributes.normal = [];
  3543. var self = this;
  3544. morphTarget.rawTargets.forEach(function (rawTarget) {
  3545. var morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  3546. if (morphGeoNode !== undefined) {
  3547. self.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform);
  3548. }
  3549. });
  3550. },
  3551. // a morph geometry node is similar to a standard node, and the node is also contained
  3552. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  3553. // and a special attribute Index defining which vertices of the original geometry are affected
  3554. // Normal and position attributes only have data for the vertices that are affected by the morph
  3555. genMorphGeometry: function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) {
  3556. var morphGeo = new THREE.BufferGeometry();
  3557. if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName;
  3558. var vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  3559. // make a copy of the parent's vertex positions
  3560. var vertexPositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a.slice() : [];
  3561. var morphPositions = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  3562. var indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  3563. for (var i = 0; i < indices.length; i++) {
  3564. var morphIndex = indices[i] * 3;
  3565. // FBX format uses blend shapes rather than morph targets. This can be converted
  3566. // by additively combining the blend shape positions with the original geometry's positions
  3567. vertexPositions[morphIndex] += morphPositions[i * 3];
  3568. vertexPositions[morphIndex + 1] += morphPositions[i * 3 + 1];
  3569. vertexPositions[morphIndex + 2] += morphPositions[i * 3 + 2];
  3570. }
  3571. // TODO: add morph normal support
  3572. var morphGeoInfo = {
  3573. vertexIndices: vertexIndices,
  3574. vertexPositions: vertexPositions
  3575. };
  3576. var morphBuffers = this.genBuffers(morphGeoInfo);
  3577. var positionAttribute = new THREE.Float32BufferAttribute(morphBuffers.vertex, 3);
  3578. positionAttribute.name = morphGeoNode.attrName;
  3579. preTransform.applyToBufferAttribute(positionAttribute);
  3580. parentGeo.morphAttributes.position.push(positionAttribute);
  3581. },
  3582. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  3583. parseNormals: function parseNormals(NormalNode) {
  3584. var mappingType = NormalNode.MappingInformationType;
  3585. var referenceType = NormalNode.ReferenceInformationType;
  3586. var buffer = NormalNode.Normals.a;
  3587. var indexBuffer = [];
  3588. if (referenceType === 'IndexToDirect') {
  3589. if ('NormalIndex' in NormalNode) {
  3590. indexBuffer = NormalNode.NormalIndex.a;
  3591. } else if ('NormalsIndex' in NormalNode) {
  3592. indexBuffer = NormalNode.NormalsIndex.a;
  3593. }
  3594. }
  3595. return {
  3596. dataSize: 3,
  3597. buffer: buffer,
  3598. indices: indexBuffer,
  3599. mappingType: mappingType,
  3600. referenceType: referenceType
  3601. };
  3602. },
  3603. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  3604. parseUVs: function parseUVs(UVNode) {
  3605. var mappingType = UVNode.MappingInformationType;
  3606. var referenceType = UVNode.ReferenceInformationType;
  3607. var buffer = UVNode.UV.a;
  3608. var indexBuffer = [];
  3609. if (referenceType === 'IndexToDirect') {
  3610. indexBuffer = UVNode.UVIndex.a;
  3611. }
  3612. return {
  3613. dataSize: 2,
  3614. buffer: buffer,
  3615. indices: indexBuffer,
  3616. mappingType: mappingType,
  3617. referenceType: referenceType
  3618. };
  3619. },
  3620. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  3621. parseVertexColors: function parseVertexColors(ColorNode) {
  3622. var mappingType = ColorNode.MappingInformationType;
  3623. var referenceType = ColorNode.ReferenceInformationType;
  3624. var buffer = ColorNode.Colors.a;
  3625. var indexBuffer = [];
  3626. if (referenceType === 'IndexToDirect') {
  3627. indexBuffer = ColorNode.ColorIndex.a;
  3628. }
  3629. return {
  3630. dataSize: 4,
  3631. buffer: buffer,
  3632. indices: indexBuffer,
  3633. mappingType: mappingType,
  3634. referenceType: referenceType
  3635. };
  3636. },
  3637. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  3638. parseMaterialIndices: function parseMaterialIndices(MaterialNode) {
  3639. var mappingType = MaterialNode.MappingInformationType;
  3640. var referenceType = MaterialNode.ReferenceInformationType;
  3641. if (mappingType === 'NoMappingInformation') {
  3642. return {
  3643. dataSize: 1,
  3644. buffer: [0],
  3645. indices: [0],
  3646. mappingType: 'AllSame',
  3647. referenceType: referenceType
  3648. };
  3649. }
  3650. var materialIndexBuffer = MaterialNode.Materials.a;
  3651. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  3652. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  3653. // for conforming with the other functions we've written for other data.
  3654. var materialIndices = [];
  3655. for (var i = 0; i < materialIndexBuffer.length; ++i) {
  3656. materialIndices.push(i);
  3657. }
  3658. return {
  3659. dataSize: 1,
  3660. buffer: materialIndexBuffer,
  3661. indices: materialIndices,
  3662. mappingType: mappingType,
  3663. referenceType: referenceType
  3664. };
  3665. },
  3666. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  3667. parseNurbsGeometry: function parseNurbsGeometry(geoNode) {
  3668. if (THREE.NURBSCurve === undefined) {
  3669. console.error('THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.');
  3670. return new THREE.BufferGeometry();
  3671. }
  3672. var order = parseInt(geoNode.Order);
  3673. if (isNaN(order)) {
  3674. console.error('THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id);
  3675. return new THREE.BufferGeometry();
  3676. }
  3677. var degree = order - 1;
  3678. var knots = geoNode.KnotVector.a;
  3679. var controlPoints = [];
  3680. var pointsValues = geoNode.Points.a;
  3681. for (var i = 0, l = pointsValues.length; i < l; i += 4) {
  3682. controlPoints.push(new THREE.Vector4().fromArray(pointsValues, i));
  3683. }
  3684. var startKnot, endKnot;
  3685. if (geoNode.Form === 'Closed') {
  3686. controlPoints.push(controlPoints[0]);
  3687. } else if (geoNode.Form === 'Periodic') {
  3688. startKnot = degree;
  3689. endKnot = knots.length - 1 - startKnot;
  3690. for (var i = 0; i < degree; ++i) {
  3691. controlPoints.push(controlPoints[i]);
  3692. }
  3693. }
  3694. var curve = new THREE.NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
  3695. var vertices = curve.getPoints(controlPoints.length * 7);
  3696. var positions = new Float32Array(vertices.length * 3);
  3697. vertices.forEach(function (vertex, i) {
  3698. vertex.toArray(positions, i * 3);
  3699. });
  3700. var geometry = new THREE.BufferGeometry();
  3701. geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
  3702. return geometry;
  3703. }
  3704. };
  3705. // parse animation data from FBXTree
  3706. function AnimationParser() {}
  3707. AnimationParser.prototype = {
  3708. constructor: AnimationParser,
  3709. // take raw animation clips and turn them into three.js animation clips
  3710. parse: function parse() {
  3711. var animationClips = [];
  3712. var rawClips = this.parseClips();
  3713. if (rawClips === undefined) return animationClips;
  3714. for (var key in rawClips) {
  3715. var rawClip = rawClips[key];
  3716. var clip = this.addClip(rawClip);
  3717. animationClips.push(clip);
  3718. }
  3719. return animationClips;
  3720. },
  3721. parseClips: function parseClips() {
  3722. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  3723. // if this is undefined we can safely assume there are no animations
  3724. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  3725. var curveNodesMap = this.parseAnimationCurveNodes();
  3726. this.parseAnimationCurves(curveNodesMap);
  3727. var layersMap = this.parseAnimationLayers(curveNodesMap);
  3728. var rawClips = this.parseAnimStacks(layersMap);
  3729. return rawClips;
  3730. },
  3731. // parse nodes in FBXTree.Objects.AnimationCurveNode
  3732. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  3733. // and is referenced by an AnimationLayer
  3734. parseAnimationCurveNodes: function parseAnimationCurveNodes() {
  3735. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  3736. var curveNodesMap = new Map();
  3737. for (var nodeID in rawCurveNodes) {
  3738. var rawCurveNode = rawCurveNodes[nodeID];
  3739. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  3740. var curveNode = {
  3741. id: rawCurveNode.id,
  3742. attr: rawCurveNode.attrName,
  3743. curves: {}
  3744. };
  3745. curveNodesMap.set(curveNode.id, curveNode);
  3746. }
  3747. }
  3748. return curveNodesMap;
  3749. },
  3750. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  3751. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  3752. // axis ( e.g. times and values of x rotation)
  3753. parseAnimationCurves: function parseAnimationCurves(curveNodesMap) {
  3754. var rawCurves = fbxTree.Objects.AnimationCurve;
  3755. // TODO: Many values are identical up to roundoff error, but won't be optimised
  3756. // e.g. position times: [0, 0.4, 0. 8]
  3757. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  3758. // clearly, this should be optimised to
  3759. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  3760. // this shows up in nearly every FBX file, and generally time array is length > 100
  3761. for (var nodeID in rawCurves) {
  3762. var animationCurve = {
  3763. id: rawCurves[nodeID].id,
  3764. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  3765. values: rawCurves[nodeID].KeyValueFloat.a
  3766. };
  3767. var relationships = connections.get(animationCurve.id);
  3768. if (relationships !== undefined) {
  3769. var animationCurveID = relationships.parents[0].ID;
  3770. var animationCurveRelationship = relationships.parents[0].relationship;
  3771. if (animationCurveRelationship.match(/X/)) {
  3772. curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;
  3773. } else if (animationCurveRelationship.match(/Y/)) {
  3774. curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;
  3775. } else if (animationCurveRelationship.match(/Z/)) {
  3776. curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;
  3777. } else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveID)) {
  3778. curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;
  3779. }
  3780. }
  3781. }
  3782. },
  3783. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  3784. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  3785. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  3786. parseAnimationLayers: function parseAnimationLayers(curveNodesMap) {
  3787. var rawLayers = fbxTree.Objects.AnimationLayer;
  3788. var layersMap = new Map();
  3789. for (var nodeID in rawLayers) {
  3790. var layerCurveNodes = [];
  3791. var connection = connections.get(parseInt(nodeID));
  3792. if (connection !== undefined) {
  3793. // all the animationCurveNodes used in the layer
  3794. var children = connection.children;
  3795. var self = this;
  3796. children.forEach(function (child, i) {
  3797. if (curveNodesMap.has(child.ID)) {
  3798. var curveNode = curveNodesMap.get(child.ID);
  3799. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  3800. if (curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined) {
  3801. if (layerCurveNodes[i] === undefined) {
  3802. var modelID;
  3803. connections.get(child.ID).parents.forEach(function (parent) {
  3804. if (parent.relationship !== undefined) modelID = parent.ID;
  3805. });
  3806. var rawModel = fbxTree.Objects.Model[modelID.toString()];
  3807. var node = {
  3808. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3809. initialPosition: [0, 0, 0],
  3810. initialRotation: [0, 0, 0],
  3811. initialScale: [1, 1, 1],
  3812. transform: self.getModelAnimTransform(rawModel)
  3813. };
  3814. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  3815. // animation value as well
  3816. if ('PreRotation' in rawModel) node.preRotations = rawModel.PreRotation.value;
  3817. if ('PostRotation' in rawModel) node.postRotations = rawModel.PostRotation.value;
  3818. layerCurveNodes[i] = node;
  3819. }
  3820. layerCurveNodes[i][curveNode.attr] = curveNode;
  3821. } else if (curveNode.curves.morph !== undefined) {
  3822. if (layerCurveNodes[i] === undefined) {
  3823. var deformerID;
  3824. connections.get(child.ID).parents.forEach(function (parent) {
  3825. if (parent.relationship !== undefined) deformerID = parent.ID;
  3826. });
  3827. var morpherID = connections.get(deformerID).parents[0].ID;
  3828. var geoID = connections.get(morpherID).parents[0].ID;
  3829. // assuming geometry is not used in more than one model
  3830. var modelID = connections.get(geoID).parents[0].ID;
  3831. var rawModel = fbxTree.Objects.Model[modelID];
  3832. var node = {
  3833. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3834. morphName: fbxTree.Objects.Deformer[deformerID].attrName
  3835. };
  3836. layerCurveNodes[i] = node;
  3837. }
  3838. layerCurveNodes[i][curveNode.attr] = curveNode;
  3839. }
  3840. }
  3841. });
  3842. layersMap.set(parseInt(nodeID), layerCurveNodes);
  3843. }
  3844. }
  3845. return layersMap;
  3846. },
  3847. getModelAnimTransform: function getModelAnimTransform(modelNode) {
  3848. var transformData = {};
  3849. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3850. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3851. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3852. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3853. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3854. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3855. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3856. return generateTransform(transformData);
  3857. },
  3858. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  3859. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  3860. parseAnimStacks: function parseAnimStacks(layersMap) {
  3861. var rawStacks = fbxTree.Objects.AnimationStack;
  3862. // connect the stacks (clips) up to the layers
  3863. var rawClips = {};
  3864. for (var nodeID in rawStacks) {
  3865. var children = connections.get(parseInt(nodeID)).children;
  3866. if (children.length > 1) {
  3867. // it seems like stacks will always be associated with a single layer. But just in case there are files
  3868. // where there are multiple layers per stack, we'll display a warning
  3869. console.warn('THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.');
  3870. }
  3871. var layer = layersMap.get(children[0].ID);
  3872. rawClips[nodeID] = {
  3873. name: rawStacks[nodeID].attrName,
  3874. layer: layer
  3875. };
  3876. }
  3877. return rawClips;
  3878. },
  3879. addClip: function addClip(rawClip) {
  3880. var tracks = [];
  3881. var self = this;
  3882. rawClip.layer.forEach(function (rawTracks) {
  3883. tracks = tracks.concat(self.generateTracks(rawTracks));
  3884. });
  3885. return new THREE.AnimationClip(rawClip.name, -1, tracks);
  3886. },
  3887. generateTracks: function generateTracks(rawTracks) {
  3888. var tracks = [];
  3889. var initialPosition = new THREE.Vector3();
  3890. var initialRotation = new THREE.Quaternion();
  3891. var initialScale = new THREE.Vector3();
  3892. if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale);
  3893. initialPosition = initialPosition.toArray();
  3894. initialRotation = new THREE.Euler().setFromQuaternion(initialRotation).toArray(); // todo: euler order
  3895. initialScale = initialScale.toArray();
  3896. if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {
  3897. var positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position');
  3898. if (positionTrack !== undefined) tracks.push(positionTrack);
  3899. }
  3900. if (rawTracks.R !== undefined && Object.keys(rawTracks.R.curves).length > 0) {
  3901. var rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations);
  3902. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  3903. }
  3904. if (rawTracks.S !== undefined && Object.keys(rawTracks.S.curves).length > 0) {
  3905. var scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale');
  3906. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  3907. }
  3908. if (rawTracks.DeformPercent !== undefined) {
  3909. var morphTrack = this.generateMorphTrack(rawTracks);
  3910. if (morphTrack !== undefined) tracks.push(morphTrack);
  3911. }
  3912. return tracks;
  3913. },
  3914. generateVectorTrack: function generateVectorTrack(modelName, curves, initialValue, type) {
  3915. var times = this.getTimesForAllAxes(curves);
  3916. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3917. return new THREE.VectorKeyframeTrack(modelName + '.' + type, times, values);
  3918. },
  3919. generateRotationTrack: function generateRotationTrack(modelName, curves, initialValue, preRotations, postRotations) {
  3920. if (curves.x !== undefined) {
  3921. this.interpolateRotations(curves.x);
  3922. curves.x.values = curves.x.values.map(THREE.Math.degToRad);
  3923. }
  3924. if (curves.y !== undefined) {
  3925. this.interpolateRotations(curves.y);
  3926. curves.y.values = curves.y.values.map(THREE.Math.degToRad);
  3927. }
  3928. if (curves.z !== undefined) {
  3929. this.interpolateRotations(curves.z);
  3930. curves.z.values = curves.z.values.map(THREE.Math.degToRad);
  3931. }
  3932. var times = this.getTimesForAllAxes(curves);
  3933. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3934. if (preRotations !== undefined) {
  3935. preRotations = preRotations.map(THREE.Math.degToRad);
  3936. preRotations.push('ZYX');
  3937. preRotations = new THREE.Euler().fromArray(preRotations);
  3938. preRotations = new THREE.Quaternion().setFromEuler(preRotations);
  3939. }
  3940. if (postRotations !== undefined) {
  3941. postRotations = postRotations.map(THREE.Math.degToRad);
  3942. postRotations.push('ZYX');
  3943. postRotations = new THREE.Euler().fromArray(postRotations);
  3944. postRotations = new THREE.Quaternion().setFromEuler(postRotations).inverse();
  3945. }
  3946. var quaternion = new THREE.Quaternion();
  3947. var euler = new THREE.Euler();
  3948. var quaternionValues = [];
  3949. for (var i = 0; i < values.length; i += 3) {
  3950. euler.set(values[i], values[i + 1], values[i + 2], 'ZYX');
  3951. quaternion.setFromEuler(euler);
  3952. if (preRotations !== undefined) quaternion.premultiply(preRotations);
  3953. if (postRotations !== undefined) quaternion.multiply(postRotations);
  3954. quaternion.toArray(quaternionValues, i / 3 * 4);
  3955. }
  3956. return new THREE.QuaternionKeyframeTrack(modelName + '.quaternion', times, quaternionValues);
  3957. },
  3958. generateMorphTrack: function generateMorphTrack(rawTracks) {
  3959. var curves = rawTracks.DeformPercent.curves.morph;
  3960. var values = curves.values.map(function (val) {
  3961. return val / 100;
  3962. });
  3963. var morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
  3964. return new THREE.NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);
  3965. },
  3966. // For all animated objects, times are defined separately for each axis
  3967. // Here we'll combine the times into one sorted array without duplicates
  3968. getTimesForAllAxes: function getTimesForAllAxes(curves) {
  3969. var times = [];
  3970. // first join together the times for each axis, if defined
  3971. if (curves.x !== undefined) times = times.concat(curves.x.times);
  3972. if (curves.y !== undefined) times = times.concat(curves.y.times);
  3973. if (curves.z !== undefined) times = times.concat(curves.z.times);
  3974. // then sort them and remove duplicates
  3975. times = times.sort(function (a, b) {
  3976. return a - b;
  3977. }).filter(function (elem, index, array) {
  3978. return array.indexOf(elem) == index;
  3979. });
  3980. return times;
  3981. },
  3982. getKeyframeTrackValues: function getKeyframeTrackValues(times, curves, initialValue) {
  3983. var prevValue = initialValue;
  3984. var values = [];
  3985. var xIndex = -1;
  3986. var yIndex = -1;
  3987. var zIndex = -1;
  3988. times.forEach(function (time) {
  3989. if (curves.x) xIndex = curves.x.times.indexOf(time);
  3990. if (curves.y) yIndex = curves.y.times.indexOf(time);
  3991. if (curves.z) zIndex = curves.z.times.indexOf(time);
  3992. // if there is an x value defined for this frame, use that
  3993. if (xIndex !== -1) {
  3994. var xValue = curves.x.values[xIndex];
  3995. values.push(xValue);
  3996. prevValue[0] = xValue;
  3997. } else {
  3998. // otherwise use the x value from the previous frame
  3999. values.push(prevValue[0]);
  4000. }
  4001. if (yIndex !== -1) {
  4002. var yValue = curves.y.values[yIndex];
  4003. values.push(yValue);
  4004. prevValue[1] = yValue;
  4005. } else {
  4006. values.push(prevValue[1]);
  4007. }
  4008. if (zIndex !== -1) {
  4009. var zValue = curves.z.values[zIndex];
  4010. values.push(zValue);
  4011. prevValue[2] = zValue;
  4012. } else {
  4013. values.push(prevValue[2]);
  4014. }
  4015. });
  4016. return values;
  4017. },
  4018. // Rotations are defined as Euler angles which can have values of any size
  4019. // These will be converted to quaternions which don't support values greater than
  4020. // PI, so we'll interpolate large rotations
  4021. interpolateRotations: function interpolateRotations(curve) {
  4022. for (var i = 1; i < curve.values.length; i++) {
  4023. var initialValue = curve.values[i - 1];
  4024. var valuesSpan = curve.values[i] - initialValue;
  4025. var absoluteSpan = Math.abs(valuesSpan);
  4026. if (absoluteSpan >= 180) {
  4027. var numSubIntervals = absoluteSpan / 180;
  4028. var step = valuesSpan / numSubIntervals;
  4029. var nextValue = initialValue + step;
  4030. var initialTime = curve.times[i - 1];
  4031. var timeSpan = curve.times[i] - initialTime;
  4032. var interval = timeSpan / numSubIntervals;
  4033. var nextTime = initialTime + interval;
  4034. var interpolatedTimes = [];
  4035. var interpolatedValues = [];
  4036. while (nextTime < curve.times[i]) {
  4037. interpolatedTimes.push(nextTime);
  4038. nextTime += interval;
  4039. interpolatedValues.push(nextValue);
  4040. nextValue += step;
  4041. }
  4042. curve.times = inject(curve.times, i, interpolatedTimes);
  4043. curve.values = inject(curve.values, i, interpolatedValues);
  4044. }
  4045. }
  4046. }
  4047. };
  4048. // parse an FBX file in ASCII format
  4049. function TextParser() {}
  4050. TextParser.prototype = {
  4051. constructor: TextParser,
  4052. getPrevNode: function getPrevNode() {
  4053. return this.nodeStack[this.currentIndent - 2];
  4054. },
  4055. getCurrentNode: function getCurrentNode() {
  4056. return this.nodeStack[this.currentIndent - 1];
  4057. },
  4058. getCurrentProp: function getCurrentProp() {
  4059. return this.currentProp;
  4060. },
  4061. pushStack: function pushStack(node) {
  4062. this.nodeStack.push(node);
  4063. this.currentIndent += 1;
  4064. },
  4065. popStack: function popStack() {
  4066. this.nodeStack.pop();
  4067. this.currentIndent -= 1;
  4068. },
  4069. setCurrentProp: function setCurrentProp(val, name) {
  4070. this.currentProp = val;
  4071. this.currentPropName = name;
  4072. },
  4073. parse: function parse(text) {
  4074. this.currentIndent = 0;
  4075. console.log("FBXTree: ", FBXTree);
  4076. this.allNodes = new FBXTree();
  4077. this.nodeStack = [];
  4078. this.currentProp = [];
  4079. this.currentPropName = '';
  4080. var self = this;
  4081. var split = text.split(/[\r\n]+/);
  4082. split.forEach(function (line, i) {
  4083. var matchComment = line.match(/^[\s\t]*;/);
  4084. var matchEmpty = line.match(/^[\s\t]*$/);
  4085. if (matchComment || matchEmpty) return;
  4086. var matchBeginning = line.match('^\\t{' + self.currentIndent + '}(\\w+):(.*){', '');
  4087. var matchProperty = line.match('^\\t{' + self.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)');
  4088. var matchEnd = line.match('^\\t{' + (self.currentIndent - 1) + '}}');
  4089. if (matchBeginning) {
  4090. self.parseNodeBegin(line, matchBeginning);
  4091. } else if (matchProperty) {
  4092. self.parseNodeProperty(line, matchProperty, split[++i]);
  4093. } else if (matchEnd) {
  4094. self.popStack();
  4095. } else if (line.match(/^[^\s\t}]/)) {
  4096. // large arrays are split over multiple lines terminated with a ',' character
  4097. // if this is encountered the line needs to be joined to the previous line
  4098. self.parseNodePropertyContinued(line);
  4099. }
  4100. });
  4101. return this.allNodes;
  4102. },
  4103. parseNodeBegin: function parseNodeBegin(line, property) {
  4104. var nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');
  4105. var nodeAttrs = property[2].split(',').map(function (attr) {
  4106. return attr.trim().replace(/^"/, '').replace(/"$/, '');
  4107. });
  4108. var node = { name: nodeName };
  4109. var attrs = this.parseNodeAttr(nodeAttrs);
  4110. var currentNode = this.getCurrentNode();
  4111. // a top node
  4112. if (this.currentIndent === 0) {
  4113. this.allNodes.add(nodeName, node);
  4114. } else {
  4115. // a subnode
  4116. // if the subnode already exists, append it
  4117. if (nodeName in currentNode) {
  4118. // special case Pose needs PoseNodes as an array
  4119. if (nodeName === 'PoseNode') {
  4120. currentNode.PoseNode.push(node);
  4121. } else if (currentNode[nodeName].id !== undefined) {
  4122. currentNode[nodeName] = {};
  4123. currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
  4124. }
  4125. if (attrs.id !== '') currentNode[nodeName][attrs.id] = node;
  4126. } else if (typeof attrs.id === 'number') {
  4127. currentNode[nodeName] = {};
  4128. currentNode[nodeName][attrs.id] = node;
  4129. } else if (nodeName !== 'Properties70') {
  4130. if (nodeName === 'PoseNode') currentNode[nodeName] = [node];else currentNode[nodeName] = node;
  4131. }
  4132. }
  4133. if (typeof attrs.id === 'number') node.id = attrs.id;
  4134. if (attrs.name !== '') node.attrName = attrs.name;
  4135. if (attrs.type !== '') node.attrType = attrs.type;
  4136. this.pushStack(node);
  4137. },
  4138. parseNodeAttr: function parseNodeAttr(attrs) {
  4139. var id = attrs[0];
  4140. if (attrs[0] !== '') {
  4141. id = parseInt(attrs[0]);
  4142. if (isNaN(id)) {
  4143. id = attrs[0];
  4144. }
  4145. }
  4146. var name = '',
  4147. type = '';
  4148. if (attrs.length > 1) {
  4149. name = attrs[1].replace(/^(\w+)::/, '');
  4150. type = attrs[2];
  4151. }
  4152. return { id: id, name: name, type: type };
  4153. },
  4154. parseNodeProperty: function parseNodeProperty(line, property, contentLine) {
  4155. var propName = property[1].replace(/^"/, '').replace(/"$/, '').trim();
  4156. var propValue = property[2].replace(/^"/, '').replace(/"$/, '').trim();
  4157. // for special case: base64 image data follows "Content: ," line
  4158. // Content: ,
  4159. // "/9j/4RDaRXhpZgAATU0A..."
  4160. if (propName === 'Content' && propValue === ',') {
  4161. propValue = contentLine.replace(/"/g, '').replace(/,$/, '').trim();
  4162. }
  4163. var currentNode = this.getCurrentNode();
  4164. var parentName = currentNode.name;
  4165. if (parentName === 'Properties70') {
  4166. this.parseNodeSpecialProperty(line, propName, propValue);
  4167. return;
  4168. }
  4169. // Connections
  4170. if (propName === 'C') {
  4171. var connProps = propValue.split(',').slice(1);
  4172. var from = parseInt(connProps[0]);
  4173. var to = parseInt(connProps[1]);
  4174. var rest = propValue.split(',').slice(3);
  4175. rest = rest.map(function (elem) {
  4176. return elem.trim().replace(/^"/, '');
  4177. });
  4178. propName = 'connections';
  4179. propValue = [from, to];
  4180. append(propValue, rest);
  4181. if (currentNode[propName] === undefined) {
  4182. currentNode[propName] = [];
  4183. }
  4184. }
  4185. // Node
  4186. if (propName === 'Node') currentNode.id = propValue;
  4187. // connections
  4188. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  4189. currentNode[propName].push(propValue);
  4190. } else {
  4191. if (propName !== 'a') currentNode[propName] = propValue;else currentNode.a = propValue;
  4192. }
  4193. this.setCurrentProp(currentNode, propName);
  4194. // convert string to array, unless it ends in ',' in which case more will be added to it
  4195. if (propName === 'a' && propValue.slice(-1) !== ',') {
  4196. currentNode.a = parseNumberArray(propValue);
  4197. }
  4198. },
  4199. parseNodePropertyContinued: function parseNodePropertyContinued(line) {
  4200. var currentNode = this.getCurrentNode();
  4201. currentNode.a += line;
  4202. // if the line doesn't end in ',' we have reached the end of the property value
  4203. // so convert the string to an array
  4204. if (line.slice(-1) !== ',') {
  4205. currentNode.a = parseNumberArray(currentNode.a);
  4206. }
  4207. },
  4208. // parse "Property70"
  4209. parseNodeSpecialProperty: function parseNodeSpecialProperty(line, propName, propValue) {
  4210. // split this
  4211. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  4212. // into array like below
  4213. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  4214. var props = propValue.split('",').map(function (prop) {
  4215. return prop.trim().replace(/^\"/, '').replace(/\s/, '_');
  4216. });
  4217. var innerPropName = props[0];
  4218. var innerPropType1 = props[1];
  4219. var innerPropType2 = props[2];
  4220. var innerPropFlag = props[3];
  4221. var innerPropValue = props[4];
  4222. // cast values where needed, otherwise leave as strings
  4223. switch (innerPropType1) {
  4224. case 'int':
  4225. case 'enum':
  4226. case 'bool':
  4227. case 'ULongLong':
  4228. case 'double':
  4229. case 'Number':
  4230. case 'FieldOfView':
  4231. innerPropValue = parseFloat(innerPropValue);
  4232. break;
  4233. case 'Color':
  4234. case 'ColorRGB':
  4235. case 'Vector3D':
  4236. case 'Lcl_Translation':
  4237. case 'Lcl_Rotation':
  4238. case 'Lcl_Scaling':
  4239. innerPropValue = parseNumberArray(innerPropValue);
  4240. break;
  4241. }
  4242. // CAUTION: these props must append to parent's parent
  4243. this.getPrevNode()[innerPropName] = {
  4244. 'type': innerPropType1,
  4245. 'type2': innerPropType2,
  4246. 'flag': innerPropFlag,
  4247. 'value': innerPropValue
  4248. };
  4249. this.setCurrentProp(this.getPrevNode(), innerPropName);
  4250. }
  4251. };
  4252. // Parse an FBX file in Binary format
  4253. function BinaryParser() {}
  4254. BinaryParser.prototype = {
  4255. constructor: BinaryParser,
  4256. parse: function parse(buffer) {
  4257. var reader = new BinaryReader(buffer);
  4258. reader.skip(23); // skip magic 23 bytes
  4259. var version = reader.getUint32();
  4260. console.log('THREE.FBXLoader: FBX binary version: ' + version);
  4261. var allNodes = new FBXTree();
  4262. while (!this.endOfContent(reader)) {
  4263. var node = this.parseNode(reader, version);
  4264. if (node !== null) allNodes.add(node.name, node);
  4265. }
  4266. return allNodes;
  4267. },
  4268. // Check if reader has reached the end of content.
  4269. endOfContent: function endOfContent(reader) {
  4270. // footer size: 160bytes + 16-byte alignment padding
  4271. // - 16bytes: magic
  4272. // - padding til 16-byte alignment (at least 1byte?)
  4273. // (seems like some exporters embed fixed 15 or 16bytes?)
  4274. // - 4bytes: magic
  4275. // - 4bytes: version
  4276. // - 120bytes: zero
  4277. // - 16bytes: magic
  4278. if (reader.size() % 16 === 0) {
  4279. return (reader.getOffset() + 160 + 16 & ~0xf) >= reader.size();
  4280. } else {
  4281. return reader.getOffset() + 160 + 16 >= reader.size();
  4282. }
  4283. },
  4284. // recursively parse nodes until the end of the file is reached
  4285. parseNode: function parseNode(reader, version) {
  4286. var node = {};
  4287. // The first three data sizes depends on version.
  4288. var endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4289. var numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4290. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  4291. var propertyListLen = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4292. var nameLen = reader.getUint8();
  4293. var name = reader.getString(nameLen);
  4294. // Regards this node as NULL-record if endOffset is zero
  4295. if (endOffset === 0) return null;
  4296. var propertyList = [];
  4297. for (var i = 0; i < numProperties; i++) {
  4298. propertyList.push(this.parseProperty(reader));
  4299. }
  4300. // Regards the first three elements in propertyList as id, attrName, and attrType
  4301. var id = propertyList.length > 0 ? propertyList[0] : '';
  4302. var attrName = propertyList.length > 1 ? propertyList[1] : '';
  4303. var attrType = propertyList.length > 2 ? propertyList[2] : '';
  4304. // check if this node represents just a single property
  4305. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  4306. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  4307. while (endOffset > reader.getOffset()) {
  4308. var subNode = this.parseNode(reader, version);
  4309. if (subNode !== null) this.parseSubNode(name, node, subNode);
  4310. }
  4311. node.propertyList = propertyList; // raw property list used by parent
  4312. if (typeof id === 'number') node.id = id;
  4313. if (attrName !== '') node.attrName = attrName;
  4314. if (attrType !== '') node.attrType = attrType;
  4315. if (name !== '') node.name = name;
  4316. return node;
  4317. },
  4318. parseSubNode: function parseSubNode(name, node, subNode) {
  4319. // special case: child node is single property
  4320. if (subNode.singleProperty === true) {
  4321. var value = subNode.propertyList[0];
  4322. if (Array.isArray(value)) {
  4323. node[subNode.name] = subNode;
  4324. subNode.a = value;
  4325. } else {
  4326. node[subNode.name] = value;
  4327. }
  4328. } else if (name === 'Connections' && subNode.name === 'C') {
  4329. var array = [];
  4330. subNode.propertyList.forEach(function (property, i) {
  4331. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  4332. if (i !== 0) array.push(property);
  4333. });
  4334. if (node.connections === undefined) {
  4335. node.connections = [];
  4336. }
  4337. node.connections.push(array);
  4338. } else if (subNode.name === 'Properties70') {
  4339. var keys = Object.keys(subNode);
  4340. keys.forEach(function (key) {
  4341. node[key] = subNode[key];
  4342. });
  4343. } else if (name === 'Properties70' && subNode.name === 'P') {
  4344. var innerPropName = subNode.propertyList[0];
  4345. var innerPropType1 = subNode.propertyList[1];
  4346. var innerPropType2 = subNode.propertyList[2];
  4347. var innerPropFlag = subNode.propertyList[3];
  4348. var innerPropValue;
  4349. if (innerPropName.indexOf('Lcl ') === 0) innerPropName = innerPropName.replace('Lcl ', 'Lcl_');
  4350. if (innerPropType1.indexOf('Lcl ') === 0) innerPropType1 = innerPropType1.replace('Lcl ', 'Lcl_');
  4351. if (innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf('Lcl_') === 0) {
  4352. innerPropValue = [subNode.propertyList[4], subNode.propertyList[5], subNode.propertyList[6]];
  4353. } else {
  4354. innerPropValue = subNode.propertyList[4];
  4355. }
  4356. // this will be copied to parent, see above
  4357. node[innerPropName] = {
  4358. 'type': innerPropType1,
  4359. 'type2': innerPropType2,
  4360. 'flag': innerPropFlag,
  4361. 'value': innerPropValue
  4362. };
  4363. } else if (node[subNode.name] === undefined) {
  4364. if (typeof subNode.id === 'number') {
  4365. node[subNode.name] = {};
  4366. node[subNode.name][subNode.id] = subNode;
  4367. } else {
  4368. node[subNode.name] = subNode;
  4369. }
  4370. } else {
  4371. if (subNode.name === 'PoseNode') {
  4372. if (!Array.isArray(node[subNode.name])) {
  4373. node[subNode.name] = [node[subNode.name]];
  4374. }
  4375. node[subNode.name].push(subNode);
  4376. } else if (node[subNode.name][subNode.id] === undefined) {
  4377. node[subNode.name][subNode.id] = subNode;
  4378. }
  4379. }
  4380. },
  4381. parseProperty: function parseProperty(reader) {
  4382. var type = reader.getString(1);
  4383. switch (type) {
  4384. case 'C':
  4385. return reader.getBoolean();
  4386. case 'D':
  4387. return reader.getFloat64();
  4388. case 'F':
  4389. return reader.getFloat32();
  4390. case 'I':
  4391. return reader.getInt32();
  4392. case 'L':
  4393. return reader.getInt64();
  4394. case 'R':
  4395. var length = reader.getUint32();
  4396. return reader.getArrayBuffer(length);
  4397. case 'S':
  4398. var length = reader.getUint32();
  4399. return reader.getString(length);
  4400. case 'Y':
  4401. return reader.getInt16();
  4402. case 'b':
  4403. case 'c':
  4404. case 'd':
  4405. case 'f':
  4406. case 'i':
  4407. case 'l':
  4408. var arrayLength = reader.getUint32();
  4409. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  4410. var compressedLength = reader.getUint32();
  4411. if (encoding === 0) {
  4412. switch (type) {
  4413. case 'b':
  4414. case 'c':
  4415. return reader.getBooleanArray(arrayLength);
  4416. case 'd':
  4417. return reader.getFloat64Array(arrayLength);
  4418. case 'f':
  4419. return reader.getFloat32Array(arrayLength);
  4420. case 'i':
  4421. return reader.getInt32Array(arrayLength);
  4422. case 'l':
  4423. return reader.getInt64Array(arrayLength);
  4424. }
  4425. }
  4426. if (typeof Zlib === 'undefined') {
  4427. console.error('THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js');
  4428. }
  4429. var inflate = new Zlib.Inflate(new Uint8Array(reader.getArrayBuffer(compressedLength))); // eslint-disable-line no-undef
  4430. var reader2 = new BinaryReader(inflate.decompress().buffer);
  4431. switch (type) {
  4432. case 'b':
  4433. case 'c':
  4434. return reader2.getBooleanArray(arrayLength);
  4435. case 'd':
  4436. return reader2.getFloat64Array(arrayLength);
  4437. case 'f':
  4438. return reader2.getFloat32Array(arrayLength);
  4439. case 'i':
  4440. return reader2.getInt32Array(arrayLength);
  4441. case 'l':
  4442. return reader2.getInt64Array(arrayLength);
  4443. }
  4444. default:
  4445. throw new Error('THREE.FBXLoader: Unknown property type ' + type);
  4446. }
  4447. }
  4448. };
  4449. function BinaryReader(buffer, littleEndian) {
  4450. this.dv = new DataView(buffer);
  4451. this.offset = 0;
  4452. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  4453. }
  4454. BinaryReader.prototype = {
  4455. constructor: BinaryReader,
  4456. getOffset: function getOffset() {
  4457. return this.offset;
  4458. },
  4459. size: function size() {
  4460. return this.dv.buffer.byteLength;
  4461. },
  4462. skip: function skip(length) {
  4463. this.offset += length;
  4464. },
  4465. // seems like true/false representation depends on exporter.
  4466. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  4467. // then sees LSB.
  4468. getBoolean: function getBoolean() {
  4469. return (this.getUint8() & 1) === 1;
  4470. },
  4471. getBooleanArray: function getBooleanArray(size) {
  4472. var a = [];
  4473. for (var i = 0; i < size; i++) {
  4474. a.push(this.getBoolean());
  4475. }
  4476. return a;
  4477. },
  4478. getUint8: function getUint8() {
  4479. var value = this.dv.getUint8(this.offset);
  4480. this.offset += 1;
  4481. return value;
  4482. },
  4483. getInt16: function getInt16() {
  4484. var value = this.dv.getInt16(this.offset, this.littleEndian);
  4485. this.offset += 2;
  4486. return value;
  4487. },
  4488. getInt32: function getInt32() {
  4489. var value = this.dv.getInt32(this.offset, this.littleEndian);
  4490. this.offset += 4;
  4491. return value;
  4492. },
  4493. getInt32Array: function getInt32Array(size) {
  4494. var a = [];
  4495. for (var i = 0; i < size; i++) {
  4496. a.push(this.getInt32());
  4497. }
  4498. return a;
  4499. },
  4500. getUint32: function getUint32() {
  4501. var value = this.dv.getUint32(this.offset, this.littleEndian);
  4502. this.offset += 4;
  4503. return value;
  4504. },
  4505. // JavaScript doesn't support 64-bit integer so calculate this here
  4506. // 1 << 32 will return 1 so using multiply operation instead here.
  4507. // There's a possibility that this method returns wrong value if the value
  4508. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  4509. // TODO: safely handle 64-bit integer
  4510. getInt64: function getInt64() {
  4511. var low, high;
  4512. if (this.littleEndian) {
  4513. low = this.getUint32();
  4514. high = this.getUint32();
  4515. } else {
  4516. high = this.getUint32();
  4517. low = this.getUint32();
  4518. }
  4519. // calculate negative value
  4520. if (high & 0x80000000) {
  4521. high = ~high & 0xFFFFFFFF;
  4522. low = ~low & 0xFFFFFFFF;
  4523. if (low === 0xFFFFFFFF) high = high + 1 & 0xFFFFFFFF;
  4524. low = low + 1 & 0xFFFFFFFF;
  4525. return -(high * 0x100000000 + low);
  4526. }
  4527. return high * 0x100000000 + low;
  4528. },
  4529. getInt64Array: function getInt64Array(size) {
  4530. var a = [];
  4531. for (var i = 0; i < size; i++) {
  4532. a.push(this.getInt64());
  4533. }
  4534. return a;
  4535. },
  4536. // Note: see getInt64() comment
  4537. getUint64: function getUint64() {
  4538. var low, high;
  4539. if (this.littleEndian) {
  4540. low = this.getUint32();
  4541. high = this.getUint32();
  4542. } else {
  4543. high = this.getUint32();
  4544. low = this.getUint32();
  4545. }
  4546. return high * 0x100000000 + low;
  4547. },
  4548. getFloat32: function getFloat32() {
  4549. var value = this.dv.getFloat32(this.offset, this.littleEndian);
  4550. this.offset += 4;
  4551. return value;
  4552. },
  4553. getFloat32Array: function getFloat32Array(size) {
  4554. var a = [];
  4555. for (var i = 0; i < size; i++) {
  4556. a.push(this.getFloat32());
  4557. }
  4558. return a;
  4559. },
  4560. getFloat64: function getFloat64() {
  4561. var value = this.dv.getFloat64(this.offset, this.littleEndian);
  4562. this.offset += 8;
  4563. return value;
  4564. },
  4565. getFloat64Array: function getFloat64Array(size) {
  4566. var a = [];
  4567. for (var i = 0; i < size; i++) {
  4568. a.push(this.getFloat64());
  4569. }
  4570. return a;
  4571. },
  4572. getArrayBuffer: function getArrayBuffer(size) {
  4573. var value = this.dv.buffer.slice(this.offset, this.offset + size);
  4574. this.offset += size;
  4575. return value;
  4576. },
  4577. getString: function getString(size) {
  4578. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  4579. var a = [];
  4580. for (var i = 0; i < size; i++) {
  4581. a[i] = this.getUint8();
  4582. }
  4583. var nullByte = a.indexOf(0);
  4584. if (nullByte >= 0) a = a.slice(0, nullByte);
  4585. return THREE.LoaderUtils.decodeText(new Uint8Array(a));
  4586. }
  4587. };
  4588. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  4589. // and BinaryParser( FBX Binary format)
  4590. function FBXTree() {}
  4591. FBXTree.prototype = {
  4592. constructor: FBXTree,
  4593. add: function add(key, val) {
  4594. this[key] = val;
  4595. }
  4596. };
  4597. // ************** UTILITY FUNCTIONS **************
  4598. function isFbxFormatBinary(buffer) {
  4599. var CORRECT = 'Kaydara FBX Binary \0';
  4600. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
  4601. }
  4602. function isFbxFormatASCII(text) {
  4603. var CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];
  4604. var cursor = 0;
  4605. function read(offset) {
  4606. var result = text[offset - 1];
  4607. text = text.slice(cursor + offset);
  4608. cursor++;
  4609. return result;
  4610. }
  4611. for (var i = 0; i < CORRECT.length; ++i) {
  4612. var num = read(1);
  4613. if (num === CORRECT[i]) {
  4614. return false;
  4615. }
  4616. }
  4617. return true;
  4618. }
  4619. function getFbxVersion(text) {
  4620. var versionRegExp = /FBXVersion: (\d+)/;
  4621. var match = text.match(versionRegExp);
  4622. if (match) {
  4623. var version = parseInt(match[1]);
  4624. return version;
  4625. }
  4626. throw new Error('THREE.FBXLoader: Cannot find the version number for the file given.');
  4627. }
  4628. // Converts FBX ticks into real time seconds.
  4629. function convertFBXTimeToSeconds(time) {
  4630. return time / 46186158000;
  4631. }
  4632. var dataArray = [];
  4633. // extracts the data from the correct position in the FBX array based on indexing type
  4634. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  4635. var index;
  4636. switch (infoObject.mappingType) {
  4637. case 'ByPolygonVertex':
  4638. index = polygonVertexIndex;
  4639. break;
  4640. case 'ByPolygon':
  4641. index = polygonIndex;
  4642. break;
  4643. case 'ByVertice':
  4644. index = vertexIndex;
  4645. break;
  4646. case 'AllSame':
  4647. index = infoObject.indices[0];
  4648. break;
  4649. default:
  4650. console.warn('THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType);
  4651. }
  4652. if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];
  4653. var from = index * infoObject.dataSize;
  4654. var to = from + infoObject.dataSize;
  4655. return slice(dataArray, infoObject.buffer, from, to);
  4656. }
  4657. var tempMat = new THREE.Matrix4();
  4658. var tempEuler = new THREE.Euler();
  4659. var tempVec = new THREE.Vector3();
  4660. var translation = new THREE.Vector3();
  4661. var rotation = new THREE.Matrix4();
  4662. // generate transformation from FBX transform data
  4663. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  4664. // transformData = {
  4665. // eulerOrder: int,
  4666. // translation: [],
  4667. // rotationOffset: [],
  4668. // preRotation
  4669. // rotation
  4670. // postRotation
  4671. // scale
  4672. // }
  4673. // all entries are optional
  4674. function generateTransform(transformData) {
  4675. var transform = new THREE.Matrix4();
  4676. translation.set(0, 0, 0);
  4677. rotation.identity();
  4678. var order = transformData.eulerOrder ? getEulerOrder(transformData.eulerOrder) : getEulerOrder(0);
  4679. if (transformData.translation) translation.fromArray(transformData.translation);
  4680. if (transformData.rotationOffset) translation.add(tempVec.fromArray(transformData.rotationOffset));
  4681. if (transformData.rotation) {
  4682. var array = transformData.rotation.map(THREE.Math.degToRad);
  4683. array.push(order);
  4684. rotation.makeRotationFromEuler(tempEuler.fromArray(array));
  4685. }
  4686. if (transformData.preRotation) {
  4687. var array = transformData.preRotation.map(THREE.Math.degToRad);
  4688. array.push(order);
  4689. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4690. rotation.premultiply(tempMat);
  4691. }
  4692. if (transformData.postRotation) {
  4693. var array = transformData.postRotation.map(THREE.Math.degToRad);
  4694. array.push(order);
  4695. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4696. tempMat.getInverse(tempMat);
  4697. rotation.multiply(tempMat);
  4698. }
  4699. if (transformData.scale) transform.scale(tempVec.fromArray(transformData.scale));
  4700. transform.setPosition(translation);
  4701. transform.multiply(rotation);
  4702. return transform;
  4703. }
  4704. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  4705. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  4706. function getEulerOrder(order) {
  4707. var enums = ['ZYX', // -> XYZ extrinsic
  4708. 'YZX', // -> XZY extrinsic
  4709. 'XZY', // -> YZX extrinsic
  4710. 'ZXY', // -> YXZ extrinsic
  4711. 'YXZ', // -> ZXY extrinsic
  4712. 'XYZ'];
  4713. if (order === 6) {
  4714. console.warn('THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.');
  4715. return enums[0];
  4716. }
  4717. return enums[order];
  4718. }
  4719. // Parses comma separated list of numbers and returns them an array.
  4720. // Used internally by the TextParser
  4721. function parseNumberArray(value) {
  4722. var array = value.split(',').map(function (val) {
  4723. return parseFloat(val);
  4724. });
  4725. return array;
  4726. }
  4727. function convertArrayBufferToString(buffer, from, to) {
  4728. if (from === undefined) from = 0;
  4729. if (to === undefined) to = buffer.byteLength;
  4730. return THREE.LoaderUtils.decodeText(new Uint8Array(buffer, from, to));
  4731. }
  4732. function append(a, b) {
  4733. for (var i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  4734. a[j] = b[i];
  4735. }
  4736. }
  4737. function slice(a, b, from, to) {
  4738. for (var i = from, j = 0; i < to; i++, j++) {
  4739. a[j] = b[i];
  4740. }
  4741. return a;
  4742. }
  4743. // inject array a2 into array a1 at index
  4744. function inject(a1, index, a2) {
  4745. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  4746. }
  4747. return FBXLoader;
  4748. }();
  4749. },{}],5:[function(require,module,exports){
  4750. "use strict";
  4751. module.exports = Object.assign(function GamepadButton() {}, {
  4752. FACE_1: 0,
  4753. FACE_2: 1,
  4754. FACE_3: 2,
  4755. FACE_4: 3,
  4756. L_SHOULDER_1: 4,
  4757. R_SHOULDER_1: 5,
  4758. L_SHOULDER_2: 6,
  4759. R_SHOULDER_2: 7,
  4760. SELECT: 8,
  4761. START: 9,
  4762. DPAD_UP: 12,
  4763. DPAD_DOWN: 13,
  4764. DPAD_LEFT: 14,
  4765. DPAD_RIGHT: 15,
  4766. VENDOR: 16
  4767. });
  4768. },{}],6:[function(require,module,exports){
  4769. "use strict";
  4770. function GamepadButtonEvent(type, index, details) {
  4771. this.type = type;
  4772. this.index = index;
  4773. this.pressed = details.pressed;
  4774. this.value = details.value;
  4775. }
  4776. module.exports = GamepadButtonEvent;
  4777. },{}],7:[function(require,module,exports){
  4778. "use strict";
  4779. module.exports = {
  4780. "size": 5,
  4781. "cellSize": 10,
  4782. "extrudeSettings": {
  4783. "amount": 1,
  4784. "bevelEnabled": true,
  4785. "bevelSegments": 1,
  4786. "steps": 1,
  4787. "bevelSize": 0.5,
  4788. "bevelThickness": 0.5
  4789. },
  4790. "autogenerated": true,
  4791. "cells": [{
  4792. "q": -1,
  4793. "r": 0,
  4794. "s": 1,
  4795. "h": 1,
  4796. "walkable": true,
  4797. "userData": {}
  4798. }, {
  4799. "q": 0,
  4800. "r": -1,
  4801. "s": 1,
  4802. "h": 1,
  4803. "walkable": true,
  4804. "userData": {}
  4805. }, {
  4806. "q": 0,
  4807. "r": 0,
  4808. "s": 0,
  4809. "h": 1,
  4810. "walkable": true,
  4811. "userData": {}
  4812. }, {
  4813. "q": 1,
  4814. "r": -1,
  4815. "s": 0,
  4816. "h": 1,
  4817. "walkable": true,
  4818. "userData": {}
  4819. }, {
  4820. "q": -1,
  4821. "r": 1,
  4822. "s": 0,
  4823. "h": 0,
  4824. "walkable": true,
  4825. "userData": {}
  4826. }, {
  4827. "q": 0,
  4828. "r": 1,
  4829. "s": -1,
  4830. "h": 0,
  4831. "walkable": true,
  4832. "userData": {}
  4833. }, {
  4834. "q": 1,
  4835. "r": 0,
  4836. "s": -1,
  4837. "h": 0,
  4838. "walkable": true,
  4839. "userData": {}
  4840. }]
  4841. };
  4842. },{}],8:[function(require,module,exports){
  4843. 'use strict';
  4844. /**
  4845. * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
  4846. */
  4847. function getScriptId() {
  4848. return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
  4849. }
  4850. function createScript(url, id) {
  4851. var script = document.createElement('script');
  4852. script.type = 'text/javascript';
  4853. script.async = true;
  4854. script.id = id;
  4855. script.src = url;
  4856. return script;
  4857. }
  4858. function removeScript(id) {
  4859. var script = document.getElementById(id);
  4860. var parent = script.parentNode;
  4861. try {
  4862. parent && parent.removeChild(script);
  4863. } catch (e) {
  4864. // ignore
  4865. }
  4866. }
  4867. function appendScript(script) {
  4868. var firstScript = document.getElementsByTagName('script')[0];
  4869. firstScript.parentNode.insertBefore(script, firstScript);
  4870. }
  4871. function fetchScriptInternal(url, options, Promise) {
  4872. return new Promise(function (resolve, reject) {
  4873. var timeout = options.timeout || 5000;
  4874. var scriptId = getScriptId();
  4875. var script = createScript(url, scriptId);
  4876. var timeoutId = setTimeout(function () {
  4877. reject(new Error('Script request to ' + url + ' timed out'));
  4878. removeScript(scriptId);
  4879. }, timeout);
  4880. var disableTimeout = function disableTimeout(timeoutId) {
  4881. clearTimeout(timeoutId);
  4882. };
  4883. script.addEventListener('load', function (e) {
  4884. resolve({ ok: true });
  4885. disableTimeout(timeoutId);
  4886. removeScript(scriptId);
  4887. });
  4888. script.addEventListener('error', function (e) {
  4889. reject(new Error('Script request to ' + url + ' failed ' + e));
  4890. disableTimeout(timeoutId);
  4891. removeScript(scriptId);
  4892. });
  4893. appendScript(script);
  4894. });
  4895. }
  4896. function fetchScript(settings) {
  4897. settings = settings || {};
  4898. return function (url, options) {
  4899. options = options || {};
  4900. return fetchScriptInternal(url, options, settings.Promise || Promise);
  4901. };
  4902. }
  4903. module.exports = fetchScript;
  4904. },{}],9:[function(require,module,exports){
  4905. "use strict";
  4906. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  4907. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  4908. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  4909. } : function (obj) {
  4910. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  4911. };
  4912. var vg = module.exports = { VERSION: "0.1.1", PI: Math.PI, TAU: 2 * Math.PI, DEG_TO_RAD: .0174532925, RAD_TO_DEG: 57.2957795, SQRT3: Math.sqrt(3), TILE: "tile", ENT: "entity", STR: "structure", HEX: "hex", SQR: "square", ABS: "abstract" };vg.Board = function (e, t) {
  4913. if (!e) throw new Error("You must pass in a grid system for the board to use.");this.tiles = [], this.tileGroup = null, this.group = new THREE.Object3D(), this.grid = null, this.overlay = null, this.finder = new vg.AStarFinder(t), vg.Loader.init(), this.setGrid(e);
  4914. }, vg.Board.prototype = { setEntityOnTile: function setEntityOnTile(e, t) {
  4915. var i = this.grid.cellToPixel(t.cell);e.position.copy(i), e.position.y += e.heightOffset || 0, e.tile && (e.tile.entity = null), e.tile = t, t.entity = e;
  4916. }, addTile: function addTile(e) {
  4917. var t = this.tiles.indexOf(e);-1 === t && (this.tiles.push(e), this.snapTileToGrid(e), e.position.y = 0, this.tileGroup.add(e.mesh), this.grid.add(e.cell), e.cell.tile = e);
  4918. }, removeTile: function removeTile(e) {
  4919. if (e) {
  4920. var t = this.tiles.indexOf(e);this.grid.remove(e.cell), -1 !== t && this.tiles.splice(t, 1), e.dispose();
  4921. }
  4922. }, removeAllTiles: function removeAllTiles() {
  4923. if (this.tileGroup) for (var e = this.tileGroup.children, t = 0; t < e.length; t++) {
  4924. this.tileGroup.remove(e[t]);
  4925. }
  4926. }, getTileAtCell: function getTileAtCell(e) {
  4927. var t = this.grid.cellToHash(e);return e.tile || ("undefined" != typeof this.grid.cells[t] ? this.grid.cells[t].tile : null);
  4928. }, snapToGrid: function snapToGrid(e) {
  4929. var t = this.grid.pixelToCell(e);e.copy(this.grid.cellToPixel(t));
  4930. }, snapTileToGrid: function snapTileToGrid(e) {
  4931. if (e.cell) e.position.copy(this.grid.cellToPixel(e.cell));else {
  4932. var t = this.grid.pixelToCell(e.position);e.position.copy(this.grid.cellToPixel(t));
  4933. }return e;
  4934. }, getRandomTile: function getRandomTile() {
  4935. var e = vg.Tools.randomInt(0, this.tiles.length - 1);return this.tiles[e];
  4936. }, findPath: function findPath(e, t, i) {
  4937. return this.finder.findPath(e.cell, t.cell, i, this.grid);
  4938. }, setGrid: function setGrid(e) {
  4939. this.group.remove(this.tileGroup), this.grid && e !== this.grid && (this.removeAllTiles(), this.tiles.forEach(function (e) {
  4940. this.grid.remove(e.cell), e.dispose();
  4941. }), this.grid.dispose()), this.grid = e, this.tiles = [], this.tileGroup = new THREE.Object3D(), this.group.add(this.tileGroup);
  4942. }, generateOverlay: function generateOverlay(e) {
  4943. var t = new THREE.LineBasicMaterial({ color: 0, opacity: .3 });this.overlay && this.group.remove(this.overlay), this.overlay = new THREE.Object3D(), this.grid.generateOverlay(e, this.overlay, t), this.group.add(this.overlay);
  4944. }, generateTilemap: function generateTilemap(e) {
  4945. this.reset();var t = this.grid.generateTiles(e);this.tiles = t, this.tileGroup = new THREE.Object3D();for (var i = 0; i < t.length; i++) {
  4946. this.tileGroup.add(t[i].mesh);
  4947. }this.group.add(this.tileGroup);
  4948. }, reset: function reset() {
  4949. this.removeAllTiles(), this.tileGroup && this.group.remove(this.tileGroup);
  4950. } }, vg.Board.prototype.constructor = vg.Board, vg.Cell = function (e, t, i, s) {
  4951. this.q = e || 0, this.r = t || 0, this.s = i || 0, this.h = s || 1, this.tile = null, this.userData = {}, this.walkable = !0, this._calcCost = 0, this._priority = 0, this._visited = !1, this._parent = null, this.uniqueID = vg.LinkedList.generateID();
  4952. }, vg.Cell.prototype = { set: function set(e, t, i) {
  4953. return this.q = e, this.r = t, this.s = i, this;
  4954. }, copy: function copy(e) {
  4955. return this.q = e.q, this.r = e.r, this.s = e.s, this.h = e.h, this.tile = e.tile || null, this.userData = e.userData || {}, this.walkable = e.walkable, this;
  4956. }, add: function add(e) {
  4957. return this.q += e.q, this.r += e.r, this.s += e.s, this;
  4958. }, equals: function equals(e) {
  4959. return this.q === e.q && this.r === e.r && this.s === e.s;
  4960. } }, vg.Cell.prototype.constructor = vg.Cell, vg.HexGrid = function (e) {
  4961. e = e || {}, this.type = vg.HEX, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t,
  4962. i = [];for (t = 0; 6 > t; t++) {
  4963. i.push(this._createVertex(t));
  4964. }for (this.cellShape = new THREE.Shape(), this.cellShape.moveTo(i[0].x, i[0].y), t = 1; 6 > t; t++) {
  4965. this.cellShape.lineTo(i[t].x, i[t].y);
  4966. }this.cellShape.lineTo(i[0].x, i[0].y), this.cellShape.autoClose = !0, this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = i, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, -1, 0), new vg.Cell(1, 0, -1), new vg.Cell(0, 1, -1), new vg.Cell(-1, 1, 0), new vg.Cell(-1, 0, 1), new vg.Cell(0, -1, 1)], this._diagonals = [new vg.Cell(2, -1, -1), new vg.Cell(1, 1, -2), new vg.Cell(-1, 2, -1), new vg.Cell(-2, 1, 1), new vg.Cell(-1, -1, 2), new vg.Cell(1, -2, 1)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  4967. }, vg.HexGrid.TWO_THIRDS = 2 / 3, vg.HexGrid.prototype = { cellToPixel: function cellToPixel(e) {
  4968. return this._vec3.x = e.q * this._cellWidth * .75, this._vec3.y = e.h, this._vec3.z = -((e.s - e.r) * this._cellLength * .5), this._vec3;
  4969. }, pixelToCell: function pixelToCell(e) {
  4970. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  4971. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel);
  4972. }, getCellAt: function getCellAt(e) {
  4973. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  4974. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel), this.cells[this.cellToHash(this._cel)];
  4975. }, getNeighbors: function getNeighbors(e, t, i) {
  4976. var s,
  4977. n,
  4978. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  4979. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  4980. }if (t) for (s = 0; l > s; s++) {
  4981. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  4982. }return this._list;
  4983. }, getRandomCell: function getRandomCell() {
  4984. var e,
  4985. t = 0,
  4986. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  4987. if (t === i) return this.cells[e];t++;
  4988. }return this.cells[e];
  4989. }, cellToHash: function cellToHash(e) {
  4990. return e.q + this._hashDelimeter + e.r + this._hashDelimeter + e.s;
  4991. }, distance: function distance(e, t) {
  4992. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r), Math.abs(e.s - t.s));return i += t.h - e.h;
  4993. }, clearPath: function clearPath() {
  4994. var e, t;for (e in this.cells) {
  4995. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  4996. }
  4997. }, traverse: function traverse(e) {
  4998. var t;for (t in this.cells) {
  4999. e(this.cells[t]);
  5000. }
  5001. }, generateTile: function generateTile(e, t, i) {
  5002. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  5003. }, generateTiles: function generateTiles(e) {
  5004. e = e || {};var t = [],
  5005. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  5006. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  5007. }return t;
  5008. }, generateTilePoly: function generateTilePoly(e) {
  5009. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  5010. }, generate: function generate(e) {
  5011. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t, i, s, n;for (t = -this.size; t < this.size + 1; t++) {
  5012. for (i = -this.size; i < this.size + 1; i++) {
  5013. s = -t - i, Math.abs(t) <= this.size && Math.abs(i) <= this.size && Math.abs(s) <= this.size && (n = new vg.Cell(t, i, s), this.add(n));
  5014. }
  5015. }
  5016. }, generateOverlay: function generateOverlay(e, t, i) {
  5017. var s,
  5018. n,
  5019. l,
  5020. r = this.cellShape.createPointsGeometry();for (s = -e; e + 1 > s; s++) {
  5021. for (n = -e; e + 1 > n; n++) {
  5022. if (l = -s - n, Math.abs(s) <= e && Math.abs(n) <= e && Math.abs(l) <= e) {
  5023. this._cel.set(s, n, l);var h = new THREE.Line(r, i);h.position.copy(this.cellToPixel(this._cel)), h.rotation.x = 90 * vg.DEG_TO_RAD, t.add(h);
  5024. }
  5025. }
  5026. }
  5027. }, add: function add(e) {
  5028. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  5029. }, remove: function remove(e) {
  5030. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  5031. }, dispose: function dispose() {
  5032. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  5033. }, load: function load(e, t, i) {
  5034. var s = this;vg.Tools.getJSON({ url: e, callback: function callback(e) {
  5035. s.fromJSON(e), t.call(i || null, e);
  5036. }, cache: !1, scope: s });
  5037. }, fromJSON: function fromJSON(e) {
  5038. var t,
  5039. i,
  5040. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  5041. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  5042. }
  5043. }, toJSON: function toJSON() {
  5044. var e,
  5045. t,
  5046. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  5047. s = [];for (t in this.cells) {
  5048. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  5049. }return i.cells = s, i;
  5050. }, _createVertex: function _createVertex(e) {
  5051. var t = vg.TAU / 6 * e;return new THREE.Vector3(this.cellSize * Math.cos(t), this.cellSize * Math.sin(t), 0);
  5052. }, _cubeRound: function _cubeRound(e) {
  5053. var t = Math.round(e.q),
  5054. i = Math.round(e.r),
  5055. s = Math.round(e.s),
  5056. n = Math.abs(t - e.q),
  5057. l = Math.abs(i - e.r),
  5058. r = Math.abs(s - e.s);return n > l && n > r ? t = -i - s : l > r ? i = -t - s : s = -t - i, this._cel.set(t, i, s);
  5059. } }, vg.HexGrid.prototype.constructor = vg.HexGrid, vg.SqrGrid = function (e) {
  5060. e = e || {}, this.type = vg.SQR, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t = [];t.push(new THREE.Vector3()), t.push(new THREE.Vector3(-this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, -this.cellSize)), this.cellShape = new THREE.Shape(), this.cellShape.moveTo(-this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, -this.cellSize), this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = t, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._fullCellSize = 2 * this.cellSize, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, 0, 0), new vg.Cell(0, -1, 0), new vg.Cell(-1, 0, 0), new vg.Cell(0, 1, 0)], this._diagonals = [new vg.Cell(-1, -1, 0), new vg.Cell(-1, 1, 0), new vg.Cell(1, 1, 0), new vg.Cell(1, -1, 0)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  5061. }, vg.SqrGrid.prototype = { cellToPixel: function cellToPixel(e) {
  5062. return this._vec3.x = e.q * this._fullCellSize, this._vec3.y = e.h, this._vec3.z = e.r * this._fullCellSize, this._vec3;
  5063. }, pixelToCell: function pixelToCell(e) {
  5064. var t = Math.round(e.x / this._fullCellSize),
  5065. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i, 0);
  5066. }, getCellAt: function getCellAt(e) {
  5067. var t = Math.round(e.x / this._fullCellSize),
  5068. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i), this.cells[this.cellToHash(this._cel)];
  5069. }, getNeighbors: function getNeighbors(e, t, i) {
  5070. var s,
  5071. n,
  5072. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  5073. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  5074. }if (t) for (s = 0; l > s; s++) {
  5075. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  5076. }return this._list;
  5077. }, getRandomCell: function getRandomCell() {
  5078. var e,
  5079. t = 0,
  5080. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  5081. if (t === i) return this.cells[e];t++;
  5082. }return this.cells[e];
  5083. }, cellToHash: function cellToHash(e) {
  5084. return e.q + this._hashDelimeter + e.r;
  5085. }, distance: function distance(e, t) {
  5086. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r));return i += t.h - e.h;
  5087. }, clearPath: function clearPath() {
  5088. var e, t;for (e in this.cells) {
  5089. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  5090. }
  5091. }, traverse: function traverse(e) {
  5092. var t;for (t in this.cells) {
  5093. e(this.cells[t]);
  5094. }
  5095. }, generateTile: function generateTile(e, t, i) {
  5096. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  5097. }, generateTiles: function generateTiles(e) {
  5098. e = e || {};var t = [],
  5099. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._fullCellSize = 2 * this.cellSize, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  5100. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  5101. }return t;
  5102. }, generateTilePoly: function generateTilePoly(e) {
  5103. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  5104. }, generate: function generate(e) {
  5105. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t,
  5106. i,
  5107. s,
  5108. n = Math.ceil(this.size / 2);for (t = -n; n > t; t++) {
  5109. for (i = -n; n > i; i++) {
  5110. s = new vg.Cell(t, i + 1), this.add(s);
  5111. }
  5112. }
  5113. }, generateOverlay: function generateOverlay(e, t, i) {
  5114. var s,
  5115. n,
  5116. l = Math.ceil(e / 2);for (s = -l; l > s; s++) {
  5117. for (n = -l; l > n; n++) {
  5118. this._cel.set(s, n);var r = new THREE.Line(this.cellGeo, i);r.position.copy(this.cellToPixel(this._cel)), r.rotation.x = 90 * vg.DEG_TO_RAD, t.add(r);
  5119. }
  5120. }
  5121. }, add: function add(e) {
  5122. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  5123. }, remove: function remove(e) {
  5124. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  5125. }, dispose: function dispose() {
  5126. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  5127. }, load: function load(e, t, i) {
  5128. vg.Tools.getJSON({ url: e, callback: function callback(e) {
  5129. this.fromJSON(e), t.call(i || null, e);
  5130. }, cache: !1, scope: this });
  5131. }, fromJSON: function fromJSON(e) {
  5132. var t,
  5133. i,
  5134. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._fullCellSize = 2 * this.cellSize, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  5135. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  5136. }
  5137. }, toJSON: function toJSON() {
  5138. var e,
  5139. t,
  5140. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  5141. s = [];for (t in this.cells) {
  5142. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  5143. }return i.cells = s, i;
  5144. } }, vg.SqrGrid.prototype.constructor = vg.SqrGrid, vg.Tile = function (e) {
  5145. e = e || {};var t = { cell: null, geometry: null, material: null };if (t = vg.Tools.merge(t, e), !t.cell || !t.geometry) throw new Error("Missing vg.Tile configuration");this.cell = t.cell, this.cell.tile && this.cell.tile !== this && this.cell.tile.dispose(), this.cell.tile = this, this.uniqueID = vg.Tools.generateID(), this.geometry = t.geometry, this.material = t.material, this.material || (this.material = new THREE.MeshPhongMaterial({ color: vg.Tools.randomizeRGB("30, 30, 30", 13) })), this.objectType = vg.TILE, this.entity = null, this.userData = {}, this.selected = !1, this.highlight = "0x0084cc", this.mesh = new THREE.Mesh(this.geometry, this.material), this.mesh.userData.structure = this, this.position = this.mesh.position, this.rotation = this.mesh.rotation, this.rotation.x = -90 * vg.DEG_TO_RAD, this.mesh.scale.set(t.scale, t.scale, 1), this.material.emissive ? this._emissive = this.material.emissive.getHex() : this._emissive = null;
  5146. }, vg.Tile.prototype = { select: function select() {
  5147. return this.material.emissive && this.material.emissive.setHex(this.highlight), this.selected = !0, this;
  5148. }, deselect: function deselect() {
  5149. return null !== this._emissive && this.material.emissive && this.material.emissive.setHex(this._emissive), this.selected = !1, this;
  5150. }, toggle: function toggle() {
  5151. return this.selected ? this.deselect() : this.select(), this;
  5152. }, dispose: function dispose() {
  5153. this.cell && this.cell.tile && (this.cell.tile = null), this.cell = null, this.position = null, this.rotation = null, this.mesh.parent && this.mesh.parent.remove(this.mesh), this.mesh.userData.structure = null, this.mesh = null, this.material = null, this.userData = null, this.entity = null, this.geometry = null, this._emissive = null;
  5154. } }, vg.Tile.prototype.constructor = vg.Tile, function () {
  5155. var e = function e() {
  5156. this.obj = null, this.next = null, this.prev = null, this.free = !0;
  5157. },
  5158. t = function t() {
  5159. this.first = null, this.last = null, this.length = 0, this.objToNodeMap = {}, this.uniqueID = Date.now() + "" + Math.floor(1e3 * Math.random()), this.sortArray = [];
  5160. };t.generateID = function () {
  5161. return Math.random().toString(36).slice(2) + Date.now();
  5162. }, t.prototype = { getNode: function getNode(e) {
  5163. return this.objToNodeMap[e.uniqueID];
  5164. }, addNode: function addNode(i) {
  5165. var s = new e();if (!i.uniqueID) try {
  5166. i.uniqueID = t.generateID();
  5167. } catch (n) {
  5168. return console.error("[LinkedList.addNode] obj passed is immutable: cannot attach necessary identifier"), null;
  5169. }return s.obj = i, s.free = !1, this.objToNodeMap[i.uniqueID] = s, s;
  5170. }, swapObjects: function swapObjects(e, t) {
  5171. this.objToNodeMap[e.obj.uniqueID] = null, this.objToNodeMap[t.uniqueID] = e, e.obj = t;
  5172. }, add: function add(e) {
  5173. var t = this.objToNodeMap[e.uniqueID];if (t) {
  5174. if (t.free === !1) return;t.obj = e, t.free = !1, t.next = null, t.prev = null;
  5175. } else t = this.addNode(e);if (this.first) {
  5176. if (!this.last) throw new Error("[LinkedList.add] No last in the list -- that shouldn't happen here");this.last.next = t, t.prev = this.last, this.last = t, t.next = null;
  5177. } else this.first = t, this.last = t, t.next = null, t.prev = null;this.length++, this.showDebug && this.dump("after add");
  5178. }, has: function has(e) {
  5179. return !!this.objToNodeMap[e.uniqueID];
  5180. }, moveUp: function moveUp(e) {
  5181. this.dump("before move up");var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.prev) {
  5182. var i = t.prev,
  5183. s = i.prev;t == this.last && (this.last = i);var n = t.next;s && (s.next = t), t.next = i, t.prev = i.prev, i.next = n, i.prev = t, this.first == i && (this.first = t);
  5184. }
  5185. }, moveDown: function moveDown(e) {
  5186. var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.next) {
  5187. var i = t.next;this.moveUp(i.obj), this.last == i && (this.last = t);
  5188. }
  5189. }, sort: function sort(e) {
  5190. var t,
  5191. i,
  5192. s = this.sortArray,
  5193. n = this.first;for (s.length = 0; n;) {
  5194. s.push(n.obj), n = n.next;
  5195. }for (this.clear(), s.sort(e), i = s.length, t = 0; i > t; t++) {
  5196. this.add(s[t]);
  5197. }
  5198. }, remove: function remove(e) {
  5199. var t = this.getNode(e);return !t || t.free ? !1 : (t.prev && (t.prev.next = t.next), t.next && (t.next.prev = t.prev), t.prev || (this.first = t.next), t.next || (this.last = t.prev), t.free = !0, t.prev = null, t.next = null, this.length--, !0);
  5200. }, shift: function shift() {
  5201. var e = this.first;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.first = e.next, e.next || (this.last = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  5202. }, pop: function pop() {
  5203. var e = this.last;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.last = e.prev, e.prev || (this.first = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  5204. }, concat: function concat(e) {
  5205. for (var t = e.first; t;) {
  5206. this.add(t.obj), t = t.next;
  5207. }
  5208. }, clear: function clear() {
  5209. for (var e = this.first; e;) {
  5210. e.free = !0, e = e.next;
  5211. }this.first = null, this.length = 0;
  5212. }, dispose: function dispose() {
  5213. for (var e = this.first; e;) {
  5214. e.obj = null, e = e.next;
  5215. }this.first = null, this.objToNodeMap = null;
  5216. }, dump: function dump(e) {
  5217. console.log("====================" + e + "=====================");for (var t = this.first; t;) {
  5218. console.log("{" + t.obj.toString() + "} previous=" + (t.prev ? t.prev.obj : "NULL")), t = t.next();
  5219. }console.log("==================================="), console.log("Last: {" + (this.last ? this.last.obj : "NULL") + "} First: {" + (this.first ? this.first.obj : "NULL") + "}");
  5220. } }, t.prototype.constructor = t, vg.LinkedList = t;
  5221. }(), function () {
  5222. var e = function e(_e, t, i, s, n) {
  5223. this._listener = t, this.isOnce = i, this.context = s, this.signal = _e, this._priority = n || 0;
  5224. };e.prototype = { active: !0, params: null, execute: function execute(e) {
  5225. var t, i;return this.active && this._listener && (i = this.params ? this.params.concat(e) : e, t = this._listener.apply(this.context, i), this.isOnce && this.detach()), t;
  5226. }, detach: function detach() {
  5227. return this.isBound() ? this.signal.remove(this._listener, this.context) : null;
  5228. }, isBound: function isBound() {
  5229. return !!this.signal && !!this._listener;
  5230. }, _destroy: function _destroy() {
  5231. delete this.signal, delete this._listener, delete this.context;
  5232. }, toString: function toString() {
  5233. return "[SignalBinding isOnce:" + this.isOnce + ", isBound:" + this.isBound() + ", active:" + this.active + "]";
  5234. } }, e.prototype.constructor = e;var t = function t() {
  5235. this._bindings = [], this._prevParams = null;var e = this;this.dispatch = function () {
  5236. t.prototype.dispatch.apply(e, arguments);
  5237. };
  5238. };t.prototype = { memorize: !1, _shouldPropagate: !0, active: !0, validateListener: function validateListener(e, t) {
  5239. if ("function" != typeof e) throw new Error("Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}", t));
  5240. }, _registerListener: function _registerListener(t, i, s, n) {
  5241. var l,
  5242. r = this._indexOfListener(t, s);if (-1 !== r) {
  5243. if (l = this._bindings[r], l.isOnce !== i) throw new Error("You cannot add" + (i ? "" : "Once") + "() then add" + (i ? "Once" : "") + "() the same listener without removing the relationship first.");
  5244. } else l = new e(this, t, i, s, n), this._addBinding(l);return this.memorize && this._prevParams && l.execute(this._prevParams), l;
  5245. }, _addBinding: function _addBinding(e) {
  5246. var t = this._bindings.length;do {
  5247. t--;
  5248. } while (this._bindings[t] && e._priority <= this._bindings[t]._priority);this._bindings.splice(t + 1, 0, e);
  5249. }, _indexOfListener: function _indexOfListener(e, t) {
  5250. for (var i, s = this._bindings.length; s--;) {
  5251. if (i = this._bindings[s], i._listener === e && i.context === t) return s;
  5252. }return -1;
  5253. }, has: function has(e, t) {
  5254. return -1 !== this._indexOfListener(e, t);
  5255. }, add: function add(e, t, i) {
  5256. return this.validateListener(e, "add"), this._registerListener(e, !1, t, i);
  5257. }, addOnce: function addOnce(e, t, i) {
  5258. return this.validateListener(e, "addOnce"), this._registerListener(e, !0, t, i);
  5259. }, remove: function remove(e, t) {
  5260. this.validateListener(e, "remove");var i = this._indexOfListener(e, t);return -1 !== i && (this._bindings[i]._destroy(), this._bindings.splice(i, 1)), e;
  5261. }, removeAll: function removeAll(e) {
  5262. "undefined" == typeof e && (e = null);for (var t = this._bindings.length; t--;) {
  5263. e ? this._bindings[t].context === e && (this._bindings[t]._destroy(), this._bindings.splice(t, 1)) : this._bindings[t]._destroy();
  5264. }e || (this._bindings.length = 0);
  5265. }, getNumListeners: function getNumListeners() {
  5266. return this._bindings.length;
  5267. }, halt: function halt() {
  5268. this._shouldPropagate = !1;
  5269. }, dispatch: function dispatch() {
  5270. if (this.active) {
  5271. var e,
  5272. t = Array.prototype.slice.call(arguments),
  5273. i = this._bindings.length;if (this.memorize && (this._prevParams = t), i) {
  5274. e = this._bindings.slice(), this._shouldPropagate = !0;do {
  5275. i--;
  5276. } while (e[i] && this._shouldPropagate && e[i].execute(t) !== !1);
  5277. }
  5278. }
  5279. }, forget: function forget() {
  5280. this._prevParams = null;
  5281. }, dispose: function dispose() {
  5282. this.removeAll(), delete this._bindings, delete this._prevParams;
  5283. }, toString: function toString() {
  5284. return "[Signal active:" + this.active + " numListeners:" + this.getNumListeners() + "]";
  5285. } }, t.prototype.constructor = t, vg.Signal = t;
  5286. }(), vg.AStarFinder = function (e) {
  5287. e = e || {};var t = { allowDiagonal: !1, heuristicFilter: null };t = vg.Tools.merge(t, e), this.allowDiagonal = t.allowDiagonal, this.heuristicFilter = t.heuristicFilter, this.list = new vg.LinkedList();
  5288. }, vg.AStarFinder.prototype = { findPath: function findPath(e, t, i, s) {
  5289. var n, l, r, h, o, a;for (i = i || this.heuristicFilter, s.clearPath(), this.list.clear(), this.list.add(e); this.list.length > 0;) {
  5290. if (this.list.sort(this.compare), n = this.list.shift(), n._visited = !0, n === t) return vg.PathUtil.backtrace(t);for (r = s.getNeighbors(n, this.allowDiagonal, i), o = 0, a = r.length; a > o; o++) {
  5291. if (h = r[o], h.walkable && (l = n._calcCost + s.distance(n, h), !h._visited || l < h._calcCost)) {
  5292. if (h._visited = !0, h._parent = n, h._calcCost = l, h._priority = l + s.distance(t, h), h === t) return vg.PathUtil.backtrace(t);this.list.add(h);
  5293. }
  5294. }
  5295. }return null;
  5296. }, compare: function compare(e, t) {
  5297. return e._priority - t._priority;
  5298. } }, vg.AStarFinder.prototype.constructor = vg.AStarFinder, vg.PathUtil = { backtrace: function backtrace(e) {
  5299. for (var t = [e]; e._parent;) {
  5300. e = e._parent, t.push(e);
  5301. }return t.reverse();
  5302. }, biBacktrace: function biBacktrace(e, t) {
  5303. var i = this.backtrace(e),
  5304. s = this.backtrace(t);return i.concat(s.reverse());
  5305. }, pathLength: function pathLength(e) {
  5306. var t,
  5307. i,
  5308. s,
  5309. n,
  5310. l,
  5311. r = 0;for (t = 1; t < e.length; ++t) {
  5312. i = e[t - 1], s = e[t], n = i[0] - s[0], l = i[1] - s[1], r += Math.sqrt(n * n + l * l);
  5313. }return r;
  5314. }, interpolate: function interpolate(e, t, i, s) {
  5315. var n,
  5316. l,
  5317. r,
  5318. h,
  5319. o,
  5320. a,
  5321. c = Math.abs,
  5322. u = [];for (r = c(i - e), h = c(s - t), n = i > e ? 1 : -1, l = s > t ? 1 : -1, o = r - h; e !== i || t !== s;) {
  5323. u.push([e, t]), a = 2 * o, a > -h && (o -= h, e += n), r > a && (o += r, t += l);
  5324. }return u;
  5325. }, expandPath: function expandPath(e) {
  5326. var t,
  5327. i,
  5328. s,
  5329. n,
  5330. l,
  5331. r,
  5332. h = [],
  5333. o = e.length;if (2 > o) return h;for (l = 0; o - 1 > l; ++l) {
  5334. for (t = e[l], i = e[l + 1], s = this.interpolate(t[0], t[1], i[0], i[1]), n = s.length, r = 0; n - 1 > r; ++r) {
  5335. h.push(s[r]);
  5336. }
  5337. }return h.push(e[o - 1]), h;
  5338. }, smoothenPath: function smoothenPath(e, t) {
  5339. var i,
  5340. s,
  5341. n,
  5342. l,
  5343. r,
  5344. h,
  5345. o,
  5346. a,
  5347. c,
  5348. u,
  5349. d,
  5350. g,
  5351. p = t.length,
  5352. v = t[0][0],
  5353. f = t[0][1],
  5354. m = t[p - 1][0],
  5355. _ = t[p - 1][1];for (i = v, s = f, r = [[i, s]], o = 2; p > o; ++o) {
  5356. for (c = t[o], n = c[0], l = c[1], u = this.interpolate(i, s, n, l), g = !1, a = 1; a < u.length; ++a) {
  5357. if (d = u[a], !e.isWalkableAt(d[0], d[1])) {
  5358. g = !0;break;
  5359. }
  5360. }g && (h = t[o - 1], r.push(h), i = h[0], s = h[1]);
  5361. }return r.push([m, _]), r;
  5362. }, compressPath: function compressPath(e) {
  5363. if (e.length < 3) return e;var t,
  5364. i,
  5365. s,
  5366. n,
  5367. l,
  5368. r,
  5369. h = [],
  5370. o = e[0][0],
  5371. a = e[0][1],
  5372. c = e[1][0],
  5373. u = e[1][1],
  5374. d = c - o,
  5375. g = u - a;for (l = Math.sqrt(d * d + g * g), d /= l, g /= l, h.push([o, a]), r = 2; r < e.length; r++) {
  5376. t = c, i = u, s = d, n = g, c = e[r][0], u = e[r][1], d = c - t, g = u - i, l = Math.sqrt(d * d + g * g), d /= l, g /= l, (d !== s || g !== n) && h.push([t, i]);
  5377. }return h.push([c, u]), h;
  5378. } }, vg.Loader = { manager: null, imageLoader: null, crossOrigin: !1, init: function init(e) {
  5379. this.crossOrigin = e || !1, this.manager = new THREE.LoadingManager(function () {}, function () {}, function () {
  5380. console.warn("Error loading images");
  5381. }), this.imageLoader = new THREE.ImageLoader(this.manager), this.imageLoader.crossOrigin = e;
  5382. }, loadTexture: function loadTexture(e, t, i, s) {
  5383. var n = new THREE.Texture(null, t);return this.imageLoader.load(e, function (e) {
  5384. n.image = e, n.needsUpdate = !0, i && i(n);
  5385. }, null, function (e) {
  5386. s && s(e);
  5387. }), n.sourceFile = e, n;
  5388. } }, vg.MouseCaster = function (e, t, i) {
  5389. this.down = !1, this.rightDown = !1, this.pickedObject = null, this.selectedObject = null, this.allHits = null, this.active = !0, this.shift = !1, this.ctrl = !1, this.wheel = 0, this.position = new THREE.Vector3(), this.screenPosition = new THREE.Vector2(), this.signal = new vg.Signal(), this.group = e, this._camera = t, this._raycaster = new THREE.Raycaster(), this._preventDefault = !1, i = i || document, i.addEventListener("mousemove", this._onDocumentMouseMove.bind(this), !1), i.addEventListener("mousedown", this._onDocumentMouseDown.bind(this), !1), i.addEventListener("mouseup", this._onDocumentMouseUp.bind(this), !1), i.addEventListener("mousewheel", this._onMouseWheel.bind(this), !1), i.addEventListener("DOMMouseScroll", this._onMouseWheel.bind(this), !1);
  5390. }, vg.MouseCaster.OVER = "over", vg.MouseCaster.OUT = "out", vg.MouseCaster.DOWN = "down", vg.MouseCaster.UP = "up", vg.MouseCaster.CLICK = "click", vg.MouseCaster.WHEEL = "wheel", vg.MouseCaster.prototype = { update: function update() {
  5391. if (this.active) {
  5392. this._raycaster.setFromCamera(this.screenPosition, this._camera);var e,
  5393. t,
  5394. i = this._raycaster.intersectObject(this.group, !0);i.length > 0 ? (e = i[0], t = e.object.userData.structure, this.pickedObject != t && (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = t, this.selectedObject = null, this.signal.dispatch(vg.MouseCaster.OVER, this.pickedObject)), this.position.copy(e.point), this.screenPosition.z = e.distance) : (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = null, this.selectedObject = null), this.allHits = i;
  5395. }
  5396. }, preventDefault: function preventDefault() {
  5397. this._preventDefault = !0;
  5398. }, _onDocumentMouseDown: function _onDocumentMouseDown(e) {
  5399. return e = e || window.event, e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.pickedObject && (this.selectedObject = this.pickedObject), this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.down = 1 === e.which, this.rightDown = 3 === e.which, void this.signal.dispatch(vg.MouseCaster.DOWN, this.pickedObject));
  5400. }, _onDocumentMouseUp: function _onDocumentMouseUp(e) {
  5401. return e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.signal.dispatch(vg.MouseCaster.UP, this.pickedObject), this.selectedObject && this.pickedObject && this.selectedObject.uniqueID === this.pickedObject.uniqueID && this.signal.dispatch(vg.MouseCaster.CLICK, this.pickedObject), this.down = 1 === e.which ? !1 : this.down, void (this.rightDown = 3 === e.which ? !1 : this.rightDown));
  5402. }, _onDocumentMouseMove: function _onDocumentMouseMove(e) {
  5403. e.preventDefault(), this.screenPosition.x = e.clientX / window.innerWidth * 2 - 1, this.screenPosition.y = 2 * -(e.clientY / window.innerHeight) + 1;
  5404. }, _onMouseWheel: function _onMouseWheel(e) {
  5405. if (this.active) {
  5406. e.preventDefault(), e.stopPropagation();var t = 0;void 0 !== e.wheelDelta ? t = e.wheelDelta : void 0 !== e.detail && (t = -e.detail), t > 0 ? this.wheel++ : this.wheel--, this.signal.dispatch(vg.MouseCaster.WHEEL, this.wheel);
  5407. }
  5408. } }, vg.MouseCaster.prototype.constructor = vg.MouseCaster, vg.Scene = function (e, t) {
  5409. var i = { element: document.body, alpha: !0, antialias: !0, clearColor: "#fff", sortObjects: !1, fog: null, light: new THREE.DirectionalLight(16777215), lightPosition: null, cameraType: "PerspectiveCamera", cameraPosition: null, orthoZoom: 4 },
  5410. s = { minDistance: 100, maxDistance: 1e3, zoomSpeed: 2, noZoom: !1 };if (i = vg.Tools.merge(i, e), "boolean" != typeof t && (s = vg.Tools.merge(s, t)), this.renderer = new THREE.WebGLRenderer({ alpha: i.alpha, antialias: i.antialias }), this.renderer.setClearColor(i.clearColor, 0), this.renderer.sortObjects = i.sortObjects, this.width = window.innerWidth, this.height = window.innerHeight, this.orthoZoom = i.orthoZoom, this.container = new THREE.Scene(), this.container.fog = i.fog, this.container.add(new THREE.AmbientLight(14540253)), i.lightPosition || i.light.position.set(-1, 1, -1).normalize(), this.container.add(i.light), "OrthographicCamera" === i.cameraType) {
  5411. var n = window.innerWidth / this.orthoZoom,
  5412. l = window.innerHeight / this.orthoZoom;this.camera = new THREE.OrthographicCamera(n / -2, n / 2, l / 2, l / -2, 1, 5e3);
  5413. } else this.camera = new THREE.PerspectiveCamera(50, this.width / this.height, 1, 5e3);this.contolled = !!t, this.contolled && (this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement), this.controls.minDistance = s.minDistance, this.controls.maxDistance = s.maxDistance, this.controls.zoomSpeed = s.zoomSpeed, this.controls.noZoom = s.noZoom), i.cameraPosition && this.camera.position.copy(i.cameraPosition), window.addEventListener("resize", function () {
  5414. if (this.width = window.innerWidth, this.height = window.innerHeight, "OrthographicCamera" === this.camera.type) {
  5415. var e = this.width / this.orthoZoom,
  5416. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2;
  5417. } else this.camera.aspect = this.width / this.height;this.camera.updateProjectionMatrix(), this.renderer.setSize(this.width, this.height);
  5418. }.bind(this), !1), this.attachTo(i.element);
  5419. }, vg.Scene.prototype = { attachTo: function attachTo(e) {
  5420. e.style.width = this.width + "px", e.style.height = this.height + "px", this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.setSize(this.width, this.height), e.appendChild(this.renderer.domElement);
  5421. }, add: function add(e) {
  5422. this.container.add(e);
  5423. }, remove: function remove(e) {
  5424. this.container.remove(e);
  5425. }, render: function render() {
  5426. this.contolled && this.controls.update(), this.renderer.render(this.container, this.camera);
  5427. }, updateOrthoZoom: function updateOrthoZoom() {
  5428. if (this.orthoZoom <= 0) return void (this.orthoZoom = 0);var e = this.width / this.orthoZoom,
  5429. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2, this.camera.updateProjectionMatrix();
  5430. }, focusOn: function focusOn(e) {
  5431. this.camera.lookAt(e.position);
  5432. } }, vg.Scene.prototype.constructor = vg.Scene, vg.SelectionManager = function (e) {
  5433. this.mouse = e, this.onSelect = new vg.Signal(), this.onDeselect = new vg.Signal(), this.selected = null, this.toggleSelection = !1, this.mouse.signal.add(this.onMouse, this);
  5434. }, vg.SelectionManager.prototype = { select: function select(e, t) {
  5435. e && (t = t || !0, this.selected !== e && this.clearSelection(t), e.selected ? this.toggleSelection && (t && this.onDeselect.dispatch(e), e.deselect()) : e.select(), this.selected = e, t && this.onSelect.dispatch(e));
  5436. }, clearSelection: function clearSelection(e) {
  5437. e = e || !0, this.selected && (e && this.onDeselect.dispatch(this.selected), this.selected.deselect()), this.selected = null;
  5438. }, onMouse: function onMouse(e, t) {
  5439. switch (e) {case vg.MouseCaster.DOWN:
  5440. t || this.clearSelection();break;case vg.MouseCaster.CLICK:
  5441. this.select(t);}
  5442. } }, vg.SelectionManager.prototype.constructor = vg.SelectionManager, vg.Tools = { clamp: function clamp(e, t, i) {
  5443. return Math.max(t, Math.min(i, e));
  5444. }, sign: function sign(e) {
  5445. return e && e / Math.abs(e);
  5446. }, random: function random(e, t) {
  5447. return 1 === arguments.length ? Math.random() * e - .5 * e : Math.random() * (t - e) + e;
  5448. }, randomInt: function randomInt(e, t) {
  5449. return 1 === arguments.length ? Math.random() * e - .5 * e | 0 : Math.random() * (t - e + 1) + e | 0;
  5450. }, normalize: function normalize(e, t, i) {
  5451. return (e - t) / (i - t);
  5452. }, getShortRotation: function getShortRotation(e) {
  5453. return e %= this.TAU, e > this.PI ? e -= this.TAU : e < -this.PI && (e += this.TAU), e;
  5454. }, generateID: function generateID() {
  5455. return Math.random().toString(36).slice(2) + Date.now();
  5456. }, isPlainObject: function isPlainObject(e) {
  5457. if ("object" != (typeof e === "undefined" ? "undefined" : _typeof(e)) || e.nodeType || e === e.window) return !1;try {
  5458. if (e.constructor && !Object.prototype.hasOwnProperty.call(e.constructor.prototype, "isPrototypeOf")) return !1;
  5459. } catch (t) {
  5460. return !1;
  5461. }return !0;
  5462. }, merge: function merge(e, t) {
  5463. var i = this,
  5464. s = Array.isArray(t),
  5465. n = s && [] || {};return s ? (e = e || [], n = n.concat(e), t.forEach(function (t, s) {
  5466. "undefined" == typeof n[s] ? n[s] = t : i.isPlainObject(t) ? n[s] = i.merge(e[s], t) : -1 === e.indexOf(t) && n.push(t);
  5467. }), n) : (e && i.isPlainObject(e) && Object.keys(e).forEach(function (t) {
  5468. n[t] = e[t];
  5469. }), Object.keys(t).forEach(function (s) {
  5470. t[s] && i.isPlainObject(t[s]) && e[s] ? n[s] = i.merge(e[s], t[s]) : n[s] = t[s];
  5471. }), n);
  5472. }, now: function now() {
  5473. return window.nwf ? window.nwf.system.Performance.elapsedTime : window.performance.now();
  5474. }, empty: function empty(e) {
  5475. for (; e.lastChild;) {
  5476. e.removeChild(e.lastChild);
  5477. }
  5478. }, radixSort: function radixSort(e, t, i, s) {
  5479. if (t = t || 0, i = i || e.length, s = s || 31, !(t >= i - 1 || 0 > s)) {
  5480. for (var n = t, l = i, r = 1 << s; l > n;) {
  5481. if (e[n] & r) {
  5482. --l;var h = e[n];e[n] = e[l], e[l] = h;
  5483. } else ++n;
  5484. }this.radixSort(e, t, l, s - 1), this.radixSort(e, l, i, s - 1);
  5485. }
  5486. }, randomizeRGB: function randomizeRGB(e, t) {
  5487. var i,
  5488. s,
  5489. n = e.split(","),
  5490. l = "rgb(";for (t = this.randomInt(t), i = 0; 3 > i; i++) {
  5491. s = parseInt(n[i]) + t, 0 > s ? s = 0 : s > 255 && (s = 255), l += s + ",";
  5492. }return l = l.substring(0, l.length - 1), l += ")";
  5493. }, getJSON: function getJSON(e) {
  5494. var t = new XMLHttpRequest(),
  5495. i = "undefined" == typeof e.cache ? !1 : e.cache,
  5496. s = i ? e.url : e.url + "?t=" + Math.floor(1e4 * Math.random()) + Date.now();t.onreadystatechange = function () {
  5497. if (200 === this.status) {
  5498. var t = null;try {
  5499. t = JSON.parse(this.responseText);
  5500. } catch (i) {
  5501. return;
  5502. }return void e.callback.call(e.scope || null, t);
  5503. }0 !== this.status && console.warn("[Tools.getJSON] Error: " + this.status + " (" + this.statusText + ") :: " + e.url);
  5504. }, t.open("GET", s, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Content-Type", "application/json"), t.send("");
  5505. } };
  5506. },{}],10:[function(require,module,exports){
  5507. 'use strict';
  5508. /**
  5509. * Polyfill for the additional KeyboardEvent properties defined in the D3E and
  5510. * D4E draft specifications, by @inexorabletash.
  5511. *
  5512. * See: https://github.com/inexorabletash/polyfill
  5513. */
  5514. (function (global) {
  5515. var nativeKeyboardEvent = 'KeyboardEvent' in global;
  5516. if (!nativeKeyboardEvent) global.KeyboardEvent = function KeyboardEvent() {
  5517. throw TypeError('Illegal constructor');
  5518. };
  5519. if (!('DOM_KEY_LOCATION_STANDARD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_STANDARD = 0x00; // Default or unknown location
  5520. if (!('DOM_KEY_LOCATION_LEFT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_LEFT = 0x01; // e.g. Left Alt key
  5521. if (!('DOM_KEY_LOCATION_RIGHT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_RIGHT = 0x02; // e.g. Right Alt key
  5522. if (!('DOM_KEY_LOCATION_NUMPAD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD = 0x03; // e.g. Numpad 0 or +
  5523. var STANDARD = window.KeyboardEvent.DOM_KEY_LOCATION_STANDARD,
  5524. LEFT = window.KeyboardEvent.DOM_KEY_LOCATION_LEFT,
  5525. RIGHT = window.KeyboardEvent.DOM_KEY_LOCATION_RIGHT,
  5526. NUMPAD = window.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD;
  5527. //--------------------------------------------------------------------
  5528. //
  5529. // Utilities
  5530. //
  5531. //--------------------------------------------------------------------
  5532. function contains(s, ss) {
  5533. return String(s).indexOf(ss) !== -1;
  5534. }
  5535. var os = function () {
  5536. if (contains(navigator.platform, 'Win')) {
  5537. return 'win';
  5538. }
  5539. if (contains(navigator.platform, 'Mac')) {
  5540. return 'mac';
  5541. }
  5542. if (contains(navigator.platform, 'CrOS')) {
  5543. return 'cros';
  5544. }
  5545. if (contains(navigator.platform, 'Linux')) {
  5546. return 'linux';
  5547. }
  5548. if (contains(navigator.userAgent, 'iPad') || contains(navigator.platform, 'iPod') || contains(navigator.platform, 'iPhone')) {
  5549. return 'ios';
  5550. }
  5551. return '';
  5552. }();
  5553. var browser = function () {
  5554. if (contains(navigator.userAgent, 'Chrome/')) {
  5555. return 'chrome';
  5556. }
  5557. if (contains(navigator.vendor, 'Apple')) {
  5558. return 'safari';
  5559. }
  5560. if (contains(navigator.userAgent, 'MSIE')) {
  5561. return 'ie';
  5562. }
  5563. if (contains(navigator.userAgent, 'Gecko/')) {
  5564. return 'moz';
  5565. }
  5566. if (contains(navigator.userAgent, 'Opera/')) {
  5567. return 'opera';
  5568. }
  5569. return '';
  5570. }();
  5571. var browser_os = browser + '-' + os;
  5572. function mergeIf(baseTable, select, table) {
  5573. if (browser_os === select || browser === select || os === select) {
  5574. Object.keys(table).forEach(function (keyCode) {
  5575. baseTable[keyCode] = table[keyCode];
  5576. });
  5577. }
  5578. }
  5579. function remap(o, key) {
  5580. var r = {};
  5581. Object.keys(o).forEach(function (k) {
  5582. var item = o[k];
  5583. if (key in item) {
  5584. r[item[key]] = item;
  5585. }
  5586. });
  5587. return r;
  5588. }
  5589. function invert(o) {
  5590. var r = {};
  5591. Object.keys(o).forEach(function (k) {
  5592. r[o[k]] = k;
  5593. });
  5594. return r;
  5595. }
  5596. //--------------------------------------------------------------------
  5597. //
  5598. // Generic Mappings
  5599. //
  5600. //--------------------------------------------------------------------
  5601. // "keyInfo" is a dictionary:
  5602. // code: string - name from DOM Level 3 KeyboardEvent code Values
  5603. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-code.html
  5604. // location (optional): number - one of the DOM_KEY_LOCATION values
  5605. // keyCap (optional): string - keyboard label in en-US locale
  5606. // USB code Usage ID from page 0x07 unless otherwise noted (Informative)
  5607. // Map of keyCode to keyInfo
  5608. var keyCodeToInfoTable = {
  5609. // 0x01 - VK_LBUTTON
  5610. // 0x02 - VK_RBUTTON
  5611. 0x03: { code: 'Cancel' }, // [USB: 0x9b] char \x0018 ??? (Not in D3E)
  5612. // 0x04 - VK_MBUTTON
  5613. // 0x05 - VK_XBUTTON1
  5614. // 0x06 - VK_XBUTTON2
  5615. 0x06: { code: 'Help' }, // [USB: 0x75] ???
  5616. // 0x07 - undefined
  5617. 0x08: { code: 'Backspace' }, // [USB: 0x2a] Labelled Delete on Macintosh keyboards.
  5618. 0x09: { code: 'Tab' }, // [USB: 0x2b]
  5619. // 0x0A-0x0B - reserved
  5620. 0X0C: { code: 'Clear' }, // [USB: 0x9c] NumPad Center (Not in D3E)
  5621. 0X0D: { code: 'Enter' }, // [USB: 0x28]
  5622. // 0x0E-0x0F - undefined
  5623. 0x10: { code: 'Shift' },
  5624. 0x11: { code: 'Control' },
  5625. 0x12: { code: 'Alt' },
  5626. 0x13: { code: 'Pause' }, // [USB: 0x48]
  5627. 0x14: { code: 'CapsLock' }, // [USB: 0x39]
  5628. 0x15: { code: 'KanaMode' }, // [USB: 0x88] - "HangulMode" for Korean layout
  5629. 0x16: { code: 'HangulMode' }, // [USB: 0x90] 0x15 as well in MSDN VK table ???
  5630. 0x17: { code: 'JunjaMode' }, // (Not in D3E)
  5631. 0x18: { code: 'FinalMode' }, // (Not in D3E)
  5632. 0x19: { code: 'KanjiMode' }, // [USB: 0x91] - "HanjaMode" for Korean layout
  5633. // 0x1A - undefined
  5634. 0x1B: { code: 'Escape' }, // [USB: 0x29]
  5635. 0x1C: { code: 'Convert' }, // [USB: 0x8a]
  5636. 0x1D: { code: 'NonConvert' }, // [USB: 0x8b]
  5637. 0x1E: { code: 'Accept' }, // (Not in D3E)
  5638. 0x1F: { code: 'ModeChange' }, // (Not in D3E)
  5639. 0x20: { code: 'Space' }, // [USB: 0x2c]
  5640. 0x21: { code: 'PageUp' }, // [USB: 0x4b]
  5641. 0x22: { code: 'PageDown' }, // [USB: 0x4e]
  5642. 0x23: { code: 'End' }, // [USB: 0x4d]
  5643. 0x24: { code: 'Home' }, // [USB: 0x4a]
  5644. 0x25: { code: 'ArrowLeft' }, // [USB: 0x50]
  5645. 0x26: { code: 'ArrowUp' }, // [USB: 0x52]
  5646. 0x27: { code: 'ArrowRight' }, // [USB: 0x4f]
  5647. 0x28: { code: 'ArrowDown' }, // [USB: 0x51]
  5648. 0x29: { code: 'Select' }, // (Not in D3E)
  5649. 0x2A: { code: 'Print' }, // (Not in D3E)
  5650. 0x2B: { code: 'Execute' }, // [USB: 0x74] (Not in D3E)
  5651. 0x2C: { code: 'PrintScreen' }, // [USB: 0x46]
  5652. 0x2D: { code: 'Insert' }, // [USB: 0x49]
  5653. 0x2E: { code: 'Delete' }, // [USB: 0x4c]
  5654. 0x2F: { code: 'Help' }, // [USB: 0x75] ???
  5655. 0x30: { code: 'Digit0', keyCap: '0' }, // [USB: 0x27] 0)
  5656. 0x31: { code: 'Digit1', keyCap: '1' }, // [USB: 0x1e] 1!
  5657. 0x32: { code: 'Digit2', keyCap: '2' }, // [USB: 0x1f] 2@
  5658. 0x33: { code: 'Digit3', keyCap: '3' }, // [USB: 0x20] 3#
  5659. 0x34: { code: 'Digit4', keyCap: '4' }, // [USB: 0x21] 4$
  5660. 0x35: { code: 'Digit5', keyCap: '5' }, // [USB: 0x22] 5%
  5661. 0x36: { code: 'Digit6', keyCap: '6' }, // [USB: 0x23] 6^
  5662. 0x37: { code: 'Digit7', keyCap: '7' }, // [USB: 0x24] 7&
  5663. 0x38: { code: 'Digit8', keyCap: '8' }, // [USB: 0x25] 8*
  5664. 0x39: { code: 'Digit9', keyCap: '9' }, // [USB: 0x26] 9(
  5665. // 0x3A-0x40 - undefined
  5666. 0x41: { code: 'KeyA', keyCap: 'a' }, // [USB: 0x04]
  5667. 0x42: { code: 'KeyB', keyCap: 'b' }, // [USB: 0x05]
  5668. 0x43: { code: 'KeyC', keyCap: 'c' }, // [USB: 0x06]
  5669. 0x44: { code: 'KeyD', keyCap: 'd' }, // [USB: 0x07]
  5670. 0x45: { code: 'KeyE', keyCap: 'e' }, // [USB: 0x08]
  5671. 0x46: { code: 'KeyF', keyCap: 'f' }, // [USB: 0x09]
  5672. 0x47: { code: 'KeyG', keyCap: 'g' }, // [USB: 0x0a]
  5673. 0x48: { code: 'KeyH', keyCap: 'h' }, // [USB: 0x0b]
  5674. 0x49: { code: 'KeyI', keyCap: 'i' }, // [USB: 0x0c]
  5675. 0x4A: { code: 'KeyJ', keyCap: 'j' }, // [USB: 0x0d]
  5676. 0x4B: { code: 'KeyK', keyCap: 'k' }, // [USB: 0x0e]
  5677. 0x4C: { code: 'KeyL', keyCap: 'l' }, // [USB: 0x0f]
  5678. 0x4D: { code: 'KeyM', keyCap: 'm' }, // [USB: 0x10]
  5679. 0x4E: { code: 'KeyN', keyCap: 'n' }, // [USB: 0x11]
  5680. 0x4F: { code: 'KeyO', keyCap: 'o' }, // [USB: 0x12]
  5681. 0x50: { code: 'KeyP', keyCap: 'p' }, // [USB: 0x13]
  5682. 0x51: { code: 'KeyQ', keyCap: 'q' }, // [USB: 0x14]
  5683. 0x52: { code: 'KeyR', keyCap: 'r' }, // [USB: 0x15]
  5684. 0x53: { code: 'KeyS', keyCap: 's' }, // [USB: 0x16]
  5685. 0x54: { code: 'KeyT', keyCap: 't' }, // [USB: 0x17]
  5686. 0x55: { code: 'KeyU', keyCap: 'u' }, // [USB: 0x18]
  5687. 0x56: { code: 'KeyV', keyCap: 'v' }, // [USB: 0x19]
  5688. 0x57: { code: 'KeyW', keyCap: 'w' }, // [USB: 0x1a]
  5689. 0x58: { code: 'KeyX', keyCap: 'x' }, // [USB: 0x1b]
  5690. 0x59: { code: 'KeyY', keyCap: 'y' }, // [USB: 0x1c]
  5691. 0x5A: { code: 'KeyZ', keyCap: 'z' }, // [USB: 0x1d]
  5692. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  5693. 0x5C: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  5694. 0x5D: { code: 'ContextMenu' }, // [USB: 0x65] Context Menu
  5695. // 0x5E - reserved
  5696. 0x5F: { code: 'Standby' }, // [USB: 0x82] Sleep
  5697. 0x60: { code: 'Numpad0', keyCap: '0', location: NUMPAD }, // [USB: 0x62]
  5698. 0x61: { code: 'Numpad1', keyCap: '1', location: NUMPAD }, // [USB: 0x59]
  5699. 0x62: { code: 'Numpad2', keyCap: '2', location: NUMPAD }, // [USB: 0x5a]
  5700. 0x63: { code: 'Numpad3', keyCap: '3', location: NUMPAD }, // [USB: 0x5b]
  5701. 0x64: { code: 'Numpad4', keyCap: '4', location: NUMPAD }, // [USB: 0x5c]
  5702. 0x65: { code: 'Numpad5', keyCap: '5', location: NUMPAD }, // [USB: 0x5d]
  5703. 0x66: { code: 'Numpad6', keyCap: '6', location: NUMPAD }, // [USB: 0x5e]
  5704. 0x67: { code: 'Numpad7', keyCap: '7', location: NUMPAD }, // [USB: 0x5f]
  5705. 0x68: { code: 'Numpad8', keyCap: '8', location: NUMPAD }, // [USB: 0x60]
  5706. 0x69: { code: 'Numpad9', keyCap: '9', location: NUMPAD }, // [USB: 0x61]
  5707. 0x6A: { code: 'NumpadMultiply', keyCap: '*', location: NUMPAD }, // [USB: 0x55]
  5708. 0x6B: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  5709. 0x6C: { code: 'NumpadComma', keyCap: ',', location: NUMPAD }, // [USB: 0x85]
  5710. 0x6D: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD }, // [USB: 0x56]
  5711. 0x6E: { code: 'NumpadDecimal', keyCap: '.', location: NUMPAD }, // [USB: 0x63]
  5712. 0x6F: { code: 'NumpadDivide', keyCap: '/', location: NUMPAD }, // [USB: 0x54]
  5713. 0x70: { code: 'F1' }, // [USB: 0x3a]
  5714. 0x71: { code: 'F2' }, // [USB: 0x3b]
  5715. 0x72: { code: 'F3' }, // [USB: 0x3c]
  5716. 0x73: { code: 'F4' }, // [USB: 0x3d]
  5717. 0x74: { code: 'F5' }, // [USB: 0x3e]
  5718. 0x75: { code: 'F6' }, // [USB: 0x3f]
  5719. 0x76: { code: 'F7' }, // [USB: 0x40]
  5720. 0x77: { code: 'F8' }, // [USB: 0x41]
  5721. 0x78: { code: 'F9' }, // [USB: 0x42]
  5722. 0x79: { code: 'F10' }, // [USB: 0x43]
  5723. 0x7A: { code: 'F11' }, // [USB: 0x44]
  5724. 0x7B: { code: 'F12' }, // [USB: 0x45]
  5725. 0x7C: { code: 'F13' }, // [USB: 0x68]
  5726. 0x7D: { code: 'F14' }, // [USB: 0x69]
  5727. 0x7E: { code: 'F15' }, // [USB: 0x6a]
  5728. 0x7F: { code: 'F16' }, // [USB: 0x6b]
  5729. 0x80: { code: 'F17' }, // [USB: 0x6c]
  5730. 0x81: { code: 'F18' }, // [USB: 0x6d]
  5731. 0x82: { code: 'F19' }, // [USB: 0x6e]
  5732. 0x83: { code: 'F20' }, // [USB: 0x6f]
  5733. 0x84: { code: 'F21' }, // [USB: 0x70]
  5734. 0x85: { code: 'F22' }, // [USB: 0x71]
  5735. 0x86: { code: 'F23' }, // [USB: 0x72]
  5736. 0x87: { code: 'F24' }, // [USB: 0x73]
  5737. // 0x88-0x8F - unassigned
  5738. 0x90: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5739. 0x91: { code: 'ScrollLock' }, // [USB: 0x47]
  5740. // 0x92-0x96 - OEM specific
  5741. // 0x97-0x9F - unassigned
  5742. // NOTE: 0xA0-0xA5 usually mapped to 0x10-0x12 in browsers
  5743. 0xA0: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  5744. 0xA1: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  5745. 0xA2: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  5746. 0xA3: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  5747. 0xA4: { code: 'AltLeft', location: LEFT }, // [USB: 0xe2]
  5748. 0xA5: { code: 'AltRight', location: RIGHT }, // [USB: 0xe6]
  5749. 0xA6: { code: 'BrowserBack' }, // [USB: 0x0c/0x0224]
  5750. 0xA7: { code: 'BrowserForward' }, // [USB: 0x0c/0x0225]
  5751. 0xA8: { code: 'BrowserRefresh' }, // [USB: 0x0c/0x0227]
  5752. 0xA9: { code: 'BrowserStop' }, // [USB: 0x0c/0x0226]
  5753. 0xAA: { code: 'BrowserSearch' }, // [USB: 0x0c/0x0221]
  5754. 0xAB: { code: 'BrowserFavorites' }, // [USB: 0x0c/0x0228]
  5755. 0xAC: { code: 'BrowserHome' }, // [USB: 0x0c/0x0222]
  5756. 0xAD: { code: 'VolumeMute' }, // [USB: 0x7f]
  5757. 0xAE: { code: 'VolumeDown' }, // [USB: 0x81]
  5758. 0xAF: { code: 'VolumeUp' }, // [USB: 0x80]
  5759. 0xB0: { code: 'MediaTrackNext' }, // [USB: 0x0c/0x00b5]
  5760. 0xB1: { code: 'MediaTrackPrevious' }, // [USB: 0x0c/0x00b6]
  5761. 0xB2: { code: 'MediaStop' }, // [USB: 0x0c/0x00b7]
  5762. 0xB3: { code: 'MediaPlayPause' }, // [USB: 0x0c/0x00cd]
  5763. 0xB4: { code: 'LaunchMail' }, // [USB: 0x0c/0x018a]
  5764. 0xB5: { code: 'MediaSelect' },
  5765. 0xB6: { code: 'LaunchApp1' },
  5766. 0xB7: { code: 'LaunchApp2' },
  5767. // 0xB8-0xB9 - reserved
  5768. 0xBA: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  5769. 0xBB: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5770. 0xBC: { code: 'Comma', keyCap: ',' }, // [USB: 0x36] ,<
  5771. 0xBD: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  5772. 0xBE: { code: 'Period', keyCap: '.' }, // [USB: 0x37] .>
  5773. 0xBF: { code: 'Slash', keyCap: '/' }, // [USB: 0x38] /? (US Standard 101)
  5774. 0xC0: { code: 'Backquote', keyCap: '`' }, // [USB: 0x35] `~ (US Standard 101)
  5775. // 0xC1-0xCF - reserved
  5776. // 0xD0-0xD7 - reserved
  5777. // 0xD8-0xDA - unassigned
  5778. 0xDB: { code: 'BracketLeft', keyCap: '[' }, // [USB: 0x2f] [{ (US Standard 101)
  5779. 0xDC: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5780. 0xDD: { code: 'BracketRight', keyCap: ']' }, // [USB: 0x30] ]} (US Standard 101)
  5781. 0xDE: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5782. // 0xDF - miscellaneous/varies
  5783. // 0xE0 - reserved
  5784. // 0xE1 - OEM specific
  5785. 0xE2: { code: 'IntlBackslash', keyCap: '\\' }, // [USB: 0x64] \| (UK Standard 102)
  5786. // 0xE3-0xE4 - OEM specific
  5787. 0xE5: { code: 'Process' }, // (Not in D3E)
  5788. // 0xE6 - OEM specific
  5789. // 0xE7 - VK_PACKET
  5790. // 0xE8 - unassigned
  5791. // 0xE9-0xEF - OEM specific
  5792. // 0xF0-0xF5 - OEM specific
  5793. 0xF6: { code: 'Attn' }, // [USB: 0x9a] (Not in D3E)
  5794. 0xF7: { code: 'CrSel' }, // [USB: 0xa3] (Not in D3E)
  5795. 0xF8: { code: 'ExSel' }, // [USB: 0xa4] (Not in D3E)
  5796. 0xF9: { code: 'EraseEof' }, // (Not in D3E)
  5797. 0xFA: { code: 'Play' }, // (Not in D3E)
  5798. 0xFB: { code: 'ZoomToggle' }, // (Not in D3E)
  5799. // 0xFC - VK_NONAME - reserved
  5800. // 0xFD - VK_PA1
  5801. 0xFE: { code: 'Clear' // [USB: 0x9c] (Not in D3E)
  5802. } };
  5803. // No legacy keyCode, but listed in D3E:
  5804. // code: usb
  5805. // 'IntlHash': 0x070032,
  5806. // 'IntlRo': 0x070087,
  5807. // 'IntlYen': 0x070089,
  5808. // 'NumpadBackspace': 0x0700bb,
  5809. // 'NumpadClear': 0x0700d8,
  5810. // 'NumpadClearEntry': 0x0700d9,
  5811. // 'NumpadMemoryAdd': 0x0700d3,
  5812. // 'NumpadMemoryClear': 0x0700d2,
  5813. // 'NumpadMemoryRecall': 0x0700d1,
  5814. // 'NumpadMemoryStore': 0x0700d0,
  5815. // 'NumpadMemorySubtract': 0x0700d4,
  5816. // 'NumpadParenLeft': 0x0700b6,
  5817. // 'NumpadParenRight': 0x0700b7,
  5818. //--------------------------------------------------------------------
  5819. //
  5820. // Browser/OS Specific Mappings
  5821. //
  5822. //--------------------------------------------------------------------
  5823. mergeIf(keyCodeToInfoTable, 'moz', {
  5824. 0x3B: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  5825. 0x3D: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5826. 0x6B: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5827. 0x6D: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  5828. 0xBB: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  5829. 0xBD: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD // [USB: 0x56]
  5830. } });
  5831. mergeIf(keyCodeToInfoTable, 'moz-mac', {
  5832. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5833. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  5834. } });
  5835. mergeIf(keyCodeToInfoTable, 'moz-win', {
  5836. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  5837. } });
  5838. mergeIf(keyCodeToInfoTable, 'chrome-mac', {
  5839. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5840. } });
  5841. // Windows via Bootcamp (!)
  5842. if (0) {
  5843. mergeIf(keyCodeToInfoTable, 'chrome-win', {
  5844. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5845. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5846. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  5847. } });
  5848. mergeIf(keyCodeToInfoTable, 'ie', {
  5849. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5850. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5851. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  5852. } });
  5853. }
  5854. mergeIf(keyCodeToInfoTable, 'safari', {
  5855. 0x03: { code: 'Enter' }, // [USB: 0x28] old Safari
  5856. 0x19: { code: 'Tab' // [USB: 0x2b] old Safari for Shift+Tab
  5857. } });
  5858. mergeIf(keyCodeToInfoTable, 'ios', {
  5859. 0x0A: { code: 'Enter', location: STANDARD // [USB: 0x28]
  5860. } });
  5861. mergeIf(keyCodeToInfoTable, 'safari-mac', {
  5862. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  5863. 0x5D: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  5864. 0xE5: { code: 'KeyQ', keyCap: 'Q' // [USB: 0x14] On alternate presses, Ctrl+Q sends this
  5865. } });
  5866. //--------------------------------------------------------------------
  5867. //
  5868. // Identifier Mappings
  5869. //
  5870. //--------------------------------------------------------------------
  5871. // Cases where newer-ish browsers send keyIdentifier which can be
  5872. // used to disambiguate keys.
  5873. // keyIdentifierTable[keyIdentifier] -> keyInfo
  5874. var keyIdentifierTable = {};
  5875. if ('cros' === os) {
  5876. keyIdentifierTable['U+00A0'] = { code: 'ShiftLeft', location: LEFT };
  5877. keyIdentifierTable['U+00A1'] = { code: 'ShiftRight', location: RIGHT };
  5878. keyIdentifierTable['U+00A2'] = { code: 'ControlLeft', location: LEFT };
  5879. keyIdentifierTable['U+00A3'] = { code: 'ControlRight', location: RIGHT };
  5880. keyIdentifierTable['U+00A4'] = { code: 'AltLeft', location: LEFT };
  5881. keyIdentifierTable['U+00A5'] = { code: 'AltRight', location: RIGHT };
  5882. }
  5883. if ('chrome-mac' === browser_os) {
  5884. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  5885. }
  5886. if ('safari-mac' === browser_os) {
  5887. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  5888. }
  5889. if ('ios' === os) {
  5890. // These only generate keyup events
  5891. keyIdentifierTable['U+0010'] = { code: 'Function' };
  5892. keyIdentifierTable['U+001C'] = { code: 'ArrowLeft' };
  5893. keyIdentifierTable['U+001D'] = { code: 'ArrowRight' };
  5894. keyIdentifierTable['U+001E'] = { code: 'ArrowUp' };
  5895. keyIdentifierTable['U+001F'] = { code: 'ArrowDown' };
  5896. keyIdentifierTable['U+0001'] = { code: 'Home' }; // [USB: 0x4a] Fn + ArrowLeft
  5897. keyIdentifierTable['U+0004'] = { code: 'End' }; // [USB: 0x4d] Fn + ArrowRight
  5898. keyIdentifierTable['U+000B'] = { code: 'PageUp' }; // [USB: 0x4b] Fn + ArrowUp
  5899. keyIdentifierTable['U+000C'] = { code: 'PageDown' }; // [USB: 0x4e] Fn + ArrowDown
  5900. }
  5901. //--------------------------------------------------------------------
  5902. //
  5903. // Location Mappings
  5904. //
  5905. //--------------------------------------------------------------------
  5906. // Cases where newer-ish browsers send location/keyLocation which
  5907. // can be used to disambiguate keys.
  5908. // locationTable[location][keyCode] -> keyInfo
  5909. var locationTable = [];
  5910. locationTable[LEFT] = {
  5911. 0x10: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  5912. 0x11: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  5913. 0x12: { code: 'AltLeft', location: LEFT // [USB: 0xe2]
  5914. } };
  5915. locationTable[RIGHT] = {
  5916. 0x10: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  5917. 0x11: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  5918. 0x12: { code: 'AltRight', location: RIGHT // [USB: 0xe6]
  5919. } };
  5920. locationTable[NUMPAD] = {
  5921. 0x0D: { code: 'NumpadEnter', location: NUMPAD // [USB: 0x58]
  5922. } };
  5923. mergeIf(locationTable[NUMPAD], 'moz', {
  5924. 0x6D: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  5925. 0x6B: { code: 'NumpadAdd', location: NUMPAD // [USB: 0x57]
  5926. } });
  5927. mergeIf(locationTable[LEFT], 'moz-mac', {
  5928. 0xE0: { code: 'OSLeft', location: LEFT // [USB: 0xe3]
  5929. } });
  5930. mergeIf(locationTable[RIGHT], 'moz-mac', {
  5931. 0xE0: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5932. } });
  5933. mergeIf(locationTable[RIGHT], 'moz-win', {
  5934. 0x5B: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5935. } });
  5936. mergeIf(locationTable[RIGHT], 'mac', {
  5937. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5938. } });
  5939. mergeIf(locationTable[NUMPAD], 'chrome-mac', {
  5940. 0x0C: { code: 'NumLock', location: NUMPAD // [USB: 0x53]
  5941. } });
  5942. mergeIf(locationTable[NUMPAD], 'safari-mac', {
  5943. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5944. 0xBB: { code: 'NumpadAdd', location: NUMPAD }, // [USB: 0x57]
  5945. 0xBD: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  5946. 0xBE: { code: 'NumpadDecimal', location: NUMPAD }, // [USB: 0x63]
  5947. 0xBF: { code: 'NumpadDivide', location: NUMPAD // [USB: 0x54]
  5948. } });
  5949. //--------------------------------------------------------------------
  5950. //
  5951. // Key Values
  5952. //
  5953. //--------------------------------------------------------------------
  5954. // Mapping from `code` values to `key` values. Values defined at:
  5955. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html
  5956. // Entries are only provided when `key` differs from `code`. If
  5957. // printable, `shiftKey` has the shifted printable character. This
  5958. // assumes US Standard 101 layout
  5959. var codeToKeyTable = {
  5960. // Modifier Keys
  5961. ShiftLeft: { key: 'Shift' },
  5962. ShiftRight: { key: 'Shift' },
  5963. ControlLeft: { key: 'Control' },
  5964. ControlRight: { key: 'Control' },
  5965. AltLeft: { key: 'Alt' },
  5966. AltRight: { key: 'Alt' },
  5967. OSLeft: { key: 'OS' },
  5968. OSRight: { key: 'OS' },
  5969. // Whitespace Keys
  5970. NumpadEnter: { key: 'Enter' },
  5971. Space: { key: ' ' },
  5972. // Printable Keys
  5973. Digit0: { key: '0', shiftKey: ')' },
  5974. Digit1: { key: '1', shiftKey: '!' },
  5975. Digit2: { key: '2', shiftKey: '@' },
  5976. Digit3: { key: '3', shiftKey: '#' },
  5977. Digit4: { key: '4', shiftKey: '$' },
  5978. Digit5: { key: '5', shiftKey: '%' },
  5979. Digit6: { key: '6', shiftKey: '^' },
  5980. Digit7: { key: '7', shiftKey: '&' },
  5981. Digit8: { key: '8', shiftKey: '*' },
  5982. Digit9: { key: '9', shiftKey: '(' },
  5983. KeyA: { key: 'a', shiftKey: 'A' },
  5984. KeyB: { key: 'b', shiftKey: 'B' },
  5985. KeyC: { key: 'c', shiftKey: 'C' },
  5986. KeyD: { key: 'd', shiftKey: 'D' },
  5987. KeyE: { key: 'e', shiftKey: 'E' },
  5988. KeyF: { key: 'f', shiftKey: 'F' },
  5989. KeyG: { key: 'g', shiftKey: 'G' },
  5990. KeyH: { key: 'h', shiftKey: 'H' },
  5991. KeyI: { key: 'i', shiftKey: 'I' },
  5992. KeyJ: { key: 'j', shiftKey: 'J' },
  5993. KeyK: { key: 'k', shiftKey: 'K' },
  5994. KeyL: { key: 'l', shiftKey: 'L' },
  5995. KeyM: { key: 'm', shiftKey: 'M' },
  5996. KeyN: { key: 'n', shiftKey: 'N' },
  5997. KeyO: { key: 'o', shiftKey: 'O' },
  5998. KeyP: { key: 'p', shiftKey: 'P' },
  5999. KeyQ: { key: 'q', shiftKey: 'Q' },
  6000. KeyR: { key: 'r', shiftKey: 'R' },
  6001. KeyS: { key: 's', shiftKey: 'S' },
  6002. KeyT: { key: 't', shiftKey: 'T' },
  6003. KeyU: { key: 'u', shiftKey: 'U' },
  6004. KeyV: { key: 'v', shiftKey: 'V' },
  6005. KeyW: { key: 'w', shiftKey: 'W' },
  6006. KeyX: { key: 'x', shiftKey: 'X' },
  6007. KeyY: { key: 'y', shiftKey: 'Y' },
  6008. KeyZ: { key: 'z', shiftKey: 'Z' },
  6009. Numpad0: { key: '0' },
  6010. Numpad1: { key: '1' },
  6011. Numpad2: { key: '2' },
  6012. Numpad3: { key: '3' },
  6013. Numpad4: { key: '4' },
  6014. Numpad5: { key: '5' },
  6015. Numpad6: { key: '6' },
  6016. Numpad7: { key: '7' },
  6017. Numpad8: { key: '8' },
  6018. Numpad9: { key: '9' },
  6019. NumpadMultiply: { key: '*' },
  6020. NumpadAdd: { key: '+' },
  6021. NumpadComma: { key: ',' },
  6022. NumpadSubtract: { key: '-' },
  6023. NumpadDecimal: { key: '.' },
  6024. NumpadDivide: { key: '/' },
  6025. Semicolon: { key: ';', shiftKey: ':' },
  6026. Equal: { key: '=', shiftKey: '+' },
  6027. Comma: { key: ',', shiftKey: '<' },
  6028. Minus: { key: '-', shiftKey: '_' },
  6029. Period: { key: '.', shiftKey: '>' },
  6030. Slash: { key: '/', shiftKey: '?' },
  6031. Backquote: { key: '`', shiftKey: '~' },
  6032. BracketLeft: { key: '[', shiftKey: '{' },
  6033. Backslash: { key: '\\', shiftKey: '|' },
  6034. BracketRight: { key: ']', shiftKey: '}' },
  6035. Quote: { key: '\'', shiftKey: '"' },
  6036. IntlBackslash: { key: '\\', shiftKey: '|' }
  6037. };
  6038. mergeIf(codeToKeyTable, 'mac', {
  6039. OSLeft: { key: 'Meta' },
  6040. OSRight: { key: 'Meta' }
  6041. });
  6042. // Corrections for 'key' names in older browsers (e.g. FF36-)
  6043. // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key#Key_values
  6044. var keyFixTable = {
  6045. Esc: 'Escape',
  6046. Nonconvert: 'NonConvert',
  6047. Left: 'ArrowLeft',
  6048. Up: 'ArrowUp',
  6049. Right: 'ArrowRight',
  6050. Down: 'ArrowDown',
  6051. Del: 'Delete',
  6052. Menu: 'ContextMenu',
  6053. MediaNextTrack: 'MediaTrackNext',
  6054. MediaPreviousTrack: 'MediaTrackPrevious',
  6055. SelectMedia: 'MediaSelect',
  6056. HalfWidth: 'Hankaku',
  6057. FullWidth: 'Zenkaku',
  6058. RomanCharacters: 'Romaji',
  6059. Crsel: 'CrSel',
  6060. Exsel: 'ExSel',
  6061. Zoom: 'ZoomToggle'
  6062. };
  6063. //--------------------------------------------------------------------
  6064. //
  6065. // Exported Functions
  6066. //
  6067. //--------------------------------------------------------------------
  6068. var codeTable = remap(keyCodeToInfoTable, 'code');
  6069. try {
  6070. var nativeLocation = nativeKeyboardEvent && 'location' in new KeyboardEvent('');
  6071. } catch (_) {}
  6072. function keyInfoForEvent(event) {
  6073. var keyCode = 'keyCode' in event ? event.keyCode : 'which' in event ? event.which : 0;
  6074. var keyInfo = function () {
  6075. if (nativeLocation || 'keyLocation' in event) {
  6076. var location = nativeLocation ? event.location : event.keyLocation;
  6077. if (location && keyCode in locationTable[location]) {
  6078. return locationTable[location][keyCode];
  6079. }
  6080. }
  6081. if ('keyIdentifier' in event && event.keyIdentifier in keyIdentifierTable) {
  6082. return keyIdentifierTable[event.keyIdentifier];
  6083. }
  6084. if (keyCode in keyCodeToInfoTable) {
  6085. return keyCodeToInfoTable[keyCode];
  6086. }
  6087. return null;
  6088. }();
  6089. // TODO: Track these down and move to general tables
  6090. if (0) {
  6091. // TODO: Map these for newerish browsers?
  6092. // TODO: iOS only?
  6093. // TODO: Override with more common keyIdentifier name?
  6094. switch (event.keyIdentifier) {
  6095. case 'U+0010':
  6096. keyInfo = { code: 'Function' };break;
  6097. case 'U+001C':
  6098. keyInfo = { code: 'ArrowLeft' };break;
  6099. case 'U+001D':
  6100. keyInfo = { code: 'ArrowRight' };break;
  6101. case 'U+001E':
  6102. keyInfo = { code: 'ArrowUp' };break;
  6103. case 'U+001F':
  6104. keyInfo = { code: 'ArrowDown' };break;
  6105. }
  6106. }
  6107. if (!keyInfo) return null;
  6108. var key = function () {
  6109. var entry = codeToKeyTable[keyInfo.code];
  6110. if (!entry) return keyInfo.code;
  6111. return event.shiftKey && 'shiftKey' in entry ? entry.shiftKey : entry.key;
  6112. }();
  6113. return {
  6114. code: keyInfo.code,
  6115. key: key,
  6116. location: keyInfo.location,
  6117. keyCap: keyInfo.keyCap
  6118. };
  6119. }
  6120. function queryKeyCap(code, locale) {
  6121. code = String(code);
  6122. if (!codeTable.hasOwnProperty(code)) return 'Undefined';
  6123. if (locale && String(locale).toLowerCase() !== 'en-us') throw Error('Unsupported locale');
  6124. var keyInfo = codeTable[code];
  6125. return keyInfo.keyCap || keyInfo.code || 'Undefined';
  6126. }
  6127. if ('KeyboardEvent' in global && 'defineProperty' in Object) {
  6128. (function () {
  6129. function define(o, p, v) {
  6130. if (p in o) return;
  6131. Object.defineProperty(o, p, v);
  6132. }
  6133. define(KeyboardEvent.prototype, 'code', { get: function get() {
  6134. var keyInfo = keyInfoForEvent(this);
  6135. return keyInfo ? keyInfo.code : '';
  6136. } });
  6137. // Fix for nonstandard `key` values (FF36-)
  6138. if ('key' in KeyboardEvent.prototype) {
  6139. var desc = Object.getOwnPropertyDescriptor(KeyboardEvent.prototype, 'key');
  6140. Object.defineProperty(KeyboardEvent.prototype, 'key', { get: function get() {
  6141. var key = desc.get.call(this);
  6142. return keyFixTable.hasOwnProperty(key) ? keyFixTable[key] : key;
  6143. } });
  6144. }
  6145. define(KeyboardEvent.prototype, 'key', { get: function get() {
  6146. var keyInfo = keyInfoForEvent(this);
  6147. return keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  6148. } });
  6149. define(KeyboardEvent.prototype, 'location', { get: function get() {
  6150. var keyInfo = keyInfoForEvent(this);
  6151. return keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  6152. } });
  6153. define(KeyboardEvent.prototype, 'locale', { get: function get() {
  6154. return '';
  6155. } });
  6156. })();
  6157. }
  6158. if (!('queryKeyCap' in global.KeyboardEvent)) global.KeyboardEvent.queryKeyCap = queryKeyCap;
  6159. // Helper for IE8-
  6160. global.identifyKey = function (event) {
  6161. if ('code' in event) return;
  6162. var keyInfo = keyInfoForEvent(event);
  6163. event.code = keyInfo ? keyInfo.code : '';
  6164. event.key = keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  6165. event.location = 'location' in event ? event.location : 'keyLocation' in event ? event.keyLocation : keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  6166. event.locale = '';
  6167. };
  6168. })(window);
  6169. },{}],11:[function(require,module,exports){
  6170. var e=function(){};e.computeCentroids=function(e){var t,n,r;for(t=0,n=e.faces.length;t<n;t++)(r=e.faces[t]).centroid=new THREE.Vector3(0,0,0),r.centroid.add(e.vertices[r.a]),r.centroid.add(e.vertices[r.b]),r.centroid.add(e.vertices[r.c]),r.centroid.divideScalar(3)},e.roundNumber=function(e,t){return Number(e.toFixed(t))},e.sample=function(e){return e[Math.floor(Math.random()*e.length)]},e.mergeVertexIds=function(e,t){var n=[];if(e.forEach(function(e){t.indexOf(e)>=0&&n.push(e)}),n.length<2)return[];n.includes(e[0])&&n.includes(e[e.length-1])&&e.push(e.shift()),n.includes(t[0])&&n.includes(t[t.length-1])&&t.push(t.shift()),n=[],e.forEach(function(e){t.includes(e)&&n.push(e)});for(var r=n[1],o=n[0],i=e.slice();i[0]!==r;)i.push(i.shift());for(var s=0,u=t.slice();u[0]!==o;)if(u.push(u.shift()),s++>10)throw new Error("Unexpected state");return u.shift(),u.pop(),i=i.concat(u)},e.setPolygonCentroid=function(e,t){var n=new THREE.Vector3,r=t.vertices;e.vertexIds.forEach(function(e){n.add(r[e])}),n.divideScalar(e.vertexIds.length),e.centroid.copy(n)},e.cleanPolygon=function(e,t){for(var n=[],r=t.vertices,o=0;o<e.vertexIds.length;o++){var i,s,u,c=r[e.vertexIds[o]];0===o?(i=e.vertexIds[1],s=e.vertexIds[e.vertexIds.length-1]):o===e.vertexIds.length-1?(i=e.vertexIds[0],s=e.vertexIds[e.vertexIds.length-2]):(i=e.vertexIds[o+1],s=e.vertexIds[o-1]),u=r[s];var h=r[i].clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d>Math.PI-.01&&d<Math.PI+.01){var f=[];e.neighbours.forEach(function(t){t.vertexIds.includes(e.vertexIds[o])||f.push(t)}),e.neighbours=f}else n.push(e.vertexIds[o])}e.vertexIds=n,this.setPolygonCentroid(e,t)},e.isConvex=function(e,t){var n=t.vertices;if(e.vertexIds.length<3)return!1;for(var r=!0,o=[],i=0;i<e.vertexIds.length;i++){var s,u,c=n[e.vertexIds[i]];0===i?(s=n[e.vertexIds[1]],u=n[e.vertexIds[e.vertexIds.length-1]]):i===e.vertexIds.length-1?(s=n[e.vertexIds[0]],u=n[e.vertexIds[e.vertexIds.length-2]]):(s=n[e.vertexIds[i+1]],u=n[e.vertexIds[i-1]]);var h=s.clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d===Math.PI||0===d)return!1;var f=h.cross(a).y;o.push(f)}return o.forEach(function(e){0===e&&(r=!1)}),o.forEach(o[0]>0?function(e){e<0&&(r=!1)}:function(e){e>0&&(r=!1)}),r},e.distanceToSquared=function(e,t){var n=e.x-t.x,r=e.y-t.y,o=e.z-t.z;return n*n+r*r+o*o},e.isPointInPoly=function(e,t){for(var n=!1,r=-1,o=e.length,i=o-1;++r<o;i=r)(e[r].z<=t.z&&t.z<e[i].z||e[i].z<=t.z&&t.z<e[r].z)&&t.x<(e[i].x-e[r].x)*(t.z-e[r].z)/(e[i].z-e[r].z)+e[r].x&&(n=!n);return n},e.isVectorInPolygon=function(e,t,n){var r=1e5,o=-1e5,i=[];return t.vertexIds.forEach(function(e){r=Math.min(n[e].y,r),o=Math.max(n[e].y,o),i.push(n[e])}),!!(e.y<o+.5&&e.y>r-.5&&this.isPointInPoly(i,e))},e.triarea2=function(e,t,n){return(n.x-e.x)*(t.z-e.z)-(t.x-e.x)*(n.z-e.z)},e.vequal=function(e,t){return this.distanceToSquared(e,t)<1e-5};var t=function(e){this.content=[],this.scoreFunction=e};t.prototype.push=function(e){this.content.push(e),this.sinkDown(this.content.length-1)},t.prototype.pop=function(){var e=this.content[0],t=this.content.pop();return this.content.length>0&&(this.content[0]=t,this.bubbleUp(0)),e},t.prototype.remove=function(e){var t=this.content.indexOf(e),n=this.content.pop();t!==this.content.length-1&&(this.content[t]=n,this.scoreFunction(n)<this.scoreFunction(e)?this.sinkDown(t):this.bubbleUp(t))},t.prototype.size=function(){return this.content.length},t.prototype.rescoreElement=function(e){this.sinkDown(this.content.indexOf(e))},t.prototype.sinkDown=function(e){for(var t=this.content[e];e>0;){var n=(e+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(t)<this.scoreFunction(r)))break;this.content[n]=t,this.content[e]=r,e=n}},t.prototype.bubbleUp=function(e){for(var t=this.content.length,n=this.content[e],r=this.scoreFunction(n);;){var o=e+1<<1,i=o-1,s=null,u=void 0;if(i<t)(u=this.scoreFunction(this.content[i]))<r&&(s=i);if(o<t)this.scoreFunction(this.content[o])<(null===s?r:u)&&(s=o);if(null===s)break;this.content[e]=this.content[s],this.content[s]=n,e=s}};var n=function(){};n.init=function(e){for(var t=0;t<e.length;t++){var n=e[t];n.f=0,n.g=0,n.h=0,n.cost=1,n.visited=!1,n.closed=!1,n.parent=null}},n.cleanUp=function(e){for(var t=0;t<e.length;t++){var n=e[t];delete n.f,delete n.g,delete n.h,delete n.cost,delete n.visited,delete n.closed,delete n.parent}},n.heap=function(){return new t(function(e){return e.f})},n.search=function(e,t,n){this.init(e);var r=this.heap();for(r.push(t);r.size()>0;){var o=r.pop();if(o===n){for(var i=o,s=[];i.parent;)s.push(i),i=i.parent;return this.cleanUp(s),s.reverse()}o.closed=!0;for(var u=this.neighbours(e,o),c=0,h=u.length;c<h;c++){var a=u[c];if(!a.closed){var d=o.g+a.cost,f=a.visited;if(!f||d<a.g){if(a.visited=!0,a.parent=o,!a.centroid||!n.centroid)throw new Error("Unexpected state");a.h=a.h||this.heuristic(a.centroid,n.centroid),a.g=d,a.f=a.g+a.h,f?r.rescoreElement(a):r.push(a)}}}}return[]},n.heuristic=function(t,n){return e.distanceToSquared(t,n)},n.neighbours=function(e,t){for(var n=[],r=0;r<t.neighbours.length;r++)n.push(e[t.neighbours[r]]);return n};var r=1,o=function(){};o.buildZone=function(t){var n=this,r=this._buildNavigationMesh(t),o={};r.vertices.forEach(function(t){t.x=e.roundNumber(t.x,2),t.y=e.roundNumber(t.y,2),t.z=e.roundNumber(t.z,2)}),o.vertices=r.vertices;var i=this._buildPolygonGroups(r);o.groups=[];var s=function(e,t){for(var n=0;n<e.length;n++)if(t===e[n])return n};return i.forEach(function(t){var r=[];t.forEach(function(o){var i=o.neighbours.map(function(e){return s(t,e)}),u=o.neighbours.map(function(e){return n._getSharedVerticesInOrder(o,e)});o.centroid.x=e.roundNumber(o.centroid.x,2),o.centroid.y=e.roundNumber(o.centroid.y,2),o.centroid.z=e.roundNumber(o.centroid.z,2),r.push({id:s(t,o),neighbours:i,vertexIds:o.vertexIds,centroid:o.centroid,portals:u})}),o.groups.push(r)}),o},o._buildNavigationMesh=function(t){return e.computeCentroids(t),t.mergeVertices(),this._buildPolygonsFromGeometry(t)},o._buildPolygonGroups=function(e){var t=[],n=0,r=function(e){e.neighbours.forEach(function(t){void 0===t.group&&(t.group=e.group,r(t))})};return e.polygons.forEach(function(e){void 0===e.group&&(e.group=n++,r(e)),t[e.group]||(t[e.group]=[]),t[e.group].push(e)}),t},o._buildPolygonNeighbours=function(e,t,n){var r=new Set,o=n.get(e.vertexIds[0]),i=n.get(e.vertexIds[1]),s=n.get(e.vertexIds[2]);o.forEach(function(e){(i.has(e)||s.has(e))&&r.add(t.polygons[e])}),i.forEach(function(e){s.has(e)&&r.add(t.polygons[e])}),e.neighbours=Array.from(r)},o._buildPolygonsFromGeometry=function(e){for(var t=this,n=[],o=e.vertices,i=e.faceVertexUvs,s=new Map,u=0;u<o.length;u++)s.set(u,new Set);e.faces.forEach(function(e){n.push({id:r++,vertexIds:[e.a,e.b,e.c],centroid:e.centroid,normal:e.normal,neighbours:[]}),s.get(e.a).add(n.length-1),s.get(e.b).add(n.length-1),s.get(e.c).add(n.length-1)});var c={polygons:n,vertices:o,faceVertexUvs:i};return n.forEach(function(e){t._buildPolygonNeighbours(e,c,s)}),c},o._getSharedVerticesInOrder=function(e,t){var n=e.vertexIds,r=t.vertexIds,o=new Set;if(n.forEach(function(e){r.includes(e)&&o.add(e)}),o.size<2)return[];o.has(n[0])&&o.has(n[n.length-1])&&n.push(n.shift()),o.has(r[0])&&o.has(r[r.length-1])&&r.push(r.shift());var i=[];return n.forEach(function(e){r.includes(e)&&i.push(e)}),i};var i=function(){this.portals=[]};i.prototype.push=function(e,t){void 0===t&&(t=e),this.portals.push({left:e,right:t})},i.prototype.stringPull=function(){var t,n,r,o=this.portals,i=[],s=0,u=0,c=0;n=o[0].left,r=o[0].right,i.push(t=o[0].left);for(var h=1;h<o.length;h++){var a=o[h].left,d=o[h].right;if(e.triarea2(t,r,d)<=0){if(!(e.vequal(t,r)||e.triarea2(t,n,d)>0)){i.push(n),n=t=n,r=t,u=s=u,c=s,h=s;continue}r=d,c=h}if(e.triarea2(t,n,a)>=0){if(!(e.vequal(t,n)||e.triarea2(t,r,a)<0)){i.push(r),n=t=r,r=t,u=s=c,c=s,h=s;continue}n=a,u=h}}return 0!==i.length&&e.vequal(i[i.length-1],o[o.length-1].left)||i.push(o[o.length-1].left),this.path=i,i};var s,u,c,h,a,d,f=function(){this.zones={}};f.createZone=function(e){return o.buildZone(e)},f.prototype.setZoneData=function(e,t){this.zones[e]=t},f.prototype.getGroup=function(t,n){if(!this.zones[t])return null;var r=null,o=Math.pow(50,2);return this.zones[t].groups.forEach(function(t,i){t.forEach(function(t){var s=e.distanceToSquared(t.centroid,n);s<o&&(r=i,o=s)})}),r},f.prototype.getRandomNode=function(t,n,r,o){if(!this.zones[t])return new THREE.Vector3;r=r||null,o=o||0;var i=[];return this.zones[t].groups[n].forEach(function(t){r&&o?e.distanceToSquared(r,t.centroid)<o*o&&i.push(t.centroid):i.push(t.centroid)}),e.sample(i)||new THREE.Vector3},f.prototype.getClosestNode=function(t,n,r,o){void 0===o&&(o=!1);var i=this.zones[n].vertices,s=null,u=Infinity;return this.zones[n].groups[r].forEach(function(n){var r=e.distanceToSquared(n.centroid,t);r<u&&(!o||e.isVectorInPolygon(t,n,i))&&(s=n,u=r)}),s},f.prototype.findPath=function(e,t,r,o){var s=this.zones[r].groups[o],u=this.zones[r].vertices,c=this.getClosestNode(e,r,o),h=this.getClosestNode(t,r,o,!0);if(!c||!h)return null;var a=n.search(s,c,h),d=function(e,t){for(var n=0;n<e.neighbours.length;n++)if(e.neighbours[n]===t.id)return e.portals[n]},f=new i;f.push(e);for(var l=0;l<a.length;l++){var v=a[l+1];if(v){var p=d(a[l],v);f.push(u[p[0]],u[p[1]])}}f.push(t),f.stringPull();var g=f.path.map(function(e){return new THREE.Vector3(e.x,e.y,e.z)});return g.shift(),g},f.prototype.clampStep=(c=new THREE.Vector3,h=new THREE.Plane,a=new THREE.Triangle,d=new THREE.Vector3,function(e,t,n,r,o,i){var f=this.zones[r].vertices,l=this.zones[r].groups[o],v=[n],p={};p[n.id]=0,s=void 0,d.set(0,0,0),u=Infinity,h.setFromCoplanarPoints(f[n.vertexIds[0]],f[n.vertexIds[1]],f[n.vertexIds[2]]),h.projectPoint(t,c),t.copy(c);for(var g=v.pop();g;g=v.pop()){a.set(f[g.vertexIds[0]],f[g.vertexIds[1]],f[g.vertexIds[2]]),a.closestPointToPoint(t,c),c.distanceToSquared(t)<u&&(s=g,d.copy(c),u=c.distanceToSquared(t));var x=p[g];if(!(x>2))for(var I=0;I<g.neighbours.length;I++){var b=l[g.neighbours[I]];b.id in p||(v.push(b),p[b.id]=x+1)}}return i.copy(d),s}),exports.Pathfinding=f;
  6171. },{}],12:[function(require,module,exports){
  6172. 'use strict';
  6173. var EPS = 0.1;
  6174. module.exports = AFRAME.registerComponent('checkpoint-controls', {
  6175. schema: {
  6176. enabled: { default: true },
  6177. mode: { default: 'teleport', oneOf: ['teleport', 'animate'] },
  6178. animateSpeed: { default: 3.0 }
  6179. },
  6180. init: function init() {
  6181. this.active = true;
  6182. this.checkpoint = null;
  6183. this.isNavMeshConstrained = false;
  6184. this.offset = new THREE.Vector3();
  6185. this.position = new THREE.Vector3();
  6186. this.targetPosition = new THREE.Vector3();
  6187. },
  6188. play: function play() {
  6189. this.active = true;
  6190. },
  6191. pause: function pause() {
  6192. this.active = false;
  6193. },
  6194. setCheckpoint: function setCheckpoint(checkpoint) {
  6195. var el = this.el;
  6196. if (!this.active) return;
  6197. if (this.checkpoint === checkpoint) return;
  6198. if (this.checkpoint) {
  6199. el.emit('navigation-end', { checkpoint: this.checkpoint });
  6200. }
  6201. this.checkpoint = checkpoint;
  6202. this.sync();
  6203. // Ignore new checkpoint if we're already there.
  6204. if (this.position.distanceTo(this.targetPosition) < EPS) {
  6205. this.checkpoint = null;
  6206. return;
  6207. }
  6208. el.emit('navigation-start', { checkpoint: checkpoint });
  6209. if (this.data.mode === 'teleport') {
  6210. this.el.setAttribute('position', this.targetPosition);
  6211. this.checkpoint = null;
  6212. el.emit('navigation-end', { checkpoint: checkpoint });
  6213. el.components['movement-controls'].updateNavLocation();
  6214. }
  6215. },
  6216. isVelocityActive: function isVelocityActive() {
  6217. return !!(this.active && this.checkpoint);
  6218. },
  6219. getVelocity: function getVelocity() {
  6220. if (!this.active) return;
  6221. var data = this.data;
  6222. var offset = this.offset;
  6223. var position = this.position;
  6224. var targetPosition = this.targetPosition;
  6225. var checkpoint = this.checkpoint;
  6226. this.sync();
  6227. if (position.distanceTo(targetPosition) < EPS) {
  6228. this.checkpoint = null;
  6229. this.el.emit('navigation-end', { checkpoint: checkpoint });
  6230. return offset.set(0, 0, 0);
  6231. }
  6232. offset.setLength(data.animateSpeed);
  6233. return offset;
  6234. },
  6235. sync: function sync() {
  6236. var offset = this.offset;
  6237. var position = this.position;
  6238. var targetPosition = this.targetPosition;
  6239. position.copy(this.el.getAttribute('position'));
  6240. this.checkpoint.object3D.getWorldPosition(targetPosition);
  6241. targetPosition.add(this.checkpoint.components.checkpoint.getOffset());
  6242. offset.copy(targetPosition).sub(position);
  6243. }
  6244. });
  6245. },{}],13:[function(require,module,exports){
  6246. 'use strict';
  6247. /**
  6248. * Gamepad controls for A-Frame.
  6249. *
  6250. * Stripped-down version of: https://github.com/donmccurdy/aframe-gamepad-controls
  6251. *
  6252. * For more information about the Gamepad API, see:
  6253. * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
  6254. */
  6255. var GamepadButton = require('../../lib/GamepadButton'),
  6256. GamepadButtonEvent = require('../../lib/GamepadButtonEvent');
  6257. var JOYSTICK_EPS = 0.2;
  6258. module.exports = AFRAME.registerComponent('gamepad-controls', {
  6259. /*******************************************************************
  6260. * Statics
  6261. */
  6262. GamepadButton: GamepadButton,
  6263. /*******************************************************************
  6264. * Schema
  6265. */
  6266. schema: {
  6267. // Controller 0-3
  6268. controller: { default: 0, oneOf: [0, 1, 2, 3] },
  6269. // Enable/disable features
  6270. enabled: { default: true },
  6271. // Debugging
  6272. debug: { default: false },
  6273. // Heading element for rotation
  6274. camera: { default: '[camera]', type: 'selector' },
  6275. // Rotation sensitivity
  6276. rotationSensitivity: { default: 2.0 }
  6277. },
  6278. /*******************************************************************
  6279. * Core
  6280. */
  6281. /**
  6282. * Called once when component is attached. Generally for initial setup.
  6283. */
  6284. init: function init() {
  6285. var scene = this.el.sceneEl;
  6286. this.prevTime = window.performance.now();
  6287. // Button state
  6288. this.buttons = {};
  6289. // Rotation
  6290. var rotation = this.el.object3D.rotation;
  6291. this.pitch = new THREE.Object3D();
  6292. this.pitch.rotation.x = THREE.Math.degToRad(rotation.x);
  6293. this.yaw = new THREE.Object3D();
  6294. this.yaw.position.y = 10;
  6295. this.yaw.rotation.y = THREE.Math.degToRad(rotation.y);
  6296. this.yaw.add(this.pitch);
  6297. scene.addBehavior(this);
  6298. },
  6299. /**
  6300. * Called when component is attached and when component data changes.
  6301. * Generally modifies the entity based on the data.
  6302. */
  6303. update: function update() {
  6304. this.tick();
  6305. },
  6306. /**
  6307. * Called on each iteration of main render loop.
  6308. */
  6309. tick: function tick(t, dt) {
  6310. this.updateButtonState();
  6311. this.updateRotation(dt);
  6312. },
  6313. /**
  6314. * Called when a component is removed (e.g., via removeAttribute).
  6315. * Generally undoes all modifications to the entity.
  6316. */
  6317. remove: function remove() {},
  6318. /*******************************************************************
  6319. * Movement
  6320. */
  6321. isVelocityActive: function isVelocityActive() {
  6322. if (!this.data.enabled || !this.isConnected()) return false;
  6323. var dpad = this.getDpad(),
  6324. joystick0 = this.getJoystick(0),
  6325. inputX = dpad.x || joystick0.x,
  6326. inputY = dpad.y || joystick0.y;
  6327. return Math.abs(inputX) > JOYSTICK_EPS || Math.abs(inputY) > JOYSTICK_EPS;
  6328. },
  6329. getVelocityDelta: function getVelocityDelta() {
  6330. var dpad = this.getDpad(),
  6331. joystick0 = this.getJoystick(0),
  6332. inputX = dpad.x || joystick0.x,
  6333. inputY = dpad.y || joystick0.y,
  6334. dVelocity = new THREE.Vector3();
  6335. if (Math.abs(inputX) > JOYSTICK_EPS) {
  6336. dVelocity.x += inputX;
  6337. }
  6338. if (Math.abs(inputY) > JOYSTICK_EPS) {
  6339. dVelocity.z += inputY;
  6340. }
  6341. return dVelocity;
  6342. },
  6343. /*******************************************************************
  6344. * Rotation
  6345. */
  6346. isRotationActive: function isRotationActive() {
  6347. if (!this.data.enabled || !this.isConnected()) return false;
  6348. var joystick1 = this.getJoystick(1);
  6349. return Math.abs(joystick1.x) > JOYSTICK_EPS || Math.abs(joystick1.y) > JOYSTICK_EPS;
  6350. },
  6351. updateRotation: function updateRotation(dt) {
  6352. if (!this.isRotationActive()) return;
  6353. var data = this.data;
  6354. var yaw = this.yaw;
  6355. var pitch = this.pitch;
  6356. var lookControls = data.camera.components['look-controls'];
  6357. var hasLookControls = lookControls && lookControls.pitchObject && lookControls.yawObject;
  6358. // Sync with look-controls pitch/yaw if available.
  6359. if (hasLookControls) {
  6360. pitch.rotation.copy(lookControls.pitchObject.rotation);
  6361. yaw.rotation.copy(lookControls.yawObject.rotation);
  6362. }
  6363. var lookVector = this.getJoystick(1);
  6364. if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
  6365. if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
  6366. lookVector.multiplyScalar(data.rotationSensitivity * dt / 1000);
  6367. yaw.rotation.y -= lookVector.x;
  6368. pitch.rotation.x -= lookVector.y;
  6369. pitch.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch.rotation.x));
  6370. data.camera.object3D.rotation.set(pitch.rotation.x, yaw.rotation.y, 0);
  6371. // Sync with look-controls pitch/yaw if available.
  6372. if (hasLookControls) {
  6373. lookControls.pitchObject.rotation.copy(pitch.rotation);
  6374. lookControls.yawObject.rotation.copy(yaw.rotation);
  6375. }
  6376. },
  6377. /*******************************************************************
  6378. * Button events
  6379. */
  6380. updateButtonState: function updateButtonState() {
  6381. var gamepad = this.getGamepad();
  6382. if (this.data.enabled && gamepad) {
  6383. // Fire DOM events for button state changes.
  6384. for (var i = 0; i < gamepad.buttons.length; i++) {
  6385. if (gamepad.buttons[i].pressed && !this.buttons[i]) {
  6386. this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
  6387. } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
  6388. this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
  6389. }
  6390. this.buttons[i] = gamepad.buttons[i].pressed;
  6391. }
  6392. } else if (Object.keys(this.buttons)) {
  6393. // Reset state if controls are disabled or controller is lost.
  6394. this.buttons = {};
  6395. }
  6396. },
  6397. emit: function emit(event) {
  6398. // Emit original event.
  6399. this.el.emit(event.type, event);
  6400. // Emit convenience event, identifying button index.
  6401. this.el.emit(event.type + ':' + event.index, new GamepadButtonEvent(event.type, event.index, event));
  6402. },
  6403. /*******************************************************************
  6404. * Gamepad state
  6405. */
  6406. /**
  6407. * Returns the Gamepad instance attached to the component. If connected,
  6408. * a proxy-controls component may provide access to Gamepad input from a
  6409. * remote device.
  6410. *
  6411. * @return {Gamepad}
  6412. */
  6413. getGamepad: function getGamepad() {
  6414. var localGamepad = navigator.getGamepads && navigator.getGamepads()[this.data.controller],
  6415. proxyControls = this.el.sceneEl.components['proxy-controls'],
  6416. proxyGamepad = proxyControls && proxyControls.isConnected() && proxyControls.getGamepad(this.data.controller);
  6417. return proxyGamepad || localGamepad;
  6418. },
  6419. /**
  6420. * Returns the state of the given button.
  6421. * @param {number} index The button (0-N) for which to find state.
  6422. * @return {GamepadButton}
  6423. */
  6424. getButton: function getButton(index) {
  6425. return this.getGamepad().buttons[index];
  6426. },
  6427. /**
  6428. * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
  6429. * represent X/Y on the first joystick, and 2-3 X/Y on the second.
  6430. * @param {number} index The axis (0-N) for which to find state.
  6431. * @return {number} On the interval [-1,1].
  6432. */
  6433. getAxis: function getAxis(index) {
  6434. return this.getGamepad().axes[index];
  6435. },
  6436. /**
  6437. * Returns the state of the given joystick (0 or 1) as a THREE.Vector2.
  6438. * @param {number} id The joystick (0, 1) for which to find state.
  6439. * @return {THREE.Vector2}
  6440. */
  6441. getJoystick: function getJoystick(index) {
  6442. var gamepad = this.getGamepad();
  6443. switch (index) {
  6444. case 0:
  6445. return new THREE.Vector2(gamepad.axes[0], gamepad.axes[1]);
  6446. case 1:
  6447. return new THREE.Vector2(gamepad.axes[2], gamepad.axes[3]);
  6448. default:
  6449. throw new Error('Unexpected joystick index "%d".', index);
  6450. }
  6451. },
  6452. /**
  6453. * Returns the state of the dpad as a THREE.Vector2.
  6454. * @return {THREE.Vector2}
  6455. */
  6456. getDpad: function getDpad() {
  6457. var gamepad = this.getGamepad();
  6458. if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
  6459. return new THREE.Vector2();
  6460. }
  6461. return new THREE.Vector2((gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0) + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0), (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0) + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0));
  6462. },
  6463. /**
  6464. * Returns true if the gamepad is currently connected to the system.
  6465. * @return {boolean}
  6466. */
  6467. isConnected: function isConnected() {
  6468. var gamepad = this.getGamepad();
  6469. return !!(gamepad && gamepad.connected);
  6470. },
  6471. /**
  6472. * Returns a string containing some information about the controller. Result
  6473. * may vary across browsers, for a given controller.
  6474. * @return {string}
  6475. */
  6476. getID: function getID() {
  6477. return this.getGamepad().id;
  6478. }
  6479. });
  6480. },{"../../lib/GamepadButton":5,"../../lib/GamepadButtonEvent":6}],14:[function(require,module,exports){
  6481. 'use strict';
  6482. require('./checkpoint-controls');
  6483. require('./gamepad-controls');
  6484. require('./keyboard-controls');
  6485. require('./touch-controls');
  6486. require('./movement-controls');
  6487. require('./trackpad-controls');
  6488. },{"./checkpoint-controls":12,"./gamepad-controls":13,"./keyboard-controls":15,"./movement-controls":16,"./touch-controls":17,"./trackpad-controls":18}],15:[function(require,module,exports){
  6489. 'use strict';
  6490. require('../../lib/keyboard.polyfill');
  6491. var MAX_DELTA = 0.2,
  6492. PROXY_FLAG = '__keyboard-controls-proxy';
  6493. var KeyboardEvent = window.KeyboardEvent;
  6494. /**
  6495. * Keyboard Controls component.
  6496. *
  6497. * Stripped-down version of: https://github.com/donmccurdy/aframe-keyboard-controls
  6498. *
  6499. * Bind keyboard events to components, or control your entities with the WASD keys.
  6500. *
  6501. * Why use KeyboardEvent.code? "This is set to a string representing the key that was pressed to
  6502. * generate the KeyboardEvent, without taking the current keyboard layout (e.g., QWERTY vs.
  6503. * Dvorak), locale (e.g., English vs. French), or any modifier keys into account. This is useful
  6504. * when you care about which physical key was pressed, rather thanwhich character it corresponds
  6505. * to. For example, if you’re a writing a game, you might want a certain set of keys to move the
  6506. * player in different directions, and that mapping should ideally be independent of keyboard
  6507. * layout. See: https://developers.google.com/web/updates/2016/04/keyboardevent-keys-codes
  6508. *
  6509. * @namespace wasd-controls
  6510. * keys the entity moves and if you release it will stop. Easing simulates friction.
  6511. * to the entity when pressing the keys.
  6512. * @param {bool} [enabled=true] - To completely enable or disable the controls
  6513. */
  6514. module.exports = AFRAME.registerComponent('keyboard-controls', {
  6515. schema: {
  6516. enabled: { default: true },
  6517. debug: { default: false }
  6518. },
  6519. init: function init() {
  6520. this.dVelocity = new THREE.Vector3();
  6521. this.localKeys = {};
  6522. this.listeners = {
  6523. keydown: this.onKeyDown.bind(this),
  6524. keyup: this.onKeyUp.bind(this),
  6525. blur: this.onBlur.bind(this)
  6526. };
  6527. this.attachEventListeners();
  6528. },
  6529. /*******************************************************************
  6530. * Movement
  6531. */
  6532. isVelocityActive: function isVelocityActive() {
  6533. return this.data.enabled && !!Object.keys(this.getKeys()).length;
  6534. },
  6535. getVelocityDelta: function getVelocityDelta() {
  6536. var data = this.data,
  6537. keys = this.getKeys();
  6538. this.dVelocity.set(0, 0, 0);
  6539. if (data.enabled) {
  6540. if (keys.KeyW || keys.ArrowUp) {
  6541. this.dVelocity.z -= 1;
  6542. }
  6543. if (keys.KeyA || keys.ArrowLeft) {
  6544. this.dVelocity.x -= 1;
  6545. }
  6546. if (keys.KeyS || keys.ArrowDown) {
  6547. this.dVelocity.z += 1;
  6548. }
  6549. if (keys.KeyD || keys.ArrowRight) {
  6550. this.dVelocity.x += 1;
  6551. }
  6552. }
  6553. return this.dVelocity.clone();
  6554. },
  6555. /*******************************************************************
  6556. * Events
  6557. */
  6558. play: function play() {
  6559. this.attachEventListeners();
  6560. },
  6561. pause: function pause() {
  6562. this.removeEventListeners();
  6563. },
  6564. remove: function remove() {
  6565. this.pause();
  6566. },
  6567. attachEventListeners: function attachEventListeners() {
  6568. window.addEventListener('keydown', this.listeners.keydown, false);
  6569. window.addEventListener('keyup', this.listeners.keyup, false);
  6570. window.addEventListener('blur', this.listeners.blur, false);
  6571. },
  6572. removeEventListeners: function removeEventListeners() {
  6573. window.removeEventListener('keydown', this.listeners.keydown);
  6574. window.removeEventListener('keyup', this.listeners.keyup);
  6575. window.removeEventListener('blur', this.listeners.blur);
  6576. },
  6577. onKeyDown: function onKeyDown(event) {
  6578. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  6579. this.localKeys[event.code] = true;
  6580. this.emit(event);
  6581. }
  6582. },
  6583. onKeyUp: function onKeyUp(event) {
  6584. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  6585. delete this.localKeys[event.code];
  6586. this.emit(event);
  6587. }
  6588. },
  6589. onBlur: function onBlur() {
  6590. for (var code in this.localKeys) {
  6591. if (this.localKeys.hasOwnProperty(code)) {
  6592. delete this.localKeys[code];
  6593. }
  6594. }
  6595. },
  6596. emit: function emit(event) {
  6597. // TODO - keydown only initially?
  6598. // TODO - where the f is the spacebar
  6599. // Emit original event.
  6600. if (PROXY_FLAG in event) {
  6601. // TODO - Method never triggered.
  6602. this.el.emit(event.type, event);
  6603. }
  6604. // Emit convenience event, identifying key.
  6605. this.el.emit(event.type + ':' + event.code, new KeyboardEvent(event.type, event));
  6606. if (this.data.debug) console.log(event.type + ':' + event.code);
  6607. },
  6608. /*******************************************************************
  6609. * Accessors
  6610. */
  6611. isPressed: function isPressed(code) {
  6612. return code in this.getKeys();
  6613. },
  6614. getKeys: function getKeys() {
  6615. if (this.isProxied()) {
  6616. return this.el.sceneEl.components['proxy-controls'].getKeyboard();
  6617. }
  6618. return this.localKeys;
  6619. },
  6620. isProxied: function isProxied() {
  6621. var proxyControls = this.el.sceneEl.components['proxy-controls'];
  6622. return proxyControls && proxyControls.isConnected();
  6623. }
  6624. });
  6625. },{"../../lib/keyboard.polyfill":10}],16:[function(require,module,exports){
  6626. 'use strict';
  6627. /**
  6628. * Movement Controls
  6629. *
  6630. * @author Don McCurdy <dm@donmccurdy.com>
  6631. */
  6632. var COMPONENT_SUFFIX = '-controls',
  6633. MAX_DELTA = 0.2,
  6634. // ms
  6635. EPS = 10e-6;
  6636. module.exports = AFRAME.registerComponent('movement-controls', {
  6637. /*******************************************************************
  6638. * Schema
  6639. */
  6640. dependencies: ['rotation'],
  6641. schema: {
  6642. enabled: { default: true },
  6643. controls: { default: ['gamepad', 'trackpad', 'keyboard', 'touch'] },
  6644. speed: { default: 0.3, min: 0 },
  6645. fly: { default: false },
  6646. constrainToNavMesh: { default: false },
  6647. camera: { default: '[movement-controls] [camera]', type: 'selector' }
  6648. },
  6649. /*******************************************************************
  6650. * Lifecycle
  6651. */
  6652. init: function init() {
  6653. var el = this.el;
  6654. this.velocityCtrl = null;
  6655. this.velocity = new THREE.Vector3();
  6656. this.heading = new THREE.Quaternion();
  6657. // Navigation
  6658. this.navGroup = null;
  6659. this.navNode = null;
  6660. if (el.sceneEl.hasLoaded) {
  6661. this.injectControls();
  6662. } else {
  6663. el.sceneEl.addEventListener('loaded', this.injectControls.bind(this));
  6664. }
  6665. },
  6666. update: function update(prevData) {
  6667. var el = this.el;
  6668. var data = this.data;
  6669. var nav = el.sceneEl.systems.nav;
  6670. if (el.sceneEl.hasLoaded) {
  6671. this.injectControls();
  6672. }
  6673. if (nav && data.constrainToNavMesh !== prevData.constrainToNavMesh) {
  6674. data.constrainToNavMesh ? nav.addAgent(this) : nav.removeAgent(this);
  6675. }
  6676. },
  6677. injectControls: function injectControls() {
  6678. var data = this.data;
  6679. var name;
  6680. for (var i = 0; i < data.controls.length; i++) {
  6681. name = data.controls[i] + COMPONENT_SUFFIX;
  6682. if (!this.el.components[name]) {
  6683. this.el.setAttribute(name, '');
  6684. }
  6685. }
  6686. },
  6687. updateNavLocation: function updateNavLocation() {
  6688. this.navGroup = null;
  6689. this.navNode = null;
  6690. },
  6691. /*******************************************************************
  6692. * Tick
  6693. */
  6694. tick: function () {
  6695. var start = new THREE.Vector3();
  6696. var end = new THREE.Vector3();
  6697. var clampedEnd = new THREE.Vector3();
  6698. return function (t, dt) {
  6699. if (!dt) return;
  6700. var el = this.el;
  6701. var data = this.data;
  6702. if (!data.enabled) return;
  6703. this.updateVelocityCtrl();
  6704. var velocityCtrl = this.velocityCtrl;
  6705. var velocity = this.velocity;
  6706. if (!velocityCtrl) return;
  6707. // Update velocity. If FPS is too low, reset.
  6708. if (dt / 1000 > MAX_DELTA) {
  6709. velocity.set(0, 0, 0);
  6710. } else {
  6711. this.updateVelocity(dt);
  6712. }
  6713. if (data.constrainToNavMesh && velocityCtrl.isNavMeshConstrained !== false) {
  6714. if (velocity.lengthSq() < EPS) return;
  6715. start.copy(el.object3D.position);
  6716. end.copy(velocity).multiplyScalar(dt / 1000).add(start);
  6717. var nav = el.sceneEl.systems.nav;
  6718. this.navGroup = this.navGroup === null ? nav.getGroup(start) : this.navGroup;
  6719. this.navNode = this.navNode || nav.getNode(start, this.navGroup);
  6720. this.navNode = nav.clampStep(start, end, this.navGroup, this.navNode, clampedEnd);
  6721. el.object3D.position.copy(clampedEnd);
  6722. } else if (el.hasAttribute('velocity')) {
  6723. el.setAttribute('velocity', velocity);
  6724. } else {
  6725. el.object3D.position.x += velocity.x * dt / 1000;
  6726. el.object3D.position.y += velocity.y * dt / 1000;
  6727. el.object3D.position.z += velocity.z * dt / 1000;
  6728. }
  6729. };
  6730. }(),
  6731. /*******************************************************************
  6732. * Movement
  6733. */
  6734. updateVelocityCtrl: function updateVelocityCtrl() {
  6735. var data = this.data;
  6736. if (data.enabled) {
  6737. for (var i = 0, l = data.controls.length; i < l; i++) {
  6738. var control = this.el.components[data.controls[i] + COMPONENT_SUFFIX];
  6739. if (control && control.isVelocityActive()) {
  6740. this.velocityCtrl = control;
  6741. return;
  6742. }
  6743. }
  6744. this.velocityCtrl = null;
  6745. }
  6746. },
  6747. updateVelocity: function () {
  6748. var vector2 = new THREE.Vector2();
  6749. var quaternion = new THREE.Quaternion();
  6750. return function (dt) {
  6751. var dVelocity = void 0;
  6752. var el = this.el;
  6753. var control = this.velocityCtrl;
  6754. var velocity = this.velocity;
  6755. var data = this.data;
  6756. if (control) {
  6757. if (control.getVelocityDelta) {
  6758. dVelocity = control.getVelocityDelta(dt);
  6759. } else if (control.getVelocity) {
  6760. velocity.copy(control.getVelocity());
  6761. return;
  6762. } else if (control.getPositionDelta) {
  6763. velocity.copy(control.getPositionDelta(dt).multiplyScalar(1000 / dt));
  6764. return;
  6765. } else {
  6766. throw new Error('Incompatible movement controls: ', control);
  6767. }
  6768. }
  6769. if (el.hasAttribute('velocity') && !data.constrainToNavMesh) {
  6770. velocity.copy(this.el.getAttribute('velocity'));
  6771. }
  6772. if (dVelocity && data.enabled) {
  6773. var cameraEl = data.camera;
  6774. // Rotate to heading
  6775. quaternion.copy(cameraEl.object3D.quaternion);
  6776. quaternion.premultiply(el.object3D.quaternion);
  6777. dVelocity.applyQuaternion(quaternion);
  6778. var factor = dVelocity.length();
  6779. if (data.fly) {
  6780. velocity.copy(dVelocity);
  6781. velocity.multiplyScalar(this.data.speed * 16.66667);
  6782. } else {
  6783. vector2.set(dVelocity.x, dVelocity.z);
  6784. vector2.setLength(factor * this.data.speed * 16.66667);
  6785. velocity.x = vector2.x;
  6786. velocity.z = vector2.y;
  6787. }
  6788. }
  6789. };
  6790. }()
  6791. });
  6792. },{}],17:[function(require,module,exports){
  6793. 'use strict';
  6794. /**
  6795. * Touch-to-move-forward controls for mobile.
  6796. */
  6797. module.exports = AFRAME.registerComponent('touch-controls', {
  6798. schema: {
  6799. enabled: { default: true },
  6800. reverseEnabled: { default: true }
  6801. },
  6802. init: function init() {
  6803. this.dVelocity = new THREE.Vector3();
  6804. this.bindMethods();
  6805. this.direction = 0;
  6806. },
  6807. play: function play() {
  6808. this.addEventListeners();
  6809. },
  6810. pause: function pause() {
  6811. this.removeEventListeners();
  6812. this.dVelocity.set(0, 0, 0);
  6813. },
  6814. remove: function remove() {
  6815. this.pause();
  6816. },
  6817. addEventListeners: function addEventListeners() {
  6818. var sceneEl = this.el.sceneEl;
  6819. var canvasEl = sceneEl.canvas;
  6820. if (!canvasEl) {
  6821. sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this));
  6822. return;
  6823. }
  6824. canvasEl.addEventListener('touchstart', this.onTouchStart);
  6825. canvasEl.addEventListener('touchend', this.onTouchEnd);
  6826. },
  6827. removeEventListeners: function removeEventListeners() {
  6828. var canvasEl = this.el.sceneEl && this.el.sceneEl.canvas;
  6829. if (!canvasEl) {
  6830. return;
  6831. }
  6832. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  6833. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  6834. },
  6835. isVelocityActive: function isVelocityActive() {
  6836. return this.data.enabled && !!this.direction;
  6837. },
  6838. getVelocityDelta: function getVelocityDelta() {
  6839. this.dVelocity.z = this.direction;
  6840. return this.dVelocity.clone();
  6841. },
  6842. bindMethods: function bindMethods() {
  6843. this.onTouchStart = this.onTouchStart.bind(this);
  6844. this.onTouchEnd = this.onTouchEnd.bind(this);
  6845. },
  6846. onTouchStart: function onTouchStart(e) {
  6847. this.direction = -1;
  6848. if (this.data.reverseEnabled && e.touches.length === 2) {
  6849. this.direction = 1;
  6850. }
  6851. e.preventDefault();
  6852. },
  6853. onTouchEnd: function onTouchEnd(e) {
  6854. this.direction = 0;
  6855. e.preventDefault();
  6856. }
  6857. });
  6858. },{}],18:[function(require,module,exports){
  6859. 'use strict';
  6860. /**
  6861. * 3dof (Gear VR, Daydream) controls for mobile.
  6862. */
  6863. module.exports = AFRAME.registerComponent('trackpad-controls', {
  6864. schema: {
  6865. enabled: { default: true },
  6866. enableNegX: { default: true },
  6867. enablePosX: { default: true },
  6868. enableNegZ: { default: true },
  6869. enablePosZ: { default: true },
  6870. mode: { default: 'touch', oneOf: ['swipe', 'touch', 'press'] }
  6871. },
  6872. init: function init() {
  6873. this.dVelocity = new THREE.Vector3();
  6874. this.zVel = 0;
  6875. this.xVel = 0;
  6876. this.bindMethods();
  6877. },
  6878. play: function play() {
  6879. this.addEventListeners();
  6880. },
  6881. pause: function pause() {
  6882. this.removeEventListeners();
  6883. this.dVelocity.set(0, 0, 0);
  6884. },
  6885. remove: function remove() {
  6886. this.pause();
  6887. },
  6888. addEventListeners: function addEventListeners() {
  6889. var data = this.data;
  6890. var sceneEl = this.el.sceneEl;
  6891. sceneEl.addEventListener('axismove', this.onAxisMove);
  6892. switch (data.mode) {
  6893. case 'swipe':
  6894. case 'touch':
  6895. sceneEl.addEventListener('trackpadtouchstart', this.onTouchStart);
  6896. sceneEl.addEventListener('trackpadtouchend', this.onTouchEnd);
  6897. break;
  6898. case 'press':
  6899. sceneEl.addEventListener('trackpaddown', this.onTouchStart);
  6900. sceneEl.addEventListener('trackpadup', this.onTouchEnd);
  6901. break;
  6902. }
  6903. },
  6904. removeEventListeners: function removeEventListeners() {
  6905. var sceneEl = this.el.sceneEl;
  6906. sceneEl.removeEventListener('axismove', this.onAxisMove);
  6907. sceneEl.removeEventListener('trackpadtouchstart', this.onTouchStart);
  6908. sceneEl.removeEventListener('trackpadtouchend', this.onTouchEnd);
  6909. sceneEl.removeEventListener('trackpaddown', this.onTouchStart);
  6910. sceneEl.removeEventListener('trackpadup', this.onTouchEnd);
  6911. },
  6912. isVelocityActive: function isVelocityActive() {
  6913. return this.data.enabled && this.isMoving;
  6914. },
  6915. getVelocityDelta: function getVelocityDelta() {
  6916. this.dVelocity.z = this.isMoving ? -this.zVel : 1;
  6917. this.dVelocity.x = this.isMoving ? this.xVel : 1;
  6918. return this.dVelocity.clone();
  6919. },
  6920. bindMethods: function bindMethods() {
  6921. this.onTouchStart = this.onTouchStart.bind(this);
  6922. this.onTouchEnd = this.onTouchEnd.bind(this);
  6923. this.onAxisMove = this.onAxisMove.bind(this);
  6924. },
  6925. onTouchStart: function onTouchStart(e) {
  6926. switch (this.data.mode) {
  6927. case 'swipe':
  6928. this.canRecordAxis = true;
  6929. this.startingAxisData = [];
  6930. break;
  6931. case 'touch':
  6932. this.isMoving = true;
  6933. break;
  6934. case 'press':
  6935. this.isMoving = true;
  6936. break;
  6937. }
  6938. e.preventDefault();
  6939. },
  6940. onTouchEnd: function onTouchEnd(e) {
  6941. if (this.data.mode == 'swipe') {
  6942. this.startingAxisData = [];
  6943. }
  6944. this.isMoving = false;
  6945. e.preventDefault();
  6946. },
  6947. onAxisMove: function onAxisMove(e) {
  6948. switch (this.data.mode) {
  6949. case 'swipe':
  6950. return this.handleSwipeAxis(e);
  6951. case 'touch':
  6952. case 'press':
  6953. return this.handleTouchAxis(e);
  6954. }
  6955. },
  6956. handleSwipeAxis: function handleSwipeAxis(e) {
  6957. var data = this.data;
  6958. var axisData = e.detail.axis;
  6959. if (this.startingAxisData.length === 0 && this.canRecordAxis) {
  6960. this.canRecordAxis = false;
  6961. this.startingAxisData[0] = axisData[0];
  6962. this.startingAxisData[1] = axisData[1];
  6963. }
  6964. if (this.startingAxisData.length > 0) {
  6965. var velX = 0;
  6966. var velZ = 0;
  6967. if (data.enableNegX && axisData[0] < this.startingAxisData[0]) {
  6968. velX = -1;
  6969. }
  6970. if (data.enablePosX && axisData[0] > this.startingAxisData[0]) {
  6971. velX = 1;
  6972. }
  6973. if (data.enablePosZ && axisData[1] > this.startingAxisData[1]) {
  6974. velZ = -1;
  6975. }
  6976. if (data.enableNegZ && axisData[1] < this.startingAxisData[1]) {
  6977. velZ = 1;
  6978. }
  6979. var absChangeZ = Math.abs(this.startingAxisData[1] - axisData[1]);
  6980. var absChangeX = Math.abs(this.startingAxisData[0] - axisData[0]);
  6981. if (absChangeX > absChangeZ) {
  6982. this.zVel = 0;
  6983. this.xVel = velX;
  6984. this.isMoving = true;
  6985. } else {
  6986. this.xVel = 0;
  6987. this.zVel = velZ;
  6988. this.isMoving = true;
  6989. }
  6990. }
  6991. },
  6992. handleTouchAxis: function handleTouchAxis(e) {
  6993. var data = this.data;
  6994. var axisData = e.detail.axis;
  6995. var velX = 0;
  6996. var velZ = 0;
  6997. if (data.enableNegX && axisData[0] < 0) {
  6998. velX = -1;
  6999. }
  7000. if (data.enablePosX && axisData[0] > 0) {
  7001. velX = 1;
  7002. }
  7003. if (data.enablePosZ && axisData[1] > 0) {
  7004. velZ = -1;
  7005. }
  7006. if (data.enableNegZ && axisData[1] < 0) {
  7007. velZ = 1;
  7008. }
  7009. if (Math.abs(axisData[0]) > Math.abs(axisData[1])) {
  7010. this.zVel = 0;
  7011. this.xVel = velX;
  7012. } else {
  7013. this.xVel = 0;
  7014. this.zVel = velZ;
  7015. }
  7016. }
  7017. });
  7018. },{}],19:[function(require,module,exports){
  7019. 'use strict';
  7020. var LoopMode = {
  7021. once: THREE.LoopOnce,
  7022. repeat: THREE.LoopRepeat,
  7023. pingpong: THREE.LoopPingPong
  7024. };
  7025. /**
  7026. * animation-mixer
  7027. *
  7028. * Player for animation clips. Intended to be compatible with any model format that supports
  7029. * skeletal or morph animations through THREE.AnimationMixer.
  7030. * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
  7031. */
  7032. module.exports = AFRAME.registerComponent('animation-mixer', {
  7033. schema: {
  7034. clip: { default: '*' },
  7035. duration: { default: 0 },
  7036. clampWhenFinished: { default: false, type: 'boolean' },
  7037. crossFadeDuration: { default: 0 },
  7038. loop: { default: 'repeat', oneOf: Object.keys(LoopMode) },
  7039. repetitions: { default: Infinity, min: 0 },
  7040. timeScale: { default: 1 }
  7041. },
  7042. init: function init() {
  7043. var _this = this;
  7044. /** @type {THREE.Mesh} */
  7045. this.model = null;
  7046. /** @type {THREE.AnimationMixer} */
  7047. this.mixer = null;
  7048. /** @type {Array<THREE.AnimationAction>} */
  7049. this.activeActions = [];
  7050. var model = this.el.getObject3D('mesh');
  7051. if (model) {
  7052. this.load(model);
  7053. } else {
  7054. this.el.addEventListener('model-loaded', function (e) {
  7055. _this.load(e.detail.model);
  7056. });
  7057. }
  7058. },
  7059. load: function load(model) {
  7060. var el = this.el;
  7061. this.model = model;
  7062. this.mixer = new THREE.AnimationMixer(model);
  7063. this.mixer.addEventListener('loop', function (e) {
  7064. el.emit('animation-loop', { action: e.action, loopDelta: e.loopDelta });
  7065. });
  7066. this.mixer.addEventListener('finished', function (e) {
  7067. el.emit('animation-finished', { action: e.action, direction: e.direction });
  7068. });
  7069. if (this.data.clip) this.update({});
  7070. },
  7071. remove: function remove() {
  7072. if (this.mixer) this.mixer.stopAllAction();
  7073. },
  7074. update: function update(prevData) {
  7075. if (!prevData) return;
  7076. var data = this.data;
  7077. var changes = AFRAME.utils.diff(data, prevData);
  7078. // If selected clips have changed, restart animation.
  7079. if ('clip' in changes) {
  7080. this.stopAction();
  7081. if (data.clip) this.playAction();
  7082. return;
  7083. }
  7084. // Otherwise, modify running actions.
  7085. this.activeActions.forEach(function (action) {
  7086. if ('duration' in changes && data.duration) {
  7087. action.setDuration(data.duration);
  7088. }
  7089. if ('clampWhenFinished' in changes) {
  7090. action.clampWhenFinished = data.clampWhenFinished;
  7091. }
  7092. if ('loop' in changes || 'repetitions' in changes) {
  7093. action.setLoop(LoopMode[data.loop], data.repetitions);
  7094. }
  7095. if ('timeScale' in changes) {
  7096. action.setEffectiveTimeScale(data.timeScale);
  7097. }
  7098. });
  7099. },
  7100. stopAction: function stopAction() {
  7101. var data = this.data;
  7102. for (var i = 0; i < this.activeActions.length; i++) {
  7103. data.crossFadeDuration ? this.activeActions[i].fadeOut(data.crossFadeDuration) : this.activeActions[i].stop();
  7104. }
  7105. this.activeActions.length = 0;
  7106. },
  7107. playAction: function playAction() {
  7108. if (!this.mixer) return;
  7109. var model = this.model,
  7110. data = this.data,
  7111. clips = model.animations || (model.geometry || {}).animations || [];
  7112. if (!clips.length) return;
  7113. var re = wildcardToRegExp(data.clip);
  7114. for (var clip, i = 0; clip = clips[i]; i++) {
  7115. if (clip.name.match(re)) {
  7116. var action = this.mixer.clipAction(clip, model);
  7117. action.enabled = true;
  7118. action.clampWhenFinished = data.clampWhenFinished;
  7119. if (data.duration) action.setDuration(data.duration);
  7120. if (data.timeScale !== 1) action.setEffectiveTimeScale(data.timeScale);
  7121. action.setLoop(LoopMode[data.loop], data.repetitions).fadeIn(data.crossFadeDuration).play();
  7122. this.activeActions.push(action);
  7123. }
  7124. }
  7125. },
  7126. tick: function tick(t, dt) {
  7127. if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
  7128. }
  7129. });
  7130. /**
  7131. * Creates a RegExp from the given string, converting asterisks to .* expressions,
  7132. * and escaping all other characters.
  7133. */
  7134. function wildcardToRegExp(s) {
  7135. return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
  7136. }
  7137. /**
  7138. * RegExp-escapes all characters in the given string.
  7139. */
  7140. function regExpEscape(s) {
  7141. return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  7142. }
  7143. },{}],20:[function(require,module,exports){
  7144. 'use strict';
  7145. THREE.ColladaLoader = require('../../lib/ColladaLoader');
  7146. /**
  7147. * collada-model-legacy
  7148. *
  7149. * Loader for COLLADA (.dae) format.
  7150. */
  7151. module.exports.Component = AFRAME.registerComponent('collada-model-legacy', {
  7152. schema: { type: 'asset' },
  7153. init: function init() {
  7154. this.model = null;
  7155. this.loader = new THREE.ColladaLoader();
  7156. },
  7157. update: function update() {
  7158. var self = this;
  7159. var el = this.el;
  7160. var src = this.data;
  7161. var rendererSystem = this.el.sceneEl.systems.renderer;
  7162. if (!src) {
  7163. return;
  7164. }
  7165. this.remove();
  7166. this.loader.load(src, function (colladaModel) {
  7167. self.model = colladaModel.scene;
  7168. self.model.traverse(function (object) {
  7169. if (object.isMesh) {
  7170. var material = object.material;
  7171. if (material.color) rendererSystem.applyColorCorrection(material.color);
  7172. if (material.map) rendererSystem.applyColorCorrection(material.map);
  7173. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  7174. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  7175. }
  7176. });
  7177. el.setObject3D('mesh', self.model);
  7178. el.emit('model-loaded', { format: 'collada', model: self.model });
  7179. });
  7180. },
  7181. remove: function remove() {
  7182. if (!this.model) {
  7183. return;
  7184. }
  7185. this.el.removeObject3D('mesh');
  7186. }
  7187. });
  7188. },{"../../lib/ColladaLoader":3}],21:[function(require,module,exports){
  7189. 'use strict';
  7190. THREE.FBXLoader = require('../../lib/FBXLoader');
  7191. /**
  7192. * fbx-model
  7193. *
  7194. * Loader for FBX format. Supports ASCII, but *not* binary, models.
  7195. */
  7196. module.exports = AFRAME.registerComponent('fbx-model', {
  7197. schema: {
  7198. src: { type: 'asset' },
  7199. crossorigin: { default: '' }
  7200. },
  7201. init: function init() {
  7202. this.model = null;
  7203. },
  7204. update: function update() {
  7205. var data = this.data;
  7206. if (!data.src) return;
  7207. this.remove();
  7208. var loader = new THREE.FBXLoader();
  7209. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  7210. loader.load(data.src, this.load.bind(this));
  7211. },
  7212. load: function load(model) {
  7213. this.model = model;
  7214. this.el.setObject3D('mesh', model);
  7215. this.el.emit('model-loaded', { format: 'fbx', model: model });
  7216. },
  7217. remove: function remove() {
  7218. if (this.model) this.el.removeObject3D('mesh');
  7219. }
  7220. });
  7221. },{"../../lib/FBXLoader":4}],22:[function(require,module,exports){
  7222. 'use strict';
  7223. var fetchScript = require('../../lib/fetch-script')();
  7224. var LOADER_SRC = 'https://cdn.jsdelivr.net/gh/mrdoob/three.js@r86/examples/js/loaders/GLTFLoader.js';
  7225. var loadLoader = function () {
  7226. var promise = void 0;
  7227. return function () {
  7228. promise = promise || fetchScript(LOADER_SRC);
  7229. return promise;
  7230. };
  7231. }();
  7232. /**
  7233. * Legacy loader for glTF 1.0 models.
  7234. * Asynchronously loads THREE.GLTFLoader from rawgit.
  7235. */
  7236. module.exports = AFRAME.registerComponent('gltf-model-legacy', {
  7237. schema: { type: 'model' },
  7238. init: function init() {
  7239. var _this = this;
  7240. this.model = null;
  7241. this.loader = null;
  7242. this.loaderPromise = loadLoader().then(function () {
  7243. _this.loader = new THREE.GLTFLoader();
  7244. _this.loader.setCrossOrigin('Anonymous');
  7245. });
  7246. },
  7247. update: function update() {
  7248. var _this2 = this;
  7249. var self = this;
  7250. var el = this.el;
  7251. var src = this.data;
  7252. if (!src) {
  7253. return;
  7254. }
  7255. this.remove();
  7256. this.loaderPromise.then(function () {
  7257. _this2.loader.load(src, function gltfLoaded(gltfModel) {
  7258. self.model = gltfModel.scene;
  7259. self.model.animations = gltfModel.animations;
  7260. el.setObject3D('mesh', self.model);
  7261. el.emit('model-loaded', { format: 'gltf', model: self.model });
  7262. });
  7263. });
  7264. },
  7265. remove: function remove() {
  7266. if (!this.model) {
  7267. return;
  7268. }
  7269. this.el.removeObject3D('mesh');
  7270. }
  7271. });
  7272. },{"../../lib/fetch-script":8}],23:[function(require,module,exports){
  7273. 'use strict';
  7274. require('./animation-mixer');
  7275. require('./collada-model-legacy');
  7276. require('./fbx-model');
  7277. require('./gltf-model-legacy');
  7278. require('./object-model');
  7279. },{"./animation-mixer":19,"./collada-model-legacy":20,"./fbx-model":21,"./gltf-model-legacy":22,"./object-model":24}],24:[function(require,module,exports){
  7280. 'use strict';
  7281. /**
  7282. * object-model
  7283. *
  7284. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  7285. * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
  7286. * includes multiple meshes or an entire scene.
  7287. *
  7288. * Check the console for errors, if in doubt. You may need to use `json-model` or
  7289. * `blend-character-model` for some .js and .json files.
  7290. *
  7291. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  7292. */
  7293. module.exports = AFRAME.registerComponent('object-model', {
  7294. schema: {
  7295. src: { type: 'asset' },
  7296. crossorigin: { default: '' }
  7297. },
  7298. init: function init() {
  7299. this.model = null;
  7300. },
  7301. update: function update() {
  7302. var _this = this;
  7303. var loader = void 0;
  7304. var data = this.data;
  7305. if (!data.src) return;
  7306. this.remove();
  7307. loader = new THREE.ObjectLoader();
  7308. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  7309. loader.load(data.src, function (object) {
  7310. // Enable skinning, if applicable.
  7311. object.traverse(function (o) {
  7312. if (o instanceof THREE.SkinnedMesh && o.material) {
  7313. o.material.skinning = !!(o.geometry && o.geometry.bones || []).length;
  7314. }
  7315. });
  7316. _this.load(object);
  7317. });
  7318. },
  7319. load: function load(model) {
  7320. this.model = model;
  7321. this.el.setObject3D('mesh', model);
  7322. this.el.emit('model-loaded', { format: 'json', model: model });
  7323. },
  7324. remove: function remove() {
  7325. if (this.model) this.el.removeObject3D('mesh');
  7326. }
  7327. });
  7328. },{}],25:[function(require,module,exports){
  7329. 'use strict';
  7330. module.exports = AFRAME.registerComponent('checkpoint', {
  7331. schema: {
  7332. offset: { default: { x: 0, y: 0, z: 0 }, type: 'vec3' }
  7333. },
  7334. init: function init() {
  7335. this.active = false;
  7336. this.targetEl = null;
  7337. this.fire = this.fire.bind(this);
  7338. this.offset = new THREE.Vector3();
  7339. },
  7340. update: function update() {
  7341. this.offset.copy(this.data.offset);
  7342. },
  7343. play: function play() {
  7344. this.el.addEventListener('click', this.fire);
  7345. },
  7346. pause: function pause() {
  7347. this.el.removeEventListener('click', this.fire);
  7348. },
  7349. remove: function remove() {
  7350. this.pause();
  7351. },
  7352. fire: function fire() {
  7353. var targetEl = this.el.sceneEl.querySelector('[checkpoint-controls]');
  7354. if (!targetEl) {
  7355. throw new Error('No `checkpoint-controls` component found.');
  7356. }
  7357. targetEl.components['checkpoint-controls'].setCheckpoint(this.el);
  7358. },
  7359. getOffset: function getOffset() {
  7360. return this.offset.copy(this.data.offset);
  7361. }
  7362. });
  7363. },{}],26:[function(require,module,exports){
  7364. 'use strict';
  7365. /**
  7366. * @param {Array<THREE.Material>|THREE.Material} material
  7367. * @return {Array<THREE.Material>}
  7368. */
  7369. function ensureMaterialArray(material) {
  7370. if (!material) {
  7371. return [];
  7372. } else if (Array.isArray(material)) {
  7373. return material;
  7374. } else if (material.materials) {
  7375. return material.materials;
  7376. } else {
  7377. return [material];
  7378. }
  7379. }
  7380. /**
  7381. * @param {THREE.Object3D} mesh
  7382. * @param {Array<string>} materialNames
  7383. * @param {THREE.Texture} envMap
  7384. * @param {number} reflectivity [description]
  7385. */
  7386. function applyEnvMap(mesh, materialNames, envMap, reflectivity) {
  7387. if (!mesh) return;
  7388. materialNames = materialNames || [];
  7389. mesh.traverse(function (node) {
  7390. if (!node.isMesh) return;
  7391. var meshMaterials = ensureMaterialArray(node.material);
  7392. meshMaterials.forEach(function (material) {
  7393. if (material && !('envMap' in material)) return;
  7394. if (materialNames.length && materialNames.indexOf(material.name) === -1) return;
  7395. material.envMap = envMap;
  7396. material.reflectivity = reflectivity;
  7397. material.needsUpdate = true;
  7398. });
  7399. });
  7400. }
  7401. /**
  7402. * Specifies an envMap on an entity, without replacing any existing material
  7403. * properties.
  7404. */
  7405. module.exports = AFRAME.registerComponent('cube-env-map', {
  7406. multiple: true,
  7407. schema: {
  7408. path: { default: '' },
  7409. extension: { default: 'jpg', oneOf: ['jpg', 'png'] },
  7410. format: { default: 'RGBFormat', oneOf: ['RGBFormat', 'RGBAFormat'] },
  7411. enableBackground: { default: false },
  7412. reflectivity: { default: 1, min: 0, max: 1 },
  7413. materials: { default: [] }
  7414. },
  7415. init: function init() {
  7416. var _this = this;
  7417. var data = this.data;
  7418. this.texture = new THREE.CubeTextureLoader().load([data.path + 'posx.' + data.extension, data.path + 'negx.' + data.extension, data.path + 'posy.' + data.extension, data.path + 'negy.' + data.extension, data.path + 'posz.' + data.extension, data.path + 'negz.' + data.extension]);
  7419. this.texture.format = THREE[data.format];
  7420. this.object3dsetHandler = function () {
  7421. var mesh = _this.el.getObject3D('mesh');
  7422. var data = _this.data;
  7423. applyEnvMap(mesh, data.materials, _this.texture, data.reflectivity);
  7424. };
  7425. this.el.addEventListener('object3dset', this.object3dsetHandler);
  7426. },
  7427. update: function update(oldData) {
  7428. var data = this.data;
  7429. var mesh = this.el.getObject3D('mesh');
  7430. var addedMaterialNames = [];
  7431. var removedMaterialNames = [];
  7432. if (data.materials.length) {
  7433. if (oldData.materials) {
  7434. addedMaterialNames = data.materials.filter(function (name) {
  7435. return !oldData.materials.includes(name);
  7436. });
  7437. removedMaterialNames = oldData.materials.filter(function (name) {
  7438. return !data.materials.includes(name);
  7439. });
  7440. } else {
  7441. addedMaterialNames = data.materials;
  7442. }
  7443. }
  7444. if (addedMaterialNames.length) {
  7445. applyEnvMap(mesh, addedMaterialNames, this.texture, data.reflectivity);
  7446. }
  7447. if (removedMaterialNames.length) {
  7448. applyEnvMap(mesh, removedMaterialNames, null, 1);
  7449. }
  7450. if (oldData.materials && data.reflectivity !== oldData.reflectivity) {
  7451. var maintainedMaterialNames = data.materials.filter(function (name) {
  7452. return oldData.materials.includes(name);
  7453. });
  7454. if (maintainedMaterialNames.length) {
  7455. applyEnvMap(mesh, maintainedMaterialNames, this.texture, data.reflectivity);
  7456. }
  7457. }
  7458. if (this.data.enableBackground && !oldData.enableBackground) {
  7459. this.setBackground(this.texture);
  7460. } else if (!this.data.enableBackground && oldData.enableBackground) {
  7461. this.setBackground(null);
  7462. }
  7463. },
  7464. remove: function remove() {
  7465. this.el.removeEventListener('object3dset', this.object3dsetHandler);
  7466. var mesh = this.el.getObject3D('mesh');
  7467. var data = this.data;
  7468. applyEnvMap(mesh, data.materials, null, 1);
  7469. if (data.enableBackground) this.setBackground(null);
  7470. },
  7471. setBackground: function setBackground(texture) {
  7472. this.el.sceneEl.object3D.background = texture;
  7473. }
  7474. });
  7475. },{}],27:[function(require,module,exports){
  7476. 'use strict';
  7477. /* global CANNON */
  7478. /**
  7479. * Based on aframe/examples/showcase/tracked-controls.
  7480. *
  7481. * Handles events coming from the hand-controls.
  7482. * Determines if the entity is grabbed or released.
  7483. * Updates its position to move along the controller.
  7484. */
  7485. module.exports = AFRAME.registerComponent('grab', {
  7486. init: function init() {
  7487. this.system = this.el.sceneEl.systems.physics;
  7488. this.GRABBED_STATE = 'grabbed';
  7489. this.grabbing = false;
  7490. this.hitEl = /** @type {AFRAME.Element} */null;
  7491. this.physics = /** @type {AFRAME.System} */this.el.sceneEl.systems.physics;
  7492. this.constraint = /** @type {CANNON.Constraint} */null;
  7493. // Bind event handlers
  7494. this.onHit = this.onHit.bind(this);
  7495. this.onGripOpen = this.onGripOpen.bind(this);
  7496. this.onGripClose = this.onGripClose.bind(this);
  7497. },
  7498. play: function play() {
  7499. var el = this.el;
  7500. el.addEventListener('hit', this.onHit);
  7501. el.addEventListener('gripdown', this.onGripClose);
  7502. el.addEventListener('gripup', this.onGripOpen);
  7503. el.addEventListener('trackpaddown', this.onGripClose);
  7504. el.addEventListener('trackpadup', this.onGripOpen);
  7505. el.addEventListener('triggerdown', this.onGripClose);
  7506. el.addEventListener('triggerup', this.onGripOpen);
  7507. },
  7508. pause: function pause() {
  7509. var el = this.el;
  7510. el.removeEventListener('hit', this.onHit);
  7511. el.removeEventListener('gripdown', this.onGripClose);
  7512. el.removeEventListener('gripup', this.onGripOpen);
  7513. el.removeEventListener('trackpaddown', this.onGripClose);
  7514. el.removeEventListener('trackpadup', this.onGripOpen);
  7515. el.removeEventListener('triggerdown', this.onGripClose);
  7516. el.removeEventListener('triggerup', this.onGripOpen);
  7517. },
  7518. onGripClose: function onGripClose() {
  7519. this.grabbing = true;
  7520. },
  7521. onGripOpen: function onGripOpen() {
  7522. var hitEl = this.hitEl;
  7523. this.grabbing = false;
  7524. if (!hitEl) {
  7525. return;
  7526. }
  7527. hitEl.removeState(this.GRABBED_STATE);
  7528. this.hitEl = undefined;
  7529. this.system.removeConstraint(this.constraint);
  7530. this.constraint = null;
  7531. },
  7532. onHit: function onHit(evt) {
  7533. var hitEl = evt.detail.el;
  7534. // If the element is already grabbed (it could be grabbed by another controller).
  7535. // If the hand is not grabbing the element does not stick.
  7536. // If we're already grabbing something you can't grab again.
  7537. if (!hitEl || hitEl.is(this.GRABBED_STATE) || !this.grabbing || this.hitEl) {
  7538. return;
  7539. }
  7540. hitEl.addState(this.GRABBED_STATE);
  7541. this.hitEl = hitEl;
  7542. this.constraint = new CANNON.LockConstraint(this.el.body, hitEl.body);
  7543. this.system.addConstraint(this.constraint);
  7544. }
  7545. });
  7546. },{}],28:[function(require,module,exports){
  7547. 'use strict';
  7548. require('./checkpoint');
  7549. require('./cube-env-map');
  7550. require('./grab');
  7551. require('./jump-ability');
  7552. require('./kinematic-body');
  7553. require('./mesh-smooth');
  7554. require('./normal-material');
  7555. require('./sphere-collider');
  7556. },{"./checkpoint":25,"./cube-env-map":26,"./grab":27,"./jump-ability":29,"./kinematic-body":30,"./mesh-smooth":31,"./normal-material":32,"./sphere-collider":33}],29:[function(require,module,exports){
  7557. 'use strict';
  7558. var ACCEL_G = -9.8,
  7559. // m/s^2
  7560. EASING = -15; // m/s^2
  7561. /**
  7562. * Jump ability.
  7563. */
  7564. module.exports = AFRAME.registerComponent('jump-ability', {
  7565. dependencies: ['velocity'],
  7566. /* Schema
  7567. ——————————————————————————————————————————————*/
  7568. schema: {
  7569. on: { default: 'keydown:Space gamepadbuttondown:0' },
  7570. playerHeight: { default: 1.764 },
  7571. maxJumps: { default: 1 },
  7572. distance: { default: 5 },
  7573. debug: { default: false }
  7574. },
  7575. init: function init() {
  7576. this.velocity = 0;
  7577. this.numJumps = 0;
  7578. var beginJump = this.beginJump.bind(this),
  7579. events = this.data.on.split(' ');
  7580. this.bindings = {};
  7581. for (var i = 0; i < events.length; i++) {
  7582. this.bindings[events[i]] = beginJump;
  7583. this.el.addEventListener(events[i], beginJump);
  7584. }
  7585. this.bindings.collide = this.onCollide.bind(this);
  7586. this.el.addEventListener('collide', this.bindings.collide);
  7587. },
  7588. remove: function remove() {
  7589. for (var event in this.bindings) {
  7590. if (this.bindings.hasOwnProperty(event)) {
  7591. this.el.removeEventListener(event, this.bindings[event]);
  7592. delete this.bindings[event];
  7593. }
  7594. }
  7595. this.el.removeEventListener('collide', this.bindings.collide);
  7596. delete this.bindings.collide;
  7597. },
  7598. beginJump: function beginJump() {
  7599. if (this.numJumps < this.data.maxJumps) {
  7600. var data = this.data,
  7601. initialVelocity = Math.sqrt(-2 * data.distance * (ACCEL_G + EASING)),
  7602. v = this.el.getAttribute('velocity');
  7603. this.el.setAttribute('velocity', { x: v.x, y: initialVelocity, z: v.z });
  7604. this.numJumps++;
  7605. this.el.emit('jumpstart');
  7606. }
  7607. },
  7608. onCollide: function onCollide() {
  7609. if (this.numJumps > 0) this.el.emit('jumpend');
  7610. this.numJumps = 0;
  7611. }
  7612. });
  7613. },{}],30:[function(require,module,exports){
  7614. 'use strict';
  7615. /* global CANNON */
  7616. /**
  7617. * Kinematic body.
  7618. *
  7619. * Managed dynamic body, which moves but is not affected (directly) by the
  7620. * physics engine. This is not a true kinematic body, in the sense that we are
  7621. * letting the physics engine _compute_ collisions against it and selectively
  7622. * applying those collisions to the object. The physics engine does not decide
  7623. * the position/velocity/rotation of the element.
  7624. *
  7625. * Used for the camera object, because full physics simulation would create
  7626. * movement that feels unnatural to the player. Bipedal movement does not
  7627. * translate nicely to rigid body physics.
  7628. *
  7629. * See: http://www.learn-cocos2d.com/2013/08/physics-engine-platformer-terrible-idea/
  7630. * And: http://oxleygamedev.blogspot.com/2011/04/player-physics-part-2.html
  7631. */
  7632. var EPS = 0.000001;
  7633. module.exports = AFRAME.registerComponent('kinematic-body', {
  7634. dependencies: ['velocity'],
  7635. /*******************************************************************
  7636. * Schema
  7637. */
  7638. schema: {
  7639. mass: { default: 5 },
  7640. radius: { default: 1.3 },
  7641. linearDamping: { default: 0.05 },
  7642. enableSlopes: { default: true },
  7643. enableJumps: { default: false }
  7644. },
  7645. /*******************************************************************
  7646. * Lifecycle
  7647. */
  7648. init: function init() {
  7649. this.system = this.el.sceneEl.systems.physics;
  7650. this.system.addComponent(this);
  7651. var el = this.el,
  7652. data = this.data,
  7653. position = new CANNON.Vec3().copy(el.object3D.getWorldPosition(new THREE.Vector3()));
  7654. this.body = new CANNON.Body({
  7655. material: this.system.getMaterial('staticMaterial'),
  7656. position: position,
  7657. mass: data.mass,
  7658. linearDamping: data.linearDamping,
  7659. fixedRotation: true
  7660. });
  7661. this.body.addShape(new CANNON.Sphere(data.radius), new CANNON.Vec3(0, data.radius, 0));
  7662. this.body.el = this.el;
  7663. this.el.body = this.body;
  7664. this.system.addBody(this.body);
  7665. if (el.hasAttribute('wasd-controls')) {
  7666. console.warn('[kinematic-body] Not compatible with wasd-controls, use movement-controls.');
  7667. }
  7668. },
  7669. remove: function remove() {
  7670. this.system.removeBody(this.body);
  7671. this.system.removeComponent(this);
  7672. delete this.el.body;
  7673. },
  7674. /*******************************************************************
  7675. * Update
  7676. */
  7677. /**
  7678. * Checks CANNON.World for collisions and attempts to apply them to the
  7679. * element automatically, in a player-friendly way.
  7680. *
  7681. * There's extra logic for horizontal surfaces here. The basic requirements:
  7682. * (1) Only apply gravity when not in contact with _any_ horizontal surface.
  7683. * (2) When moving, project the velocity against exactly one ground surface.
  7684. * If in contact with two ground surfaces (e.g. ground + ramp), choose
  7685. * the one that collides with current velocity, if any.
  7686. */
  7687. beforeStep: function beforeStep(t, dt) {
  7688. if (!dt) return;
  7689. var el = this.el;
  7690. var data = this.data;
  7691. var body = this.body;
  7692. if (!data.enableJumps) body.velocity.set(0, 0, 0);
  7693. body.position.copy(el.getAttribute('position'));
  7694. },
  7695. step: function () {
  7696. var velocity = new THREE.Vector3(),
  7697. normalizedVelocity = new THREE.Vector3(),
  7698. currentSurfaceNormal = new THREE.Vector3(),
  7699. groundNormal = new THREE.Vector3();
  7700. return function (t, dt) {
  7701. if (!dt) return;
  7702. var body = this.body,
  7703. data = this.data,
  7704. didCollide = false,
  7705. height = void 0,
  7706. groundHeight = -Infinity,
  7707. groundBody = void 0,
  7708. contacts = this.system.getContacts();
  7709. dt = Math.min(dt, this.system.data.maxInterval * 1000);
  7710. groundNormal.set(0, 0, 0);
  7711. velocity.copy(this.el.getAttribute('velocity'));
  7712. body.velocity.copy(velocity);
  7713. for (var i = 0, contact; contact = contacts[i]; i++) {
  7714. // 1. Find any collisions involving this element. Get the contact
  7715. // normal, and make sure it's oriented _out_ of the other object and
  7716. // enabled (body.collisionReponse is true for both bodies)
  7717. if (!contact.enabled) {
  7718. continue;
  7719. }
  7720. if (body.id === contact.bi.id) {
  7721. contact.ni.negate(currentSurfaceNormal);
  7722. } else if (body.id === contact.bj.id) {
  7723. currentSurfaceNormal.copy(contact.ni);
  7724. } else {
  7725. continue;
  7726. }
  7727. didCollide = body.velocity.dot(currentSurfaceNormal) < -EPS;
  7728. if (didCollide && currentSurfaceNormal.y <= 0.5) {
  7729. // 2. If current trajectory attempts to move _through_ another
  7730. // object, project the velocity against the collision plane to
  7731. // prevent passing through.
  7732. velocity.projectOnPlane(currentSurfaceNormal);
  7733. } else if (currentSurfaceNormal.y > 0.5) {
  7734. // 3. If in contact with something roughly horizontal (+/- 45º) then
  7735. // consider that the current ground. Only the highest qualifying
  7736. // ground is retained.
  7737. height = body.id === contact.bi.id ? Math.abs(contact.rj.y + contact.bj.position.y) : Math.abs(contact.ri.y + contact.bi.position.y);
  7738. if (height > groundHeight) {
  7739. groundHeight = height;
  7740. groundNormal.copy(currentSurfaceNormal);
  7741. groundBody = body.id === contact.bi.id ? contact.bj : contact.bi;
  7742. }
  7743. }
  7744. }
  7745. normalizedVelocity.copy(velocity).normalize();
  7746. if (groundBody && (!data.enableJumps || normalizedVelocity.y < 0.5)) {
  7747. if (!data.enableSlopes) {
  7748. groundNormal.set(0, 1, 0);
  7749. } else if (groundNormal.y < 1 - EPS) {
  7750. groundNormal.copy(this.raycastToGround(groundBody, groundNormal));
  7751. }
  7752. // 4. Project trajectory onto the top-most ground object, unless
  7753. // trajectory is > 45º.
  7754. velocity.projectOnPlane(groundNormal);
  7755. } else if (this.system.driver.world) {
  7756. // 5. If not in contact with anything horizontal, apply world gravity.
  7757. // TODO - Why is the 4x scalar necessary.
  7758. // NOTE: Does not work if physics runs on a worker.
  7759. velocity.add(this.system.driver.world.gravity.scale(dt * 4.0 / 1000));
  7760. }
  7761. body.velocity.copy(velocity);
  7762. this.el.setAttribute('velocity', body.velocity);
  7763. this.el.setAttribute('position', body.position);
  7764. };
  7765. }(),
  7766. /**
  7767. * When walking on complex surfaces (trimeshes, borders between two shapes),
  7768. * the collision normals returned for the player sphere can be very
  7769. * inconsistent. To address this, raycast straight down, find the collision
  7770. * normal, and return whichever normal is more vertical.
  7771. * @param {CANNON.Body} groundBody
  7772. * @param {CANNON.Vec3} groundNormal
  7773. * @return {CANNON.Vec3}
  7774. */
  7775. raycastToGround: function raycastToGround(groundBody, groundNormal) {
  7776. var ray = void 0,
  7777. hitNormal = void 0,
  7778. vFrom = this.body.position,
  7779. vTo = this.body.position.clone();
  7780. ray = new CANNON.Ray(vFrom, vTo);
  7781. ray._updateDirection(); // TODO - Report bug.
  7782. ray.intersectBody(groundBody);
  7783. if (!ray.hasHit) return groundNormal;
  7784. // Compare ABS, in case we're projecting against the inside of the face.
  7785. hitNormal = ray.result.hitNormalWorld;
  7786. return Math.abs(hitNormal.y) > Math.abs(groundNormal.y) ? hitNormal : groundNormal;
  7787. }
  7788. });
  7789. },{}],31:[function(require,module,exports){
  7790. 'use strict';
  7791. /**
  7792. * Apply this component to models that looks "blocky", to have Three.js compute
  7793. * vertex normals on the fly for a "smoother" look.
  7794. */
  7795. module.exports = AFRAME.registerComponent('mesh-smooth', {
  7796. init: function init() {
  7797. this.el.addEventListener('model-loaded', function (e) {
  7798. e.detail.model.traverse(function (node) {
  7799. if (node.isMesh) node.geometry.computeVertexNormals();
  7800. });
  7801. });
  7802. }
  7803. });
  7804. },{}],32:[function(require,module,exports){
  7805. 'use strict';
  7806. /**
  7807. * Recursively applies a MeshNormalMaterial to the entity, such that
  7808. * face colors are determined by their orientation. Helpful for
  7809. * debugging geometry
  7810. */
  7811. module.exports = AFRAME.registerComponent('normal-material', {
  7812. init: function init() {
  7813. this.material = new THREE.MeshNormalMaterial({ flatShading: true });
  7814. this.applyMaterial = this.applyMaterial.bind(this);
  7815. this.el.addEventListener('object3dset', this.applyMaterial);
  7816. },
  7817. remove: function remove() {
  7818. this.el.removeEventListener('object3dset', this.applyMaterial);
  7819. },
  7820. applyMaterial: function applyMaterial() {
  7821. var _this = this;
  7822. this.el.object3D.traverse(function (node) {
  7823. if (node.isMesh) node.material = _this.material;
  7824. });
  7825. }
  7826. });
  7827. },{}],33:[function(require,module,exports){
  7828. 'use strict';
  7829. /**
  7830. * Based on aframe/examples/showcase/tracked-controls.
  7831. *
  7832. * Implement bounding sphere collision detection for entities with a mesh.
  7833. * Sets the specified state on the intersected entities.
  7834. *
  7835. * @property {string} objects - Selector of the entities to test for collision.
  7836. * @property {string} state - State to set on collided entities.
  7837. *
  7838. */
  7839. module.exports = AFRAME.registerComponent('sphere-collider', {
  7840. schema: {
  7841. objects: { default: '' },
  7842. state: { default: 'collided' },
  7843. radius: { default: 0.05 },
  7844. watch: { default: true }
  7845. },
  7846. init: function init() {
  7847. /** @type {MutationObserver} */
  7848. this.observer = null;
  7849. /** @type {Array<Element>} Elements to watch for collisions. */
  7850. this.els = [];
  7851. /** @type {Array<Element>} Elements currently in collision state. */
  7852. this.collisions = [];
  7853. this.handleHit = this.handleHit.bind(this);
  7854. this.handleHitEnd = this.handleHitEnd.bind(this);
  7855. },
  7856. remove: function remove() {
  7857. this.pause();
  7858. },
  7859. play: function play() {
  7860. var sceneEl = this.el.sceneEl;
  7861. if (this.data.watch) {
  7862. this.observer = new MutationObserver(this.update.bind(this, null));
  7863. this.observer.observe(sceneEl, { childList: true, subtree: true });
  7864. }
  7865. },
  7866. pause: function pause() {
  7867. if (this.observer) {
  7868. this.observer.disconnect();
  7869. this.observer = null;
  7870. }
  7871. },
  7872. /**
  7873. * Update list of entities to test for collision.
  7874. */
  7875. update: function update() {
  7876. var data = this.data;
  7877. var objectEls = void 0;
  7878. // Push entities into list of els to intersect.
  7879. if (data.objects) {
  7880. objectEls = this.el.sceneEl.querySelectorAll(data.objects);
  7881. } else {
  7882. // If objects not defined, intersect with everything.
  7883. objectEls = this.el.sceneEl.children;
  7884. }
  7885. // Convert from NodeList to Array
  7886. this.els = Array.prototype.slice.call(objectEls);
  7887. },
  7888. tick: function () {
  7889. var position = new THREE.Vector3(),
  7890. meshPosition = new THREE.Vector3(),
  7891. colliderScale = new THREE.Vector3(),
  7892. size = new THREE.Vector3(),
  7893. box = new THREE.Box3(),
  7894. distanceMap = new Map();
  7895. return function () {
  7896. var el = this.el,
  7897. data = this.data,
  7898. mesh = el.getObject3D('mesh'),
  7899. collisions = [];
  7900. var colliderRadius = void 0;
  7901. if (!mesh) {
  7902. return;
  7903. }
  7904. distanceMap.clear();
  7905. el.object3D.getWorldPosition(position);
  7906. el.object3D.getWorldScale(colliderScale);
  7907. colliderRadius = data.radius * scaleFactor(colliderScale);
  7908. // Update collision list.
  7909. this.els.forEach(intersect);
  7910. // Emit events and add collision states, in order of distance.
  7911. collisions.sort(function (a, b) {
  7912. return distanceMap.get(a) > distanceMap.get(b) ? 1 : -1;
  7913. }).forEach(this.handleHit);
  7914. // Remove collision state from current element.
  7915. if (collisions.length === 0) {
  7916. el.emit('hit', { el: null });
  7917. }
  7918. // Remove collision state from other elements.
  7919. this.collisions.filter(function (el) {
  7920. return !distanceMap.has(el);
  7921. }).forEach(this.handleHitEnd);
  7922. // Store new collisions
  7923. this.collisions = collisions;
  7924. // Bounding sphere collision detection
  7925. function intersect(el) {
  7926. var radius = void 0,
  7927. mesh = void 0,
  7928. distance = void 0,
  7929. extent = void 0;
  7930. if (!el.isEntity) {
  7931. return;
  7932. }
  7933. mesh = el.getObject3D('mesh');
  7934. if (!mesh) {
  7935. return;
  7936. }
  7937. box.setFromObject(mesh).getSize(size);
  7938. extent = Math.max(size.x, size.y, size.z) / 2;
  7939. radius = Math.sqrt(2 * extent * extent);
  7940. box.getCenter(meshPosition);
  7941. if (!radius) {
  7942. return;
  7943. }
  7944. distance = position.distanceTo(meshPosition);
  7945. if (distance < radius + colliderRadius) {
  7946. collisions.push(el);
  7947. distanceMap.set(el, distance);
  7948. }
  7949. }
  7950. // use max of scale factors to maintain bounding sphere collision
  7951. function scaleFactor(scaleVec) {
  7952. return Math.max.apply(null, scaleVec.toArray());
  7953. }
  7954. };
  7955. }(),
  7956. handleHit: function handleHit(targetEl) {
  7957. targetEl.emit('hit');
  7958. targetEl.addState(this.data.state);
  7959. this.el.emit('hit', { el: targetEl });
  7960. },
  7961. handleHitEnd: function handleHitEnd(targetEl) {
  7962. targetEl.emit('hitend');
  7963. targetEl.removeState(this.data.state);
  7964. this.el.emit('hitend', { el: targetEl });
  7965. }
  7966. });
  7967. },{}],34:[function(require,module,exports){
  7968. 'use strict';
  7969. require('./nav-mesh');
  7970. require('./nav-agent');
  7971. require('./system');
  7972. },{"./nav-agent":35,"./nav-mesh":36,"./system":37}],35:[function(require,module,exports){
  7973. 'use strict';
  7974. module.exports = AFRAME.registerComponent('nav-agent', {
  7975. schema: {
  7976. destination: { type: 'vec3' },
  7977. active: { default: false },
  7978. speed: { default: 2 }
  7979. },
  7980. init: function init() {
  7981. this.system = this.el.sceneEl.systems.nav;
  7982. this.system.addAgent(this);
  7983. this.group = null;
  7984. this.path = [];
  7985. this.raycaster = new THREE.Raycaster();
  7986. },
  7987. remove: function remove() {
  7988. this.system.removeAgent(this);
  7989. },
  7990. update: function update() {
  7991. this.path.length = 0;
  7992. },
  7993. updateNavLocation: function updateNavLocation() {
  7994. this.group = null;
  7995. this.path = [];
  7996. },
  7997. tick: function () {
  7998. var vDest = new THREE.Vector3();
  7999. var vDelta = new THREE.Vector3();
  8000. var vNext = new THREE.Vector3();
  8001. return function (t, dt) {
  8002. var el = this.el;
  8003. var data = this.data;
  8004. var raycaster = this.raycaster;
  8005. var speed = data.speed * dt / 1000;
  8006. if (!data.active) return;
  8007. // Use PatrolJS pathfinding system to get shortest path to target.
  8008. if (!this.path.length) {
  8009. var position = this.el.object3D.position;
  8010. this.group = this.group || this.system.getGroup(position);
  8011. this.path = this.system.getPath(position, vDest.copy(data.destination), this.group) || [];
  8012. el.emit('navigation-start');
  8013. }
  8014. // If no path is found, exit.
  8015. if (!this.path.length) {
  8016. console.warn('[nav] Unable to find path to %o.', data.destination);
  8017. this.el.setAttribute('nav-agent', { active: false });
  8018. el.emit('navigation-end');
  8019. return;
  8020. }
  8021. // Current segment is a vector from current position to next waypoint.
  8022. var vCurrent = el.object3D.position;
  8023. var vWaypoint = this.path[0];
  8024. vDelta.subVectors(vWaypoint, vCurrent);
  8025. var distance = vDelta.length();
  8026. var gazeTarget = void 0;
  8027. if (distance < speed) {
  8028. // If <1 step from current waypoint, discard it and move toward next.
  8029. this.path.shift();
  8030. // After discarding the last waypoint, exit pathfinding.
  8031. if (!this.path.length) {
  8032. this.el.setAttribute('nav-agent', { active: false });
  8033. el.emit('navigation-end');
  8034. return;
  8035. }
  8036. vNext.copy(vCurrent);
  8037. gazeTarget = this.path[0];
  8038. } else {
  8039. // If still far away from next waypoint, find next position for
  8040. // the current frame.
  8041. vNext.copy(vDelta.setLength(speed)).add(vCurrent);
  8042. gazeTarget = vWaypoint;
  8043. }
  8044. // Look at the next waypoint.
  8045. gazeTarget.y = vCurrent.y;
  8046. el.object3D.lookAt(gazeTarget);
  8047. // Raycast against the nav mesh, to keep the agent moving along the
  8048. // ground, not traveling in a straight line from higher to lower waypoints.
  8049. raycaster.ray.origin.copy(vNext);
  8050. raycaster.ray.origin.y += 1.5;
  8051. raycaster.ray.direction.y = -1;
  8052. var intersections = raycaster.intersectObject(this.system.getNavMesh());
  8053. if (!intersections.length) {
  8054. // Raycasting failed. Step toward the waypoint and hope for the best.
  8055. vCurrent.copy(vNext);
  8056. } else {
  8057. // Re-project next position onto nav mesh.
  8058. vDelta.subVectors(intersections[0].point, vCurrent);
  8059. vCurrent.add(vDelta.setLength(speed));
  8060. }
  8061. };
  8062. }()
  8063. });
  8064. },{}],36:[function(require,module,exports){
  8065. 'use strict';
  8066. /**
  8067. * nav-mesh
  8068. *
  8069. * Waits for a mesh to be loaded on the current entity, then sets it as the
  8070. * nav mesh in the pathfinding system.
  8071. */
  8072. module.exports = AFRAME.registerComponent('nav-mesh', {
  8073. init: function init() {
  8074. this.system = this.el.sceneEl.systems.nav;
  8075. this.hasLoadedNavMesh = false;
  8076. this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
  8077. },
  8078. play: function play() {
  8079. if (!this.hasLoadedNavMesh) this.loadNavMesh();
  8080. },
  8081. loadNavMesh: function loadNavMesh() {
  8082. var object = this.el.getObject3D('mesh');
  8083. var scene = this.el.sceneEl.object3D;
  8084. if (!object) return;
  8085. var navMesh = void 0;
  8086. object.traverse(function (node) {
  8087. if (node.isMesh) navMesh = node;
  8088. });
  8089. if (!navMesh) return;
  8090. var navMeshGeometry = navMesh.geometry.isBufferGeometry ? new THREE.Geometry().fromBufferGeometry(navMesh.geometry) : navMesh.geometry.clone();
  8091. scene.updateMatrixWorld();
  8092. navMeshGeometry.applyMatrix(navMesh.matrixWorld);
  8093. this.system.setNavMeshGeometry(navMeshGeometry);
  8094. this.hasLoadedNavMesh = true;
  8095. }
  8096. });
  8097. },{}],37:[function(require,module,exports){
  8098. 'use strict';
  8099. var _require = require('three-pathfinding'),
  8100. Pathfinding = _require.Pathfinding;
  8101. var pathfinder = new Pathfinding();
  8102. var ZONE = 'level';
  8103. /**
  8104. * nav
  8105. *
  8106. * Pathfinding system, using PatrolJS.
  8107. */
  8108. module.exports = AFRAME.registerSystem('nav', {
  8109. init: function init() {
  8110. this.navMesh = null;
  8111. this.agents = new Set();
  8112. },
  8113. /**
  8114. * @param {THREE.Geometry} geometry
  8115. */
  8116. setNavMeshGeometry: function setNavMeshGeometry(geometry) {
  8117. this.navMesh = new THREE.Mesh(geometry);
  8118. pathfinder.setZoneData(ZONE, Pathfinding.createZone(geometry));
  8119. Array.from(this.agents).forEach(function (agent) {
  8120. return agent.updateNavLocation();
  8121. });
  8122. },
  8123. /**
  8124. * @return {THREE.Mesh}
  8125. */
  8126. getNavMesh: function getNavMesh() {
  8127. return this.navMesh;
  8128. },
  8129. /**
  8130. * @param {NavAgent} ctrl
  8131. */
  8132. addAgent: function addAgent(ctrl) {
  8133. this.agents.add(ctrl);
  8134. },
  8135. /**
  8136. * @param {NavAgent} ctrl
  8137. */
  8138. removeAgent: function removeAgent(ctrl) {
  8139. this.agents.delete(ctrl);
  8140. },
  8141. /**
  8142. * @param {THREE.Vector3} start
  8143. * @param {THREE.Vector3} end
  8144. * @param {number} groupID
  8145. * @return {Array<THREE.Vector3>}
  8146. */
  8147. getPath: function getPath(start, end, groupID) {
  8148. return this.navMesh ? pathfinder.findPath(start, end, ZONE, groupID) : null;
  8149. },
  8150. /**
  8151. * @param {THREE.Vector3} position
  8152. * @return {number}
  8153. */
  8154. getGroup: function getGroup(position) {
  8155. return this.navMesh ? pathfinder.getGroup(ZONE, position) : null;
  8156. },
  8157. /**
  8158. * @param {THREE.Vector3} position
  8159. * @param {number} groupID
  8160. * @return {Node}
  8161. */
  8162. getNode: function getNode(position, groupID) {
  8163. return this.navMesh ? pathfinder.getClosestNode(position, ZONE, groupID, true) : null;
  8164. },
  8165. /**
  8166. * @param {THREE.Vector3} start Starting position.
  8167. * @param {THREE.Vector3} end Desired ending position.
  8168. * @param {number} groupID
  8169. * @param {Node} node
  8170. * @param {THREE.Vector3} endTarget (Output) Adjusted step end position.
  8171. * @return {Node} Current node, after step is taken.
  8172. */
  8173. clampStep: function clampStep(start, end, groupID, node, endTarget) {
  8174. if (!this.navMesh) {
  8175. endTarget.copy(end);
  8176. return null;
  8177. } else if (!node) {
  8178. endTarget.copy(end);
  8179. return this.getNode(end, groupID);
  8180. }
  8181. return pathfinder.clampStep(start, end, node, ZONE, groupID, endTarget);
  8182. }
  8183. });
  8184. },{"three-pathfinding":11}],38:[function(require,module,exports){
  8185. 'use strict';
  8186. /**
  8187. * Flat grid.
  8188. *
  8189. * Defaults to 75x75.
  8190. */
  8191. module.exports = AFRAME.registerPrimitive('a-grid', {
  8192. defaultComponents: {
  8193. geometry: {
  8194. primitive: 'plane',
  8195. width: 75,
  8196. height: 75
  8197. },
  8198. rotation: { x: -90, y: 0, z: 0 },
  8199. material: {
  8200. src: 'url(https://cdn.jsdelivr.net/gh/donmccurdy/aframe-extras@v1.16.3/assets/grid.png)',
  8201. repeat: '75 75'
  8202. }
  8203. },
  8204. mappings: {
  8205. width: 'geometry.width',
  8206. height: 'geometry.height',
  8207. src: 'material.src'
  8208. }
  8209. });
  8210. },{}],39:[function(require,module,exports){
  8211. 'use strict';
  8212. var vg = require('../../lib/hex-grid.min.js');
  8213. var defaultHexGrid = require('../../lib/default-hex-grid');
  8214. /**
  8215. * Hex grid.
  8216. */
  8217. module.exports.Primitive = AFRAME.registerPrimitive('a-hexgrid', {
  8218. defaultComponents: {
  8219. 'hexgrid': {}
  8220. },
  8221. mappings: {
  8222. src: 'hexgrid.src'
  8223. }
  8224. });
  8225. module.exports.Component = AFRAME.registerComponent('hexgrid', {
  8226. dependencies: ['material'],
  8227. schema: {
  8228. src: { type: 'asset' }
  8229. },
  8230. init: function init() {
  8231. var _this = this;
  8232. var data = this.data;
  8233. if (data.src) {
  8234. fetch(data.src).then(function (response) {
  8235. return response.json();
  8236. }).then(function (json) {
  8237. return _this.addMesh(json);
  8238. });
  8239. } else {
  8240. this.addMesh(defaultHexGrid);
  8241. }
  8242. },
  8243. addMesh: function addMesh(json) {
  8244. var grid = new vg.HexGrid();
  8245. grid.fromJSON(json);
  8246. var board = new vg.Board(grid);
  8247. board.generateTilemap();
  8248. this.el.setObject3D('mesh', board.group);
  8249. this.addMaterial();
  8250. },
  8251. addMaterial: function addMaterial() {
  8252. var materialComponent = this.el.components.material;
  8253. var material = (materialComponent || {}).material;
  8254. if (!material) return;
  8255. this.el.object3D.traverse(function (node) {
  8256. if (node.isMesh) {
  8257. node.material = material;
  8258. }
  8259. });
  8260. },
  8261. remove: function remove() {
  8262. this.el.removeObject3D('mesh');
  8263. }
  8264. });
  8265. },{"../../lib/default-hex-grid":7,"../../lib/hex-grid.min.js":9}],40:[function(require,module,exports){
  8266. 'use strict';
  8267. /**
  8268. * Flat-shaded ocean primitive.
  8269. *
  8270. * Based on a Codrops tutorial:
  8271. * http://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/
  8272. */
  8273. module.exports.Primitive = AFRAME.registerPrimitive('a-ocean', {
  8274. defaultComponents: {
  8275. ocean: {},
  8276. rotation: { x: -90, y: 0, z: 0 }
  8277. },
  8278. mappings: {
  8279. width: 'ocean.width',
  8280. depth: 'ocean.depth',
  8281. density: 'ocean.density',
  8282. amplitude: 'ocean.amplitude',
  8283. amplitudeVariance: 'ocean.amplitudeVariance',
  8284. speed: 'ocean.speed',
  8285. speedVariance: 'ocean.speedVariance',
  8286. color: 'ocean.color',
  8287. opacity: 'ocean.opacity'
  8288. }
  8289. });
  8290. module.exports.Component = AFRAME.registerComponent('ocean', {
  8291. schema: {
  8292. // Dimensions of the ocean area.
  8293. width: { default: 10, min: 0 },
  8294. depth: { default: 10, min: 0 },
  8295. // Density of waves.
  8296. density: { default: 10 },
  8297. // Wave amplitude and variance.
  8298. amplitude: { default: 0.1 },
  8299. amplitudeVariance: { default: 0.3 },
  8300. // Wave speed and variance.
  8301. speed: { default: 1 },
  8302. speedVariance: { default: 2 },
  8303. // Material.
  8304. color: { default: '#7AD2F7', type: 'color' },
  8305. opacity: { default: 0.8 }
  8306. },
  8307. /**
  8308. * Use play() instead of init(), because component mappings – unavailable as dependencies – are
  8309. * not guaranteed to have parsed when this component is initialized.
  8310. */
  8311. play: function play() {
  8312. var el = this.el,
  8313. data = this.data;
  8314. var material = el.components.material;
  8315. var geometry = new THREE.PlaneGeometry(data.width, data.depth, data.density, data.density);
  8316. geometry.mergeVertices();
  8317. this.waves = [];
  8318. for (var v, i = 0, l = geometry.vertices.length; i < l; i++) {
  8319. v = geometry.vertices[i];
  8320. this.waves.push({
  8321. z: v.z,
  8322. ang: Math.random() * Math.PI * 2,
  8323. amp: data.amplitude + Math.random() * data.amplitudeVariance,
  8324. speed: (data.speed + Math.random() * data.speedVariance) / 1000 // radians / frame
  8325. });
  8326. }
  8327. if (!material) {
  8328. material = {};
  8329. material.material = new THREE.MeshPhongMaterial({
  8330. color: data.color,
  8331. transparent: data.opacity < 1,
  8332. opacity: data.opacity,
  8333. shading: THREE.FlatShading
  8334. });
  8335. }
  8336. this.mesh = new THREE.Mesh(geometry, material.material);
  8337. el.setObject3D('mesh', this.mesh);
  8338. },
  8339. remove: function remove() {
  8340. this.el.removeObject3D('mesh');
  8341. },
  8342. tick: function tick(t, dt) {
  8343. if (!dt) return;
  8344. var verts = this.mesh.geometry.vertices;
  8345. for (var v, vprops, i = 0; v = verts[i]; i++) {
  8346. vprops = this.waves[i];
  8347. v.z = vprops.z + Math.sin(vprops.ang) * vprops.amp;
  8348. vprops.ang += vprops.speed * dt;
  8349. }
  8350. this.mesh.geometry.verticesNeedUpdate = true;
  8351. }
  8352. });
  8353. },{}],41:[function(require,module,exports){
  8354. 'use strict';
  8355. /**
  8356. * Tube following a custom path.
  8357. *
  8358. * Usage:
  8359. *
  8360. * ```html
  8361. * <a-tube path="5 0 5, 5 0 -5, -5 0 -5" radius="0.5"></a-tube>
  8362. * ```
  8363. */
  8364. module.exports.Primitive = AFRAME.registerPrimitive('a-tube', {
  8365. defaultComponents: {
  8366. tube: {}
  8367. },
  8368. mappings: {
  8369. path: 'tube.path',
  8370. segments: 'tube.segments',
  8371. radius: 'tube.radius',
  8372. 'radial-segments': 'tube.radialSegments',
  8373. closed: 'tube.closed'
  8374. }
  8375. });
  8376. module.exports.Component = AFRAME.registerComponent('tube', {
  8377. schema: {
  8378. path: { default: [] },
  8379. segments: { default: 64 },
  8380. radius: { default: 1 },
  8381. radialSegments: { default: 8 },
  8382. closed: { default: false }
  8383. },
  8384. init: function init() {
  8385. var el = this.el,
  8386. data = this.data;
  8387. var material = el.components.material;
  8388. if (!data.path.length) {
  8389. console.error('[a-tube] `path` property expected but not found.');
  8390. return;
  8391. }
  8392. var curve = new THREE.CatmullRomCurve3(data.path.map(function (point) {
  8393. point = point.split(' ');
  8394. return new THREE.Vector3(Number(point[0]), Number(point[1]), Number(point[2]));
  8395. }));
  8396. var geometry = new THREE.TubeGeometry(curve, data.segments, data.radius, data.radialSegments, data.closed);
  8397. if (!material) {
  8398. material = {};
  8399. material.material = new THREE.MeshPhongMaterial();
  8400. }
  8401. this.mesh = new THREE.Mesh(geometry, material.material);
  8402. this.el.setObject3D('mesh', this.mesh);
  8403. },
  8404. update: function update(prevData) {
  8405. if (!Object.keys(prevData).length) return;
  8406. this.remove();
  8407. this.init();
  8408. },
  8409. remove: function remove() {
  8410. if (this.mesh) this.el.removeObject3D('mesh');
  8411. }
  8412. });
  8413. },{}],42:[function(require,module,exports){
  8414. 'use strict';
  8415. require('./a-grid');
  8416. require('./a-hexgrid');
  8417. require('./a-ocean');
  8418. require('./a-tube');
  8419. },{"./a-grid":38,"./a-hexgrid":39,"./a-ocean":40,"./a-tube":41}]},{},[1]);