aframe-extras.loaders.js 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634
  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('./src/loaders');
  4. },{"./src/loaders":9}],2:[function(require,module,exports){
  5. 'use strict';
  6. /**
  7. * @author mrdoob / http://mrdoob.com/
  8. * @author Mugen87 / https://github.com/Mugen87
  9. */
  10. module.exports = THREE.ColladaLoader = function (manager) {
  11. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  12. };
  13. THREE.ColladaLoader.prototype = {
  14. constructor: THREE.ColladaLoader,
  15. crossOrigin: 'anonymous',
  16. load: function load(url, onLoad, onProgress, onError) {
  17. var scope = this;
  18. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase(url) : scope.path;
  19. var loader = new THREE.FileLoader(scope.manager);
  20. loader.setPath(scope.path);
  21. loader.load(url, function (text) {
  22. onLoad(scope.parse(text, path));
  23. }, onProgress, onError);
  24. },
  25. setPath: function setPath(value) {
  26. this.path = value;
  27. return this;
  28. },
  29. setResourcePath: function setResourcePath(value) {
  30. this.resourcePath = value;
  31. return this;
  32. },
  33. options: {
  34. set convertUpAxis(value) {
  35. console.warn('THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.');
  36. }
  37. },
  38. setCrossOrigin: function setCrossOrigin(value) {
  39. this.crossOrigin = value;
  40. return this;
  41. },
  42. parse: function parse(text, path) {
  43. function getElementsByTagName(xml, name) {
  44. // Non recursive xml.getElementsByTagName() ...
  45. var array = [];
  46. var childNodes = xml.childNodes;
  47. for (var i = 0, l = childNodes.length; i < l; i++) {
  48. var child = childNodes[i];
  49. if (child.nodeName === name) {
  50. array.push(child);
  51. }
  52. }
  53. return array;
  54. }
  55. function parseStrings(text) {
  56. if (text.length === 0) return [];
  57. var parts = text.trim().split(/\s+/);
  58. var array = new Array(parts.length);
  59. for (var i = 0, l = parts.length; i < l; i++) {
  60. array[i] = parts[i];
  61. }
  62. return array;
  63. }
  64. function parseFloats(text) {
  65. if (text.length === 0) return [];
  66. var parts = text.trim().split(/\s+/);
  67. var array = new Array(parts.length);
  68. for (var i = 0, l = parts.length; i < l; i++) {
  69. array[i] = parseFloat(parts[i]);
  70. }
  71. return array;
  72. }
  73. function parseInts(text) {
  74. if (text.length === 0) return [];
  75. var parts = text.trim().split(/\s+/);
  76. var array = new Array(parts.length);
  77. for (var i = 0, l = parts.length; i < l; i++) {
  78. array[i] = parseInt(parts[i]);
  79. }
  80. return array;
  81. }
  82. function parseId(text) {
  83. return text.substring(1);
  84. }
  85. function generateId() {
  86. return 'three_default_' + count++;
  87. }
  88. function isEmpty(object) {
  89. return Object.keys(object).length === 0;
  90. }
  91. // asset
  92. function parseAsset(xml) {
  93. return {
  94. unit: parseAssetUnit(getElementsByTagName(xml, 'unit')[0]),
  95. upAxis: parseAssetUpAxis(getElementsByTagName(xml, 'up_axis')[0])
  96. };
  97. }
  98. function parseAssetUnit(xml) {
  99. if (xml !== undefined && xml.hasAttribute('meter') === true) {
  100. return parseFloat(xml.getAttribute('meter'));
  101. } else {
  102. return 1; // default 1 meter
  103. }
  104. }
  105. function parseAssetUpAxis(xml) {
  106. return xml !== undefined ? xml.textContent : 'Y_UP';
  107. }
  108. // library
  109. function parseLibrary(xml, libraryName, nodeName, parser) {
  110. var library = getElementsByTagName(xml, libraryName)[0];
  111. if (library !== undefined) {
  112. var elements = getElementsByTagName(library, nodeName);
  113. for (var i = 0; i < elements.length; i++) {
  114. parser(elements[i]);
  115. }
  116. }
  117. }
  118. function buildLibrary(data, builder) {
  119. for (var name in data) {
  120. var object = data[name];
  121. object.build = builder(data[name]);
  122. }
  123. }
  124. // get
  125. function getBuild(data, builder) {
  126. if (data.build !== undefined) return data.build;
  127. data.build = builder(data);
  128. return data.build;
  129. }
  130. // animation
  131. function parseAnimation(xml) {
  132. var data = {
  133. sources: {},
  134. samplers: {},
  135. channels: {}
  136. };
  137. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  138. var child = xml.childNodes[i];
  139. if (child.nodeType !== 1) continue;
  140. var id;
  141. switch (child.nodeName) {
  142. case 'source':
  143. id = child.getAttribute('id');
  144. data.sources[id] = parseSource(child);
  145. break;
  146. case 'sampler':
  147. id = child.getAttribute('id');
  148. data.samplers[id] = parseAnimationSampler(child);
  149. break;
  150. case 'channel':
  151. id = child.getAttribute('target');
  152. data.channels[id] = parseAnimationChannel(child);
  153. break;
  154. default:
  155. console.log(child);
  156. }
  157. }
  158. library.animations[xml.getAttribute('id')] = data;
  159. }
  160. function parseAnimationSampler(xml) {
  161. var data = {
  162. inputs: {}
  163. };
  164. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  165. var child = xml.childNodes[i];
  166. if (child.nodeType !== 1) continue;
  167. switch (child.nodeName) {
  168. case 'input':
  169. var id = parseId(child.getAttribute('source'));
  170. var semantic = child.getAttribute('semantic');
  171. data.inputs[semantic] = id;
  172. break;
  173. }
  174. }
  175. return data;
  176. }
  177. function parseAnimationChannel(xml) {
  178. var data = {};
  179. var target = xml.getAttribute('target');
  180. // parsing SID Addressing Syntax
  181. var parts = target.split('/');
  182. var id = parts.shift();
  183. var sid = parts.shift();
  184. // check selection syntax
  185. var arraySyntax = sid.indexOf('(') !== -1;
  186. var memberSyntax = sid.indexOf('.') !== -1;
  187. if (memberSyntax) {
  188. // member selection access
  189. parts = sid.split('.');
  190. sid = parts.shift();
  191. data.member = parts.shift();
  192. } else if (arraySyntax) {
  193. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  194. var indices = sid.split('(');
  195. sid = indices.shift();
  196. for (var i = 0; i < indices.length; i++) {
  197. indices[i] = parseInt(indices[i].replace(/\)/, ''));
  198. }
  199. data.indices = indices;
  200. }
  201. data.id = id;
  202. data.sid = sid;
  203. data.arraySyntax = arraySyntax;
  204. data.memberSyntax = memberSyntax;
  205. data.sampler = parseId(xml.getAttribute('source'));
  206. return data;
  207. }
  208. function buildAnimation(data) {
  209. var tracks = [];
  210. var channels = data.channels;
  211. var samplers = data.samplers;
  212. var sources = data.sources;
  213. for (var target in channels) {
  214. if (channels.hasOwnProperty(target)) {
  215. var channel = channels[target];
  216. var sampler = samplers[channel.sampler];
  217. var inputId = sampler.inputs.INPUT;
  218. var outputId = sampler.inputs.OUTPUT;
  219. var inputSource = sources[inputId];
  220. var outputSource = sources[outputId];
  221. var animation = buildAnimationChannel(channel, inputSource, outputSource);
  222. createKeyframeTracks(animation, tracks);
  223. }
  224. }
  225. return tracks;
  226. }
  227. function getAnimation(id) {
  228. return getBuild(library.animations[id], buildAnimation);
  229. }
  230. function buildAnimationChannel(channel, inputSource, outputSource) {
  231. var node = library.nodes[channel.id];
  232. var object3D = getNode(node.id);
  233. var transform = node.transforms[channel.sid];
  234. var defaultMatrix = node.matrix.clone().transpose();
  235. var time, stride;
  236. var i, il, j, jl;
  237. var data = {};
  238. // the collada spec allows the animation of data in various ways.
  239. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  240. switch (transform) {
  241. case 'matrix':
  242. for (i = 0, il = inputSource.array.length; i < il; i++) {
  243. time = inputSource.array[i];
  244. stride = i * outputSource.stride;
  245. if (data[time] === undefined) data[time] = {};
  246. if (channel.arraySyntax === true) {
  247. var value = outputSource.array[stride];
  248. var index = channel.indices[0] + 4 * channel.indices[1];
  249. data[time][index] = value;
  250. } else {
  251. for (j = 0, jl = outputSource.stride; j < jl; j++) {
  252. data[time][j] = outputSource.array[stride + j];
  253. }
  254. }
  255. }
  256. break;
  257. case 'translate':
  258. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  259. break;
  260. case 'rotate':
  261. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  262. break;
  263. case 'scale':
  264. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  265. break;
  266. }
  267. var keyframes = prepareAnimationData(data, defaultMatrix);
  268. var animation = {
  269. name: object3D.uuid,
  270. keyframes: keyframes
  271. };
  272. return animation;
  273. }
  274. function prepareAnimationData(data, defaultMatrix) {
  275. var keyframes = [];
  276. // transfer data into a sortable array
  277. for (var time in data) {
  278. keyframes.push({ time: parseFloat(time), value: data[time] });
  279. }
  280. // ensure keyframes are sorted by time
  281. keyframes.sort(ascending);
  282. // now we clean up all animation data, so we can use them for keyframe tracks
  283. for (var i = 0; i < 16; i++) {
  284. transformAnimationData(keyframes, i, defaultMatrix.elements[i]);
  285. }
  286. return keyframes;
  287. // array sort function
  288. function ascending(a, b) {
  289. return a.time - b.time;
  290. }
  291. }
  292. var position = new THREE.Vector3();
  293. var scale = new THREE.Vector3();
  294. var quaternion = new THREE.Quaternion();
  295. function createKeyframeTracks(animation, tracks) {
  296. var keyframes = animation.keyframes;
  297. var name = animation.name;
  298. var times = [];
  299. var positionData = [];
  300. var quaternionData = [];
  301. var scaleData = [];
  302. for (var i = 0, l = keyframes.length; i < l; i++) {
  303. var keyframe = keyframes[i];
  304. var time = keyframe.time;
  305. var value = keyframe.value;
  306. matrix.fromArray(value).transpose();
  307. matrix.decompose(position, quaternion, scale);
  308. times.push(time);
  309. positionData.push(position.x, position.y, position.z);
  310. quaternionData.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  311. scaleData.push(scale.x, scale.y, scale.z);
  312. }
  313. if (positionData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.position', times, positionData));
  314. if (quaternionData.length > 0) tracks.push(new THREE.QuaternionKeyframeTrack(name + '.quaternion', times, quaternionData));
  315. if (scaleData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.scale', times, scaleData));
  316. return tracks;
  317. }
  318. function transformAnimationData(keyframes, property, defaultValue) {
  319. var keyframe;
  320. var empty = true;
  321. var i, l;
  322. // check, if values of a property are missing in our keyframes
  323. for (i = 0, l = keyframes.length; i < l; i++) {
  324. keyframe = keyframes[i];
  325. if (keyframe.value[property] === undefined) {
  326. keyframe.value[property] = null; // mark as missing
  327. } else {
  328. empty = false;
  329. }
  330. }
  331. if (empty === true) {
  332. // no values at all, so we set a default value
  333. for (i = 0, l = keyframes.length; i < l; i++) {
  334. keyframe = keyframes[i];
  335. keyframe.value[property] = defaultValue;
  336. }
  337. } else {
  338. // filling gaps
  339. createMissingKeyframes(keyframes, property);
  340. }
  341. }
  342. function createMissingKeyframes(keyframes, property) {
  343. var prev, next;
  344. for (var i = 0, l = keyframes.length; i < l; i++) {
  345. var keyframe = keyframes[i];
  346. if (keyframe.value[property] === null) {
  347. prev = getPrev(keyframes, i, property);
  348. next = getNext(keyframes, i, property);
  349. if (prev === null) {
  350. keyframe.value[property] = next.value[property];
  351. continue;
  352. }
  353. if (next === null) {
  354. keyframe.value[property] = prev.value[property];
  355. continue;
  356. }
  357. interpolate(keyframe, prev, next, property);
  358. }
  359. }
  360. }
  361. function getPrev(keyframes, i, property) {
  362. while (i >= 0) {
  363. var keyframe = keyframes[i];
  364. if (keyframe.value[property] !== null) return keyframe;
  365. i--;
  366. }
  367. return null;
  368. }
  369. function getNext(keyframes, i, property) {
  370. while (i < keyframes.length) {
  371. var keyframe = keyframes[i];
  372. if (keyframe.value[property] !== null) return keyframe;
  373. i++;
  374. }
  375. return null;
  376. }
  377. function interpolate(key, prev, next, property) {
  378. if (next.time - prev.time === 0) {
  379. key.value[property] = prev.value[property];
  380. return;
  381. }
  382. key.value[property] = (key.time - prev.time) * (next.value[property] - prev.value[property]) / (next.time - prev.time) + prev.value[property];
  383. }
  384. // animation clips
  385. function parseAnimationClip(xml) {
  386. var data = {
  387. name: xml.getAttribute('id') || 'default',
  388. start: parseFloat(xml.getAttribute('start') || 0),
  389. end: parseFloat(xml.getAttribute('end') || 0),
  390. animations: []
  391. };
  392. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  393. var child = xml.childNodes[i];
  394. if (child.nodeType !== 1) continue;
  395. switch (child.nodeName) {
  396. case 'instance_animation':
  397. data.animations.push(parseId(child.getAttribute('url')));
  398. break;
  399. }
  400. }
  401. library.clips[xml.getAttribute('id')] = data;
  402. }
  403. function buildAnimationClip(data) {
  404. var tracks = [];
  405. var name = data.name;
  406. var duration = data.end - data.start || -1;
  407. var animations = data.animations;
  408. for (var i = 0, il = animations.length; i < il; i++) {
  409. var animationTracks = getAnimation(animations[i]);
  410. for (var j = 0, jl = animationTracks.length; j < jl; j++) {
  411. tracks.push(animationTracks[j]);
  412. }
  413. }
  414. return new THREE.AnimationClip(name, duration, tracks);
  415. }
  416. function getAnimationClip(id) {
  417. return getBuild(library.clips[id], buildAnimationClip);
  418. }
  419. // controller
  420. function parseController(xml) {
  421. var data = {};
  422. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  423. var child = xml.childNodes[i];
  424. if (child.nodeType !== 1) continue;
  425. switch (child.nodeName) {
  426. case 'skin':
  427. // there is exactly one skin per controller
  428. data.id = parseId(child.getAttribute('source'));
  429. data.skin = parseSkin(child);
  430. break;
  431. case 'morph':
  432. data.id = parseId(child.getAttribute('source'));
  433. console.warn('THREE.ColladaLoader: Morph target animation not supported yet.');
  434. break;
  435. }
  436. }
  437. library.controllers[xml.getAttribute('id')] = data;
  438. }
  439. function parseSkin(xml) {
  440. var data = {
  441. sources: {}
  442. };
  443. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  444. var child = xml.childNodes[i];
  445. if (child.nodeType !== 1) continue;
  446. switch (child.nodeName) {
  447. case 'bind_shape_matrix':
  448. data.bindShapeMatrix = parseFloats(child.textContent);
  449. break;
  450. case 'source':
  451. var id = child.getAttribute('id');
  452. data.sources[id] = parseSource(child);
  453. break;
  454. case 'joints':
  455. data.joints = parseJoints(child);
  456. break;
  457. case 'vertex_weights':
  458. data.vertexWeights = parseVertexWeights(child);
  459. break;
  460. }
  461. }
  462. return data;
  463. }
  464. function parseJoints(xml) {
  465. var data = {
  466. inputs: {}
  467. };
  468. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  469. var child = xml.childNodes[i];
  470. if (child.nodeType !== 1) continue;
  471. switch (child.nodeName) {
  472. case 'input':
  473. var semantic = child.getAttribute('semantic');
  474. var id = parseId(child.getAttribute('source'));
  475. data.inputs[semantic] = id;
  476. break;
  477. }
  478. }
  479. return data;
  480. }
  481. function parseVertexWeights(xml) {
  482. var data = {
  483. inputs: {}
  484. };
  485. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  486. var child = xml.childNodes[i];
  487. if (child.nodeType !== 1) continue;
  488. switch (child.nodeName) {
  489. case 'input':
  490. var semantic = child.getAttribute('semantic');
  491. var id = parseId(child.getAttribute('source'));
  492. var offset = parseInt(child.getAttribute('offset'));
  493. data.inputs[semantic] = { id: id, offset: offset };
  494. break;
  495. case 'vcount':
  496. data.vcount = parseInts(child.textContent);
  497. break;
  498. case 'v':
  499. data.v = parseInts(child.textContent);
  500. break;
  501. }
  502. }
  503. return data;
  504. }
  505. function buildController(data) {
  506. var build = {
  507. id: data.id
  508. };
  509. var geometry = library.geometries[build.id];
  510. if (data.skin !== undefined) {
  511. build.skin = buildSkin(data.skin);
  512. // we enhance the 'sources' property of the corresponding geometry with our skin data
  513. geometry.sources.skinIndices = build.skin.indices;
  514. geometry.sources.skinWeights = build.skin.weights;
  515. }
  516. return build;
  517. }
  518. function buildSkin(data) {
  519. var BONE_LIMIT = 4;
  520. var build = {
  521. joints: [], // this must be an array to preserve the joint order
  522. indices: {
  523. array: [],
  524. stride: BONE_LIMIT
  525. },
  526. weights: {
  527. array: [],
  528. stride: BONE_LIMIT
  529. }
  530. };
  531. var sources = data.sources;
  532. var vertexWeights = data.vertexWeights;
  533. var vcount = vertexWeights.vcount;
  534. var v = vertexWeights.v;
  535. var jointOffset = vertexWeights.inputs.JOINT.offset;
  536. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  537. var jointSource = data.sources[data.joints.inputs.JOINT];
  538. var inverseSource = data.sources[data.joints.inputs.INV_BIND_MATRIX];
  539. var weights = sources[vertexWeights.inputs.WEIGHT.id].array;
  540. var stride = 0;
  541. var i, j, l;
  542. // procces skin data for each vertex
  543. for (i = 0, l = vcount.length; i < l; i++) {
  544. var jointCount = vcount[i]; // this is the amount of joints that affect a single vertex
  545. var vertexSkinData = [];
  546. for (j = 0; j < jointCount; j++) {
  547. var skinIndex = v[stride + jointOffset];
  548. var weightId = v[stride + weightOffset];
  549. var skinWeight = weights[weightId];
  550. vertexSkinData.push({ index: skinIndex, weight: skinWeight });
  551. stride += 2;
  552. }
  553. // we sort the joints in descending order based on the weights.
  554. // this ensures, we only procced the most important joints of the vertex
  555. vertexSkinData.sort(descending);
  556. // now we provide for each vertex a set of four index and weight values.
  557. // the order of the skin data matches the order of vertices
  558. for (j = 0; j < BONE_LIMIT; j++) {
  559. var d = vertexSkinData[j];
  560. if (d !== undefined) {
  561. build.indices.array.push(d.index);
  562. build.weights.array.push(d.weight);
  563. } else {
  564. build.indices.array.push(0);
  565. build.weights.array.push(0);
  566. }
  567. }
  568. }
  569. // setup bind matrix
  570. if (data.bindShapeMatrix) {
  571. build.bindMatrix = new THREE.Matrix4().fromArray(data.bindShapeMatrix).transpose();
  572. } else {
  573. build.bindMatrix = new THREE.Matrix4().identity();
  574. }
  575. // process bones and inverse bind matrix data
  576. for (i = 0, l = jointSource.array.length; i < l; i++) {
  577. var name = jointSource.array[i];
  578. var boneInverse = new THREE.Matrix4().fromArray(inverseSource.array, i * inverseSource.stride).transpose();
  579. build.joints.push({ name: name, boneInverse: boneInverse });
  580. }
  581. return build;
  582. // array sort function
  583. function descending(a, b) {
  584. return b.weight - a.weight;
  585. }
  586. }
  587. function getController(id) {
  588. return getBuild(library.controllers[id], buildController);
  589. }
  590. // image
  591. function parseImage(xml) {
  592. var data = {
  593. init_from: getElementsByTagName(xml, 'init_from')[0].textContent
  594. };
  595. library.images[xml.getAttribute('id')] = data;
  596. }
  597. function buildImage(data) {
  598. if (data.build !== undefined) return data.build;
  599. return data.init_from;
  600. }
  601. function getImage(id) {
  602. var data = library.images[id];
  603. if (data !== undefined) {
  604. return getBuild(data, buildImage);
  605. }
  606. console.warn('THREE.ColladaLoader: Couldn\'t find image with ID:', id);
  607. return null;
  608. }
  609. // effect
  610. function parseEffect(xml) {
  611. var data = {};
  612. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  613. var child = xml.childNodes[i];
  614. if (child.nodeType !== 1) continue;
  615. switch (child.nodeName) {
  616. case 'profile_COMMON':
  617. data.profile = parseEffectProfileCOMMON(child);
  618. break;
  619. }
  620. }
  621. library.effects[xml.getAttribute('id')] = data;
  622. }
  623. function parseEffectProfileCOMMON(xml) {
  624. var data = {
  625. surfaces: {},
  626. samplers: {}
  627. };
  628. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  629. var child = xml.childNodes[i];
  630. if (child.nodeType !== 1) continue;
  631. switch (child.nodeName) {
  632. case 'newparam':
  633. parseEffectNewparam(child, data);
  634. break;
  635. case 'technique':
  636. data.technique = parseEffectTechnique(child);
  637. break;
  638. case 'extra':
  639. data.extra = parseEffectExtra(child);
  640. break;
  641. }
  642. }
  643. return data;
  644. }
  645. function parseEffectNewparam(xml, data) {
  646. var sid = xml.getAttribute('sid');
  647. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  648. var child = xml.childNodes[i];
  649. if (child.nodeType !== 1) continue;
  650. switch (child.nodeName) {
  651. case 'surface':
  652. data.surfaces[sid] = parseEffectSurface(child);
  653. break;
  654. case 'sampler2D':
  655. data.samplers[sid] = parseEffectSampler(child);
  656. break;
  657. }
  658. }
  659. }
  660. function parseEffectSurface(xml) {
  661. var data = {};
  662. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  663. var child = xml.childNodes[i];
  664. if (child.nodeType !== 1) continue;
  665. switch (child.nodeName) {
  666. case 'init_from':
  667. data.init_from = child.textContent;
  668. break;
  669. }
  670. }
  671. return data;
  672. }
  673. function parseEffectSampler(xml) {
  674. var data = {};
  675. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  676. var child = xml.childNodes[i];
  677. if (child.nodeType !== 1) continue;
  678. switch (child.nodeName) {
  679. case 'source':
  680. data.source = child.textContent;
  681. break;
  682. }
  683. }
  684. return data;
  685. }
  686. function parseEffectTechnique(xml) {
  687. var data = {};
  688. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  689. var child = xml.childNodes[i];
  690. if (child.nodeType !== 1) continue;
  691. switch (child.nodeName) {
  692. case 'constant':
  693. case 'lambert':
  694. case 'blinn':
  695. case 'phong':
  696. data.type = child.nodeName;
  697. data.parameters = parseEffectParameters(child);
  698. break;
  699. }
  700. }
  701. return data;
  702. }
  703. function parseEffectParameters(xml) {
  704. var data = {};
  705. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  706. var child = xml.childNodes[i];
  707. if (child.nodeType !== 1) continue;
  708. switch (child.nodeName) {
  709. case 'emission':
  710. case 'diffuse':
  711. case 'specular':
  712. case 'bump':
  713. case 'ambient':
  714. case 'shininess':
  715. case 'transparency':
  716. data[child.nodeName] = parseEffectParameter(child);
  717. break;
  718. case 'transparent':
  719. data[child.nodeName] = {
  720. opaque: child.getAttribute('opaque'),
  721. data: parseEffectParameter(child)
  722. };
  723. break;
  724. }
  725. }
  726. return data;
  727. }
  728. function parseEffectParameter(xml) {
  729. var data = {};
  730. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  731. var child = xml.childNodes[i];
  732. if (child.nodeType !== 1) continue;
  733. switch (child.nodeName) {
  734. case 'color':
  735. data[child.nodeName] = parseFloats(child.textContent);
  736. break;
  737. case 'float':
  738. data[child.nodeName] = parseFloat(child.textContent);
  739. break;
  740. case 'texture':
  741. data[child.nodeName] = { id: child.getAttribute('texture'), extra: parseEffectParameterTexture(child) };
  742. break;
  743. }
  744. }
  745. return data;
  746. }
  747. function parseEffectParameterTexture(xml) {
  748. var data = {
  749. technique: {}
  750. };
  751. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  752. var child = xml.childNodes[i];
  753. if (child.nodeType !== 1) continue;
  754. switch (child.nodeName) {
  755. case 'extra':
  756. parseEffectParameterTextureExtra(child, data);
  757. break;
  758. }
  759. }
  760. return data;
  761. }
  762. function parseEffectParameterTextureExtra(xml, data) {
  763. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  764. var child = xml.childNodes[i];
  765. if (child.nodeType !== 1) continue;
  766. switch (child.nodeName) {
  767. case 'technique':
  768. parseEffectParameterTextureExtraTechnique(child, data);
  769. break;
  770. }
  771. }
  772. }
  773. function parseEffectParameterTextureExtraTechnique(xml, data) {
  774. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  775. var child = xml.childNodes[i];
  776. if (child.nodeType !== 1) continue;
  777. switch (child.nodeName) {
  778. case 'repeatU':
  779. case 'repeatV':
  780. case 'offsetU':
  781. case 'offsetV':
  782. data.technique[child.nodeName] = parseFloat(child.textContent);
  783. break;
  784. case 'wrapU':
  785. case 'wrapV':
  786. // some files have values for wrapU/wrapV which become NaN via parseInt
  787. if (child.textContent.toUpperCase() === 'TRUE') {
  788. data.technique[child.nodeName] = 1;
  789. } else if (child.textContent.toUpperCase() === 'FALSE') {
  790. data.technique[child.nodeName] = 0;
  791. } else {
  792. data.technique[child.nodeName] = parseInt(child.textContent);
  793. }
  794. break;
  795. }
  796. }
  797. }
  798. function parseEffectExtra(xml) {
  799. var data = {};
  800. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  801. var child = xml.childNodes[i];
  802. if (child.nodeType !== 1) continue;
  803. switch (child.nodeName) {
  804. case 'technique':
  805. data.technique = parseEffectExtraTechnique(child);
  806. break;
  807. }
  808. }
  809. return data;
  810. }
  811. function parseEffectExtraTechnique(xml) {
  812. var data = {};
  813. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  814. var child = xml.childNodes[i];
  815. if (child.nodeType !== 1) continue;
  816. switch (child.nodeName) {
  817. case 'double_sided':
  818. data[child.nodeName] = parseInt(child.textContent);
  819. break;
  820. }
  821. }
  822. return data;
  823. }
  824. function buildEffect(data) {
  825. return data;
  826. }
  827. function getEffect(id) {
  828. return getBuild(library.effects[id], buildEffect);
  829. }
  830. // material
  831. function parseMaterial(xml) {
  832. var data = {
  833. name: xml.getAttribute('name')
  834. };
  835. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  836. var child = xml.childNodes[i];
  837. if (child.nodeType !== 1) continue;
  838. switch (child.nodeName) {
  839. case 'instance_effect':
  840. data.url = parseId(child.getAttribute('url'));
  841. break;
  842. }
  843. }
  844. library.materials[xml.getAttribute('id')] = data;
  845. }
  846. function getTextureLoader(image) {
  847. var loader;
  848. var extension = image.slice((image.lastIndexOf('.') - 1 >>> 0) + 2); // http://www.jstips.co/en/javascript/get-file-extension/
  849. extension = extension.toLowerCase();
  850. switch (extension) {
  851. case 'tga':
  852. loader = tgaLoader;
  853. break;
  854. default:
  855. loader = textureLoader;
  856. }
  857. return loader;
  858. }
  859. function buildMaterial(data) {
  860. var effect = getEffect(data.url);
  861. var technique = effect.profile.technique;
  862. var extra = effect.profile.extra;
  863. var material;
  864. switch (technique.type) {
  865. case 'phong':
  866. case 'blinn':
  867. material = new THREE.MeshPhongMaterial();
  868. break;
  869. case 'lambert':
  870. material = new THREE.MeshLambertMaterial();
  871. break;
  872. default:
  873. material = new THREE.MeshBasicMaterial();
  874. break;
  875. }
  876. material.name = data.name;
  877. function getTexture(textureObject) {
  878. var sampler = effect.profile.samplers[textureObject.id];
  879. var image = null;
  880. // get image
  881. if (sampler !== undefined) {
  882. var surface = effect.profile.surfaces[sampler.source];
  883. image = getImage(surface.init_from);
  884. } else {
  885. console.warn('THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).');
  886. image = getImage(textureObject.id);
  887. }
  888. // create texture if image is avaiable
  889. if (image !== null) {
  890. var loader = getTextureLoader(image);
  891. if (loader !== undefined) {
  892. var texture = loader.load(image);
  893. var extra = textureObject.extra;
  894. if (extra !== undefined && extra.technique !== undefined && isEmpty(extra.technique) === false) {
  895. var technique = extra.technique;
  896. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  897. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  898. texture.offset.set(technique.offsetU || 0, technique.offsetV || 0);
  899. texture.repeat.set(technique.repeatU || 1, technique.repeatV || 1);
  900. } else {
  901. texture.wrapS = THREE.RepeatWrapping;
  902. texture.wrapT = THREE.RepeatWrapping;
  903. }
  904. return texture;
  905. } else {
  906. console.warn('THREE.ColladaLoader: Loader for texture %s not found.', image);
  907. return null;
  908. }
  909. } else {
  910. console.warn('THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id);
  911. return null;
  912. }
  913. }
  914. var parameters = technique.parameters;
  915. for (var key in parameters) {
  916. var parameter = parameters[key];
  917. switch (key) {
  918. case 'diffuse':
  919. if (parameter.color) material.color.fromArray(parameter.color);
  920. if (parameter.texture) material.map = getTexture(parameter.texture);
  921. break;
  922. case 'specular':
  923. if (parameter.color && material.specular) material.specular.fromArray(parameter.color);
  924. if (parameter.texture) material.specularMap = getTexture(parameter.texture);
  925. break;
  926. case 'bump':
  927. if (parameter.texture) material.normalMap = getTexture(parameter.texture);
  928. break;
  929. case 'ambient':
  930. if (parameter.texture) material.lightMap = getTexture(parameter.texture);
  931. break;
  932. case 'shininess':
  933. if (parameter.float && material.shininess) material.shininess = parameter.float;
  934. break;
  935. case 'emission':
  936. if (parameter.color && material.emissive) material.emissive.fromArray(parameter.color);
  937. if (parameter.texture) material.emissiveMap = getTexture(parameter.texture);
  938. break;
  939. }
  940. }
  941. //
  942. var transparent = parameters['transparent'];
  943. var transparency = parameters['transparency'];
  944. // <transparency> does not exist but <transparent>
  945. if (transparency === undefined && transparent) {
  946. transparency = {
  947. float: 1
  948. };
  949. }
  950. // <transparent> does not exist but <transparency>
  951. if (transparent === undefined && transparency) {
  952. transparent = {
  953. opaque: 'A_ONE',
  954. data: {
  955. color: [1, 1, 1, 1]
  956. } };
  957. }
  958. if (transparent && transparency) {
  959. // handle case if a texture exists but no color
  960. if (transparent.data.texture) {
  961. // we do not set an alpha map (see #13792)
  962. material.transparent = true;
  963. } else {
  964. var color = transparent.data.color;
  965. switch (transparent.opaque) {
  966. case 'A_ONE':
  967. material.opacity = color[3] * transparency.float;
  968. break;
  969. case 'RGB_ZERO':
  970. material.opacity = 1 - color[0] * transparency.float;
  971. break;
  972. case 'A_ZERO':
  973. material.opacity = 1 - color[3] * transparency.float;
  974. break;
  975. case 'RGB_ONE':
  976. material.opacity = color[0] * transparency.float;
  977. break;
  978. default:
  979. console.warn('THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque);
  980. }
  981. if (material.opacity < 1) material.transparent = true;
  982. }
  983. }
  984. //
  985. if (extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1) {
  986. material.side = THREE.DoubleSide;
  987. }
  988. return material;
  989. }
  990. function getMaterial(id) {
  991. return getBuild(library.materials[id], buildMaterial);
  992. }
  993. // camera
  994. function parseCamera(xml) {
  995. var data = {
  996. name: xml.getAttribute('name')
  997. };
  998. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  999. var child = xml.childNodes[i];
  1000. if (child.nodeType !== 1) continue;
  1001. switch (child.nodeName) {
  1002. case 'optics':
  1003. data.optics = parseCameraOptics(child);
  1004. break;
  1005. }
  1006. }
  1007. library.cameras[xml.getAttribute('id')] = data;
  1008. }
  1009. function parseCameraOptics(xml) {
  1010. for (var i = 0; i < xml.childNodes.length; i++) {
  1011. var child = xml.childNodes[i];
  1012. switch (child.nodeName) {
  1013. case 'technique_common':
  1014. return parseCameraTechnique(child);
  1015. }
  1016. }
  1017. return {};
  1018. }
  1019. function parseCameraTechnique(xml) {
  1020. var data = {};
  1021. for (var i = 0; i < xml.childNodes.length; i++) {
  1022. var child = xml.childNodes[i];
  1023. switch (child.nodeName) {
  1024. case 'perspective':
  1025. case 'orthographic':
  1026. data.technique = child.nodeName;
  1027. data.parameters = parseCameraParameters(child);
  1028. break;
  1029. }
  1030. }
  1031. return data;
  1032. }
  1033. function parseCameraParameters(xml) {
  1034. var data = {};
  1035. for (var i = 0; i < xml.childNodes.length; i++) {
  1036. var child = xml.childNodes[i];
  1037. switch (child.nodeName) {
  1038. case 'xfov':
  1039. case 'yfov':
  1040. case 'xmag':
  1041. case 'ymag':
  1042. case 'znear':
  1043. case 'zfar':
  1044. case 'aspect_ratio':
  1045. data[child.nodeName] = parseFloat(child.textContent);
  1046. break;
  1047. }
  1048. }
  1049. return data;
  1050. }
  1051. function buildCamera(data) {
  1052. var camera;
  1053. switch (data.optics.technique) {
  1054. case 'perspective':
  1055. camera = new THREE.PerspectiveCamera(data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar);
  1056. break;
  1057. case 'orthographic':
  1058. var ymag = data.optics.parameters.ymag;
  1059. var xmag = data.optics.parameters.xmag;
  1060. var aspectRatio = data.optics.parameters.aspect_ratio;
  1061. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1062. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1063. xmag *= 0.5;
  1064. ymag *= 0.5;
  1065. camera = new THREE.OrthographicCamera(-xmag, xmag, ymag, -ymag, // left, right, top, bottom
  1066. data.optics.parameters.znear, data.optics.parameters.zfar);
  1067. break;
  1068. default:
  1069. camera = new THREE.PerspectiveCamera();
  1070. break;
  1071. }
  1072. camera.name = data.name;
  1073. return camera;
  1074. }
  1075. function getCamera(id) {
  1076. var data = library.cameras[id];
  1077. if (data !== undefined) {
  1078. return getBuild(data, buildCamera);
  1079. }
  1080. console.warn('THREE.ColladaLoader: Couldn\'t find camera with ID:', id);
  1081. return null;
  1082. }
  1083. // light
  1084. function parseLight(xml) {
  1085. var data = {};
  1086. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1087. var child = xml.childNodes[i];
  1088. if (child.nodeType !== 1) continue;
  1089. switch (child.nodeName) {
  1090. case 'technique_common':
  1091. data = parseLightTechnique(child);
  1092. break;
  1093. }
  1094. }
  1095. library.lights[xml.getAttribute('id')] = data;
  1096. }
  1097. function parseLightTechnique(xml) {
  1098. var data = {};
  1099. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1100. var child = xml.childNodes[i];
  1101. if (child.nodeType !== 1) continue;
  1102. switch (child.nodeName) {
  1103. case 'directional':
  1104. case 'point':
  1105. case 'spot':
  1106. case 'ambient':
  1107. data.technique = child.nodeName;
  1108. data.parameters = parseLightParameters(child);
  1109. }
  1110. }
  1111. return data;
  1112. }
  1113. function parseLightParameters(xml) {
  1114. var data = {};
  1115. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1116. var child = xml.childNodes[i];
  1117. if (child.nodeType !== 1) continue;
  1118. switch (child.nodeName) {
  1119. case 'color':
  1120. var array = parseFloats(child.textContent);
  1121. data.color = new THREE.Color().fromArray(array);
  1122. break;
  1123. case 'falloff_angle':
  1124. data.falloffAngle = parseFloat(child.textContent);
  1125. break;
  1126. case 'quadratic_attenuation':
  1127. var f = parseFloat(child.textContent);
  1128. data.distance = f ? Math.sqrt(1 / f) : 0;
  1129. break;
  1130. }
  1131. }
  1132. return data;
  1133. }
  1134. function buildLight(data) {
  1135. var light;
  1136. switch (data.technique) {
  1137. case 'directional':
  1138. light = new THREE.DirectionalLight();
  1139. break;
  1140. case 'point':
  1141. light = new THREE.PointLight();
  1142. break;
  1143. case 'spot':
  1144. light = new THREE.SpotLight();
  1145. break;
  1146. case 'ambient':
  1147. light = new THREE.AmbientLight();
  1148. break;
  1149. }
  1150. if (data.parameters.color) light.color.copy(data.parameters.color);
  1151. if (data.parameters.distance) light.distance = data.parameters.distance;
  1152. return light;
  1153. }
  1154. function getLight(id) {
  1155. var data = library.lights[id];
  1156. if (data !== undefined) {
  1157. return getBuild(data, buildLight);
  1158. }
  1159. console.warn('THREE.ColladaLoader: Couldn\'t find light with ID:', id);
  1160. return null;
  1161. }
  1162. // geometry
  1163. function parseGeometry(xml) {
  1164. var data = {
  1165. name: xml.getAttribute('name'),
  1166. sources: {},
  1167. vertices: {},
  1168. primitives: []
  1169. };
  1170. var mesh = getElementsByTagName(xml, 'mesh')[0];
  1171. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1172. if (mesh === undefined) return;
  1173. for (var i = 0; i < mesh.childNodes.length; i++) {
  1174. var child = mesh.childNodes[i];
  1175. if (child.nodeType !== 1) continue;
  1176. var id = child.getAttribute('id');
  1177. switch (child.nodeName) {
  1178. case 'source':
  1179. data.sources[id] = parseSource(child);
  1180. break;
  1181. case 'vertices':
  1182. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1183. data.vertices = parseGeometryVertices(child);
  1184. break;
  1185. case 'polygons':
  1186. console.warn('THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName);
  1187. break;
  1188. case 'lines':
  1189. case 'linestrips':
  1190. case 'polylist':
  1191. case 'triangles':
  1192. data.primitives.push(parseGeometryPrimitive(child));
  1193. break;
  1194. default:
  1195. console.log(child);
  1196. }
  1197. }
  1198. library.geometries[xml.getAttribute('id')] = data;
  1199. }
  1200. function parseSource(xml) {
  1201. var data = {
  1202. array: [],
  1203. stride: 3
  1204. };
  1205. for (var i = 0; i < xml.childNodes.length; i++) {
  1206. var child = xml.childNodes[i];
  1207. if (child.nodeType !== 1) continue;
  1208. switch (child.nodeName) {
  1209. case 'float_array':
  1210. data.array = parseFloats(child.textContent);
  1211. break;
  1212. case 'Name_array':
  1213. data.array = parseStrings(child.textContent);
  1214. break;
  1215. case 'technique_common':
  1216. var accessor = getElementsByTagName(child, 'accessor')[0];
  1217. if (accessor !== undefined) {
  1218. data.stride = parseInt(accessor.getAttribute('stride'));
  1219. }
  1220. break;
  1221. }
  1222. }
  1223. return data;
  1224. }
  1225. function parseGeometryVertices(xml) {
  1226. var data = {};
  1227. for (var i = 0; i < xml.childNodes.length; i++) {
  1228. var child = xml.childNodes[i];
  1229. if (child.nodeType !== 1) continue;
  1230. data[child.getAttribute('semantic')] = parseId(child.getAttribute('source'));
  1231. }
  1232. return data;
  1233. }
  1234. function parseGeometryPrimitive(xml) {
  1235. var primitive = {
  1236. type: xml.nodeName,
  1237. material: xml.getAttribute('material'),
  1238. count: parseInt(xml.getAttribute('count')),
  1239. inputs: {},
  1240. stride: 0,
  1241. hasUV: false
  1242. };
  1243. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1244. var child = xml.childNodes[i];
  1245. if (child.nodeType !== 1) continue;
  1246. switch (child.nodeName) {
  1247. case 'input':
  1248. var id = parseId(child.getAttribute('source'));
  1249. var semantic = child.getAttribute('semantic');
  1250. var offset = parseInt(child.getAttribute('offset'));
  1251. var set = parseInt(child.getAttribute('set'));
  1252. var inputname = set > 0 ? semantic + set : semantic;
  1253. primitive.inputs[inputname] = { id: id, offset: offset };
  1254. primitive.stride = Math.max(primitive.stride, offset + 1);
  1255. if (semantic === 'TEXCOORD') primitive.hasUV = true;
  1256. break;
  1257. case 'vcount':
  1258. primitive.vcount = parseInts(child.textContent);
  1259. break;
  1260. case 'p':
  1261. primitive.p = parseInts(child.textContent);
  1262. break;
  1263. }
  1264. }
  1265. return primitive;
  1266. }
  1267. function groupPrimitives(primitives) {
  1268. var build = {};
  1269. for (var i = 0; i < primitives.length; i++) {
  1270. var primitive = primitives[i];
  1271. if (build[primitive.type] === undefined) build[primitive.type] = [];
  1272. build[primitive.type].push(primitive);
  1273. }
  1274. return build;
  1275. }
  1276. function checkUVCoordinates(primitives) {
  1277. var count = 0;
  1278. for (var i = 0, l = primitives.length; i < l; i++) {
  1279. var primitive = primitives[i];
  1280. if (primitive.hasUV === true) {
  1281. count++;
  1282. }
  1283. }
  1284. if (count > 0 && count < primitives.length) {
  1285. primitives.uvsNeedsFix = true;
  1286. }
  1287. }
  1288. function buildGeometry(data) {
  1289. var build = {};
  1290. var sources = data.sources;
  1291. var vertices = data.vertices;
  1292. var primitives = data.primitives;
  1293. if (primitives.length === 0) return {};
  1294. // our goal is to create one buffer geometry for a single type of primitives
  1295. // first, we group all primitives by their type
  1296. var groupedPrimitives = groupPrimitives(primitives);
  1297. for (var type in groupedPrimitives) {
  1298. var primitiveType = groupedPrimitives[type];
  1299. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1300. checkUVCoordinates(primitiveType);
  1301. // third, create a buffer geometry for each type of primitives
  1302. build[type] = buildGeometryType(primitiveType, sources, vertices);
  1303. }
  1304. return build;
  1305. }
  1306. function buildGeometryType(primitives, sources, vertices) {
  1307. var build = {};
  1308. var position = { array: [], stride: 0 };
  1309. var normal = { array: [], stride: 0 };
  1310. var uv = { array: [], stride: 0 };
  1311. var uv2 = { array: [], stride: 0 };
  1312. var color = { array: [], stride: 0 };
  1313. var skinIndex = { array: [], stride: 4 };
  1314. var skinWeight = { array: [], stride: 4 };
  1315. var geometry = new THREE.BufferGeometry();
  1316. var materialKeys = [];
  1317. var start = 0;
  1318. for (var p = 0; p < primitives.length; p++) {
  1319. var primitive = primitives[p];
  1320. var inputs = primitive.inputs;
  1321. // groups
  1322. var count = 0;
  1323. switch (primitive.type) {
  1324. case 'lines':
  1325. case 'linestrips':
  1326. count = primitive.count * 2;
  1327. break;
  1328. case 'triangles':
  1329. count = primitive.count * 3;
  1330. break;
  1331. case 'polylist':
  1332. for (var g = 0; g < primitive.count; g++) {
  1333. var vc = primitive.vcount[g];
  1334. switch (vc) {
  1335. case 3:
  1336. count += 3; // single triangle
  1337. break;
  1338. case 4:
  1339. count += 6; // quad, subdivided into two triangles
  1340. break;
  1341. default:
  1342. count += (vc - 2) * 3; // polylist with more than four vertices
  1343. break;
  1344. }
  1345. }
  1346. break;
  1347. default:
  1348. console.warn('THREE.ColladaLoader: Unknow primitive type:', primitive.type);
  1349. }
  1350. geometry.addGroup(start, count, p);
  1351. start += count;
  1352. // material
  1353. if (primitive.material) {
  1354. materialKeys.push(primitive.material);
  1355. }
  1356. // geometry data
  1357. for (var name in inputs) {
  1358. var input = inputs[name];
  1359. switch (name) {
  1360. case 'VERTEX':
  1361. for (var key in vertices) {
  1362. var id = vertices[key];
  1363. switch (key) {
  1364. case 'POSITION':
  1365. var prevLength = position.array.length;
  1366. buildGeometryData(primitive, sources[id], input.offset, position.array);
  1367. position.stride = sources[id].stride;
  1368. if (sources.skinWeights && sources.skinIndices) {
  1369. buildGeometryData(primitive, sources.skinIndices, input.offset, skinIndex.array);
  1370. buildGeometryData(primitive, sources.skinWeights, input.offset, skinWeight.array);
  1371. }
  1372. // see #3803
  1373. if (primitive.hasUV === false && primitives.uvsNeedsFix === true) {
  1374. var count = (position.array.length - prevLength) / position.stride;
  1375. for (var i = 0; i < count; i++) {
  1376. // fill missing uv coordinates
  1377. uv.array.push(0, 0);
  1378. }
  1379. }
  1380. break;
  1381. case 'NORMAL':
  1382. buildGeometryData(primitive, sources[id], input.offset, normal.array);
  1383. normal.stride = sources[id].stride;
  1384. break;
  1385. case 'COLOR':
  1386. buildGeometryData(primitive, sources[id], input.offset, color.array);
  1387. color.stride = sources[id].stride;
  1388. break;
  1389. case 'TEXCOORD':
  1390. buildGeometryData(primitive, sources[id], input.offset, uv.array);
  1391. uv.stride = sources[id].stride;
  1392. break;
  1393. case 'TEXCOORD1':
  1394. buildGeometryData(primitive, sources[id], input.offset, uv2.array);
  1395. uv.stride = sources[id].stride;
  1396. break;
  1397. default:
  1398. console.warn('THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key);
  1399. }
  1400. }
  1401. break;
  1402. case 'NORMAL':
  1403. buildGeometryData(primitive, sources[input.id], input.offset, normal.array);
  1404. normal.stride = sources[input.id].stride;
  1405. break;
  1406. case 'COLOR':
  1407. buildGeometryData(primitive, sources[input.id], input.offset, color.array);
  1408. color.stride = sources[input.id].stride;
  1409. break;
  1410. case 'TEXCOORD':
  1411. buildGeometryData(primitive, sources[input.id], input.offset, uv.array);
  1412. uv.stride = sources[input.id].stride;
  1413. break;
  1414. case 'TEXCOORD1':
  1415. buildGeometryData(primitive, sources[input.id], input.offset, uv2.array);
  1416. uv2.stride = sources[input.id].stride;
  1417. break;
  1418. }
  1419. }
  1420. }
  1421. // build geometry
  1422. if (position.array.length > 0) geometry.addAttribute('position', new THREE.Float32BufferAttribute(position.array, position.stride));
  1423. if (normal.array.length > 0) geometry.addAttribute('normal', new THREE.Float32BufferAttribute(normal.array, normal.stride));
  1424. if (color.array.length > 0) geometry.addAttribute('color', new THREE.Float32BufferAttribute(color.array, color.stride));
  1425. if (uv.array.length > 0) geometry.addAttribute('uv', new THREE.Float32BufferAttribute(uv.array, uv.stride));
  1426. if (uv2.array.length > 0) geometry.addAttribute('uv2', new THREE.Float32BufferAttribute(uv2.array, uv2.stride));
  1427. if (skinIndex.array.length > 0) geometry.addAttribute('skinIndex', new THREE.Float32BufferAttribute(skinIndex.array, skinIndex.stride));
  1428. if (skinWeight.array.length > 0) geometry.addAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeight.array, skinWeight.stride));
  1429. build.data = geometry;
  1430. build.type = primitives[0].type;
  1431. build.materialKeys = materialKeys;
  1432. return build;
  1433. }
  1434. function buildGeometryData(primitive, source, offset, array) {
  1435. var indices = primitive.p;
  1436. var stride = primitive.stride;
  1437. var vcount = primitive.vcount;
  1438. function pushVector(i) {
  1439. var index = indices[i + offset] * sourceStride;
  1440. var length = index + sourceStride;
  1441. for (; index < length; index++) {
  1442. array.push(sourceArray[index]);
  1443. }
  1444. }
  1445. var sourceArray = source.array;
  1446. var sourceStride = source.stride;
  1447. if (primitive.vcount !== undefined) {
  1448. var index = 0;
  1449. for (var i = 0, l = vcount.length; i < l; i++) {
  1450. var count = vcount[i];
  1451. if (count === 4) {
  1452. var a = index + stride * 0;
  1453. var b = index + stride * 1;
  1454. var c = index + stride * 2;
  1455. var d = index + stride * 3;
  1456. pushVector(a);pushVector(b);pushVector(d);
  1457. pushVector(b);pushVector(c);pushVector(d);
  1458. } else if (count === 3) {
  1459. var a = index + stride * 0;
  1460. var b = index + stride * 1;
  1461. var c = index + stride * 2;
  1462. pushVector(a);pushVector(b);pushVector(c);
  1463. } else if (count > 4) {
  1464. for (var k = 1, kl = count - 2; k <= kl; k++) {
  1465. var a = index + stride * 0;
  1466. var b = index + stride * k;
  1467. var c = index + stride * (k + 1);
  1468. pushVector(a);pushVector(b);pushVector(c);
  1469. }
  1470. }
  1471. index += stride * count;
  1472. }
  1473. } else {
  1474. for (var i = 0, l = indices.length; i < l; i += stride) {
  1475. pushVector(i);
  1476. }
  1477. }
  1478. }
  1479. function getGeometry(id) {
  1480. return getBuild(library.geometries[id], buildGeometry);
  1481. }
  1482. // kinematics
  1483. function parseKinematicsModel(xml) {
  1484. var data = {
  1485. name: xml.getAttribute('name') || '',
  1486. joints: {},
  1487. links: []
  1488. };
  1489. for (var i = 0; i < xml.childNodes.length; i++) {
  1490. var child = xml.childNodes[i];
  1491. if (child.nodeType !== 1) continue;
  1492. switch (child.nodeName) {
  1493. case 'technique_common':
  1494. parseKinematicsTechniqueCommon(child, data);
  1495. break;
  1496. }
  1497. }
  1498. library.kinematicsModels[xml.getAttribute('id')] = data;
  1499. }
  1500. function buildKinematicsModel(data) {
  1501. if (data.build !== undefined) return data.build;
  1502. return data;
  1503. }
  1504. function getKinematicsModel(id) {
  1505. return getBuild(library.kinematicsModels[id], buildKinematicsModel);
  1506. }
  1507. function parseKinematicsTechniqueCommon(xml, data) {
  1508. for (var i = 0; i < xml.childNodes.length; i++) {
  1509. var child = xml.childNodes[i];
  1510. if (child.nodeType !== 1) continue;
  1511. switch (child.nodeName) {
  1512. case 'joint':
  1513. data.joints[child.getAttribute('sid')] = parseKinematicsJoint(child);
  1514. break;
  1515. case 'link':
  1516. data.links.push(parseKinematicsLink(child));
  1517. break;
  1518. }
  1519. }
  1520. }
  1521. function parseKinematicsJoint(xml) {
  1522. var data;
  1523. for (var i = 0; i < xml.childNodes.length; i++) {
  1524. var child = xml.childNodes[i];
  1525. if (child.nodeType !== 1) continue;
  1526. switch (child.nodeName) {
  1527. case 'prismatic':
  1528. case 'revolute':
  1529. data = parseKinematicsJointParameter(child);
  1530. break;
  1531. }
  1532. }
  1533. return data;
  1534. }
  1535. function parseKinematicsJointParameter(xml, data) {
  1536. var data = {
  1537. sid: xml.getAttribute('sid'),
  1538. name: xml.getAttribute('name') || '',
  1539. axis: new THREE.Vector3(),
  1540. limits: {
  1541. min: 0,
  1542. max: 0
  1543. },
  1544. type: xml.nodeName,
  1545. static: false,
  1546. zeroPosition: 0,
  1547. middlePosition: 0
  1548. };
  1549. for (var i = 0; i < xml.childNodes.length; i++) {
  1550. var child = xml.childNodes[i];
  1551. if (child.nodeType !== 1) continue;
  1552. switch (child.nodeName) {
  1553. case 'axis':
  1554. var array = parseFloats(child.textContent);
  1555. data.axis.fromArray(array);
  1556. break;
  1557. case 'limits':
  1558. var max = child.getElementsByTagName('max')[0];
  1559. var min = child.getElementsByTagName('min')[0];
  1560. data.limits.max = parseFloat(max.textContent);
  1561. data.limits.min = parseFloat(min.textContent);
  1562. break;
  1563. }
  1564. }
  1565. // if min is equal to or greater than max, consider the joint static
  1566. if (data.limits.min >= data.limits.max) {
  1567. data.static = true;
  1568. }
  1569. // calculate middle position
  1570. data.middlePosition = (data.limits.min + data.limits.max) / 2.0;
  1571. return data;
  1572. }
  1573. function parseKinematicsLink(xml) {
  1574. var data = {
  1575. sid: xml.getAttribute('sid'),
  1576. name: xml.getAttribute('name') || '',
  1577. attachments: [],
  1578. transforms: []
  1579. };
  1580. for (var i = 0; i < xml.childNodes.length; i++) {
  1581. var child = xml.childNodes[i];
  1582. if (child.nodeType !== 1) continue;
  1583. switch (child.nodeName) {
  1584. case 'attachment_full':
  1585. data.attachments.push(parseKinematicsAttachment(child));
  1586. break;
  1587. case 'matrix':
  1588. case 'translate':
  1589. case 'rotate':
  1590. data.transforms.push(parseKinematicsTransform(child));
  1591. break;
  1592. }
  1593. }
  1594. return data;
  1595. }
  1596. function parseKinematicsAttachment(xml) {
  1597. var data = {
  1598. joint: xml.getAttribute('joint').split('/').pop(),
  1599. transforms: [],
  1600. links: []
  1601. };
  1602. for (var i = 0; i < xml.childNodes.length; i++) {
  1603. var child = xml.childNodes[i];
  1604. if (child.nodeType !== 1) continue;
  1605. switch (child.nodeName) {
  1606. case 'link':
  1607. data.links.push(parseKinematicsLink(child));
  1608. break;
  1609. case 'matrix':
  1610. case 'translate':
  1611. case 'rotate':
  1612. data.transforms.push(parseKinematicsTransform(child));
  1613. break;
  1614. }
  1615. }
  1616. return data;
  1617. }
  1618. function parseKinematicsTransform(xml) {
  1619. var data = {
  1620. type: xml.nodeName
  1621. };
  1622. var array = parseFloats(xml.textContent);
  1623. switch (data.type) {
  1624. case 'matrix':
  1625. data.obj = new THREE.Matrix4();
  1626. data.obj.fromArray(array).transpose();
  1627. break;
  1628. case 'translate':
  1629. data.obj = new THREE.Vector3();
  1630. data.obj.fromArray(array);
  1631. break;
  1632. case 'rotate':
  1633. data.obj = new THREE.Vector3();
  1634. data.obj.fromArray(array);
  1635. data.angle = THREE.Math.degToRad(array[3]);
  1636. break;
  1637. }
  1638. return data;
  1639. }
  1640. // physics
  1641. function parsePhysicsModel(xml) {
  1642. var data = {
  1643. name: xml.getAttribute('name') || '',
  1644. rigidBodies: {}
  1645. };
  1646. for (var i = 0; i < xml.childNodes.length; i++) {
  1647. var child = xml.childNodes[i];
  1648. if (child.nodeType !== 1) continue;
  1649. switch (child.nodeName) {
  1650. case 'rigid_body':
  1651. data.rigidBodies[child.getAttribute('name')] = {};
  1652. parsePhysicsRigidBody(child, data.rigidBodies[child.getAttribute('name')]);
  1653. break;
  1654. }
  1655. }
  1656. library.physicsModels[xml.getAttribute('id')] = data;
  1657. }
  1658. function parsePhysicsRigidBody(xml, data) {
  1659. for (var i = 0; i < xml.childNodes.length; i++) {
  1660. var child = xml.childNodes[i];
  1661. if (child.nodeType !== 1) continue;
  1662. switch (child.nodeName) {
  1663. case 'technique_common':
  1664. parsePhysicsTechniqueCommon(child, data);
  1665. break;
  1666. }
  1667. }
  1668. }
  1669. function parsePhysicsTechniqueCommon(xml, data) {
  1670. for (var i = 0; i < xml.childNodes.length; i++) {
  1671. var child = xml.childNodes[i];
  1672. if (child.nodeType !== 1) continue;
  1673. switch (child.nodeName) {
  1674. case 'inertia':
  1675. data.inertia = parseFloats(child.textContent);
  1676. break;
  1677. case 'mass':
  1678. data.mass = parseFloats(child.textContent)[0];
  1679. break;
  1680. }
  1681. }
  1682. }
  1683. // scene
  1684. function parseKinematicsScene(xml) {
  1685. var data = {
  1686. bindJointAxis: []
  1687. };
  1688. for (var i = 0; i < xml.childNodes.length; i++) {
  1689. var child = xml.childNodes[i];
  1690. if (child.nodeType !== 1) continue;
  1691. switch (child.nodeName) {
  1692. case 'bind_joint_axis':
  1693. data.bindJointAxis.push(parseKinematicsBindJointAxis(child));
  1694. break;
  1695. }
  1696. }
  1697. library.kinematicsScenes[parseId(xml.getAttribute('url'))] = data;
  1698. }
  1699. function parseKinematicsBindJointAxis(xml) {
  1700. var data = {
  1701. target: xml.getAttribute('target').split('/').pop()
  1702. };
  1703. for (var i = 0; i < xml.childNodes.length; i++) {
  1704. var child = xml.childNodes[i];
  1705. if (child.nodeType !== 1) continue;
  1706. switch (child.nodeName) {
  1707. case 'axis':
  1708. var param = child.getElementsByTagName('param')[0];
  1709. data.axis = param.textContent;
  1710. var tmpJointIndex = data.axis.split('inst_').pop().split('axis')[0];
  1711. data.jointIndex = tmpJointIndex.substr(0, tmpJointIndex.length - 1);
  1712. break;
  1713. }
  1714. }
  1715. return data;
  1716. }
  1717. function buildKinematicsScene(data) {
  1718. if (data.build !== undefined) return data.build;
  1719. return data;
  1720. }
  1721. function getKinematicsScene(id) {
  1722. return getBuild(library.kinematicsScenes[id], buildKinematicsScene);
  1723. }
  1724. function setupKinematics() {
  1725. var kinematicsModelId = Object.keys(library.kinematicsModels)[0];
  1726. var kinematicsSceneId = Object.keys(library.kinematicsScenes)[0];
  1727. var visualSceneId = Object.keys(library.visualScenes)[0];
  1728. if (kinematicsModelId === undefined || kinematicsSceneId === undefined) return;
  1729. var kinematicsModel = getKinematicsModel(kinematicsModelId);
  1730. var kinematicsScene = getKinematicsScene(kinematicsSceneId);
  1731. var visualScene = getVisualScene(visualSceneId);
  1732. var bindJointAxis = kinematicsScene.bindJointAxis;
  1733. var jointMap = {};
  1734. for (var i = 0, l = bindJointAxis.length; i < l; i++) {
  1735. var axis = bindJointAxis[i];
  1736. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1737. var targetElement = collada.querySelector('[sid="' + axis.target + '"]');
  1738. if (targetElement) {
  1739. // get the parent of the transfrom element
  1740. var parentVisualElement = targetElement.parentElement;
  1741. // connect the joint of the kinematics model with the element in the visual scene
  1742. connect(axis.jointIndex, parentVisualElement);
  1743. }
  1744. }
  1745. function connect(jointIndex, visualElement) {
  1746. var visualElementName = visualElement.getAttribute('name');
  1747. var joint = kinematicsModel.joints[jointIndex];
  1748. visualScene.traverse(function (object) {
  1749. if (object.name === visualElementName) {
  1750. jointMap[jointIndex] = {
  1751. object: object,
  1752. transforms: buildTransformList(visualElement),
  1753. joint: joint,
  1754. position: joint.zeroPosition
  1755. };
  1756. }
  1757. });
  1758. }
  1759. var m0 = new THREE.Matrix4();
  1760. kinematics = {
  1761. joints: kinematicsModel && kinematicsModel.joints,
  1762. getJointValue: function getJointValue(jointIndex) {
  1763. var jointData = jointMap[jointIndex];
  1764. if (jointData) {
  1765. return jointData.position;
  1766. } else {
  1767. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.');
  1768. }
  1769. },
  1770. setJointValue: function setJointValue(jointIndex, value) {
  1771. var jointData = jointMap[jointIndex];
  1772. if (jointData) {
  1773. var joint = jointData.joint;
  1774. if (value > joint.limits.max || value < joint.limits.min) {
  1775. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').');
  1776. } else if (joint.static) {
  1777. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' is static.');
  1778. } else {
  1779. var object = jointData.object;
  1780. var axis = joint.axis;
  1781. var transforms = jointData.transforms;
  1782. matrix.identity();
  1783. // each update, we have to apply all transforms in the correct order
  1784. for (var i = 0; i < transforms.length; i++) {
  1785. var transform = transforms[i];
  1786. // if there is a connection of the transform node with a joint, apply the joint value
  1787. if (transform.sid && transform.sid.indexOf(jointIndex) !== -1) {
  1788. switch (joint.type) {
  1789. case 'revolute':
  1790. matrix.multiply(m0.makeRotationAxis(axis, THREE.Math.degToRad(value)));
  1791. break;
  1792. case 'prismatic':
  1793. matrix.multiply(m0.makeTranslation(axis.x * value, axis.y * value, axis.z * value));
  1794. break;
  1795. default:
  1796. console.warn('THREE.ColladaLoader: Unknown joint type: ' + joint.type);
  1797. break;
  1798. }
  1799. } else {
  1800. switch (transform.type) {
  1801. case 'matrix':
  1802. matrix.multiply(transform.obj);
  1803. break;
  1804. case 'translate':
  1805. matrix.multiply(m0.makeTranslation(transform.obj.x, transform.obj.y, transform.obj.z));
  1806. break;
  1807. case 'scale':
  1808. matrix.scale(transform.obj);
  1809. break;
  1810. case 'rotate':
  1811. matrix.multiply(m0.makeRotationAxis(transform.obj, transform.angle));
  1812. break;
  1813. }
  1814. }
  1815. }
  1816. object.matrix.copy(matrix);
  1817. object.matrix.decompose(object.position, object.quaternion, object.scale);
  1818. jointMap[jointIndex].position = value;
  1819. }
  1820. } else {
  1821. console.log('THREE.ColladaLoader: ' + jointIndex + ' does not exist.');
  1822. }
  1823. }
  1824. };
  1825. }
  1826. function buildTransformList(node) {
  1827. var transforms = [];
  1828. var xml = collada.querySelector('[id="' + node.id + '"]');
  1829. for (var i = 0; i < xml.childNodes.length; i++) {
  1830. var child = xml.childNodes[i];
  1831. if (child.nodeType !== 1) continue;
  1832. switch (child.nodeName) {
  1833. case 'matrix':
  1834. var array = parseFloats(child.textContent);
  1835. var matrix = new THREE.Matrix4().fromArray(array).transpose();
  1836. transforms.push({
  1837. sid: child.getAttribute('sid'),
  1838. type: child.nodeName,
  1839. obj: matrix
  1840. });
  1841. break;
  1842. case 'translate':
  1843. case 'scale':
  1844. var array = parseFloats(child.textContent);
  1845. var vector = new THREE.Vector3().fromArray(array);
  1846. transforms.push({
  1847. sid: child.getAttribute('sid'),
  1848. type: child.nodeName,
  1849. obj: vector
  1850. });
  1851. break;
  1852. case 'rotate':
  1853. var array = parseFloats(child.textContent);
  1854. var vector = new THREE.Vector3().fromArray(array);
  1855. var angle = THREE.Math.degToRad(array[3]);
  1856. transforms.push({
  1857. sid: child.getAttribute('sid'),
  1858. type: child.nodeName,
  1859. obj: vector,
  1860. angle: angle
  1861. });
  1862. break;
  1863. }
  1864. }
  1865. return transforms;
  1866. }
  1867. // nodes
  1868. function prepareNodes(xml) {
  1869. var elements = xml.getElementsByTagName('node');
  1870. // ensure all node elements have id attributes
  1871. for (var i = 0; i < elements.length; i++) {
  1872. var element = elements[i];
  1873. if (element.hasAttribute('id') === false) {
  1874. element.setAttribute('id', generateId());
  1875. }
  1876. }
  1877. }
  1878. var matrix = new THREE.Matrix4();
  1879. var vector = new THREE.Vector3();
  1880. function parseNode(xml) {
  1881. var data = {
  1882. name: xml.getAttribute('name') || '',
  1883. type: xml.getAttribute('type'),
  1884. id: xml.getAttribute('id'),
  1885. sid: xml.getAttribute('sid'),
  1886. matrix: new THREE.Matrix4(),
  1887. nodes: [],
  1888. instanceCameras: [],
  1889. instanceControllers: [],
  1890. instanceLights: [],
  1891. instanceGeometries: [],
  1892. instanceNodes: [],
  1893. transforms: {}
  1894. };
  1895. for (var i = 0; i < xml.childNodes.length; i++) {
  1896. var child = xml.childNodes[i];
  1897. if (child.nodeType !== 1) continue;
  1898. switch (child.nodeName) {
  1899. case 'node':
  1900. data.nodes.push(child.getAttribute('id'));
  1901. parseNode(child);
  1902. break;
  1903. case 'instance_camera':
  1904. data.instanceCameras.push(parseId(child.getAttribute('url')));
  1905. break;
  1906. case 'instance_controller':
  1907. data.instanceControllers.push(parseNodeInstance(child));
  1908. break;
  1909. case 'instance_light':
  1910. data.instanceLights.push(parseId(child.getAttribute('url')));
  1911. break;
  1912. case 'instance_geometry':
  1913. data.instanceGeometries.push(parseNodeInstance(child));
  1914. break;
  1915. case 'instance_node':
  1916. data.instanceNodes.push(parseId(child.getAttribute('url')));
  1917. break;
  1918. case 'matrix':
  1919. var array = parseFloats(child.textContent);
  1920. data.matrix.multiply(matrix.fromArray(array).transpose());
  1921. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1922. break;
  1923. case 'translate':
  1924. var array = parseFloats(child.textContent);
  1925. vector.fromArray(array);
  1926. data.matrix.multiply(matrix.makeTranslation(vector.x, vector.y, vector.z));
  1927. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1928. break;
  1929. case 'rotate':
  1930. var array = parseFloats(child.textContent);
  1931. var angle = THREE.Math.degToRad(array[3]);
  1932. data.matrix.multiply(matrix.makeRotationAxis(vector.fromArray(array), angle));
  1933. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1934. break;
  1935. case 'scale':
  1936. var array = parseFloats(child.textContent);
  1937. data.matrix.scale(vector.fromArray(array));
  1938. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1939. break;
  1940. case 'extra':
  1941. break;
  1942. default:
  1943. console.log(child);
  1944. }
  1945. }
  1946. if (hasNode(data.id)) {
  1947. console.warn('THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id);
  1948. } else {
  1949. library.nodes[data.id] = data;
  1950. }
  1951. return data;
  1952. }
  1953. function parseNodeInstance(xml) {
  1954. var data = {
  1955. id: parseId(xml.getAttribute('url')),
  1956. materials: {},
  1957. skeletons: []
  1958. };
  1959. for (var i = 0; i < xml.childNodes.length; i++) {
  1960. var child = xml.childNodes[i];
  1961. switch (child.nodeName) {
  1962. case 'bind_material':
  1963. var instances = child.getElementsByTagName('instance_material');
  1964. for (var j = 0; j < instances.length; j++) {
  1965. var instance = instances[j];
  1966. var symbol = instance.getAttribute('symbol');
  1967. var target = instance.getAttribute('target');
  1968. data.materials[symbol] = parseId(target);
  1969. }
  1970. break;
  1971. case 'skeleton':
  1972. data.skeletons.push(parseId(child.textContent));
  1973. break;
  1974. default:
  1975. break;
  1976. }
  1977. }
  1978. return data;
  1979. }
  1980. function buildSkeleton(skeletons, joints) {
  1981. var boneData = [];
  1982. var sortedBoneData = [];
  1983. var i, j, data;
  1984. // a skeleton can have multiple root bones. collada expresses this
  1985. // situtation with multiple "skeleton" tags per controller instance
  1986. for (i = 0; i < skeletons.length; i++) {
  1987. var skeleton = skeletons[i];
  1988. var root;
  1989. if (hasNode(skeleton)) {
  1990. root = getNode(skeleton);
  1991. buildBoneHierarchy(root, joints, boneData);
  1992. } else if (hasVisualScene(skeleton)) {
  1993. // handle case where the skeleton refers to the visual scene (#13335)
  1994. var visualScene = library.visualScenes[skeleton];
  1995. var children = visualScene.children;
  1996. for (var j = 0; j < children.length; j++) {
  1997. var child = children[j];
  1998. if (child.type === 'JOINT') {
  1999. var root = getNode(child.id);
  2000. buildBoneHierarchy(root, joints, boneData);
  2001. }
  2002. }
  2003. } else {
  2004. console.error('THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton);
  2005. }
  2006. }
  2007. // sort bone data (the order is defined in the corresponding controller)
  2008. for (i = 0; i < joints.length; i++) {
  2009. for (j = 0; j < boneData.length; j++) {
  2010. data = boneData[j];
  2011. if (data.bone.name === joints[i].name) {
  2012. sortedBoneData[i] = data;
  2013. data.processed = true;
  2014. break;
  2015. }
  2016. }
  2017. }
  2018. // add unprocessed bone data at the end of the list
  2019. for (i = 0; i < boneData.length; i++) {
  2020. data = boneData[i];
  2021. if (data.processed === false) {
  2022. sortedBoneData.push(data);
  2023. data.processed = true;
  2024. }
  2025. }
  2026. // setup arrays for skeleton creation
  2027. var bones = [];
  2028. var boneInverses = [];
  2029. for (i = 0; i < sortedBoneData.length; i++) {
  2030. data = sortedBoneData[i];
  2031. bones.push(data.bone);
  2032. boneInverses.push(data.boneInverse);
  2033. }
  2034. return new THREE.Skeleton(bones, boneInverses);
  2035. }
  2036. function buildBoneHierarchy(root, joints, boneData) {
  2037. // setup bone data from visual scene
  2038. root.traverse(function (object) {
  2039. if (object.isBone === true) {
  2040. var boneInverse;
  2041. // retrieve the boneInverse from the controller data
  2042. for (var i = 0; i < joints.length; i++) {
  2043. var joint = joints[i];
  2044. if (joint.name === object.name) {
  2045. boneInverse = joint.boneInverse;
  2046. break;
  2047. }
  2048. }
  2049. if (boneInverse === undefined) {
  2050. // Unfortunately, there can be joints in the visual scene that are not part of the
  2051. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2052. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2053. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2054. // ensure a correct animation of the model.
  2055. boneInverse = new THREE.Matrix4();
  2056. }
  2057. boneData.push({ bone: object, boneInverse: boneInverse, processed: false });
  2058. }
  2059. });
  2060. }
  2061. function buildNode(data) {
  2062. var objects = [];
  2063. var matrix = data.matrix;
  2064. var nodes = data.nodes;
  2065. var type = data.type;
  2066. var instanceCameras = data.instanceCameras;
  2067. var instanceControllers = data.instanceControllers;
  2068. var instanceLights = data.instanceLights;
  2069. var instanceGeometries = data.instanceGeometries;
  2070. var instanceNodes = data.instanceNodes;
  2071. // nodes
  2072. for (var i = 0, l = nodes.length; i < l; i++) {
  2073. objects.push(getNode(nodes[i]));
  2074. }
  2075. // instance cameras
  2076. for (var i = 0, l = instanceCameras.length; i < l; i++) {
  2077. var instanceCamera = getCamera(instanceCameras[i]);
  2078. if (instanceCamera !== null) {
  2079. objects.push(instanceCamera.clone());
  2080. }
  2081. }
  2082. // instance controllers
  2083. for (var i = 0, l = instanceControllers.length; i < l; i++) {
  2084. var instance = instanceControllers[i];
  2085. var controller = getController(instance.id);
  2086. var geometries = getGeometry(controller.id);
  2087. var newObjects = buildObjects(geometries, instance.materials);
  2088. var skeletons = instance.skeletons;
  2089. var joints = controller.skin.joints;
  2090. var skeleton = buildSkeleton(skeletons, joints);
  2091. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2092. var object = newObjects[j];
  2093. if (object.isSkinnedMesh) {
  2094. object.bind(skeleton, controller.skin.bindMatrix);
  2095. object.normalizeSkinWeights();
  2096. }
  2097. objects.push(object);
  2098. }
  2099. }
  2100. // instance lights
  2101. for (var i = 0, l = instanceLights.length; i < l; i++) {
  2102. var instanceLight = getLight(instanceLights[i]);
  2103. if (instanceLight !== null) {
  2104. objects.push(instanceLight.clone());
  2105. }
  2106. }
  2107. // instance geometries
  2108. for (var i = 0, l = instanceGeometries.length; i < l; i++) {
  2109. var instance = instanceGeometries[i];
  2110. // a single geometry instance in collada can lead to multiple object3Ds.
  2111. // this is the case when primitives are combined like triangles and lines
  2112. var geometries = getGeometry(instance.id);
  2113. var newObjects = buildObjects(geometries, instance.materials);
  2114. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2115. objects.push(newObjects[j]);
  2116. }
  2117. }
  2118. // instance nodes
  2119. for (var i = 0, l = instanceNodes.length; i < l; i++) {
  2120. objects.push(getNode(instanceNodes[i]).clone());
  2121. }
  2122. var object;
  2123. if (nodes.length === 0 && objects.length === 1) {
  2124. object = objects[0];
  2125. } else {
  2126. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2127. for (var i = 0; i < objects.length; i++) {
  2128. object.add(objects[i]);
  2129. }
  2130. }
  2131. if (object.name === '') {
  2132. object.name = type === 'JOINT' ? data.sid : data.name;
  2133. }
  2134. object.matrix.copy(matrix);
  2135. object.matrix.decompose(object.position, object.quaternion, object.scale);
  2136. return object;
  2137. }
  2138. var fallbackMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff });
  2139. function resolveMaterialBinding(keys, instanceMaterials) {
  2140. var materials = [];
  2141. for (var i = 0, l = keys.length; i < l; i++) {
  2142. var id = instanceMaterials[keys[i]];
  2143. if (id === undefined) {
  2144. console.warn('THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[i]);
  2145. materials.push(fallbackMaterial);
  2146. } else {
  2147. materials.push(getMaterial(id));
  2148. }
  2149. }
  2150. return materials;
  2151. }
  2152. function buildObjects(geometries, instanceMaterials) {
  2153. var objects = [];
  2154. for (var type in geometries) {
  2155. var geometry = geometries[type];
  2156. var materials = resolveMaterialBinding(geometry.materialKeys, instanceMaterials);
  2157. // handle case if no materials are defined
  2158. if (materials.length === 0) {
  2159. if (type === 'lines' || type === 'linestrips') {
  2160. materials.push(new THREE.LineBasicMaterial());
  2161. } else {
  2162. materials.push(new THREE.MeshPhongMaterial());
  2163. }
  2164. }
  2165. // regard skinning
  2166. var skinning = geometry.data.attributes.skinIndex !== undefined;
  2167. if (skinning) {
  2168. for (var i = 0, l = materials.length; i < l; i++) {
  2169. materials[i].skinning = true;
  2170. }
  2171. }
  2172. // choose between a single or multi materials (material array)
  2173. var material = materials.length === 1 ? materials[0] : materials;
  2174. // now create a specific 3D object
  2175. var object;
  2176. switch (type) {
  2177. case 'lines':
  2178. object = new THREE.LineSegments(geometry.data, material);
  2179. break;
  2180. case 'linestrips':
  2181. object = new THREE.Line(geometry.data, material);
  2182. break;
  2183. case 'triangles':
  2184. case 'polylist':
  2185. if (skinning) {
  2186. object = new THREE.SkinnedMesh(geometry.data, material);
  2187. } else {
  2188. object = new THREE.Mesh(geometry.data, material);
  2189. }
  2190. break;
  2191. }
  2192. objects.push(object);
  2193. }
  2194. return objects;
  2195. }
  2196. function hasNode(id) {
  2197. return library.nodes[id] !== undefined;
  2198. }
  2199. function getNode(id) {
  2200. return getBuild(library.nodes[id], buildNode);
  2201. }
  2202. // visual scenes
  2203. function parseVisualScene(xml) {
  2204. var data = {
  2205. name: xml.getAttribute('name'),
  2206. children: []
  2207. };
  2208. prepareNodes(xml);
  2209. var elements = getElementsByTagName(xml, 'node');
  2210. for (var i = 0; i < elements.length; i++) {
  2211. data.children.push(parseNode(elements[i]));
  2212. }
  2213. library.visualScenes[xml.getAttribute('id')] = data;
  2214. }
  2215. function buildVisualScene(data) {
  2216. var group = new THREE.Group();
  2217. group.name = data.name;
  2218. var children = data.children;
  2219. for (var i = 0; i < children.length; i++) {
  2220. var child = children[i];
  2221. group.add(getNode(child.id));
  2222. }
  2223. return group;
  2224. }
  2225. function hasVisualScene(id) {
  2226. return library.visualScenes[id] !== undefined;
  2227. }
  2228. function getVisualScene(id) {
  2229. return getBuild(library.visualScenes[id], buildVisualScene);
  2230. }
  2231. // scenes
  2232. function parseScene(xml) {
  2233. var instance = getElementsByTagName(xml, 'instance_visual_scene')[0];
  2234. return getVisualScene(parseId(instance.getAttribute('url')));
  2235. }
  2236. function setupAnimations() {
  2237. var clips = library.clips;
  2238. if (isEmpty(clips) === true) {
  2239. if (isEmpty(library.animations) === false) {
  2240. // if there are animations but no clips, we create a default clip for playback
  2241. var tracks = [];
  2242. for (var id in library.animations) {
  2243. var animationTracks = getAnimation(id);
  2244. for (var i = 0, l = animationTracks.length; i < l; i++) {
  2245. tracks.push(animationTracks[i]);
  2246. }
  2247. }
  2248. animations.push(new THREE.AnimationClip('default', -1, tracks));
  2249. }
  2250. } else {
  2251. for (var id in clips) {
  2252. animations.push(getAnimationClip(id));
  2253. }
  2254. }
  2255. }
  2256. if (text.length === 0) {
  2257. return { scene: new THREE.Scene() };
  2258. }
  2259. var xml = new DOMParser().parseFromString(text, 'application/xml');
  2260. var collada = getElementsByTagName(xml, 'COLLADA')[0];
  2261. // metadata
  2262. var version = collada.getAttribute('version');
  2263. console.log('THREE.ColladaLoader: File version', version);
  2264. var asset = parseAsset(getElementsByTagName(collada, 'asset')[0]);
  2265. var textureLoader = new THREE.TextureLoader(this.manager);
  2266. textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
  2267. var tgaLoader;
  2268. if (THREE.TGALoader) {
  2269. tgaLoader = new THREE.TGALoader(this.manager);
  2270. tgaLoader.setPath(this.resourcePath || path);
  2271. }
  2272. //
  2273. var animations = [];
  2274. var kinematics = {};
  2275. var count = 0;
  2276. //
  2277. var library = {
  2278. animations: {},
  2279. clips: {},
  2280. controllers: {},
  2281. images: {},
  2282. effects: {},
  2283. materials: {},
  2284. cameras: {},
  2285. lights: {},
  2286. geometries: {},
  2287. nodes: {},
  2288. visualScenes: {},
  2289. kinematicsModels: {},
  2290. physicsModels: {},
  2291. kinematicsScenes: {}
  2292. };
  2293. parseLibrary(collada, 'library_animations', 'animation', parseAnimation);
  2294. parseLibrary(collada, 'library_animation_clips', 'animation_clip', parseAnimationClip);
  2295. parseLibrary(collada, 'library_controllers', 'controller', parseController);
  2296. parseLibrary(collada, 'library_images', 'image', parseImage);
  2297. parseLibrary(collada, 'library_effects', 'effect', parseEffect);
  2298. parseLibrary(collada, 'library_materials', 'material', parseMaterial);
  2299. parseLibrary(collada, 'library_cameras', 'camera', parseCamera);
  2300. parseLibrary(collada, 'library_lights', 'light', parseLight);
  2301. parseLibrary(collada, 'library_geometries', 'geometry', parseGeometry);
  2302. parseLibrary(collada, 'library_nodes', 'node', parseNode);
  2303. parseLibrary(collada, 'library_visual_scenes', 'visual_scene', parseVisualScene);
  2304. parseLibrary(collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel);
  2305. parseLibrary(collada, 'library_physics_models', 'physics_model', parsePhysicsModel);
  2306. parseLibrary(collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene);
  2307. buildLibrary(library.animations, buildAnimation);
  2308. buildLibrary(library.clips, buildAnimationClip);
  2309. buildLibrary(library.controllers, buildController);
  2310. buildLibrary(library.images, buildImage);
  2311. buildLibrary(library.effects, buildEffect);
  2312. buildLibrary(library.materials, buildMaterial);
  2313. buildLibrary(library.cameras, buildCamera);
  2314. buildLibrary(library.lights, buildLight);
  2315. buildLibrary(library.geometries, buildGeometry);
  2316. buildLibrary(library.visualScenes, buildVisualScene);
  2317. setupAnimations();
  2318. setupKinematics();
  2319. var scene = parseScene(getElementsByTagName(collada, 'scene')[0]);
  2320. if (asset.upAxis === 'Z_UP') {
  2321. scene.quaternion.setFromEuler(new THREE.Euler(-Math.PI / 2, 0, 0));
  2322. }
  2323. scene.scale.multiplyScalar(asset.unit);
  2324. return {
  2325. animations: animations,
  2326. kinematics: kinematics,
  2327. library: library,
  2328. scene: scene
  2329. };
  2330. }
  2331. };
  2332. },{}],3:[function(require,module,exports){
  2333. 'use strict';
  2334. 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; };
  2335. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  2336. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2337. } : function (obj) {
  2338. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2339. };
  2340. /**
  2341. * @author Kyle-Larson https://github.com/Kyle-Larson
  2342. * @author Takahiro https://github.com/takahirox
  2343. * @author Lewy Blue https://github.com/looeee
  2344. *
  2345. * Loader loads FBX file and generates Group representing FBX scene.
  2346. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  2347. * Versions lower than this may load but will probably have errors
  2348. *
  2349. * Needs Support:
  2350. * Morph normals / blend shape normals
  2351. *
  2352. * FBX format references:
  2353. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  2354. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  2355. *
  2356. * Binary format specification:
  2357. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  2358. */
  2359. module.exports = THREE.FBXLoader = function () {
  2360. var fbxTree;
  2361. var connections;
  2362. var sceneGraph;
  2363. function FBXLoader(manager) {
  2364. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  2365. }
  2366. FBXLoader.prototype = {
  2367. constructor: FBXLoader,
  2368. crossOrigin: 'anonymous',
  2369. load: function load(url, onLoad, onProgress, onError) {
  2370. var self = this;
  2371. var resourceDirectory = THREE.LoaderUtils.extractUrlBase(url);
  2372. var loader = new THREE.FileLoader(this.manager);
  2373. loader.setResponseType('arraybuffer');
  2374. loader.load(url, function (buffer) {
  2375. try {
  2376. var scene = self.parse(buffer, resourceDirectory);
  2377. onLoad(scene);
  2378. } catch (error) {
  2379. setTimeout(function () {
  2380. if (onError) onError(error);
  2381. self.manager.itemError(url);
  2382. }, 0);
  2383. }
  2384. }, onProgress, onError);
  2385. },
  2386. setCrossOrigin: function setCrossOrigin(value) {
  2387. this.crossOrigin = value;
  2388. return this;
  2389. },
  2390. parse: function parse(FBXBuffer, resourceDirectory) {
  2391. if (isFbxFormatBinary(FBXBuffer)) {
  2392. fbxTree = new BinaryParser().parse(FBXBuffer);
  2393. } else {
  2394. var FBXText = convertArrayBufferToString(FBXBuffer);
  2395. if (!isFbxFormatASCII(FBXText)) {
  2396. throw new Error('THREE.FBXLoader: Unknown format.');
  2397. }
  2398. if (getFbxVersion(FBXText) < 7000) {
  2399. throw new Error('THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion(FBXText));
  2400. }
  2401. fbxTree = new TextParser().parse(FBXText);
  2402. }
  2403. //console.log( FBXTree );
  2404. var textureLoader = new THREE.TextureLoader(this.manager).setPath(resourceDirectory).setCrossOrigin(this.crossOrigin);
  2405. return new FBXTreeParser(textureLoader).parse(fbxTree);
  2406. }
  2407. };
  2408. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  2409. function FBXTreeParser(textureLoader) {
  2410. this.textureLoader = textureLoader;
  2411. }
  2412. FBXTreeParser.prototype = {
  2413. constructor: FBXTreeParser,
  2414. parse: function parse() {
  2415. connections = this.parseConnections();
  2416. var images = this.parseImages();
  2417. var textures = this.parseTextures(images);
  2418. var materials = this.parseMaterials(textures);
  2419. var deformers = this.parseDeformers();
  2420. var geometryMap = new GeometryParser().parse(deformers);
  2421. this.parseScene(deformers, geometryMap, materials);
  2422. return sceneGraph;
  2423. },
  2424. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  2425. // and details the connection type
  2426. parseConnections: function parseConnections() {
  2427. var connectionMap = new Map();
  2428. if ('Connections' in fbxTree) {
  2429. var rawConnections = fbxTree.Connections.connections;
  2430. rawConnections.forEach(function (rawConnection) {
  2431. var fromID = rawConnection[0];
  2432. var toID = rawConnection[1];
  2433. var relationship = rawConnection[2];
  2434. if (!connectionMap.has(fromID)) {
  2435. connectionMap.set(fromID, {
  2436. parents: [],
  2437. children: []
  2438. });
  2439. }
  2440. var parentRelationship = { ID: toID, relationship: relationship };
  2441. connectionMap.get(fromID).parents.push(parentRelationship);
  2442. if (!connectionMap.has(toID)) {
  2443. connectionMap.set(toID, {
  2444. parents: [],
  2445. children: []
  2446. });
  2447. }
  2448. var childRelationship = { ID: fromID, relationship: relationship };
  2449. connectionMap.get(toID).children.push(childRelationship);
  2450. });
  2451. }
  2452. return connectionMap;
  2453. },
  2454. // Parse FBXTree.Objects.Video for embedded image data
  2455. // These images are connected to textures in FBXTree.Objects.Textures
  2456. // via FBXTree.Connections.
  2457. parseImages: function parseImages() {
  2458. var images = {};
  2459. var blobs = {};
  2460. if ('Video' in fbxTree.Objects) {
  2461. var videoNodes = fbxTree.Objects.Video;
  2462. for (var nodeID in videoNodes) {
  2463. var videoNode = videoNodes[nodeID];
  2464. var id = parseInt(nodeID);
  2465. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  2466. // raw image data is in videoNode.Content
  2467. if ('Content' in videoNode) {
  2468. var arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  2469. var base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  2470. if (arrayBufferContent || base64Content) {
  2471. var image = this.parseImage(videoNodes[nodeID]);
  2472. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  2473. }
  2474. }
  2475. }
  2476. }
  2477. for (var id in images) {
  2478. var filename = images[id];
  2479. if (blobs[filename] !== undefined) images[id] = blobs[filename];else images[id] = images[id].split('\\').pop();
  2480. }
  2481. return images;
  2482. },
  2483. // Parse embedded image data in FBXTree.Video.Content
  2484. parseImage: function parseImage(videoNode) {
  2485. var content = videoNode.Content;
  2486. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  2487. var extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
  2488. var type;
  2489. switch (extension) {
  2490. case 'bmp':
  2491. type = 'image/bmp';
  2492. break;
  2493. case 'jpg':
  2494. case 'jpeg':
  2495. type = 'image/jpeg';
  2496. break;
  2497. case 'png':
  2498. type = 'image/png';
  2499. break;
  2500. case 'tif':
  2501. type = 'image/tiff';
  2502. break;
  2503. case 'tga':
  2504. if (typeof THREE.TGALoader !== 'function') {
  2505. console.warn('FBXLoader: THREE.TGALoader is required to load TGA textures');
  2506. return;
  2507. } else {
  2508. if (THREE.Loader.Handlers.get('.tga') === null) {
  2509. THREE.Loader.Handlers.add(/\.tga$/i, new THREE.TGALoader());
  2510. }
  2511. type = 'image/tga';
  2512. break;
  2513. }
  2514. default:
  2515. console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
  2516. return;
  2517. }
  2518. if (typeof content === 'string') {
  2519. // ASCII format
  2520. return 'data:' + type + ';base64,' + content;
  2521. } else {
  2522. // Binary Format
  2523. var array = new Uint8Array(content);
  2524. return window.URL.createObjectURL(new Blob([array], { type: type }));
  2525. }
  2526. },
  2527. // Parse nodes in FBXTree.Objects.Texture
  2528. // These contain details such as UV scaling, cropping, rotation etc and are connected
  2529. // to images in FBXTree.Objects.Video
  2530. parseTextures: function parseTextures(images) {
  2531. var textureMap = new Map();
  2532. if ('Texture' in fbxTree.Objects) {
  2533. var textureNodes = fbxTree.Objects.Texture;
  2534. for (var nodeID in textureNodes) {
  2535. var texture = this.parseTexture(textureNodes[nodeID], images);
  2536. textureMap.set(parseInt(nodeID), texture);
  2537. }
  2538. }
  2539. return textureMap;
  2540. },
  2541. // Parse individual node in FBXTree.Objects.Texture
  2542. parseTexture: function parseTexture(textureNode, images) {
  2543. var texture = this.loadTexture(textureNode, images);
  2544. texture.ID = textureNode.id;
  2545. texture.name = textureNode.attrName;
  2546. var wrapModeU = textureNode.WrapModeU;
  2547. var wrapModeV = textureNode.WrapModeV;
  2548. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  2549. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  2550. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  2551. // 0: repeat(default), 1: clamp
  2552. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2553. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2554. if ('Scaling' in textureNode) {
  2555. var values = textureNode.Scaling.value;
  2556. texture.repeat.x = values[0];
  2557. texture.repeat.y = values[1];
  2558. }
  2559. return texture;
  2560. },
  2561. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  2562. loadTexture: function loadTexture(textureNode, images) {
  2563. var fileName;
  2564. var currentPath = this.textureLoader.path;
  2565. var children = connections.get(textureNode.id).children;
  2566. if (children !== undefined && children.length > 0 && images[children[0].ID] !== undefined) {
  2567. fileName = images[children[0].ID];
  2568. if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {
  2569. this.textureLoader.setPath(undefined);
  2570. }
  2571. }
  2572. var texture;
  2573. var extension = textureNode.FileName.slice(-3).toLowerCase();
  2574. if (extension === 'tga') {
  2575. var loader = THREE.Loader.Handlers.get('.tga');
  2576. if (loader === null) {
  2577. console.warn('FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName);
  2578. texture = new THREE.Texture();
  2579. } else {
  2580. texture = loader.load(fileName);
  2581. }
  2582. } else if (extension === 'psd') {
  2583. console.warn('FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName);
  2584. texture = new THREE.Texture();
  2585. } else {
  2586. texture = this.textureLoader.load(fileName);
  2587. }
  2588. this.textureLoader.setPath(currentPath);
  2589. return texture;
  2590. },
  2591. // Parse nodes in FBXTree.Objects.Material
  2592. parseMaterials: function parseMaterials(textureMap) {
  2593. var materialMap = new Map();
  2594. if ('Material' in fbxTree.Objects) {
  2595. var materialNodes = fbxTree.Objects.Material;
  2596. for (var nodeID in materialNodes) {
  2597. var material = this.parseMaterial(materialNodes[nodeID], textureMap);
  2598. if (material !== null) materialMap.set(parseInt(nodeID), material);
  2599. }
  2600. }
  2601. return materialMap;
  2602. },
  2603. // Parse single node in FBXTree.Objects.Material
  2604. // Materials are connected to texture maps in FBXTree.Objects.Textures
  2605. // FBX format currently only supports Lambert and Phong shading models
  2606. parseMaterial: function parseMaterial(materialNode, textureMap) {
  2607. var ID = materialNode.id;
  2608. var name = materialNode.attrName;
  2609. var type = materialNode.ShadingModel;
  2610. // Case where FBX wraps shading model in property object.
  2611. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
  2612. type = type.value;
  2613. }
  2614. // Ignore unused materials which don't have any connections.
  2615. if (!connections.has(ID)) return null;
  2616. var parameters = this.parseParameters(materialNode, textureMap, ID);
  2617. var material;
  2618. switch (type.toLowerCase()) {
  2619. case 'phong':
  2620. material = new THREE.MeshPhongMaterial();
  2621. break;
  2622. case 'lambert':
  2623. material = new THREE.MeshLambertMaterial();
  2624. break;
  2625. default:
  2626. console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
  2627. material = new THREE.MeshPhongMaterial({ color: 0x3300ff });
  2628. break;
  2629. }
  2630. material.setValues(parameters);
  2631. material.name = name;
  2632. return material;
  2633. },
  2634. // Parse FBX material and return parameters suitable for a three.js material
  2635. // Also parse the texture map and return any textures associated with the material
  2636. parseParameters: function parseParameters(materialNode, textureMap, ID) {
  2637. var parameters = {};
  2638. if (materialNode.BumpFactor) {
  2639. parameters.bumpScale = materialNode.BumpFactor.value;
  2640. }
  2641. if (materialNode.Diffuse) {
  2642. parameters.color = new THREE.Color().fromArray(materialNode.Diffuse.value);
  2643. } else if (materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color') {
  2644. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  2645. parameters.color = new THREE.Color().fromArray(materialNode.DiffuseColor.value);
  2646. }
  2647. if (materialNode.DisplacementFactor) {
  2648. parameters.displacementScale = materialNode.DisplacementFactor.value;
  2649. }
  2650. if (materialNode.Emissive) {
  2651. parameters.emissive = new THREE.Color().fromArray(materialNode.Emissive.value);
  2652. } else if (materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color') {
  2653. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  2654. parameters.emissive = new THREE.Color().fromArray(materialNode.EmissiveColor.value);
  2655. }
  2656. if (materialNode.EmissiveFactor) {
  2657. parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
  2658. }
  2659. if (materialNode.Opacity) {
  2660. parameters.opacity = parseFloat(materialNode.Opacity.value);
  2661. }
  2662. if (parameters.opacity < 1.0) {
  2663. parameters.transparent = true;
  2664. }
  2665. if (materialNode.ReflectionFactor) {
  2666. parameters.reflectivity = materialNode.ReflectionFactor.value;
  2667. }
  2668. if (materialNode.Shininess) {
  2669. parameters.shininess = materialNode.Shininess.value;
  2670. }
  2671. if (materialNode.Specular) {
  2672. parameters.specular = new THREE.Color().fromArray(materialNode.Specular.value);
  2673. } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color') {
  2674. // The blender exporter exports specular color here instead of in materialNode.Specular
  2675. parameters.specular = new THREE.Color().fromArray(materialNode.SpecularColor.value);
  2676. }
  2677. var self = this;
  2678. connections.get(ID).children.forEach(function (child) {
  2679. var type = child.relationship;
  2680. switch (type) {
  2681. case 'Bump':
  2682. parameters.bumpMap = self.getTexture(textureMap, child.ID);
  2683. break;
  2684. case 'DiffuseColor':
  2685. parameters.map = self.getTexture(textureMap, child.ID);
  2686. break;
  2687. case 'DisplacementColor':
  2688. parameters.displacementMap = self.getTexture(textureMap, child.ID);
  2689. break;
  2690. case 'EmissiveColor':
  2691. parameters.emissiveMap = self.getTexture(textureMap, child.ID);
  2692. break;
  2693. case 'NormalMap':
  2694. parameters.normalMap = self.getTexture(textureMap, child.ID);
  2695. break;
  2696. case 'ReflectionColor':
  2697. parameters.envMap = self.getTexture(textureMap, child.ID);
  2698. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  2699. break;
  2700. case 'SpecularColor':
  2701. parameters.specularMap = self.getTexture(textureMap, child.ID);
  2702. break;
  2703. case 'TransparentColor':
  2704. parameters.alphaMap = self.getTexture(textureMap, child.ID);
  2705. parameters.transparent = true;
  2706. break;
  2707. case 'AmbientColor':
  2708. case 'ShininessExponent': // AKA glossiness map
  2709. case 'SpecularFactor': // AKA specularLevel
  2710. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  2711. default:
  2712. console.warn('THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type);
  2713. break;
  2714. }
  2715. });
  2716. return parameters;
  2717. },
  2718. // get a texture from the textureMap for use by a material.
  2719. getTexture: function getTexture(textureMap, id) {
  2720. // if the texture is a layered texture, just use the first layer and issue a warning
  2721. if ('LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
  2722. console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');
  2723. id = connections.get(id).children[0].ID;
  2724. }
  2725. return textureMap.get(id);
  2726. },
  2727. // Parse nodes in FBXTree.Objects.Deformer
  2728. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  2729. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  2730. parseDeformers: function parseDeformers() {
  2731. var skeletons = {};
  2732. var morphTargets = {};
  2733. if ('Deformer' in fbxTree.Objects) {
  2734. var DeformerNodes = fbxTree.Objects.Deformer;
  2735. for (var nodeID in DeformerNodes) {
  2736. var deformerNode = DeformerNodes[nodeID];
  2737. var relationships = connections.get(parseInt(nodeID));
  2738. if (deformerNode.attrType === 'Skin') {
  2739. var skeleton = this.parseSkeleton(relationships, DeformerNodes);
  2740. skeleton.ID = nodeID;
  2741. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: skeleton attached to more than one geometry is not supported.');
  2742. skeleton.geometryID = relationships.parents[0].ID;
  2743. skeletons[nodeID] = skeleton;
  2744. } else if (deformerNode.attrType === 'BlendShape') {
  2745. var morphTarget = {
  2746. id: nodeID
  2747. };
  2748. morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
  2749. morphTarget.id = nodeID;
  2750. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: morph target attached to more than one geometry is not supported.');
  2751. morphTargets[nodeID] = morphTarget;
  2752. }
  2753. }
  2754. }
  2755. return {
  2756. skeletons: skeletons,
  2757. morphTargets: morphTargets
  2758. };
  2759. },
  2760. // Parse single nodes in FBXTree.Objects.Deformer
  2761. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  2762. // Each skin node represents a skeleton and each cluster node represents a bone
  2763. parseSkeleton: function parseSkeleton(relationships, deformerNodes) {
  2764. var rawBones = [];
  2765. relationships.children.forEach(function (child) {
  2766. var boneNode = deformerNodes[child.ID];
  2767. if (boneNode.attrType !== 'Cluster') return;
  2768. var rawBone = {
  2769. ID: child.ID,
  2770. indices: [],
  2771. weights: [],
  2772. transform: new THREE.Matrix4().fromArray(boneNode.Transform.a),
  2773. transformLink: new THREE.Matrix4().fromArray(boneNode.TransformLink.a),
  2774. linkMode: boneNode.Mode
  2775. };
  2776. if ('Indexes' in boneNode) {
  2777. rawBone.indices = boneNode.Indexes.a;
  2778. rawBone.weights = boneNode.Weights.a;
  2779. }
  2780. rawBones.push(rawBone);
  2781. });
  2782. return {
  2783. rawBones: rawBones,
  2784. bones: []
  2785. };
  2786. },
  2787. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  2788. parseMorphTargets: function parseMorphTargets(relationships, deformerNodes) {
  2789. var rawMorphTargets = [];
  2790. for (var i = 0; i < relationships.children.length; i++) {
  2791. if (i === 8) {
  2792. console.warn('FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.');
  2793. break;
  2794. }
  2795. var child = relationships.children[i];
  2796. var morphTargetNode = deformerNodes[child.ID];
  2797. var rawMorphTarget = {
  2798. name: morphTargetNode.attrName,
  2799. initialWeight: morphTargetNode.DeformPercent,
  2800. id: morphTargetNode.id,
  2801. fullWeights: morphTargetNode.FullWeights.a
  2802. };
  2803. if (morphTargetNode.attrType !== 'BlendShapeChannel') return;
  2804. var targetRelationships = connections.get(parseInt(child.ID));
  2805. targetRelationships.children.forEach(function (child) {
  2806. if (child.relationship === undefined) rawMorphTarget.geoID = child.ID;
  2807. });
  2808. rawMorphTargets.push(rawMorphTarget);
  2809. }
  2810. return rawMorphTargets;
  2811. },
  2812. // create the main THREE.Group() to be returned by the loader
  2813. parseScene: function parseScene(deformers, geometryMap, materialMap) {
  2814. sceneGraph = new THREE.Group();
  2815. var modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
  2816. var modelNodes = fbxTree.Objects.Model;
  2817. var self = this;
  2818. modelMap.forEach(function (model) {
  2819. var modelNode = modelNodes[model.ID];
  2820. self.setLookAtProperties(model, modelNode);
  2821. var parentConnections = connections.get(model.ID).parents;
  2822. parentConnections.forEach(function (connection) {
  2823. var parent = modelMap.get(connection.ID);
  2824. if (parent !== undefined) parent.add(model);
  2825. });
  2826. if (model.parent === null) {
  2827. sceneGraph.add(model);
  2828. }
  2829. });
  2830. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  2831. this.createAmbientLight();
  2832. this.setupMorphMaterials();
  2833. var animations = new AnimationParser().parse();
  2834. // if all the models where already combined in a single group, just return that
  2835. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  2836. sceneGraph.children[0].animations = animations;
  2837. sceneGraph = sceneGraph.children[0];
  2838. }
  2839. sceneGraph.animations = animations;
  2840. },
  2841. // parse nodes in FBXTree.Objects.Model
  2842. parseModels: function parseModels(skeletons, geometryMap, materialMap) {
  2843. var modelMap = new Map();
  2844. var modelNodes = fbxTree.Objects.Model;
  2845. for (var nodeID in modelNodes) {
  2846. var id = parseInt(nodeID);
  2847. var node = modelNodes[nodeID];
  2848. var relationships = connections.get(id);
  2849. var model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
  2850. if (!model) {
  2851. switch (node.attrType) {
  2852. case 'Camera':
  2853. model = this.createCamera(relationships);
  2854. break;
  2855. case 'Light':
  2856. model = this.createLight(relationships);
  2857. break;
  2858. case 'Mesh':
  2859. model = this.createMesh(relationships, geometryMap, materialMap);
  2860. break;
  2861. case 'NurbsCurve':
  2862. model = this.createCurve(relationships, geometryMap);
  2863. break;
  2864. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  2865. case 'Null':
  2866. default:
  2867. model = new THREE.Group();
  2868. break;
  2869. }
  2870. model.name = THREE.PropertyBinding.sanitizeNodeName(node.attrName);
  2871. model.ID = id;
  2872. }
  2873. this.setModelTransforms(model, node);
  2874. modelMap.set(id, model);
  2875. }
  2876. return modelMap;
  2877. },
  2878. buildSkeleton: function buildSkeleton(relationships, skeletons, id, name) {
  2879. var bone = null;
  2880. relationships.parents.forEach(function (parent) {
  2881. for (var ID in skeletons) {
  2882. var skeleton = skeletons[ID];
  2883. skeleton.rawBones.forEach(function (rawBone, i) {
  2884. if (rawBone.ID === parent.ID) {
  2885. var subBone = bone;
  2886. bone = new THREE.Bone();
  2887. bone.matrixWorld.copy(rawBone.transformLink);
  2888. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  2889. bone.name = THREE.PropertyBinding.sanitizeNodeName(name);
  2890. bone.ID = id;
  2891. skeleton.bones[i] = bone;
  2892. // In cases where a bone is shared between multiple meshes
  2893. // duplicate the bone here and and it as a child of the first bone
  2894. if (subBone !== null) {
  2895. bone.add(subBone);
  2896. }
  2897. }
  2898. });
  2899. }
  2900. });
  2901. return bone;
  2902. },
  2903. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  2904. createCamera: function createCamera(relationships) {
  2905. var model;
  2906. var cameraAttribute;
  2907. relationships.children.forEach(function (child) {
  2908. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2909. if (attr !== undefined) {
  2910. cameraAttribute = attr;
  2911. }
  2912. });
  2913. if (cameraAttribute === undefined) {
  2914. model = new THREE.Object3D();
  2915. } else {
  2916. var type = 0;
  2917. if (cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1) {
  2918. type = 1;
  2919. }
  2920. var nearClippingPlane = 1;
  2921. if (cameraAttribute.NearPlane !== undefined) {
  2922. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  2923. }
  2924. var farClippingPlane = 1000;
  2925. if (cameraAttribute.FarPlane !== undefined) {
  2926. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  2927. }
  2928. var width = window.innerWidth;
  2929. var height = window.innerHeight;
  2930. if (cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined) {
  2931. width = cameraAttribute.AspectWidth.value;
  2932. height = cameraAttribute.AspectHeight.value;
  2933. }
  2934. var aspect = width / height;
  2935. var fov = 45;
  2936. if (cameraAttribute.FieldOfView !== undefined) {
  2937. fov = cameraAttribute.FieldOfView.value;
  2938. }
  2939. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  2940. switch (type) {
  2941. case 0:
  2942. // Perspective
  2943. model = new THREE.PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
  2944. if (focalLength !== null) model.setFocalLength(focalLength);
  2945. break;
  2946. case 1:
  2947. // Orthographic
  2948. model = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane);
  2949. break;
  2950. default:
  2951. console.warn('THREE.FBXLoader: Unknown camera type ' + type + '.');
  2952. model = new THREE.Object3D();
  2953. break;
  2954. }
  2955. }
  2956. return model;
  2957. },
  2958. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  2959. createLight: function createLight(relationships) {
  2960. var model;
  2961. var lightAttribute;
  2962. relationships.children.forEach(function (child) {
  2963. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2964. if (attr !== undefined) {
  2965. lightAttribute = attr;
  2966. }
  2967. });
  2968. if (lightAttribute === undefined) {
  2969. model = new THREE.Object3D();
  2970. } else {
  2971. var type;
  2972. // LightType can be undefined for Point lights
  2973. if (lightAttribute.LightType === undefined) {
  2974. type = 0;
  2975. } else {
  2976. type = lightAttribute.LightType.value;
  2977. }
  2978. var color = 0xffffff;
  2979. if (lightAttribute.Color !== undefined) {
  2980. color = new THREE.Color().fromArray(lightAttribute.Color.value);
  2981. }
  2982. var intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100;
  2983. // light disabled
  2984. if (lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0) {
  2985. intensity = 0;
  2986. }
  2987. var distance = 0;
  2988. if (lightAttribute.FarAttenuationEnd !== undefined) {
  2989. if (lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0) {
  2990. distance = 0;
  2991. } else {
  2992. distance = lightAttribute.FarAttenuationEnd.value;
  2993. }
  2994. }
  2995. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  2996. var decay = 1;
  2997. switch (type) {
  2998. case 0:
  2999. // Point
  3000. model = new THREE.PointLight(color, intensity, distance, decay);
  3001. break;
  3002. case 1:
  3003. // Directional
  3004. model = new THREE.DirectionalLight(color, intensity);
  3005. break;
  3006. case 2:
  3007. // Spot
  3008. var angle = Math.PI / 3;
  3009. if (lightAttribute.InnerAngle !== undefined) {
  3010. angle = THREE.Math.degToRad(lightAttribute.InnerAngle.value);
  3011. }
  3012. var penumbra = 0;
  3013. if (lightAttribute.OuterAngle !== undefined) {
  3014. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  3015. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  3016. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  3017. penumbra = THREE.Math.degToRad(lightAttribute.OuterAngle.value);
  3018. penumbra = Math.max(penumbra, 1);
  3019. }
  3020. model = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
  3021. break;
  3022. default:
  3023. console.warn('THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.');
  3024. model = new THREE.PointLight(color, intensity);
  3025. break;
  3026. }
  3027. if (lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1) {
  3028. model.castShadow = true;
  3029. }
  3030. }
  3031. return model;
  3032. },
  3033. createMesh: function createMesh(relationships, geometryMap, materialMap) {
  3034. var model;
  3035. var geometry = null;
  3036. var material = null;
  3037. var materials = [];
  3038. // get geometry and materials(s) from connections
  3039. relationships.children.forEach(function (child) {
  3040. if (geometryMap.has(child.ID)) {
  3041. geometry = geometryMap.get(child.ID);
  3042. }
  3043. if (materialMap.has(child.ID)) {
  3044. materials.push(materialMap.get(child.ID));
  3045. }
  3046. });
  3047. if (materials.length > 1) {
  3048. material = materials;
  3049. } else if (materials.length > 0) {
  3050. material = materials[0];
  3051. } else {
  3052. material = new THREE.MeshPhongMaterial({ color: 0xcccccc });
  3053. materials.push(material);
  3054. }
  3055. if ('color' in geometry.attributes) {
  3056. materials.forEach(function (material) {
  3057. material.vertexColors = THREE.VertexColors;
  3058. });
  3059. }
  3060. if (geometry.FBX_Deformer) {
  3061. materials.forEach(function (material) {
  3062. material.skinning = true;
  3063. });
  3064. model = new THREE.SkinnedMesh(geometry, material);
  3065. } else {
  3066. model = new THREE.Mesh(geometry, material);
  3067. }
  3068. return model;
  3069. },
  3070. createCurve: function createCurve(relationships, geometryMap) {
  3071. var geometry = relationships.children.reduce(function (geo, child) {
  3072. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  3073. return geo;
  3074. }, null);
  3075. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  3076. var material = new THREE.LineBasicMaterial({ color: 0x3300ff, linewidth: 1 });
  3077. return new THREE.Line(geometry, material);
  3078. },
  3079. // parse the model node for transform details and apply them to the model
  3080. setModelTransforms: function setModelTransforms(model, modelNode) {
  3081. var transformData = {};
  3082. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3083. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3084. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3085. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3086. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3087. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3088. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3089. var transform = generateTransform(transformData);
  3090. model.applyMatrix(transform);
  3091. },
  3092. setLookAtProperties: function setLookAtProperties(model, modelNode) {
  3093. if ('LookAtProperty' in modelNode) {
  3094. var children = connections.get(model.ID).children;
  3095. children.forEach(function (child) {
  3096. if (child.relationship === 'LookAtProperty') {
  3097. var lookAtTarget = fbxTree.Objects.Model[child.ID];
  3098. if ('Lcl_Translation' in lookAtTarget) {
  3099. var pos = lookAtTarget.Lcl_Translation.value;
  3100. // DirectionalLight, SpotLight
  3101. if (model.target !== undefined) {
  3102. model.target.position.fromArray(pos);
  3103. sceneGraph.add(model.target);
  3104. } else {
  3105. // Cameras and other Object3Ds
  3106. model.lookAt(new THREE.Vector3().fromArray(pos));
  3107. }
  3108. }
  3109. }
  3110. });
  3111. }
  3112. },
  3113. bindSkeleton: function bindSkeleton(skeletons, geometryMap, modelMap) {
  3114. var bindMatrices = this.parsePoseNodes();
  3115. for (var ID in skeletons) {
  3116. var skeleton = skeletons[ID];
  3117. var parents = connections.get(parseInt(skeleton.ID)).parents;
  3118. parents.forEach(function (parent) {
  3119. if (geometryMap.has(parent.ID)) {
  3120. var geoID = parent.ID;
  3121. var geoRelationships = connections.get(geoID);
  3122. geoRelationships.parents.forEach(function (geoConnParent) {
  3123. if (modelMap.has(geoConnParent.ID)) {
  3124. var model = modelMap.get(geoConnParent.ID);
  3125. model.bind(new THREE.Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
  3126. }
  3127. });
  3128. }
  3129. });
  3130. }
  3131. },
  3132. parsePoseNodes: function parsePoseNodes() {
  3133. var bindMatrices = {};
  3134. if ('Pose' in fbxTree.Objects) {
  3135. var BindPoseNode = fbxTree.Objects.Pose;
  3136. for (var nodeID in BindPoseNode) {
  3137. if (BindPoseNode[nodeID].attrType === 'BindPose') {
  3138. var poseNodes = BindPoseNode[nodeID].PoseNode;
  3139. if (Array.isArray(poseNodes)) {
  3140. poseNodes.forEach(function (poseNode) {
  3141. bindMatrices[poseNode.Node] = new THREE.Matrix4().fromArray(poseNode.Matrix.a);
  3142. });
  3143. } else {
  3144. bindMatrices[poseNodes.Node] = new THREE.Matrix4().fromArray(poseNodes.Matrix.a);
  3145. }
  3146. }
  3147. }
  3148. }
  3149. return bindMatrices;
  3150. },
  3151. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  3152. createAmbientLight: function createAmbientLight() {
  3153. if ('GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings) {
  3154. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  3155. var r = ambientColor[0];
  3156. var g = ambientColor[1];
  3157. var b = ambientColor[2];
  3158. if (r !== 0 || g !== 0 || b !== 0) {
  3159. var color = new THREE.Color(r, g, b);
  3160. sceneGraph.add(new THREE.AmbientLight(color, 1));
  3161. }
  3162. }
  3163. },
  3164. setupMorphMaterials: function setupMorphMaterials() {
  3165. sceneGraph.traverse(function (child) {
  3166. if (child.isMesh) {
  3167. if (child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal) {
  3168. var uuid = child.uuid;
  3169. var matUuid = child.material.uuid;
  3170. // if a geometry has morph targets, it cannot share the material with other geometries
  3171. var sharedMat = false;
  3172. sceneGraph.traverse(function (child) {
  3173. if (child.isMesh) {
  3174. if (child.material.uuid === matUuid && child.uuid !== uuid) sharedMat = true;
  3175. }
  3176. });
  3177. if (sharedMat === true) child.material = child.material.clone();
  3178. child.material.morphTargets = true;
  3179. }
  3180. }
  3181. });
  3182. }
  3183. };
  3184. // parse Geometry data from FBXTree and return map of BufferGeometries
  3185. function GeometryParser() {}
  3186. GeometryParser.prototype = {
  3187. constructor: GeometryParser,
  3188. // Parse nodes in FBXTree.Objects.Geometry
  3189. parse: function parse(deformers) {
  3190. var geometryMap = new Map();
  3191. if ('Geometry' in fbxTree.Objects) {
  3192. var geoNodes = fbxTree.Objects.Geometry;
  3193. for (var nodeID in geoNodes) {
  3194. var relationships = connections.get(parseInt(nodeID));
  3195. var geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
  3196. geometryMap.set(parseInt(nodeID), geo);
  3197. }
  3198. }
  3199. return geometryMap;
  3200. },
  3201. // Parse single node in FBXTree.Objects.Geometry
  3202. parseGeometry: function parseGeometry(relationships, geoNode, deformers) {
  3203. switch (geoNode.attrType) {
  3204. case 'Mesh':
  3205. return this.parseMeshGeometry(relationships, geoNode, deformers);
  3206. break;
  3207. case 'NurbsCurve':
  3208. return this.parseNurbsGeometry(geoNode);
  3209. break;
  3210. }
  3211. },
  3212. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  3213. parseMeshGeometry: function parseMeshGeometry(relationships, geoNode, deformers) {
  3214. var skeletons = deformers.skeletons;
  3215. var morphTargets = deformers.morphTargets;
  3216. var modelNodes = relationships.parents.map(function (parent) {
  3217. return fbxTree.Objects.Model[parent.ID];
  3218. });
  3219. // don't create geometry if it is not associated with any models
  3220. if (modelNodes.length === 0) return;
  3221. var skeleton = relationships.children.reduce(function (skeleton, child) {
  3222. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  3223. return skeleton;
  3224. }, null);
  3225. var morphTarget = relationships.children.reduce(function (morphTarget, child) {
  3226. if (morphTargets[child.ID] !== undefined) morphTarget = morphTargets[child.ID];
  3227. return morphTarget;
  3228. }, null);
  3229. // TODO: if there is more than one model associated with the geometry, AND the models have
  3230. // different geometric transforms, then this will cause problems
  3231. // if ( modelNodes.length > 1 ) { }
  3232. // For now just assume one model and get the preRotations from that
  3233. var modelNode = modelNodes[0];
  3234. var transformData = {};
  3235. if ('RotationOrder' in modelNode) transformData.eulerOrder = modelNode.RotationOrder.value;
  3236. if ('GeometricTranslation' in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
  3237. if ('GeometricRotation' in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
  3238. if ('GeometricScaling' in modelNode) transformData.scale = modelNode.GeometricScaling.value;
  3239. var transform = generateTransform(transformData);
  3240. return this.genGeometry(geoNode, skeleton, morphTarget, transform);
  3241. },
  3242. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  3243. genGeometry: function genGeometry(geoNode, skeleton, morphTarget, preTransform) {
  3244. var geo = new THREE.BufferGeometry();
  3245. if (geoNode.attrName) geo.name = geoNode.attrName;
  3246. var geoInfo = this.parseGeoNode(geoNode, skeleton);
  3247. var buffers = this.genBuffers(geoInfo);
  3248. var positionAttribute = new THREE.Float32BufferAttribute(buffers.vertex, 3);
  3249. preTransform.applyToBufferAttribute(positionAttribute);
  3250. geo.addAttribute('position', positionAttribute);
  3251. if (buffers.colors.length > 0) {
  3252. geo.addAttribute('color', new THREE.Float32BufferAttribute(buffers.colors, 3));
  3253. }
  3254. if (skeleton) {
  3255. geo.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(buffers.weightsIndices, 4));
  3256. geo.addAttribute('skinWeight', new THREE.Float32BufferAttribute(buffers.vertexWeights, 4));
  3257. // used later to bind the skeleton to the model
  3258. geo.FBX_Deformer = skeleton;
  3259. }
  3260. if (buffers.normal.length > 0) {
  3261. var normalAttribute = new THREE.Float32BufferAttribute(buffers.normal, 3);
  3262. var normalMatrix = new THREE.Matrix3().getNormalMatrix(preTransform);
  3263. normalMatrix.applyToBufferAttribute(normalAttribute);
  3264. geo.addAttribute('normal', normalAttribute);
  3265. }
  3266. buffers.uvs.forEach(function (uvBuffer, i) {
  3267. // subsequent uv buffers are called 'uv1', 'uv2', ...
  3268. var name = 'uv' + (i + 1).toString();
  3269. // the first uv buffer is just called 'uv'
  3270. if (i === 0) {
  3271. name = 'uv';
  3272. }
  3273. geo.addAttribute(name, new THREE.Float32BufferAttribute(buffers.uvs[i], 2));
  3274. });
  3275. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3276. // Convert the material indices of each vertex into rendering groups on the geometry.
  3277. var prevMaterialIndex = buffers.materialIndex[0];
  3278. var startIndex = 0;
  3279. buffers.materialIndex.forEach(function (currentIndex, i) {
  3280. if (currentIndex !== prevMaterialIndex) {
  3281. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  3282. prevMaterialIndex = currentIndex;
  3283. startIndex = i;
  3284. }
  3285. });
  3286. // the loop above doesn't add the last group, do that here.
  3287. if (geo.groups.length > 0) {
  3288. var lastGroup = geo.groups[geo.groups.length - 1];
  3289. var lastIndex = lastGroup.start + lastGroup.count;
  3290. if (lastIndex !== buffers.materialIndex.length) {
  3291. geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
  3292. }
  3293. }
  3294. // case where there are multiple materials but the whole geometry is only
  3295. // using one of them
  3296. if (geo.groups.length === 0) {
  3297. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  3298. }
  3299. }
  3300. this.addMorphTargets(geo, geoNode, morphTarget, preTransform);
  3301. return geo;
  3302. },
  3303. parseGeoNode: function parseGeoNode(geoNode, skeleton) {
  3304. var geoInfo = {};
  3305. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  3306. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  3307. if (geoNode.LayerElementColor) {
  3308. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  3309. }
  3310. if (geoNode.LayerElementMaterial) {
  3311. geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
  3312. }
  3313. if (geoNode.LayerElementNormal) {
  3314. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  3315. }
  3316. if (geoNode.LayerElementUV) {
  3317. geoInfo.uv = [];
  3318. var i = 0;
  3319. while (geoNode.LayerElementUV[i]) {
  3320. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  3321. i++;
  3322. }
  3323. }
  3324. geoInfo.weightTable = {};
  3325. if (skeleton !== null) {
  3326. geoInfo.skeleton = skeleton;
  3327. skeleton.rawBones.forEach(function (rawBone, i) {
  3328. // loop over the bone's vertex indices and weights
  3329. rawBone.indices.forEach(function (index, j) {
  3330. if (geoInfo.weightTable[index] === undefined) geoInfo.weightTable[index] = [];
  3331. geoInfo.weightTable[index].push({
  3332. id: i,
  3333. weight: rawBone.weights[j]
  3334. });
  3335. });
  3336. });
  3337. }
  3338. return geoInfo;
  3339. },
  3340. genBuffers: function genBuffers(geoInfo) {
  3341. var buffers = {
  3342. vertex: [],
  3343. normal: [],
  3344. colors: [],
  3345. uvs: [],
  3346. materialIndex: [],
  3347. vertexWeights: [],
  3348. weightsIndices: []
  3349. };
  3350. var polygonIndex = 0;
  3351. var faceLength = 0;
  3352. var displayedWeightsWarning = false;
  3353. // these will hold data for a single face
  3354. var facePositionIndexes = [];
  3355. var faceNormals = [];
  3356. var faceColors = [];
  3357. var faceUVs = [];
  3358. var faceWeights = [];
  3359. var faceWeightIndices = [];
  3360. var self = this;
  3361. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  3362. var endOfFace = false;
  3363. // Face index and vertex index arrays are combined in a single array
  3364. // A cube with quad faces looks like this:
  3365. // PolygonVertexIndex: *24 {
  3366. // 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
  3367. // }
  3368. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  3369. // to find index of last vertex bit shift the index: ^ - 1
  3370. if (vertexIndex < 0) {
  3371. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  3372. endOfFace = true;
  3373. }
  3374. var weightIndices = [];
  3375. var weights = [];
  3376. facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
  3377. if (geoInfo.color) {
  3378. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
  3379. faceColors.push(data[0], data[1], data[2]);
  3380. }
  3381. if (geoInfo.skeleton) {
  3382. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  3383. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  3384. weights.push(wt.weight);
  3385. weightIndices.push(wt.id);
  3386. });
  3387. }
  3388. if (weights.length > 4) {
  3389. if (!displayedWeightsWarning) {
  3390. console.warn('THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.');
  3391. displayedWeightsWarning = true;
  3392. }
  3393. var wIndex = [0, 0, 0, 0];
  3394. var Weight = [0, 0, 0, 0];
  3395. weights.forEach(function (weight, weightIndex) {
  3396. var currentWeight = weight;
  3397. var currentIndex = weightIndices[weightIndex];
  3398. Weight.forEach(function (comparedWeight, comparedWeightIndex, comparedWeightArray) {
  3399. if (currentWeight > comparedWeight) {
  3400. comparedWeightArray[comparedWeightIndex] = currentWeight;
  3401. currentWeight = comparedWeight;
  3402. var tmp = wIndex[comparedWeightIndex];
  3403. wIndex[comparedWeightIndex] = currentIndex;
  3404. currentIndex = tmp;
  3405. }
  3406. });
  3407. });
  3408. weightIndices = wIndex;
  3409. weights = Weight;
  3410. }
  3411. // if the weight array is shorter than 4 pad with 0s
  3412. while (weights.length < 4) {
  3413. weights.push(0);
  3414. weightIndices.push(0);
  3415. }
  3416. for (var i = 0; i < 4; ++i) {
  3417. faceWeights.push(weights[i]);
  3418. faceWeightIndices.push(weightIndices[i]);
  3419. }
  3420. }
  3421. if (geoInfo.normal) {
  3422. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
  3423. faceNormals.push(data[0], data[1], data[2]);
  3424. }
  3425. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3426. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
  3427. }
  3428. if (geoInfo.uv) {
  3429. geoInfo.uv.forEach(function (uv, i) {
  3430. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
  3431. if (faceUVs[i] === undefined) {
  3432. faceUVs[i] = [];
  3433. }
  3434. faceUVs[i].push(data[0]);
  3435. faceUVs[i].push(data[1]);
  3436. });
  3437. }
  3438. faceLength++;
  3439. if (endOfFace) {
  3440. self.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
  3441. polygonIndex++;
  3442. faceLength = 0;
  3443. // reset arrays for the next face
  3444. facePositionIndexes = [];
  3445. faceNormals = [];
  3446. faceColors = [];
  3447. faceUVs = [];
  3448. faceWeights = [];
  3449. faceWeightIndices = [];
  3450. }
  3451. });
  3452. return buffers;
  3453. },
  3454. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  3455. genFace: function genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
  3456. for (var i = 2; i < faceLength; i++) {
  3457. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  3458. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  3459. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  3460. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]);
  3461. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]);
  3462. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]);
  3463. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  3464. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]);
  3465. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]);
  3466. if (geoInfo.skeleton) {
  3467. buffers.vertexWeights.push(faceWeights[0]);
  3468. buffers.vertexWeights.push(faceWeights[1]);
  3469. buffers.vertexWeights.push(faceWeights[2]);
  3470. buffers.vertexWeights.push(faceWeights[3]);
  3471. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  3472. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  3473. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  3474. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  3475. buffers.vertexWeights.push(faceWeights[i * 4]);
  3476. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  3477. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  3478. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  3479. buffers.weightsIndices.push(faceWeightIndices[0]);
  3480. buffers.weightsIndices.push(faceWeightIndices[1]);
  3481. buffers.weightsIndices.push(faceWeightIndices[2]);
  3482. buffers.weightsIndices.push(faceWeightIndices[3]);
  3483. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  3484. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  3485. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  3486. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  3487. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  3488. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  3489. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  3490. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  3491. }
  3492. if (geoInfo.color) {
  3493. buffers.colors.push(faceColors[0]);
  3494. buffers.colors.push(faceColors[1]);
  3495. buffers.colors.push(faceColors[2]);
  3496. buffers.colors.push(faceColors[(i - 1) * 3]);
  3497. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  3498. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  3499. buffers.colors.push(faceColors[i * 3]);
  3500. buffers.colors.push(faceColors[i * 3 + 1]);
  3501. buffers.colors.push(faceColors[i * 3 + 2]);
  3502. }
  3503. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3504. buffers.materialIndex.push(materialIndex);
  3505. buffers.materialIndex.push(materialIndex);
  3506. buffers.materialIndex.push(materialIndex);
  3507. }
  3508. if (geoInfo.normal) {
  3509. buffers.normal.push(faceNormals[0]);
  3510. buffers.normal.push(faceNormals[1]);
  3511. buffers.normal.push(faceNormals[2]);
  3512. buffers.normal.push(faceNormals[(i - 1) * 3]);
  3513. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  3514. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  3515. buffers.normal.push(faceNormals[i * 3]);
  3516. buffers.normal.push(faceNormals[i * 3 + 1]);
  3517. buffers.normal.push(faceNormals[i * 3 + 2]);
  3518. }
  3519. if (geoInfo.uv) {
  3520. geoInfo.uv.forEach(function (uv, j) {
  3521. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  3522. buffers.uvs[j].push(faceUVs[j][0]);
  3523. buffers.uvs[j].push(faceUVs[j][1]);
  3524. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  3525. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  3526. buffers.uvs[j].push(faceUVs[j][i * 2]);
  3527. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  3528. });
  3529. }
  3530. }
  3531. },
  3532. addMorphTargets: function addMorphTargets(parentGeo, parentGeoNode, morphTarget, preTransform) {
  3533. if (morphTarget === null) return;
  3534. parentGeo.morphAttributes.position = [];
  3535. parentGeo.morphAttributes.normal = [];
  3536. var self = this;
  3537. morphTarget.rawTargets.forEach(function (rawTarget) {
  3538. var morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  3539. if (morphGeoNode !== undefined) {
  3540. self.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform);
  3541. }
  3542. });
  3543. },
  3544. // a morph geometry node is similar to a standard node, and the node is also contained
  3545. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  3546. // and a special attribute Index defining which vertices of the original geometry are affected
  3547. // Normal and position attributes only have data for the vertices that are affected by the morph
  3548. genMorphGeometry: function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) {
  3549. var morphGeo = new THREE.BufferGeometry();
  3550. if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName;
  3551. var vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  3552. // make a copy of the parent's vertex positions
  3553. var vertexPositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a.slice() : [];
  3554. var morphPositions = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  3555. var indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  3556. for (var i = 0; i < indices.length; i++) {
  3557. var morphIndex = indices[i] * 3;
  3558. // FBX format uses blend shapes rather than morph targets. This can be converted
  3559. // by additively combining the blend shape positions with the original geometry's positions
  3560. vertexPositions[morphIndex] += morphPositions[i * 3];
  3561. vertexPositions[morphIndex + 1] += morphPositions[i * 3 + 1];
  3562. vertexPositions[morphIndex + 2] += morphPositions[i * 3 + 2];
  3563. }
  3564. // TODO: add morph normal support
  3565. var morphGeoInfo = {
  3566. vertexIndices: vertexIndices,
  3567. vertexPositions: vertexPositions
  3568. };
  3569. var morphBuffers = this.genBuffers(morphGeoInfo);
  3570. var positionAttribute = new THREE.Float32BufferAttribute(morphBuffers.vertex, 3);
  3571. positionAttribute.name = morphGeoNode.attrName;
  3572. preTransform.applyToBufferAttribute(positionAttribute);
  3573. parentGeo.morphAttributes.position.push(positionAttribute);
  3574. },
  3575. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  3576. parseNormals: function parseNormals(NormalNode) {
  3577. var mappingType = NormalNode.MappingInformationType;
  3578. var referenceType = NormalNode.ReferenceInformationType;
  3579. var buffer = NormalNode.Normals.a;
  3580. var indexBuffer = [];
  3581. if (referenceType === 'IndexToDirect') {
  3582. if ('NormalIndex' in NormalNode) {
  3583. indexBuffer = NormalNode.NormalIndex.a;
  3584. } else if ('NormalsIndex' in NormalNode) {
  3585. indexBuffer = NormalNode.NormalsIndex.a;
  3586. }
  3587. }
  3588. return {
  3589. dataSize: 3,
  3590. buffer: buffer,
  3591. indices: indexBuffer,
  3592. mappingType: mappingType,
  3593. referenceType: referenceType
  3594. };
  3595. },
  3596. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  3597. parseUVs: function parseUVs(UVNode) {
  3598. var mappingType = UVNode.MappingInformationType;
  3599. var referenceType = UVNode.ReferenceInformationType;
  3600. var buffer = UVNode.UV.a;
  3601. var indexBuffer = [];
  3602. if (referenceType === 'IndexToDirect') {
  3603. indexBuffer = UVNode.UVIndex.a;
  3604. }
  3605. return {
  3606. dataSize: 2,
  3607. buffer: buffer,
  3608. indices: indexBuffer,
  3609. mappingType: mappingType,
  3610. referenceType: referenceType
  3611. };
  3612. },
  3613. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  3614. parseVertexColors: function parseVertexColors(ColorNode) {
  3615. var mappingType = ColorNode.MappingInformationType;
  3616. var referenceType = ColorNode.ReferenceInformationType;
  3617. var buffer = ColorNode.Colors.a;
  3618. var indexBuffer = [];
  3619. if (referenceType === 'IndexToDirect') {
  3620. indexBuffer = ColorNode.ColorIndex.a;
  3621. }
  3622. return {
  3623. dataSize: 4,
  3624. buffer: buffer,
  3625. indices: indexBuffer,
  3626. mappingType: mappingType,
  3627. referenceType: referenceType
  3628. };
  3629. },
  3630. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  3631. parseMaterialIndices: function parseMaterialIndices(MaterialNode) {
  3632. var mappingType = MaterialNode.MappingInformationType;
  3633. var referenceType = MaterialNode.ReferenceInformationType;
  3634. if (mappingType === 'NoMappingInformation') {
  3635. return {
  3636. dataSize: 1,
  3637. buffer: [0],
  3638. indices: [0],
  3639. mappingType: 'AllSame',
  3640. referenceType: referenceType
  3641. };
  3642. }
  3643. var materialIndexBuffer = MaterialNode.Materials.a;
  3644. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  3645. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  3646. // for conforming with the other functions we've written for other data.
  3647. var materialIndices = [];
  3648. for (var i = 0; i < materialIndexBuffer.length; ++i) {
  3649. materialIndices.push(i);
  3650. }
  3651. return {
  3652. dataSize: 1,
  3653. buffer: materialIndexBuffer,
  3654. indices: materialIndices,
  3655. mappingType: mappingType,
  3656. referenceType: referenceType
  3657. };
  3658. },
  3659. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  3660. parseNurbsGeometry: function parseNurbsGeometry(geoNode) {
  3661. if (THREE.NURBSCurve === undefined) {
  3662. console.error('THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.');
  3663. return new THREE.BufferGeometry();
  3664. }
  3665. var order = parseInt(geoNode.Order);
  3666. if (isNaN(order)) {
  3667. console.error('THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id);
  3668. return new THREE.BufferGeometry();
  3669. }
  3670. var degree = order - 1;
  3671. var knots = geoNode.KnotVector.a;
  3672. var controlPoints = [];
  3673. var pointsValues = geoNode.Points.a;
  3674. for (var i = 0, l = pointsValues.length; i < l; i += 4) {
  3675. controlPoints.push(new THREE.Vector4().fromArray(pointsValues, i));
  3676. }
  3677. var startKnot, endKnot;
  3678. if (geoNode.Form === 'Closed') {
  3679. controlPoints.push(controlPoints[0]);
  3680. } else if (geoNode.Form === 'Periodic') {
  3681. startKnot = degree;
  3682. endKnot = knots.length - 1 - startKnot;
  3683. for (var i = 0; i < degree; ++i) {
  3684. controlPoints.push(controlPoints[i]);
  3685. }
  3686. }
  3687. var curve = new THREE.NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
  3688. var vertices = curve.getPoints(controlPoints.length * 7);
  3689. var positions = new Float32Array(vertices.length * 3);
  3690. vertices.forEach(function (vertex, i) {
  3691. vertex.toArray(positions, i * 3);
  3692. });
  3693. var geometry = new THREE.BufferGeometry();
  3694. geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
  3695. return geometry;
  3696. }
  3697. };
  3698. // parse animation data from FBXTree
  3699. function AnimationParser() {}
  3700. AnimationParser.prototype = {
  3701. constructor: AnimationParser,
  3702. // take raw animation clips and turn them into three.js animation clips
  3703. parse: function parse() {
  3704. var animationClips = [];
  3705. var rawClips = this.parseClips();
  3706. if (rawClips === undefined) return animationClips;
  3707. for (var key in rawClips) {
  3708. var rawClip = rawClips[key];
  3709. var clip = this.addClip(rawClip);
  3710. animationClips.push(clip);
  3711. }
  3712. return animationClips;
  3713. },
  3714. parseClips: function parseClips() {
  3715. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  3716. // if this is undefined we can safely assume there are no animations
  3717. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  3718. var curveNodesMap = this.parseAnimationCurveNodes();
  3719. this.parseAnimationCurves(curveNodesMap);
  3720. var layersMap = this.parseAnimationLayers(curveNodesMap);
  3721. var rawClips = this.parseAnimStacks(layersMap);
  3722. return rawClips;
  3723. },
  3724. // parse nodes in FBXTree.Objects.AnimationCurveNode
  3725. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  3726. // and is referenced by an AnimationLayer
  3727. parseAnimationCurveNodes: function parseAnimationCurveNodes() {
  3728. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  3729. var curveNodesMap = new Map();
  3730. for (var nodeID in rawCurveNodes) {
  3731. var rawCurveNode = rawCurveNodes[nodeID];
  3732. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  3733. var curveNode = {
  3734. id: rawCurveNode.id,
  3735. attr: rawCurveNode.attrName,
  3736. curves: {}
  3737. };
  3738. curveNodesMap.set(curveNode.id, curveNode);
  3739. }
  3740. }
  3741. return curveNodesMap;
  3742. },
  3743. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  3744. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  3745. // axis ( e.g. times and values of x rotation)
  3746. parseAnimationCurves: function parseAnimationCurves(curveNodesMap) {
  3747. var rawCurves = fbxTree.Objects.AnimationCurve;
  3748. // TODO: Many values are identical up to roundoff error, but won't be optimised
  3749. // e.g. position times: [0, 0.4, 0. 8]
  3750. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  3751. // clearly, this should be optimised to
  3752. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  3753. // this shows up in nearly every FBX file, and generally time array is length > 100
  3754. for (var nodeID in rawCurves) {
  3755. var animationCurve = {
  3756. id: rawCurves[nodeID].id,
  3757. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  3758. values: rawCurves[nodeID].KeyValueFloat.a
  3759. };
  3760. var relationships = connections.get(animationCurve.id);
  3761. if (relationships !== undefined) {
  3762. var animationCurveID = relationships.parents[0].ID;
  3763. var animationCurveRelationship = relationships.parents[0].relationship;
  3764. if (animationCurveRelationship.match(/X/)) {
  3765. curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;
  3766. } else if (animationCurveRelationship.match(/Y/)) {
  3767. curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;
  3768. } else if (animationCurveRelationship.match(/Z/)) {
  3769. curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;
  3770. } else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveID)) {
  3771. curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;
  3772. }
  3773. }
  3774. }
  3775. },
  3776. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  3777. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  3778. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  3779. parseAnimationLayers: function parseAnimationLayers(curveNodesMap) {
  3780. var rawLayers = fbxTree.Objects.AnimationLayer;
  3781. var layersMap = new Map();
  3782. for (var nodeID in rawLayers) {
  3783. var layerCurveNodes = [];
  3784. var connection = connections.get(parseInt(nodeID));
  3785. if (connection !== undefined) {
  3786. // all the animationCurveNodes used in the layer
  3787. var children = connection.children;
  3788. var self = this;
  3789. children.forEach(function (child, i) {
  3790. if (curveNodesMap.has(child.ID)) {
  3791. var curveNode = curveNodesMap.get(child.ID);
  3792. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  3793. if (curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined) {
  3794. if (layerCurveNodes[i] === undefined) {
  3795. var modelID;
  3796. connections.get(child.ID).parents.forEach(function (parent) {
  3797. if (parent.relationship !== undefined) modelID = parent.ID;
  3798. });
  3799. var rawModel = fbxTree.Objects.Model[modelID.toString()];
  3800. var node = {
  3801. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3802. initialPosition: [0, 0, 0],
  3803. initialRotation: [0, 0, 0],
  3804. initialScale: [1, 1, 1],
  3805. transform: self.getModelAnimTransform(rawModel)
  3806. };
  3807. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  3808. // animation value as well
  3809. if ('PreRotation' in rawModel) node.preRotations = rawModel.PreRotation.value;
  3810. if ('PostRotation' in rawModel) node.postRotations = rawModel.PostRotation.value;
  3811. layerCurveNodes[i] = node;
  3812. }
  3813. layerCurveNodes[i][curveNode.attr] = curveNode;
  3814. } else if (curveNode.curves.morph !== undefined) {
  3815. if (layerCurveNodes[i] === undefined) {
  3816. var deformerID;
  3817. connections.get(child.ID).parents.forEach(function (parent) {
  3818. if (parent.relationship !== undefined) deformerID = parent.ID;
  3819. });
  3820. var morpherID = connections.get(deformerID).parents[0].ID;
  3821. var geoID = connections.get(morpherID).parents[0].ID;
  3822. // assuming geometry is not used in more than one model
  3823. var modelID = connections.get(geoID).parents[0].ID;
  3824. var rawModel = fbxTree.Objects.Model[modelID];
  3825. var node = {
  3826. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3827. morphName: fbxTree.Objects.Deformer[deformerID].attrName
  3828. };
  3829. layerCurveNodes[i] = node;
  3830. }
  3831. layerCurveNodes[i][curveNode.attr] = curveNode;
  3832. }
  3833. }
  3834. });
  3835. layersMap.set(parseInt(nodeID), layerCurveNodes);
  3836. }
  3837. }
  3838. return layersMap;
  3839. },
  3840. getModelAnimTransform: function getModelAnimTransform(modelNode) {
  3841. var transformData = {};
  3842. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3843. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3844. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3845. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3846. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3847. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3848. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3849. return generateTransform(transformData);
  3850. },
  3851. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  3852. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  3853. parseAnimStacks: function parseAnimStacks(layersMap) {
  3854. var rawStacks = fbxTree.Objects.AnimationStack;
  3855. // connect the stacks (clips) up to the layers
  3856. var rawClips = {};
  3857. for (var nodeID in rawStacks) {
  3858. var children = connections.get(parseInt(nodeID)).children;
  3859. if (children.length > 1) {
  3860. // it seems like stacks will always be associated with a single layer. But just in case there are files
  3861. // where there are multiple layers per stack, we'll display a warning
  3862. console.warn('THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.');
  3863. }
  3864. var layer = layersMap.get(children[0].ID);
  3865. rawClips[nodeID] = {
  3866. name: rawStacks[nodeID].attrName,
  3867. layer: layer
  3868. };
  3869. }
  3870. return rawClips;
  3871. },
  3872. addClip: function addClip(rawClip) {
  3873. var tracks = [];
  3874. var self = this;
  3875. rawClip.layer.forEach(function (rawTracks) {
  3876. tracks = tracks.concat(self.generateTracks(rawTracks));
  3877. });
  3878. return new THREE.AnimationClip(rawClip.name, -1, tracks);
  3879. },
  3880. generateTracks: function generateTracks(rawTracks) {
  3881. var tracks = [];
  3882. var initialPosition = new THREE.Vector3();
  3883. var initialRotation = new THREE.Quaternion();
  3884. var initialScale = new THREE.Vector3();
  3885. if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale);
  3886. initialPosition = initialPosition.toArray();
  3887. initialRotation = new THREE.Euler().setFromQuaternion(initialRotation).toArray(); // todo: euler order
  3888. initialScale = initialScale.toArray();
  3889. if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {
  3890. var positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position');
  3891. if (positionTrack !== undefined) tracks.push(positionTrack);
  3892. }
  3893. if (rawTracks.R !== undefined && Object.keys(rawTracks.R.curves).length > 0) {
  3894. var rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations);
  3895. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  3896. }
  3897. if (rawTracks.S !== undefined && Object.keys(rawTracks.S.curves).length > 0) {
  3898. var scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale');
  3899. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  3900. }
  3901. if (rawTracks.DeformPercent !== undefined) {
  3902. var morphTrack = this.generateMorphTrack(rawTracks);
  3903. if (morphTrack !== undefined) tracks.push(morphTrack);
  3904. }
  3905. return tracks;
  3906. },
  3907. generateVectorTrack: function generateVectorTrack(modelName, curves, initialValue, type) {
  3908. var times = this.getTimesForAllAxes(curves);
  3909. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3910. return new THREE.VectorKeyframeTrack(modelName + '.' + type, times, values);
  3911. },
  3912. generateRotationTrack: function generateRotationTrack(modelName, curves, initialValue, preRotations, postRotations) {
  3913. if (curves.x !== undefined) {
  3914. this.interpolateRotations(curves.x);
  3915. curves.x.values = curves.x.values.map(THREE.Math.degToRad);
  3916. }
  3917. if (curves.y !== undefined) {
  3918. this.interpolateRotations(curves.y);
  3919. curves.y.values = curves.y.values.map(THREE.Math.degToRad);
  3920. }
  3921. if (curves.z !== undefined) {
  3922. this.interpolateRotations(curves.z);
  3923. curves.z.values = curves.z.values.map(THREE.Math.degToRad);
  3924. }
  3925. var times = this.getTimesForAllAxes(curves);
  3926. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3927. if (preRotations !== undefined) {
  3928. preRotations = preRotations.map(THREE.Math.degToRad);
  3929. preRotations.push('ZYX');
  3930. preRotations = new THREE.Euler().fromArray(preRotations);
  3931. preRotations = new THREE.Quaternion().setFromEuler(preRotations);
  3932. }
  3933. if (postRotations !== undefined) {
  3934. postRotations = postRotations.map(THREE.Math.degToRad);
  3935. postRotations.push('ZYX');
  3936. postRotations = new THREE.Euler().fromArray(postRotations);
  3937. postRotations = new THREE.Quaternion().setFromEuler(postRotations).inverse();
  3938. }
  3939. var quaternion = new THREE.Quaternion();
  3940. var euler = new THREE.Euler();
  3941. var quaternionValues = [];
  3942. for (var i = 0; i < values.length; i += 3) {
  3943. euler.set(values[i], values[i + 1], values[i + 2], 'ZYX');
  3944. quaternion.setFromEuler(euler);
  3945. if (preRotations !== undefined) quaternion.premultiply(preRotations);
  3946. if (postRotations !== undefined) quaternion.multiply(postRotations);
  3947. quaternion.toArray(quaternionValues, i / 3 * 4);
  3948. }
  3949. return new THREE.QuaternionKeyframeTrack(modelName + '.quaternion', times, quaternionValues);
  3950. },
  3951. generateMorphTrack: function generateMorphTrack(rawTracks) {
  3952. var curves = rawTracks.DeformPercent.curves.morph;
  3953. var values = curves.values.map(function (val) {
  3954. return val / 100;
  3955. });
  3956. var morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
  3957. return new THREE.NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);
  3958. },
  3959. // For all animated objects, times are defined separately for each axis
  3960. // Here we'll combine the times into one sorted array without duplicates
  3961. getTimesForAllAxes: function getTimesForAllAxes(curves) {
  3962. var times = [];
  3963. // first join together the times for each axis, if defined
  3964. if (curves.x !== undefined) times = times.concat(curves.x.times);
  3965. if (curves.y !== undefined) times = times.concat(curves.y.times);
  3966. if (curves.z !== undefined) times = times.concat(curves.z.times);
  3967. // then sort them and remove duplicates
  3968. times = times.sort(function (a, b) {
  3969. return a - b;
  3970. }).filter(function (elem, index, array) {
  3971. return array.indexOf(elem) == index;
  3972. });
  3973. return times;
  3974. },
  3975. getKeyframeTrackValues: function getKeyframeTrackValues(times, curves, initialValue) {
  3976. var prevValue = initialValue;
  3977. var values = [];
  3978. var xIndex = -1;
  3979. var yIndex = -1;
  3980. var zIndex = -1;
  3981. times.forEach(function (time) {
  3982. if (curves.x) xIndex = curves.x.times.indexOf(time);
  3983. if (curves.y) yIndex = curves.y.times.indexOf(time);
  3984. if (curves.z) zIndex = curves.z.times.indexOf(time);
  3985. // if there is an x value defined for this frame, use that
  3986. if (xIndex !== -1) {
  3987. var xValue = curves.x.values[xIndex];
  3988. values.push(xValue);
  3989. prevValue[0] = xValue;
  3990. } else {
  3991. // otherwise use the x value from the previous frame
  3992. values.push(prevValue[0]);
  3993. }
  3994. if (yIndex !== -1) {
  3995. var yValue = curves.y.values[yIndex];
  3996. values.push(yValue);
  3997. prevValue[1] = yValue;
  3998. } else {
  3999. values.push(prevValue[1]);
  4000. }
  4001. if (zIndex !== -1) {
  4002. var zValue = curves.z.values[zIndex];
  4003. values.push(zValue);
  4004. prevValue[2] = zValue;
  4005. } else {
  4006. values.push(prevValue[2]);
  4007. }
  4008. });
  4009. return values;
  4010. },
  4011. // Rotations are defined as Euler angles which can have values of any size
  4012. // These will be converted to quaternions which don't support values greater than
  4013. // PI, so we'll interpolate large rotations
  4014. interpolateRotations: function interpolateRotations(curve) {
  4015. for (var i = 1; i < curve.values.length; i++) {
  4016. var initialValue = curve.values[i - 1];
  4017. var valuesSpan = curve.values[i] - initialValue;
  4018. var absoluteSpan = Math.abs(valuesSpan);
  4019. if (absoluteSpan >= 180) {
  4020. var numSubIntervals = absoluteSpan / 180;
  4021. var step = valuesSpan / numSubIntervals;
  4022. var nextValue = initialValue + step;
  4023. var initialTime = curve.times[i - 1];
  4024. var timeSpan = curve.times[i] - initialTime;
  4025. var interval = timeSpan / numSubIntervals;
  4026. var nextTime = initialTime + interval;
  4027. var interpolatedTimes = [];
  4028. var interpolatedValues = [];
  4029. while (nextTime < curve.times[i]) {
  4030. interpolatedTimes.push(nextTime);
  4031. nextTime += interval;
  4032. interpolatedValues.push(nextValue);
  4033. nextValue += step;
  4034. }
  4035. curve.times = inject(curve.times, i, interpolatedTimes);
  4036. curve.values = inject(curve.values, i, interpolatedValues);
  4037. }
  4038. }
  4039. }
  4040. };
  4041. // parse an FBX file in ASCII format
  4042. function TextParser() {}
  4043. TextParser.prototype = {
  4044. constructor: TextParser,
  4045. getPrevNode: function getPrevNode() {
  4046. return this.nodeStack[this.currentIndent - 2];
  4047. },
  4048. getCurrentNode: function getCurrentNode() {
  4049. return this.nodeStack[this.currentIndent - 1];
  4050. },
  4051. getCurrentProp: function getCurrentProp() {
  4052. return this.currentProp;
  4053. },
  4054. pushStack: function pushStack(node) {
  4055. this.nodeStack.push(node);
  4056. this.currentIndent += 1;
  4057. },
  4058. popStack: function popStack() {
  4059. this.nodeStack.pop();
  4060. this.currentIndent -= 1;
  4061. },
  4062. setCurrentProp: function setCurrentProp(val, name) {
  4063. this.currentProp = val;
  4064. this.currentPropName = name;
  4065. },
  4066. parse: function parse(text) {
  4067. this.currentIndent = 0;
  4068. console.log("FBXTree: ", FBXTree);
  4069. this.allNodes = new FBXTree();
  4070. this.nodeStack = [];
  4071. this.currentProp = [];
  4072. this.currentPropName = '';
  4073. var self = this;
  4074. var split = text.split(/[\r\n]+/);
  4075. split.forEach(function (line, i) {
  4076. var matchComment = line.match(/^[\s\t]*;/);
  4077. var matchEmpty = line.match(/^[\s\t]*$/);
  4078. if (matchComment || matchEmpty) return;
  4079. var matchBeginning = line.match('^\\t{' + self.currentIndent + '}(\\w+):(.*){', '');
  4080. var matchProperty = line.match('^\\t{' + self.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)');
  4081. var matchEnd = line.match('^\\t{' + (self.currentIndent - 1) + '}}');
  4082. if (matchBeginning) {
  4083. self.parseNodeBegin(line, matchBeginning);
  4084. } else if (matchProperty) {
  4085. self.parseNodeProperty(line, matchProperty, split[++i]);
  4086. } else if (matchEnd) {
  4087. self.popStack();
  4088. } else if (line.match(/^[^\s\t}]/)) {
  4089. // large arrays are split over multiple lines terminated with a ',' character
  4090. // if this is encountered the line needs to be joined to the previous line
  4091. self.parseNodePropertyContinued(line);
  4092. }
  4093. });
  4094. return this.allNodes;
  4095. },
  4096. parseNodeBegin: function parseNodeBegin(line, property) {
  4097. var nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');
  4098. var nodeAttrs = property[2].split(',').map(function (attr) {
  4099. return attr.trim().replace(/^"/, '').replace(/"$/, '');
  4100. });
  4101. var node = { name: nodeName };
  4102. var attrs = this.parseNodeAttr(nodeAttrs);
  4103. var currentNode = this.getCurrentNode();
  4104. // a top node
  4105. if (this.currentIndent === 0) {
  4106. this.allNodes.add(nodeName, node);
  4107. } else {
  4108. // a subnode
  4109. // if the subnode already exists, append it
  4110. if (nodeName in currentNode) {
  4111. // special case Pose needs PoseNodes as an array
  4112. if (nodeName === 'PoseNode') {
  4113. currentNode.PoseNode.push(node);
  4114. } else if (currentNode[nodeName].id !== undefined) {
  4115. currentNode[nodeName] = {};
  4116. currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
  4117. }
  4118. if (attrs.id !== '') currentNode[nodeName][attrs.id] = node;
  4119. } else if (typeof attrs.id === 'number') {
  4120. currentNode[nodeName] = {};
  4121. currentNode[nodeName][attrs.id] = node;
  4122. } else if (nodeName !== 'Properties70') {
  4123. if (nodeName === 'PoseNode') currentNode[nodeName] = [node];else currentNode[nodeName] = node;
  4124. }
  4125. }
  4126. if (typeof attrs.id === 'number') node.id = attrs.id;
  4127. if (attrs.name !== '') node.attrName = attrs.name;
  4128. if (attrs.type !== '') node.attrType = attrs.type;
  4129. this.pushStack(node);
  4130. },
  4131. parseNodeAttr: function parseNodeAttr(attrs) {
  4132. var id = attrs[0];
  4133. if (attrs[0] !== '') {
  4134. id = parseInt(attrs[0]);
  4135. if (isNaN(id)) {
  4136. id = attrs[0];
  4137. }
  4138. }
  4139. var name = '',
  4140. type = '';
  4141. if (attrs.length > 1) {
  4142. name = attrs[1].replace(/^(\w+)::/, '');
  4143. type = attrs[2];
  4144. }
  4145. return { id: id, name: name, type: type };
  4146. },
  4147. parseNodeProperty: function parseNodeProperty(line, property, contentLine) {
  4148. var propName = property[1].replace(/^"/, '').replace(/"$/, '').trim();
  4149. var propValue = property[2].replace(/^"/, '').replace(/"$/, '').trim();
  4150. // for special case: base64 image data follows "Content: ," line
  4151. // Content: ,
  4152. // "/9j/4RDaRXhpZgAATU0A..."
  4153. if (propName === 'Content' && propValue === ',') {
  4154. propValue = contentLine.replace(/"/g, '').replace(/,$/, '').trim();
  4155. }
  4156. var currentNode = this.getCurrentNode();
  4157. var parentName = currentNode.name;
  4158. if (parentName === 'Properties70') {
  4159. this.parseNodeSpecialProperty(line, propName, propValue);
  4160. return;
  4161. }
  4162. // Connections
  4163. if (propName === 'C') {
  4164. var connProps = propValue.split(',').slice(1);
  4165. var from = parseInt(connProps[0]);
  4166. var to = parseInt(connProps[1]);
  4167. var rest = propValue.split(',').slice(3);
  4168. rest = rest.map(function (elem) {
  4169. return elem.trim().replace(/^"/, '');
  4170. });
  4171. propName = 'connections';
  4172. propValue = [from, to];
  4173. append(propValue, rest);
  4174. if (currentNode[propName] === undefined) {
  4175. currentNode[propName] = [];
  4176. }
  4177. }
  4178. // Node
  4179. if (propName === 'Node') currentNode.id = propValue;
  4180. // connections
  4181. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  4182. currentNode[propName].push(propValue);
  4183. } else {
  4184. if (propName !== 'a') currentNode[propName] = propValue;else currentNode.a = propValue;
  4185. }
  4186. this.setCurrentProp(currentNode, propName);
  4187. // convert string to array, unless it ends in ',' in which case more will be added to it
  4188. if (propName === 'a' && propValue.slice(-1) !== ',') {
  4189. currentNode.a = parseNumberArray(propValue);
  4190. }
  4191. },
  4192. parseNodePropertyContinued: function parseNodePropertyContinued(line) {
  4193. var currentNode = this.getCurrentNode();
  4194. currentNode.a += line;
  4195. // if the line doesn't end in ',' we have reached the end of the property value
  4196. // so convert the string to an array
  4197. if (line.slice(-1) !== ',') {
  4198. currentNode.a = parseNumberArray(currentNode.a);
  4199. }
  4200. },
  4201. // parse "Property70"
  4202. parseNodeSpecialProperty: function parseNodeSpecialProperty(line, propName, propValue) {
  4203. // split this
  4204. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  4205. // into array like below
  4206. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  4207. var props = propValue.split('",').map(function (prop) {
  4208. return prop.trim().replace(/^\"/, '').replace(/\s/, '_');
  4209. });
  4210. var innerPropName = props[0];
  4211. var innerPropType1 = props[1];
  4212. var innerPropType2 = props[2];
  4213. var innerPropFlag = props[3];
  4214. var innerPropValue = props[4];
  4215. // cast values where needed, otherwise leave as strings
  4216. switch (innerPropType1) {
  4217. case 'int':
  4218. case 'enum':
  4219. case 'bool':
  4220. case 'ULongLong':
  4221. case 'double':
  4222. case 'Number':
  4223. case 'FieldOfView':
  4224. innerPropValue = parseFloat(innerPropValue);
  4225. break;
  4226. case 'Color':
  4227. case 'ColorRGB':
  4228. case 'Vector3D':
  4229. case 'Lcl_Translation':
  4230. case 'Lcl_Rotation':
  4231. case 'Lcl_Scaling':
  4232. innerPropValue = parseNumberArray(innerPropValue);
  4233. break;
  4234. }
  4235. // CAUTION: these props must append to parent's parent
  4236. this.getPrevNode()[innerPropName] = {
  4237. 'type': innerPropType1,
  4238. 'type2': innerPropType2,
  4239. 'flag': innerPropFlag,
  4240. 'value': innerPropValue
  4241. };
  4242. this.setCurrentProp(this.getPrevNode(), innerPropName);
  4243. }
  4244. };
  4245. // Parse an FBX file in Binary format
  4246. function BinaryParser() {}
  4247. BinaryParser.prototype = {
  4248. constructor: BinaryParser,
  4249. parse: function parse(buffer) {
  4250. var reader = new BinaryReader(buffer);
  4251. reader.skip(23); // skip magic 23 bytes
  4252. var version = reader.getUint32();
  4253. console.log('THREE.FBXLoader: FBX binary version: ' + version);
  4254. var allNodes = new FBXTree();
  4255. while (!this.endOfContent(reader)) {
  4256. var node = this.parseNode(reader, version);
  4257. if (node !== null) allNodes.add(node.name, node);
  4258. }
  4259. return allNodes;
  4260. },
  4261. // Check if reader has reached the end of content.
  4262. endOfContent: function endOfContent(reader) {
  4263. // footer size: 160bytes + 16-byte alignment padding
  4264. // - 16bytes: magic
  4265. // - padding til 16-byte alignment (at least 1byte?)
  4266. // (seems like some exporters embed fixed 15 or 16bytes?)
  4267. // - 4bytes: magic
  4268. // - 4bytes: version
  4269. // - 120bytes: zero
  4270. // - 16bytes: magic
  4271. if (reader.size() % 16 === 0) {
  4272. return (reader.getOffset() + 160 + 16 & ~0xf) >= reader.size();
  4273. } else {
  4274. return reader.getOffset() + 160 + 16 >= reader.size();
  4275. }
  4276. },
  4277. // recursively parse nodes until the end of the file is reached
  4278. parseNode: function parseNode(reader, version) {
  4279. var node = {};
  4280. // The first three data sizes depends on version.
  4281. var endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4282. var numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4283. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  4284. var propertyListLen = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4285. var nameLen = reader.getUint8();
  4286. var name = reader.getString(nameLen);
  4287. // Regards this node as NULL-record if endOffset is zero
  4288. if (endOffset === 0) return null;
  4289. var propertyList = [];
  4290. for (var i = 0; i < numProperties; i++) {
  4291. propertyList.push(this.parseProperty(reader));
  4292. }
  4293. // Regards the first three elements in propertyList as id, attrName, and attrType
  4294. var id = propertyList.length > 0 ? propertyList[0] : '';
  4295. var attrName = propertyList.length > 1 ? propertyList[1] : '';
  4296. var attrType = propertyList.length > 2 ? propertyList[2] : '';
  4297. // check if this node represents just a single property
  4298. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  4299. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  4300. while (endOffset > reader.getOffset()) {
  4301. var subNode = this.parseNode(reader, version);
  4302. if (subNode !== null) this.parseSubNode(name, node, subNode);
  4303. }
  4304. node.propertyList = propertyList; // raw property list used by parent
  4305. if (typeof id === 'number') node.id = id;
  4306. if (attrName !== '') node.attrName = attrName;
  4307. if (attrType !== '') node.attrType = attrType;
  4308. if (name !== '') node.name = name;
  4309. return node;
  4310. },
  4311. parseSubNode: function parseSubNode(name, node, subNode) {
  4312. // special case: child node is single property
  4313. if (subNode.singleProperty === true) {
  4314. var value = subNode.propertyList[0];
  4315. if (Array.isArray(value)) {
  4316. node[subNode.name] = subNode;
  4317. subNode.a = value;
  4318. } else {
  4319. node[subNode.name] = value;
  4320. }
  4321. } else if (name === 'Connections' && subNode.name === 'C') {
  4322. var array = [];
  4323. subNode.propertyList.forEach(function (property, i) {
  4324. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  4325. if (i !== 0) array.push(property);
  4326. });
  4327. if (node.connections === undefined) {
  4328. node.connections = [];
  4329. }
  4330. node.connections.push(array);
  4331. } else if (subNode.name === 'Properties70') {
  4332. var keys = Object.keys(subNode);
  4333. keys.forEach(function (key) {
  4334. node[key] = subNode[key];
  4335. });
  4336. } else if (name === 'Properties70' && subNode.name === 'P') {
  4337. var innerPropName = subNode.propertyList[0];
  4338. var innerPropType1 = subNode.propertyList[1];
  4339. var innerPropType2 = subNode.propertyList[2];
  4340. var innerPropFlag = subNode.propertyList[3];
  4341. var innerPropValue;
  4342. if (innerPropName.indexOf('Lcl ') === 0) innerPropName = innerPropName.replace('Lcl ', 'Lcl_');
  4343. if (innerPropType1.indexOf('Lcl ') === 0) innerPropType1 = innerPropType1.replace('Lcl ', 'Lcl_');
  4344. if (innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf('Lcl_') === 0) {
  4345. innerPropValue = [subNode.propertyList[4], subNode.propertyList[5], subNode.propertyList[6]];
  4346. } else {
  4347. innerPropValue = subNode.propertyList[4];
  4348. }
  4349. // this will be copied to parent, see above
  4350. node[innerPropName] = {
  4351. 'type': innerPropType1,
  4352. 'type2': innerPropType2,
  4353. 'flag': innerPropFlag,
  4354. 'value': innerPropValue
  4355. };
  4356. } else if (node[subNode.name] === undefined) {
  4357. if (typeof subNode.id === 'number') {
  4358. node[subNode.name] = {};
  4359. node[subNode.name][subNode.id] = subNode;
  4360. } else {
  4361. node[subNode.name] = subNode;
  4362. }
  4363. } else {
  4364. if (subNode.name === 'PoseNode') {
  4365. if (!Array.isArray(node[subNode.name])) {
  4366. node[subNode.name] = [node[subNode.name]];
  4367. }
  4368. node[subNode.name].push(subNode);
  4369. } else if (node[subNode.name][subNode.id] === undefined) {
  4370. node[subNode.name][subNode.id] = subNode;
  4371. }
  4372. }
  4373. },
  4374. parseProperty: function parseProperty(reader) {
  4375. var type = reader.getString(1);
  4376. switch (type) {
  4377. case 'C':
  4378. return reader.getBoolean();
  4379. case 'D':
  4380. return reader.getFloat64();
  4381. case 'F':
  4382. return reader.getFloat32();
  4383. case 'I':
  4384. return reader.getInt32();
  4385. case 'L':
  4386. return reader.getInt64();
  4387. case 'R':
  4388. var length = reader.getUint32();
  4389. return reader.getArrayBuffer(length);
  4390. case 'S':
  4391. var length = reader.getUint32();
  4392. return reader.getString(length);
  4393. case 'Y':
  4394. return reader.getInt16();
  4395. case 'b':
  4396. case 'c':
  4397. case 'd':
  4398. case 'f':
  4399. case 'i':
  4400. case 'l':
  4401. var arrayLength = reader.getUint32();
  4402. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  4403. var compressedLength = reader.getUint32();
  4404. if (encoding === 0) {
  4405. switch (type) {
  4406. case 'b':
  4407. case 'c':
  4408. return reader.getBooleanArray(arrayLength);
  4409. case 'd':
  4410. return reader.getFloat64Array(arrayLength);
  4411. case 'f':
  4412. return reader.getFloat32Array(arrayLength);
  4413. case 'i':
  4414. return reader.getInt32Array(arrayLength);
  4415. case 'l':
  4416. return reader.getInt64Array(arrayLength);
  4417. }
  4418. }
  4419. if (typeof Zlib === 'undefined') {
  4420. console.error('THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js');
  4421. }
  4422. var inflate = new Zlib.Inflate(new Uint8Array(reader.getArrayBuffer(compressedLength))); // eslint-disable-line no-undef
  4423. var reader2 = new BinaryReader(inflate.decompress().buffer);
  4424. switch (type) {
  4425. case 'b':
  4426. case 'c':
  4427. return reader2.getBooleanArray(arrayLength);
  4428. case 'd':
  4429. return reader2.getFloat64Array(arrayLength);
  4430. case 'f':
  4431. return reader2.getFloat32Array(arrayLength);
  4432. case 'i':
  4433. return reader2.getInt32Array(arrayLength);
  4434. case 'l':
  4435. return reader2.getInt64Array(arrayLength);
  4436. }
  4437. default:
  4438. throw new Error('THREE.FBXLoader: Unknown property type ' + type);
  4439. }
  4440. }
  4441. };
  4442. function BinaryReader(buffer, littleEndian) {
  4443. this.dv = new DataView(buffer);
  4444. this.offset = 0;
  4445. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  4446. }
  4447. BinaryReader.prototype = {
  4448. constructor: BinaryReader,
  4449. getOffset: function getOffset() {
  4450. return this.offset;
  4451. },
  4452. size: function size() {
  4453. return this.dv.buffer.byteLength;
  4454. },
  4455. skip: function skip(length) {
  4456. this.offset += length;
  4457. },
  4458. // seems like true/false representation depends on exporter.
  4459. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  4460. // then sees LSB.
  4461. getBoolean: function getBoolean() {
  4462. return (this.getUint8() & 1) === 1;
  4463. },
  4464. getBooleanArray: function getBooleanArray(size) {
  4465. var a = [];
  4466. for (var i = 0; i < size; i++) {
  4467. a.push(this.getBoolean());
  4468. }
  4469. return a;
  4470. },
  4471. getUint8: function getUint8() {
  4472. var value = this.dv.getUint8(this.offset);
  4473. this.offset += 1;
  4474. return value;
  4475. },
  4476. getInt16: function getInt16() {
  4477. var value = this.dv.getInt16(this.offset, this.littleEndian);
  4478. this.offset += 2;
  4479. return value;
  4480. },
  4481. getInt32: function getInt32() {
  4482. var value = this.dv.getInt32(this.offset, this.littleEndian);
  4483. this.offset += 4;
  4484. return value;
  4485. },
  4486. getInt32Array: function getInt32Array(size) {
  4487. var a = [];
  4488. for (var i = 0; i < size; i++) {
  4489. a.push(this.getInt32());
  4490. }
  4491. return a;
  4492. },
  4493. getUint32: function getUint32() {
  4494. var value = this.dv.getUint32(this.offset, this.littleEndian);
  4495. this.offset += 4;
  4496. return value;
  4497. },
  4498. // JavaScript doesn't support 64-bit integer so calculate this here
  4499. // 1 << 32 will return 1 so using multiply operation instead here.
  4500. // There's a possibility that this method returns wrong value if the value
  4501. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  4502. // TODO: safely handle 64-bit integer
  4503. getInt64: function getInt64() {
  4504. var low, high;
  4505. if (this.littleEndian) {
  4506. low = this.getUint32();
  4507. high = this.getUint32();
  4508. } else {
  4509. high = this.getUint32();
  4510. low = this.getUint32();
  4511. }
  4512. // calculate negative value
  4513. if (high & 0x80000000) {
  4514. high = ~high & 0xFFFFFFFF;
  4515. low = ~low & 0xFFFFFFFF;
  4516. if (low === 0xFFFFFFFF) high = high + 1 & 0xFFFFFFFF;
  4517. low = low + 1 & 0xFFFFFFFF;
  4518. return -(high * 0x100000000 + low);
  4519. }
  4520. return high * 0x100000000 + low;
  4521. },
  4522. getInt64Array: function getInt64Array(size) {
  4523. var a = [];
  4524. for (var i = 0; i < size; i++) {
  4525. a.push(this.getInt64());
  4526. }
  4527. return a;
  4528. },
  4529. // Note: see getInt64() comment
  4530. getUint64: function getUint64() {
  4531. var low, high;
  4532. if (this.littleEndian) {
  4533. low = this.getUint32();
  4534. high = this.getUint32();
  4535. } else {
  4536. high = this.getUint32();
  4537. low = this.getUint32();
  4538. }
  4539. return high * 0x100000000 + low;
  4540. },
  4541. getFloat32: function getFloat32() {
  4542. var value = this.dv.getFloat32(this.offset, this.littleEndian);
  4543. this.offset += 4;
  4544. return value;
  4545. },
  4546. getFloat32Array: function getFloat32Array(size) {
  4547. var a = [];
  4548. for (var i = 0; i < size; i++) {
  4549. a.push(this.getFloat32());
  4550. }
  4551. return a;
  4552. },
  4553. getFloat64: function getFloat64() {
  4554. var value = this.dv.getFloat64(this.offset, this.littleEndian);
  4555. this.offset += 8;
  4556. return value;
  4557. },
  4558. getFloat64Array: function getFloat64Array(size) {
  4559. var a = [];
  4560. for (var i = 0; i < size; i++) {
  4561. a.push(this.getFloat64());
  4562. }
  4563. return a;
  4564. },
  4565. getArrayBuffer: function getArrayBuffer(size) {
  4566. var value = this.dv.buffer.slice(this.offset, this.offset + size);
  4567. this.offset += size;
  4568. return value;
  4569. },
  4570. getString: function getString(size) {
  4571. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  4572. var a = [];
  4573. for (var i = 0; i < size; i++) {
  4574. a[i] = this.getUint8();
  4575. }
  4576. var nullByte = a.indexOf(0);
  4577. if (nullByte >= 0) a = a.slice(0, nullByte);
  4578. return THREE.LoaderUtils.decodeText(new Uint8Array(a));
  4579. }
  4580. };
  4581. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  4582. // and BinaryParser( FBX Binary format)
  4583. function FBXTree() {}
  4584. FBXTree.prototype = {
  4585. constructor: FBXTree,
  4586. add: function add(key, val) {
  4587. this[key] = val;
  4588. }
  4589. };
  4590. // ************** UTILITY FUNCTIONS **************
  4591. function isFbxFormatBinary(buffer) {
  4592. var CORRECT = 'Kaydara FBX Binary \0';
  4593. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
  4594. }
  4595. function isFbxFormatASCII(text) {
  4596. var CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];
  4597. var cursor = 0;
  4598. function read(offset) {
  4599. var result = text[offset - 1];
  4600. text = text.slice(cursor + offset);
  4601. cursor++;
  4602. return result;
  4603. }
  4604. for (var i = 0; i < CORRECT.length; ++i) {
  4605. var num = read(1);
  4606. if (num === CORRECT[i]) {
  4607. return false;
  4608. }
  4609. }
  4610. return true;
  4611. }
  4612. function getFbxVersion(text) {
  4613. var versionRegExp = /FBXVersion: (\d+)/;
  4614. var match = text.match(versionRegExp);
  4615. if (match) {
  4616. var version = parseInt(match[1]);
  4617. return version;
  4618. }
  4619. throw new Error('THREE.FBXLoader: Cannot find the version number for the file given.');
  4620. }
  4621. // Converts FBX ticks into real time seconds.
  4622. function convertFBXTimeToSeconds(time) {
  4623. return time / 46186158000;
  4624. }
  4625. var dataArray = [];
  4626. // extracts the data from the correct position in the FBX array based on indexing type
  4627. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  4628. var index;
  4629. switch (infoObject.mappingType) {
  4630. case 'ByPolygonVertex':
  4631. index = polygonVertexIndex;
  4632. break;
  4633. case 'ByPolygon':
  4634. index = polygonIndex;
  4635. break;
  4636. case 'ByVertice':
  4637. index = vertexIndex;
  4638. break;
  4639. case 'AllSame':
  4640. index = infoObject.indices[0];
  4641. break;
  4642. default:
  4643. console.warn('THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType);
  4644. }
  4645. if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];
  4646. var from = index * infoObject.dataSize;
  4647. var to = from + infoObject.dataSize;
  4648. return slice(dataArray, infoObject.buffer, from, to);
  4649. }
  4650. var tempMat = new THREE.Matrix4();
  4651. var tempEuler = new THREE.Euler();
  4652. var tempVec = new THREE.Vector3();
  4653. var translation = new THREE.Vector3();
  4654. var rotation = new THREE.Matrix4();
  4655. // generate transformation from FBX transform data
  4656. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  4657. // transformData = {
  4658. // eulerOrder: int,
  4659. // translation: [],
  4660. // rotationOffset: [],
  4661. // preRotation
  4662. // rotation
  4663. // postRotation
  4664. // scale
  4665. // }
  4666. // all entries are optional
  4667. function generateTransform(transformData) {
  4668. var transform = new THREE.Matrix4();
  4669. translation.set(0, 0, 0);
  4670. rotation.identity();
  4671. var order = transformData.eulerOrder ? getEulerOrder(transformData.eulerOrder) : getEulerOrder(0);
  4672. if (transformData.translation) translation.fromArray(transformData.translation);
  4673. if (transformData.rotationOffset) translation.add(tempVec.fromArray(transformData.rotationOffset));
  4674. if (transformData.rotation) {
  4675. var array = transformData.rotation.map(THREE.Math.degToRad);
  4676. array.push(order);
  4677. rotation.makeRotationFromEuler(tempEuler.fromArray(array));
  4678. }
  4679. if (transformData.preRotation) {
  4680. var array = transformData.preRotation.map(THREE.Math.degToRad);
  4681. array.push(order);
  4682. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4683. rotation.premultiply(tempMat);
  4684. }
  4685. if (transformData.postRotation) {
  4686. var array = transformData.postRotation.map(THREE.Math.degToRad);
  4687. array.push(order);
  4688. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4689. tempMat.getInverse(tempMat);
  4690. rotation.multiply(tempMat);
  4691. }
  4692. if (transformData.scale) transform.scale(tempVec.fromArray(transformData.scale));
  4693. transform.setPosition(translation);
  4694. transform.multiply(rotation);
  4695. return transform;
  4696. }
  4697. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  4698. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  4699. function getEulerOrder(order) {
  4700. var enums = ['ZYX', // -> XYZ extrinsic
  4701. 'YZX', // -> XZY extrinsic
  4702. 'XZY', // -> YZX extrinsic
  4703. 'ZXY', // -> YXZ extrinsic
  4704. 'YXZ', // -> ZXY extrinsic
  4705. 'XYZ'];
  4706. if (order === 6) {
  4707. console.warn('THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.');
  4708. return enums[0];
  4709. }
  4710. return enums[order];
  4711. }
  4712. // Parses comma separated list of numbers and returns them an array.
  4713. // Used internally by the TextParser
  4714. function parseNumberArray(value) {
  4715. var array = value.split(',').map(function (val) {
  4716. return parseFloat(val);
  4717. });
  4718. return array;
  4719. }
  4720. function convertArrayBufferToString(buffer, from, to) {
  4721. if (from === undefined) from = 0;
  4722. if (to === undefined) to = buffer.byteLength;
  4723. return THREE.LoaderUtils.decodeText(new Uint8Array(buffer, from, to));
  4724. }
  4725. function append(a, b) {
  4726. for (var i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  4727. a[j] = b[i];
  4728. }
  4729. }
  4730. function slice(a, b, from, to) {
  4731. for (var i = from, j = 0; i < to; i++, j++) {
  4732. a[j] = b[i];
  4733. }
  4734. return a;
  4735. }
  4736. // inject array a2 into array a1 at index
  4737. function inject(a1, index, a2) {
  4738. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  4739. }
  4740. return FBXLoader;
  4741. }();
  4742. },{}],4:[function(require,module,exports){
  4743. 'use strict';
  4744. /**
  4745. * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
  4746. */
  4747. function getScriptId() {
  4748. return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
  4749. }
  4750. function createScript(url, id) {
  4751. var script = document.createElement('script');
  4752. script.type = 'text/javascript';
  4753. script.async = true;
  4754. script.id = id;
  4755. script.src = url;
  4756. return script;
  4757. }
  4758. function removeScript(id) {
  4759. var script = document.getElementById(id);
  4760. var parent = script.parentNode;
  4761. try {
  4762. parent && parent.removeChild(script);
  4763. } catch (e) {
  4764. // ignore
  4765. }
  4766. }
  4767. function appendScript(script) {
  4768. var firstScript = document.getElementsByTagName('script')[0];
  4769. firstScript.parentNode.insertBefore(script, firstScript);
  4770. }
  4771. function fetchScriptInternal(url, options, Promise) {
  4772. return new Promise(function (resolve, reject) {
  4773. var timeout = options.timeout || 5000;
  4774. var scriptId = getScriptId();
  4775. var script = createScript(url, scriptId);
  4776. var timeoutId = setTimeout(function () {
  4777. reject(new Error('Script request to ' + url + ' timed out'));
  4778. removeScript(scriptId);
  4779. }, timeout);
  4780. var disableTimeout = function disableTimeout(timeoutId) {
  4781. clearTimeout(timeoutId);
  4782. };
  4783. script.addEventListener('load', function (e) {
  4784. resolve({ ok: true });
  4785. disableTimeout(timeoutId);
  4786. removeScript(scriptId);
  4787. });
  4788. script.addEventListener('error', function (e) {
  4789. reject(new Error('Script request to ' + url + ' failed ' + e));
  4790. disableTimeout(timeoutId);
  4791. removeScript(scriptId);
  4792. });
  4793. appendScript(script);
  4794. });
  4795. }
  4796. function fetchScript(settings) {
  4797. settings = settings || {};
  4798. return function (url, options) {
  4799. options = options || {};
  4800. return fetchScriptInternal(url, options, settings.Promise || Promise);
  4801. };
  4802. }
  4803. module.exports = fetchScript;
  4804. },{}],5:[function(require,module,exports){
  4805. 'use strict';
  4806. var LoopMode = {
  4807. once: THREE.LoopOnce,
  4808. repeat: THREE.LoopRepeat,
  4809. pingpong: THREE.LoopPingPong
  4810. };
  4811. /**
  4812. * animation-mixer
  4813. *
  4814. * Player for animation clips. Intended to be compatible with any model format that supports
  4815. * skeletal or morph animations through THREE.AnimationMixer.
  4816. * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
  4817. */
  4818. module.exports = AFRAME.registerComponent('animation-mixer', {
  4819. schema: {
  4820. clip: { default: '*' },
  4821. duration: { default: 0 },
  4822. clampWhenFinished: { default: false, type: 'boolean' },
  4823. crossFadeDuration: { default: 0 },
  4824. loop: { default: 'repeat', oneOf: Object.keys(LoopMode) },
  4825. repetitions: { default: Infinity, min: 0 },
  4826. timeScale: { default: 1 }
  4827. },
  4828. init: function init() {
  4829. var _this = this;
  4830. /** @type {THREE.Mesh} */
  4831. this.model = null;
  4832. /** @type {THREE.AnimationMixer} */
  4833. this.mixer = null;
  4834. /** @type {Array<THREE.AnimationAction>} */
  4835. this.activeActions = [];
  4836. var model = this.el.getObject3D('mesh');
  4837. if (model) {
  4838. this.load(model);
  4839. } else {
  4840. this.el.addEventListener('model-loaded', function (e) {
  4841. _this.load(e.detail.model);
  4842. });
  4843. }
  4844. },
  4845. load: function load(model) {
  4846. var el = this.el;
  4847. this.model = model;
  4848. this.mixer = new THREE.AnimationMixer(model);
  4849. this.mixer.addEventListener('loop', function (e) {
  4850. el.emit('animation-loop', { action: e.action, loopDelta: e.loopDelta });
  4851. });
  4852. this.mixer.addEventListener('finished', function (e) {
  4853. el.emit('animation-finished', { action: e.action, direction: e.direction });
  4854. });
  4855. if (this.data.clip) this.update({});
  4856. },
  4857. remove: function remove() {
  4858. if (this.mixer) this.mixer.stopAllAction();
  4859. },
  4860. update: function update(prevData) {
  4861. if (!prevData) return;
  4862. var data = this.data;
  4863. var changes = AFRAME.utils.diff(data, prevData);
  4864. // If selected clips have changed, restart animation.
  4865. if ('clip' in changes) {
  4866. this.stopAction();
  4867. if (data.clip) this.playAction();
  4868. return;
  4869. }
  4870. // Otherwise, modify running actions.
  4871. this.activeActions.forEach(function (action) {
  4872. if ('duration' in changes && data.duration) {
  4873. action.setDuration(data.duration);
  4874. }
  4875. if ('clampWhenFinished' in changes) {
  4876. action.clampWhenFinished = data.clampWhenFinished;
  4877. }
  4878. if ('loop' in changes || 'repetitions' in changes) {
  4879. action.setLoop(LoopMode[data.loop], data.repetitions);
  4880. }
  4881. if ('timeScale' in changes) {
  4882. action.setEffectiveTimeScale(data.timeScale);
  4883. }
  4884. });
  4885. },
  4886. stopAction: function stopAction() {
  4887. var data = this.data;
  4888. for (var i = 0; i < this.activeActions.length; i++) {
  4889. data.crossFadeDuration ? this.activeActions[i].fadeOut(data.crossFadeDuration) : this.activeActions[i].stop();
  4890. }
  4891. this.activeActions.length = 0;
  4892. },
  4893. playAction: function playAction() {
  4894. if (!this.mixer) return;
  4895. var model = this.model,
  4896. data = this.data,
  4897. clips = model.animations || (model.geometry || {}).animations || [];
  4898. if (!clips.length) return;
  4899. var re = wildcardToRegExp(data.clip);
  4900. for (var clip, i = 0; clip = clips[i]; i++) {
  4901. if (clip.name.match(re)) {
  4902. var action = this.mixer.clipAction(clip, model);
  4903. action.enabled = true;
  4904. action.clampWhenFinished = data.clampWhenFinished;
  4905. if (data.duration) action.setDuration(data.duration);
  4906. if (data.timeScale !== 1) action.setEffectiveTimeScale(data.timeScale);
  4907. action.setLoop(LoopMode[data.loop], data.repetitions).fadeIn(data.crossFadeDuration).play();
  4908. this.activeActions.push(action);
  4909. }
  4910. }
  4911. },
  4912. tick: function tick(t, dt) {
  4913. if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
  4914. }
  4915. });
  4916. /**
  4917. * Creates a RegExp from the given string, converting asterisks to .* expressions,
  4918. * and escaping all other characters.
  4919. */
  4920. function wildcardToRegExp(s) {
  4921. return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
  4922. }
  4923. /**
  4924. * RegExp-escapes all characters in the given string.
  4925. */
  4926. function regExpEscape(s) {
  4927. return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  4928. }
  4929. },{}],6:[function(require,module,exports){
  4930. 'use strict';
  4931. THREE.ColladaLoader = require('../../lib/ColladaLoader');
  4932. /**
  4933. * collada-model-legacy
  4934. *
  4935. * Loader for COLLADA (.dae) format.
  4936. */
  4937. module.exports.Component = AFRAME.registerComponent('collada-model-legacy', {
  4938. schema: { type: 'asset' },
  4939. init: function init() {
  4940. this.model = null;
  4941. this.loader = new THREE.ColladaLoader();
  4942. },
  4943. update: function update() {
  4944. var self = this;
  4945. var el = this.el;
  4946. var src = this.data;
  4947. var rendererSystem = this.el.sceneEl.systems.renderer;
  4948. if (!src) {
  4949. return;
  4950. }
  4951. this.remove();
  4952. this.loader.load(src, function (colladaModel) {
  4953. self.model = colladaModel.scene;
  4954. self.model.traverse(function (object) {
  4955. if (object.isMesh) {
  4956. var material = object.material;
  4957. if (material.color) rendererSystem.applyColorCorrection(material.color);
  4958. if (material.map) rendererSystem.applyColorCorrection(material.map);
  4959. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  4960. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  4961. }
  4962. });
  4963. el.setObject3D('mesh', self.model);
  4964. el.emit('model-loaded', { format: 'collada', model: self.model });
  4965. });
  4966. },
  4967. remove: function remove() {
  4968. if (!this.model) {
  4969. return;
  4970. }
  4971. this.el.removeObject3D('mesh');
  4972. }
  4973. });
  4974. },{"../../lib/ColladaLoader":2}],7:[function(require,module,exports){
  4975. 'use strict';
  4976. THREE.FBXLoader = require('../../lib/FBXLoader');
  4977. /**
  4978. * fbx-model
  4979. *
  4980. * Loader for FBX format. Supports ASCII, but *not* binary, models.
  4981. */
  4982. module.exports = AFRAME.registerComponent('fbx-model', {
  4983. schema: {
  4984. src: { type: 'asset' },
  4985. crossorigin: { default: '' }
  4986. },
  4987. init: function init() {
  4988. this.model = null;
  4989. },
  4990. update: function update() {
  4991. var data = this.data;
  4992. if (!data.src) return;
  4993. this.remove();
  4994. var loader = new THREE.FBXLoader();
  4995. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  4996. loader.load(data.src, this.load.bind(this));
  4997. },
  4998. load: function load(model) {
  4999. this.model = model;
  5000. this.el.setObject3D('mesh', model);
  5001. this.el.emit('model-loaded', { format: 'fbx', model: model });
  5002. },
  5003. remove: function remove() {
  5004. if (this.model) this.el.removeObject3D('mesh');
  5005. }
  5006. });
  5007. },{"../../lib/FBXLoader":3}],8:[function(require,module,exports){
  5008. 'use strict';
  5009. var fetchScript = require('../../lib/fetch-script')();
  5010. var LOADER_SRC = 'https://cdn.jsdelivr.net/gh/mrdoob/three.js@r86/examples/js/loaders/GLTFLoader.js';
  5011. var loadLoader = function () {
  5012. var promise = void 0;
  5013. return function () {
  5014. promise = promise || fetchScript(LOADER_SRC);
  5015. return promise;
  5016. };
  5017. }();
  5018. /**
  5019. * Legacy loader for glTF 1.0 models.
  5020. * Asynchronously loads THREE.GLTFLoader from rawgit.
  5021. */
  5022. module.exports = AFRAME.registerComponent('gltf-model-legacy', {
  5023. schema: { type: 'model' },
  5024. init: function init() {
  5025. var _this = this;
  5026. this.model = null;
  5027. this.loader = null;
  5028. this.loaderPromise = loadLoader().then(function () {
  5029. _this.loader = new THREE.GLTFLoader();
  5030. _this.loader.setCrossOrigin('Anonymous');
  5031. });
  5032. },
  5033. update: function update() {
  5034. var _this2 = this;
  5035. var self = this;
  5036. var el = this.el;
  5037. var src = this.data;
  5038. if (!src) {
  5039. return;
  5040. }
  5041. this.remove();
  5042. this.loaderPromise.then(function () {
  5043. _this2.loader.load(src, function gltfLoaded(gltfModel) {
  5044. self.model = gltfModel.scene;
  5045. self.model.animations = gltfModel.animations;
  5046. el.setObject3D('mesh', self.model);
  5047. el.emit('model-loaded', { format: 'gltf', model: self.model });
  5048. });
  5049. });
  5050. },
  5051. remove: function remove() {
  5052. if (!this.model) {
  5053. return;
  5054. }
  5055. this.el.removeObject3D('mesh');
  5056. }
  5057. });
  5058. },{"../../lib/fetch-script":4}],9:[function(require,module,exports){
  5059. 'use strict';
  5060. require('./animation-mixer');
  5061. require('./collada-model-legacy');
  5062. require('./fbx-model');
  5063. require('./gltf-model-legacy');
  5064. require('./object-model');
  5065. },{"./animation-mixer":5,"./collada-model-legacy":6,"./fbx-model":7,"./gltf-model-legacy":8,"./object-model":10}],10:[function(require,module,exports){
  5066. 'use strict';
  5067. /**
  5068. * object-model
  5069. *
  5070. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  5071. * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
  5072. * includes multiple meshes or an entire scene.
  5073. *
  5074. * Check the console for errors, if in doubt. You may need to use `json-model` or
  5075. * `blend-character-model` for some .js and .json files.
  5076. *
  5077. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  5078. */
  5079. module.exports = AFRAME.registerComponent('object-model', {
  5080. schema: {
  5081. src: { type: 'asset' },
  5082. crossorigin: { default: '' }
  5083. },
  5084. init: function init() {
  5085. this.model = null;
  5086. },
  5087. update: function update() {
  5088. var _this = this;
  5089. var loader = void 0;
  5090. var data = this.data;
  5091. if (!data.src) return;
  5092. this.remove();
  5093. loader = new THREE.ObjectLoader();
  5094. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  5095. loader.load(data.src, function (object) {
  5096. // Enable skinning, if applicable.
  5097. object.traverse(function (o) {
  5098. if (o instanceof THREE.SkinnedMesh && o.material) {
  5099. o.material.skinning = !!(o.geometry && o.geometry.bones || []).length;
  5100. }
  5101. });
  5102. _this.load(object);
  5103. });
  5104. },
  5105. load: function load(model) {
  5106. this.model = model;
  5107. this.el.setObject3D('mesh', model);
  5108. this.el.emit('model-loaded', { format: 'json', model: model });
  5109. },
  5110. remove: function remove() {
  5111. if (this.model) this.el.removeObject3D('mesh');
  5112. }
  5113. });
  5114. },{}]},{},[1]);