ColladaLoader.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526
  1. /**
  2. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  3. * @author Tony Parisi / http://www.tonyparisi.com/
  4. */
  5. THREE.ColladaLoader = function () {
  6. var COLLADA = null;
  7. var scene = null;
  8. var visualScene;
  9. var kinematicsModel;
  10. var readyCallbackFunc = null;
  11. var sources = {};
  12. var images = {};
  13. var animations = {};
  14. var controllers = {};
  15. var geometries = {};
  16. var materials = {};
  17. var effects = {};
  18. var cameras = {};
  19. var lights = {};
  20. var animData;
  21. var kinematics;
  22. var visualScenes;
  23. var kinematicsModels;
  24. var baseUrl;
  25. var morphs;
  26. var skins;
  27. var flip_uv = true;
  28. var preferredShading = THREE.SmoothShading;
  29. var options = {
  30. // Force Geometry to always be centered at the local origin of the
  31. // containing Mesh.
  32. centerGeometry: false,
  33. // Axis conversion is done for geometries, animations, and controllers.
  34. // If we ever pull cameras or lights out of the COLLADA file, they'll
  35. // need extra work.
  36. convertUpAxis: false,
  37. subdivideFaces: true,
  38. upAxis: 'Y',
  39. // For reflective or refractive materials we'll use this cubemap
  40. defaultEnvMap: null
  41. };
  42. var colladaUnit = 1.0;
  43. var colladaUp = 'Y';
  44. var upConversion = null;
  45. function load ( url, readyCallback, progressCallback, failCallback ) {
  46. var length = 0;
  47. if ( document.implementation && document.implementation.createDocument ) {
  48. var request = new XMLHttpRequest();
  49. request.onreadystatechange = function() {
  50. if ( request.readyState === 4 ) {
  51. if ( request.status === 0 || request.status === 200 ) {
  52. if ( request.responseXML ) {
  53. readyCallbackFunc = readyCallback;
  54. parse( request.responseXML, undefined, url );
  55. } else if ( request.responseText ) {
  56. readyCallbackFunc = readyCallback;
  57. var xmlParser = new DOMParser();
  58. var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" );
  59. parse( responseXML, undefined, url );
  60. } else {
  61. if ( faillCallback ) {
  62. failCallback();
  63. } else {
  64. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  65. }
  66. }
  67. }
  68. } else if ( request.readyState === 3 ) {
  69. if ( progressCallback ) {
  70. if ( length === 0 ) {
  71. length = request.getResponseHeader( "Content-Length" );
  72. }
  73. progressCallback( { total: length, loaded: request.responseText.length } );
  74. }
  75. }
  76. }
  77. request.open( "GET", url, true );
  78. request.send( null );
  79. } else {
  80. alert( "Don't know how to parse XML!" );
  81. }
  82. }
  83. function parse( doc, callBack, url ) {
  84. COLLADA = doc;
  85. callBack = callBack || readyCallbackFunc;
  86. if ( url !== undefined ) {
  87. var parts = url.split( '/' );
  88. parts.pop();
  89. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  90. }
  91. parseAsset();
  92. setUpConversion();
  93. images = parseLib( "library_images image", _Image, "image" );
  94. materials = parseLib( "library_materials material", Material, "material" );
  95. effects = parseLib( "library_effects effect", Effect, "effect" );
  96. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  97. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  98. lights = parseLib( "library_lights light", Light, "light" );
  99. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  100. animations = parseLib( "library_animations animation", Animation, "animation" );
  101. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  102. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  103. morphs = [];
  104. skins = [];
  105. visualScene = parseScene();
  106. scene = new THREE.Group();
  107. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  108. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  109. }
  110. // unit conversion
  111. scene.scale.multiplyScalar( colladaUnit );
  112. createAnimations();
  113. kinematicsModel = parseKinematicsModel();
  114. createKinematics();
  115. var result = {
  116. scene: scene,
  117. morphs: morphs,
  118. skins: skins,
  119. animations: animData,
  120. kinematics: kinematics,
  121. dae: {
  122. images: images,
  123. materials: materials,
  124. cameras: cameras,
  125. lights: lights,
  126. effects: effects,
  127. geometries: geometries,
  128. controllers: controllers,
  129. animations: animations,
  130. visualScenes: visualScenes,
  131. visualScene: visualScene,
  132. scene: visualScene,
  133. kinematicsModels: kinematicsModels,
  134. kinematicsModel: kinematicsModel
  135. }
  136. };
  137. if ( callBack ) {
  138. callBack( result );
  139. }
  140. return result;
  141. }
  142. function setPreferredShading ( shading ) {
  143. preferredShading = shading;
  144. }
  145. function parseAsset () {
  146. var elements = COLLADA.querySelectorAll('asset');
  147. var element = elements[0];
  148. if ( element && element.childNodes ) {
  149. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  150. var child = element.childNodes[ i ];
  151. switch ( child.nodeName ) {
  152. case 'unit':
  153. var meter = child.getAttribute( 'meter' );
  154. if ( meter ) {
  155. colladaUnit = parseFloat( meter );
  156. }
  157. break;
  158. case 'up_axis':
  159. colladaUp = child.textContent.charAt(0);
  160. break;
  161. }
  162. }
  163. }
  164. }
  165. function parseLib ( q, classSpec, prefix ) {
  166. var elements = COLLADA.querySelectorAll(q);
  167. var lib = {};
  168. var i = 0;
  169. var elementsLength = elements.length;
  170. for ( var j = 0; j < elementsLength; j ++ ) {
  171. var element = elements[j];
  172. var daeElement = ( new classSpec() ).parse( element );
  173. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  174. lib[ daeElement.id ] = daeElement;
  175. }
  176. return lib;
  177. }
  178. function parseScene() {
  179. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  180. if ( sceneElement ) {
  181. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  182. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  183. } else {
  184. return null;
  185. }
  186. }
  187. function parseKinematicsModel() {
  188. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  189. if ( kinematicsModelElement ) {
  190. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  191. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  192. } else {
  193. return null;
  194. }
  195. }
  196. function createAnimations() {
  197. animData = [];
  198. // fill in the keys
  199. recurseHierarchy( scene );
  200. }
  201. function recurseHierarchy( node ) {
  202. var n = visualScene.getChildById( node.colladaId, true ),
  203. newData = null;
  204. if ( n && n.keys ) {
  205. newData = {
  206. fps: 60,
  207. hierarchy: [ {
  208. node: n,
  209. keys: n.keys,
  210. sids: n.sids
  211. } ],
  212. node: node,
  213. name: 'animation_' + node.name,
  214. length: 0
  215. };
  216. animData.push(newData);
  217. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  218. newData.length = Math.max( newData.length, n.keys[i].time );
  219. }
  220. } else {
  221. newData = {
  222. hierarchy: [ {
  223. keys: [],
  224. sids: []
  225. } ]
  226. }
  227. }
  228. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  229. var d = recurseHierarchy( node.children[i] );
  230. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  231. newData.hierarchy.push( {
  232. keys: [],
  233. sids: []
  234. } );
  235. }
  236. }
  237. return newData;
  238. }
  239. function calcAnimationBounds () {
  240. var start = 1000000;
  241. var end = -start;
  242. var frames = 0;
  243. var ID;
  244. for ( var id in animations ) {
  245. var animation = animations[ id ];
  246. ID = ID || animation.id;
  247. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  248. var sampler = animation.sampler[ i ];
  249. sampler.create();
  250. start = Math.min( start, sampler.startTime );
  251. end = Math.max( end, sampler.endTime );
  252. frames = Math.max( frames, sampler.input.length );
  253. }
  254. }
  255. return { start:start, end:end, frames:frames,ID:ID };
  256. }
  257. function createMorph ( geometry, ctrl ) {
  258. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  259. if ( !morphCtrl || !morphCtrl.morph ) {
  260. console.log("could not find morph controller!");
  261. return;
  262. }
  263. var morph = morphCtrl.morph;
  264. for ( var i = 0; i < morph.targets.length; i ++ ) {
  265. var target_id = morph.targets[ i ];
  266. var daeGeometry = geometries[ target_id ];
  267. if ( !daeGeometry.mesh ||
  268. !daeGeometry.mesh.primitives ||
  269. !daeGeometry.mesh.primitives.length ) {
  270. continue;
  271. }
  272. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  273. if ( target.vertices.length === geometry.vertices.length ) {
  274. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  275. }
  276. }
  277. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  278. };
  279. function createSkin ( geometry, ctrl, applyBindShape ) {
  280. var skinCtrl = controllers[ ctrl.url ];
  281. if ( !skinCtrl || !skinCtrl.skin ) {
  282. console.log( "could not find skin controller!" );
  283. return;
  284. }
  285. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  286. console.log( "could not find the skeleton for the skin!" );
  287. return;
  288. }
  289. var skin = skinCtrl.skin;
  290. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  291. var hierarchy = [];
  292. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  293. var bones = [];
  294. geometry.skinWeights = [];
  295. geometry.skinIndices = [];
  296. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  297. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  298. /*
  299. geometry.animation = {
  300. name: 'take_001',
  301. fps: 30,
  302. length: 2,
  303. JIT: true,
  304. hierarchy: hierarchy
  305. };
  306. */
  307. if ( applyBindShape ) {
  308. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  309. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  310. }
  311. }
  312. }
  313. function setupSkeleton ( node, bones, frame, parent ) {
  314. node.world = node.world || new THREE.Matrix4();
  315. node.localworld = node.localworld || new THREE.Matrix4();
  316. node.world.copy( node.matrix );
  317. node.localworld.copy( node.matrix );
  318. if ( node.channels && node.channels.length ) {
  319. var channel = node.channels[ 0 ];
  320. var m = channel.sampler.output[ frame ];
  321. if ( m instanceof THREE.Matrix4 ) {
  322. node.world.copy( m );
  323. node.localworld.copy(m);
  324. if (frame === 0)
  325. node.matrix.copy(m);
  326. }
  327. }
  328. if ( parent ) {
  329. node.world.multiplyMatrices( parent, node.world );
  330. }
  331. bones.push( node );
  332. for ( var i = 0; i < node.nodes.length; i ++ ) {
  333. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  334. }
  335. }
  336. function setupSkinningMatrices ( bones, skin ) {
  337. // FIXME: this is dumb...
  338. for ( var i = 0; i < bones.length; i ++ ) {
  339. var bone = bones[ i ];
  340. var found = -1;
  341. if ( bone.type != 'JOINT' ) continue;
  342. for ( var j = 0; j < skin.joints.length; j ++ ) {
  343. if ( bone.sid === skin.joints[ j ] ) {
  344. found = j;
  345. break;
  346. }
  347. }
  348. if ( found >= 0 ) {
  349. var inv = skin.invBindMatrices[ found ];
  350. bone.invBindMatrix = inv;
  351. bone.skinningMatrix = new THREE.Matrix4();
  352. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  353. bone.animatrix = new THREE.Matrix4();
  354. bone.animatrix.copy(bone.localworld);
  355. bone.weights = [];
  356. for ( var j = 0; j < skin.weights.length; j ++ ) {
  357. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  358. var w = skin.weights[ j ][ k ];
  359. if ( w.joint === found ) {
  360. bone.weights.push( w );
  361. }
  362. }
  363. }
  364. } else {
  365. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  366. bone.skinningMatrix = new THREE.Matrix4();
  367. bone.weights = [];
  368. }
  369. }
  370. }
  371. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  372. function flattenSkeleton(skeleton) {
  373. var list = [];
  374. var walk = function(parentid, node, list) {
  375. var bone = {};
  376. bone.name = node.sid;
  377. bone.parent = parentid;
  378. bone.matrix = node.matrix;
  379. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  380. bone.matrix.decompose(data[0], data[1], data[2]);
  381. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  382. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  383. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  384. list.push(bone);
  385. for (var i in node.nodes) {
  386. walk(node.sid, node.nodes[i], list);
  387. }
  388. };
  389. walk(-1, skeleton, list);
  390. return list;
  391. }
  392. //Move the vertices into the pose that is proper for the start of the animation
  393. function skinToBindPose(geometry,skeleton,skinController) {
  394. var bones = [];
  395. setupSkeleton( skeleton, bones, -1 );
  396. setupSkinningMatrices( bones, skinController.skin );
  397. v = new THREE.Vector3();
  398. var skinned = [];
  399. for (var i = 0; i < geometry.vertices.length; i ++) {
  400. skinned.push(new THREE.Vector3());
  401. }
  402. for ( i = 0; i < bones.length; i ++ ) {
  403. if ( bones[ i ].type != 'JOINT' ) continue;
  404. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  405. w = bones[ i ].weights[ j ];
  406. vidx = w.index;
  407. weight = w.weight;
  408. o = geometry.vertices[vidx];
  409. s = skinned[vidx];
  410. v.x = o.x;
  411. v.y = o.y;
  412. v.z = o.z;
  413. v.applyMatrix4( bones[i].skinningMatrix );
  414. s.x += (v.x * weight);
  415. s.y += (v.y * weight);
  416. s.z += (v.z * weight);
  417. }
  418. }
  419. for (var i = 0; i < geometry.vertices.length; i ++) {
  420. geometry.vertices[i] = skinned[i];
  421. }
  422. }
  423. function applySkin ( geometry, instanceCtrl, frame ) {
  424. var skinController = controllers[ instanceCtrl.url ];
  425. frame = frame !== undefined ? frame : 40;
  426. if ( !skinController || !skinController.skin ) {
  427. console.log( 'ColladaLoader: Could not find skin controller.' );
  428. return;
  429. }
  430. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  431. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  432. return;
  433. }
  434. var animationBounds = calcAnimationBounds();
  435. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  436. //flatten the skeleton into a list of bones
  437. var bonelist = flattenSkeleton(skeleton);
  438. var joints = skinController.skin.joints;
  439. //sort that list so that the order reflects the order in the joint list
  440. var sortedbones = [];
  441. for (var i = 0; i < joints.length; i ++) {
  442. for (var j = 0; j < bonelist.length; j ++) {
  443. if (bonelist[j].name === joints[i]) {
  444. sortedbones[i] = bonelist[j];
  445. }
  446. }
  447. }
  448. //hook up the parents by index instead of name
  449. for (var i = 0; i < sortedbones.length; i ++) {
  450. for (var j = 0; j < sortedbones.length; j ++) {
  451. if (sortedbones[i].parent === sortedbones[j].name) {
  452. sortedbones[i].parent = j;
  453. }
  454. }
  455. }
  456. var i, j, w, vidx, weight;
  457. var v = new THREE.Vector3(), o, s;
  458. // move vertices to bind shape
  459. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  460. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  461. }
  462. var skinIndices = [];
  463. var skinWeights = [];
  464. var weights = skinController.skin.weights;
  465. // hook up the skin weights
  466. // TODO - this might be a good place to choose greatest 4 weights
  467. for ( var i =0; i < weights.length; i ++ ) {
  468. var indicies = new THREE.Vector4(weights[i][0] ? weights[i][0].joint : 0,weights[i][1] ? weights[i][1].joint : 0,weights[i][2] ? weights[i][2].joint : 0,weights[i][3] ? weights[i][3].joint : 0);
  469. var weight = new THREE.Vector4(weights[i][0] ? weights[i][0].weight : 0,weights[i][1] ? weights[i][1].weight : 0,weights[i][2] ? weights[i][2].weight : 0,weights[i][3] ? weights[i][3].weight : 0);
  470. skinIndices.push(indicies);
  471. skinWeights.push(weight);
  472. }
  473. geometry.skinIndices = skinIndices;
  474. geometry.skinWeights = skinWeights;
  475. geometry.bones = sortedbones;
  476. // process animation, or simply pose the rig if no animation
  477. //create an animation for the animated bones
  478. //NOTE: this has no effect when using morphtargets
  479. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  480. for (var j = 0; j < sortedbones.length; j ++) {
  481. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  482. }
  483. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  484. skinToBindPose(geometry, skeleton, skinController);
  485. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  486. var bones = [];
  487. var skinned = [];
  488. // process the frame and setup the rig with a fresh
  489. // transform, possibly from the bone's animation channel(s)
  490. setupSkeleton( skeleton, bones, frame );
  491. setupSkinningMatrices( bones, skinController.skin );
  492. for (var i = 0; i < bones.length; i ++) {
  493. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  494. if (animationdata.hierarchy[j].name === bones[i].sid) {
  495. var key = {};
  496. key.time = (frame / 30);
  497. key.matrix = bones[i].animatrix;
  498. if (frame === 0)
  499. bones[i].matrix = key.matrix;
  500. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  501. key.matrix.decompose(data[0], data[1], data[2]);
  502. key.pos = [ data[0].x,data[0].y,data[0].z ];
  503. key.scl = [ data[2].x,data[2].y,data[2].z ];
  504. key.rot = data[1];
  505. animationdata.hierarchy[j].keys.push(key);
  506. }
  507. }
  508. }
  509. geometry.animation = animationdata;
  510. }
  511. };
  512. function createKinematics() {
  513. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  514. kinematics = undefined;
  515. return;
  516. }
  517. var jointMap = {};
  518. var _addToMap = function( jointIndex, parentVisualElement ) {
  519. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  520. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  521. var joint = kinematicsModel.joints[ jointIndex ];
  522. scene.traverse(function( node ) {
  523. if ( node.colladaId == parentVisualElementId ) {
  524. jointMap[ jointIndex ] = {
  525. node: node,
  526. transforms: colladaNode.transforms,
  527. joint: joint,
  528. position: joint.zeroPosition
  529. };
  530. }
  531. });
  532. };
  533. kinematics = {
  534. joints: kinematicsModel && kinematicsModel.joints,
  535. getJointValue: function( jointIndex ) {
  536. var jointData = jointMap[ jointIndex ];
  537. if ( jointData ) {
  538. return jointData.position;
  539. } else {
  540. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  541. }
  542. },
  543. setJointValue: function( jointIndex, value ) {
  544. var jointData = jointMap[ jointIndex ];
  545. if ( jointData ) {
  546. var joint = jointData.joint;
  547. if ( value > joint.limits.max || value < joint.limits.min ) {
  548. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  549. } else if ( joint.static ) {
  550. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  551. } else {
  552. var threejsNode = jointData.node;
  553. var axis = joint.axis;
  554. var transforms = jointData.transforms;
  555. var matrix = new THREE.Matrix4();
  556. for (i = 0; i < transforms.length; i ++ ) {
  557. var transform = transforms[ i ];
  558. // kinda ghetto joint detection
  559. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  560. // apply actual joint value here
  561. switch ( joint.type ) {
  562. case 'revolute':
  563. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  564. break;
  565. case 'prismatic':
  566. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  567. break;
  568. default:
  569. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  570. break;
  571. }
  572. } else {
  573. var m1 = new THREE.Matrix4();
  574. switch ( transform.type ) {
  575. case 'matrix':
  576. matrix.multiply( transform.obj );
  577. break;
  578. case 'translate':
  579. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  580. break;
  581. case 'rotate':
  582. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  583. break;
  584. }
  585. }
  586. }
  587. // apply the matrix to the threejs node
  588. var elementsFloat32Arr = matrix.elements;
  589. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  590. var elementsRowMajor = [
  591. elements[ 0 ],
  592. elements[ 4 ],
  593. elements[ 8 ],
  594. elements[ 12 ],
  595. elements[ 1 ],
  596. elements[ 5 ],
  597. elements[ 9 ],
  598. elements[ 13 ],
  599. elements[ 2 ],
  600. elements[ 6 ],
  601. elements[ 10 ],
  602. elements[ 14 ],
  603. elements[ 3 ],
  604. elements[ 7 ],
  605. elements[ 11 ],
  606. elements[ 15 ]
  607. ];
  608. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  609. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  610. }
  611. } else {
  612. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  613. }
  614. }
  615. };
  616. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  617. if ( element ) {
  618. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  619. var child = element.childNodes[ i ];
  620. if ( child.nodeType != 1 ) continue;
  621. switch ( child.nodeName ) {
  622. case 'bind_joint_axis':
  623. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  624. var axis = child.querySelector('axis param').textContent;
  625. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  626. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  627. if ( visualTargetElement ) {
  628. var parentVisualElement = visualTargetElement.parentElement;
  629. _addToMap(jointIndex, parentVisualElement);
  630. }
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. }
  637. };
  638. function createSceneGraph ( node, parent ) {
  639. var obj = new THREE.Object3D();
  640. var skinned = false;
  641. var skinController;
  642. var morphController;
  643. var i, j;
  644. // FIXME: controllers
  645. for ( i = 0; i < node.controllers.length; i ++ ) {
  646. var controller = controllers[ node.controllers[ i ].url ];
  647. switch ( controller.type ) {
  648. case 'skin':
  649. if ( geometries[ controller.skin.source ] ) {
  650. var inst_geom = new InstanceGeometry();
  651. inst_geom.url = controller.skin.source;
  652. inst_geom.instance_material = node.controllers[ i ].instance_material;
  653. node.geometries.push( inst_geom );
  654. skinned = true;
  655. skinController = node.controllers[ i ];
  656. } else if ( controllers[ controller.skin.source ] ) {
  657. // urgh: controller can be chained
  658. // handle the most basic case...
  659. var second = controllers[ controller.skin.source ];
  660. morphController = second;
  661. // skinController = node.controllers[i];
  662. if ( second.morph && geometries[ second.morph.source ] ) {
  663. var inst_geom = new InstanceGeometry();
  664. inst_geom.url = second.morph.source;
  665. inst_geom.instance_material = node.controllers[ i ].instance_material;
  666. node.geometries.push( inst_geom );
  667. }
  668. }
  669. break;
  670. case 'morph':
  671. if ( geometries[ controller.morph.source ] ) {
  672. var inst_geom = new InstanceGeometry();
  673. inst_geom.url = controller.morph.source;
  674. inst_geom.instance_material = node.controllers[ i ].instance_material;
  675. node.geometries.push( inst_geom );
  676. morphController = node.controllers[ i ];
  677. }
  678. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  679. default:
  680. break;
  681. }
  682. }
  683. // geometries
  684. var double_sided_materials = {};
  685. for ( i = 0; i < node.geometries.length; i ++ ) {
  686. var instance_geometry = node.geometries[i];
  687. var instance_materials = instance_geometry.instance_material;
  688. var geometry = geometries[ instance_geometry.url ];
  689. var used_materials = {};
  690. var used_materials_array = [];
  691. var num_materials = 0;
  692. var first_material;
  693. if ( geometry ) {
  694. if ( !geometry.mesh || !geometry.mesh.primitives )
  695. continue;
  696. if ( obj.name.length === 0 ) {
  697. obj.name = geometry.id;
  698. }
  699. // collect used fx for this geometry-instance
  700. if ( instance_materials ) {
  701. for ( j = 0; j < instance_materials.length; j ++ ) {
  702. var instance_material = instance_materials[ j ];
  703. var mat = materials[ instance_material.target ];
  704. var effect_id = mat.instance_effect.url;
  705. var shader = effects[ effect_id ].shader;
  706. var material3js = shader.material;
  707. if ( geometry.doubleSided ) {
  708. if ( !( instance_material.symbol in double_sided_materials ) ) {
  709. var _copied_material = material3js.clone();
  710. _copied_material.side = THREE.DoubleSide;
  711. double_sided_materials[ instance_material.symbol ] = _copied_material;
  712. }
  713. material3js = double_sided_materials[ instance_material.symbol ];
  714. }
  715. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  716. used_materials[ instance_material.symbol ] = num_materials;
  717. used_materials_array.push( material3js );
  718. first_material = material3js;
  719. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  720. num_materials ++;
  721. }
  722. }
  723. var mesh;
  724. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  725. var geom = geometry.mesh.geometry3js;
  726. if ( num_materials > 1 ) {
  727. material = new THREE.MeshFaceMaterial( used_materials_array );
  728. for ( j = 0; j < geom.faces.length; j ++ ) {
  729. var face = geom.faces[ j ];
  730. face.materialIndex = used_materials[ face.daeMaterial ]
  731. }
  732. }
  733. if ( skinController !== undefined ) {
  734. applySkin( geom, skinController );
  735. if ( geom.morphTargets.length > 0 ) {
  736. material.morphTargets = true;
  737. material.skinning = false;
  738. } else {
  739. material.morphTargets = false;
  740. material.skinning = true;
  741. }
  742. mesh = new THREE.SkinnedMesh( geom, material, false );
  743. //mesh.skeleton = skinController.skeleton;
  744. //mesh.skinController = controllers[ skinController.url ];
  745. //mesh.skinInstanceController = skinController;
  746. mesh.name = 'skin_' + skins.length;
  747. //mesh.animationHandle.setKey(0);
  748. skins.push( mesh );
  749. } else if ( morphController !== undefined ) {
  750. createMorph( geom, morphController );
  751. material.morphTargets = true;
  752. mesh = new THREE.Mesh( geom, material );
  753. mesh.name = 'morph_' + morphs.length;
  754. morphs.push( mesh );
  755. } else {
  756. if ( geom.isLineStrip === true ) {
  757. mesh = new THREE.Line( geom );
  758. } else {
  759. mesh = new THREE.Mesh( geom, material );
  760. }
  761. }
  762. obj.add(mesh);
  763. }
  764. }
  765. for ( i = 0; i < node.cameras.length; i ++ ) {
  766. var instance_camera = node.cameras[i];
  767. var cparams = cameras[instance_camera.url];
  768. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  769. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  770. obj.add(cam);
  771. }
  772. for ( i = 0; i < node.lights.length; i ++ ) {
  773. var light = null;
  774. var instance_light = node.lights[i];
  775. var lparams = lights[instance_light.url];
  776. if ( lparams && lparams.technique ) {
  777. var color = lparams.color.getHex();
  778. var intensity = lparams.intensity;
  779. var distance = lparams.distance;
  780. var angle = lparams.falloff_angle;
  781. var exponent; // Intentionally undefined, don't know what this is yet
  782. switch ( lparams.technique ) {
  783. case 'directional':
  784. light = new THREE.DirectionalLight( color, intensity, distance );
  785. light.position.set(0, 0, 1);
  786. break;
  787. case 'point':
  788. light = new THREE.PointLight( color, intensity, distance );
  789. break;
  790. case 'spot':
  791. light = new THREE.SpotLight( color, intensity, distance, angle, exponent );
  792. light.position.set(0, 0, 1);
  793. break;
  794. case 'ambient':
  795. light = new THREE.AmbientLight( color );
  796. break;
  797. }
  798. }
  799. if (light) {
  800. obj.add(light);
  801. }
  802. }
  803. obj.name = node.name || node.id || "";
  804. obj.colladaId = node.id || "";
  805. obj.layer = node.layer || "";
  806. obj.matrix = node.matrix;
  807. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  808. if ( options.centerGeometry && obj.geometry ) {
  809. var delta = obj.geometry.center();
  810. delta.multiply( obj.scale );
  811. delta.applyQuaternion( obj.quaternion );
  812. obj.position.sub( delta );
  813. }
  814. for ( i = 0; i < node.nodes.length; i ++ ) {
  815. obj.add( createSceneGraph( node.nodes[i], node ) );
  816. }
  817. return obj;
  818. };
  819. function getJointId( skin, id ) {
  820. for ( var i = 0; i < skin.joints.length; i ++ ) {
  821. if ( skin.joints[ i ] === id ) {
  822. return i;
  823. }
  824. }
  825. };
  826. function getLibraryNode( id ) {
  827. var nodes = COLLADA.querySelectorAll('library_nodes node');
  828. <<<<<<< HEAD
  829. for ( var i = 0; i < nodes.length; i++ ) {
  830. var attObj = nodes[i].attributes.getNamedItem('id');
  831. if ( attObj && attObj.value === id ) {
  832. return nodes[i];
  833. }
  834. =======
  835. for ( var i = 0; i < nodes.length; i ++ ) {
  836. var attObj = nodes[i].attributes.getNamedItem('id');
  837. if ( attObj && attObj.value === id ) {
  838. return nodes[i];
  839. }
  840. >>>>>>> 4501d5a51d49e2e709930188a02af8d3dec5da61
  841. }
  842. return undefined;
  843. };
  844. function getChannelsForNode ( node ) {
  845. var channels = [];
  846. var startTime = 1000000;
  847. var endTime = -1000000;
  848. for ( var id in animations ) {
  849. var animation = animations[id];
  850. for ( var i = 0; i < animation.channel.length; i ++ ) {
  851. var channel = animation.channel[i];
  852. var sampler = animation.sampler[i];
  853. var id = channel.target.split('/')[0];
  854. if ( id == node.id ) {
  855. sampler.create();
  856. channel.sampler = sampler;
  857. startTime = Math.min(startTime, sampler.startTime);
  858. endTime = Math.max(endTime, sampler.endTime);
  859. channels.push(channel);
  860. }
  861. }
  862. }
  863. if ( channels.length ) {
  864. node.startTime = startTime;
  865. node.endTime = endTime;
  866. }
  867. return channels;
  868. };
  869. function calcFrameDuration( node ) {
  870. var minT = 10000000;
  871. for ( var i = 0; i < node.channels.length; i ++ ) {
  872. var sampler = node.channels[i].sampler;
  873. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  874. var t0 = sampler.input[ j ];
  875. var t1 = sampler.input[ j + 1 ];
  876. minT = Math.min( minT, t1 - t0 );
  877. }
  878. }
  879. return minT;
  880. };
  881. function calcMatrixAt( node, t ) {
  882. var animated = {};
  883. var i, j;
  884. for ( i = 0; i < node.channels.length; i ++ ) {
  885. var channel = node.channels[ i ];
  886. animated[ channel.sid ] = channel;
  887. }
  888. var matrix = new THREE.Matrix4();
  889. for ( i = 0; i < node.transforms.length; i ++ ) {
  890. var transform = node.transforms[ i ];
  891. var channel = animated[ transform.sid ];
  892. if ( channel !== undefined ) {
  893. var sampler = channel.sampler;
  894. var value;
  895. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  896. if ( sampler.input[ j + 1 ] > t ) {
  897. value = sampler.output[ j ];
  898. //console.log(value.flatten)
  899. break;
  900. }
  901. }
  902. if ( value !== undefined ) {
  903. if ( value instanceof THREE.Matrix4 ) {
  904. matrix.multiplyMatrices( matrix, value );
  905. } else {
  906. // FIXME: handle other types
  907. matrix.multiplyMatrices( matrix, transform.matrix );
  908. }
  909. } else {
  910. matrix.multiplyMatrices( matrix, transform.matrix );
  911. }
  912. } else {
  913. matrix.multiplyMatrices( matrix, transform.matrix );
  914. }
  915. }
  916. return matrix;
  917. };
  918. function bakeAnimations ( node ) {
  919. if ( node.channels && node.channels.length ) {
  920. var keys = [],
  921. sids = [];
  922. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  923. var channel = node.channels[i],
  924. fullSid = channel.fullSid,
  925. sampler = channel.sampler,
  926. input = sampler.input,
  927. transform = node.getTransformBySid( channel.sid ),
  928. member;
  929. if ( channel.arrIndices ) {
  930. member = [];
  931. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  932. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  933. }
  934. } else {
  935. member = getConvertedMember( channel.member );
  936. }
  937. if ( transform ) {
  938. if ( sids.indexOf( fullSid ) === -1 ) {
  939. sids.push( fullSid );
  940. }
  941. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  942. var time = input[j],
  943. data = sampler.getData( transform.type, j, member ),
  944. key = findKey( keys, time );
  945. if ( !key ) {
  946. key = new Key( time );
  947. var timeNdx = findTimeNdx( keys, time );
  948. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  949. }
  950. key.addTarget( fullSid, transform, member, data );
  951. }
  952. } else {
  953. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  954. }
  955. }
  956. // post process
  957. for ( var i = 0; i < sids.length; i ++ ) {
  958. var sid = sids[ i ];
  959. for ( var j = 0; j < keys.length; j ++ ) {
  960. var key = keys[ j ];
  961. if ( !key.hasTarget( sid ) ) {
  962. interpolateKeys( keys, key, j, sid );
  963. }
  964. }
  965. }
  966. node.keys = keys;
  967. node.sids = sids;
  968. }
  969. };
  970. function findKey ( keys, time) {
  971. var retVal = null;
  972. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  973. var key = keys[i];
  974. if ( key.time === time ) {
  975. retVal = key;
  976. } else if ( key.time > time ) {
  977. break;
  978. }
  979. }
  980. return retVal;
  981. };
  982. function findTimeNdx ( keys, time) {
  983. var ndx = -1;
  984. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  985. var key = keys[i];
  986. if ( key.time >= time ) {
  987. ndx = i;
  988. }
  989. }
  990. return ndx;
  991. };
  992. function interpolateKeys ( keys, key, ndx, fullSid ) {
  993. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  994. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  995. if ( prevKey && nextKey ) {
  996. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  997. prevTarget = prevKey.getTarget( fullSid ),
  998. nextData = nextKey.getTarget( fullSid ).data,
  999. prevData = prevTarget.data,
  1000. data;
  1001. if ( prevTarget.type === 'matrix' ) {
  1002. data = prevData;
  1003. } else if ( prevData.length ) {
  1004. data = [];
  1005. for ( var i = 0; i < prevData.length; ++ i ) {
  1006. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  1007. }
  1008. } else {
  1009. data = prevData + ( nextData - prevData ) * scale;
  1010. }
  1011. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  1012. }
  1013. };
  1014. // Get next key with given sid
  1015. function getNextKeyWith( keys, fullSid, ndx ) {
  1016. for ( ; ndx < keys.length; ndx ++ ) {
  1017. var key = keys[ ndx ];
  1018. if ( key.hasTarget( fullSid ) ) {
  1019. return key;
  1020. }
  1021. }
  1022. return null;
  1023. };
  1024. // Get previous key with given sid
  1025. function getPrevKeyWith( keys, fullSid, ndx ) {
  1026. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  1027. for ( ; ndx >= 0; ndx -- ) {
  1028. var key = keys[ ndx ];
  1029. if ( key.hasTarget( fullSid ) ) {
  1030. return key;
  1031. }
  1032. }
  1033. return null;
  1034. };
  1035. function _Image() {
  1036. this.id = "";
  1037. this.init_from = "";
  1038. };
  1039. _Image.prototype.parse = function(element) {
  1040. this.id = element.getAttribute('id');
  1041. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1042. var child = element.childNodes[ i ];
  1043. if ( child.nodeName === 'init_from' ) {
  1044. this.init_from = child.textContent;
  1045. }
  1046. }
  1047. return this;
  1048. };
  1049. function Controller() {
  1050. this.id = "";
  1051. this.name = "";
  1052. this.type = "";
  1053. this.skin = null;
  1054. this.morph = null;
  1055. };
  1056. Controller.prototype.parse = function( element ) {
  1057. this.id = element.getAttribute('id');
  1058. this.name = element.getAttribute('name');
  1059. this.type = "none";
  1060. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1061. var child = element.childNodes[ i ];
  1062. switch ( child.nodeName ) {
  1063. case 'skin':
  1064. this.skin = (new Skin()).parse(child);
  1065. this.type = child.nodeName;
  1066. break;
  1067. case 'morph':
  1068. this.morph = (new Morph()).parse(child);
  1069. this.type = child.nodeName;
  1070. break;
  1071. default:
  1072. break;
  1073. }
  1074. }
  1075. return this;
  1076. };
  1077. function Morph() {
  1078. this.method = null;
  1079. this.source = null;
  1080. this.targets = null;
  1081. this.weights = null;
  1082. };
  1083. Morph.prototype.parse = function( element ) {
  1084. var sources = {};
  1085. var inputs = [];
  1086. var i;
  1087. this.method = element.getAttribute( 'method' );
  1088. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1089. for ( i = 0; i < element.childNodes.length; i ++ ) {
  1090. var child = element.childNodes[ i ];
  1091. if ( child.nodeType != 1 ) continue;
  1092. switch ( child.nodeName ) {
  1093. case 'source':
  1094. var source = ( new Source() ).parse( child );
  1095. sources[ source.id ] = source;
  1096. break;
  1097. case 'targets':
  1098. inputs = this.parseInputs( child );
  1099. break;
  1100. default:
  1101. console.log( child.nodeName );
  1102. break;
  1103. }
  1104. }
  1105. for ( i = 0; i < inputs.length; i ++ ) {
  1106. var input = inputs[ i ];
  1107. var source = sources[ input.source ];
  1108. switch ( input.semantic ) {
  1109. case 'MORPH_TARGET':
  1110. this.targets = source.read();
  1111. break;
  1112. case 'MORPH_WEIGHT':
  1113. this.weights = source.read();
  1114. break;
  1115. default:
  1116. break;
  1117. }
  1118. }
  1119. return this;
  1120. };
  1121. Morph.prototype.parseInputs = function(element) {
  1122. var inputs = [];
  1123. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1124. var child = element.childNodes[i];
  1125. if ( child.nodeType != 1) continue;
  1126. switch ( child.nodeName ) {
  1127. case 'input':
  1128. inputs.push( (new Input()).parse(child) );
  1129. break;
  1130. default:
  1131. break;
  1132. }
  1133. }
  1134. return inputs;
  1135. };
  1136. function Skin() {
  1137. this.source = "";
  1138. this.bindShapeMatrix = null;
  1139. this.invBindMatrices = [];
  1140. this.joints = [];
  1141. this.weights = [];
  1142. };
  1143. Skin.prototype.parse = function( element ) {
  1144. var sources = {};
  1145. var joints, weights;
  1146. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1147. this.invBindMatrices = [];
  1148. this.joints = [];
  1149. this.weights = [];
  1150. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1151. var child = element.childNodes[i];
  1152. if ( child.nodeType != 1 ) continue;
  1153. switch ( child.nodeName ) {
  1154. case 'bind_shape_matrix':
  1155. var f = _floats(child.textContent);
  1156. this.bindShapeMatrix = getConvertedMat4( f );
  1157. break;
  1158. case 'source':
  1159. var src = new Source().parse(child);
  1160. sources[ src.id ] = src;
  1161. break;
  1162. case 'joints':
  1163. joints = child;
  1164. break;
  1165. case 'vertex_weights':
  1166. weights = child;
  1167. break;
  1168. default:
  1169. console.log( child.nodeName );
  1170. break;
  1171. }
  1172. }
  1173. this.parseJoints( joints, sources );
  1174. this.parseWeights( weights, sources );
  1175. return this;
  1176. };
  1177. Skin.prototype.parseJoints = function ( element, sources ) {
  1178. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1179. var child = element.childNodes[ i ];
  1180. if ( child.nodeType != 1 ) continue;
  1181. switch ( child.nodeName ) {
  1182. case 'input':
  1183. var input = ( new Input() ).parse( child );
  1184. var source = sources[ input.source ];
  1185. if ( input.semantic === 'JOINT' ) {
  1186. this.joints = source.read();
  1187. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  1188. this.invBindMatrices = source.read();
  1189. }
  1190. break;
  1191. default:
  1192. break;
  1193. }
  1194. }
  1195. };
  1196. Skin.prototype.parseWeights = function ( element, sources ) {
  1197. var v, vcount, inputs = [];
  1198. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1199. var child = element.childNodes[ i ];
  1200. if ( child.nodeType != 1 ) continue;
  1201. switch ( child.nodeName ) {
  1202. case 'input':
  1203. inputs.push( ( new Input() ).parse( child ) );
  1204. break;
  1205. case 'v':
  1206. v = _ints( child.textContent );
  1207. break;
  1208. case 'vcount':
  1209. vcount = _ints( child.textContent );
  1210. break;
  1211. default:
  1212. break;
  1213. }
  1214. }
  1215. var index = 0;
  1216. for ( var i = 0; i < vcount.length; i ++ ) {
  1217. var numBones = vcount[i];
  1218. var vertex_weights = [];
  1219. for ( var j = 0; j < numBones; j ++ ) {
  1220. var influence = {};
  1221. for ( var k = 0; k < inputs.length; k ++ ) {
  1222. var input = inputs[ k ];
  1223. var value = v[ index + input.offset ];
  1224. switch ( input.semantic ) {
  1225. case 'JOINT':
  1226. influence.joint = value;//this.joints[value];
  1227. break;
  1228. case 'WEIGHT':
  1229. influence.weight = sources[ input.source ].data[ value ];
  1230. break;
  1231. default:
  1232. break;
  1233. }
  1234. }
  1235. vertex_weights.push( influence );
  1236. index += inputs.length;
  1237. }
  1238. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  1239. vertex_weights[ j ].index = i;
  1240. }
  1241. this.weights.push( vertex_weights );
  1242. }
  1243. };
  1244. function VisualScene () {
  1245. this.id = "";
  1246. this.name = "";
  1247. this.nodes = [];
  1248. this.scene = new THREE.Group();
  1249. };
  1250. VisualScene.prototype.getChildById = function( id, recursive ) {
  1251. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1252. var node = this.nodes[ i ].getChildById( id, recursive );
  1253. if ( node ) {
  1254. return node;
  1255. }
  1256. }
  1257. return null;
  1258. };
  1259. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  1260. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1261. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  1262. if ( node ) {
  1263. return node;
  1264. }
  1265. }
  1266. return null;
  1267. };
  1268. VisualScene.prototype.parse = function( element ) {
  1269. this.id = element.getAttribute( 'id' );
  1270. this.name = element.getAttribute( 'name' );
  1271. this.nodes = [];
  1272. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1273. var child = element.childNodes[ i ];
  1274. if ( child.nodeType != 1 ) continue;
  1275. switch ( child.nodeName ) {
  1276. case 'node':
  1277. this.nodes.push( ( new Node() ).parse( child ) );
  1278. break;
  1279. default:
  1280. break;
  1281. }
  1282. }
  1283. return this;
  1284. };
  1285. function Node() {
  1286. this.id = "";
  1287. this.name = "";
  1288. this.sid = "";
  1289. this.nodes = [];
  1290. this.controllers = [];
  1291. this.transforms = [];
  1292. this.geometries = [];
  1293. this.channels = [];
  1294. this.matrix = new THREE.Matrix4();
  1295. };
  1296. Node.prototype.getChannelForTransform = function( transformSid ) {
  1297. for ( var i = 0; i < this.channels.length; i ++ ) {
  1298. var channel = this.channels[i];
  1299. var parts = channel.target.split('/');
  1300. var id = parts.shift();
  1301. var sid = parts.shift();
  1302. var dotSyntax = (sid.indexOf(".") >= 0);
  1303. var arrSyntax = (sid.indexOf("(") >= 0);
  1304. var arrIndices;
  1305. var member;
  1306. if ( dotSyntax ) {
  1307. parts = sid.split(".");
  1308. sid = parts.shift();
  1309. member = parts.shift();
  1310. } else if ( arrSyntax ) {
  1311. arrIndices = sid.split("(");
  1312. sid = arrIndices.shift();
  1313. for ( var j = 0; j < arrIndices.length; j ++ ) {
  1314. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  1315. }
  1316. }
  1317. if ( sid === transformSid ) {
  1318. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  1319. return channel;
  1320. }
  1321. }
  1322. return null;
  1323. };
  1324. Node.prototype.getChildById = function ( id, recursive ) {
  1325. if ( this.id === id ) {
  1326. return this;
  1327. }
  1328. if ( recursive ) {
  1329. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1330. var n = this.nodes[ i ].getChildById( id, recursive );
  1331. if ( n ) {
  1332. return n;
  1333. }
  1334. }
  1335. }
  1336. return null;
  1337. };
  1338. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1339. if ( this.sid === sid ) {
  1340. return this;
  1341. }
  1342. if ( recursive ) {
  1343. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1344. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1345. if ( n ) {
  1346. return n;
  1347. }
  1348. }
  1349. }
  1350. return null;
  1351. };
  1352. Node.prototype.getTransformBySid = function ( sid ) {
  1353. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1354. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  1355. }
  1356. return null;
  1357. };
  1358. Node.prototype.parse = function( element ) {
  1359. var url;
  1360. this.id = element.getAttribute('id');
  1361. this.sid = element.getAttribute('sid');
  1362. this.name = element.getAttribute('name');
  1363. this.type = element.getAttribute('type');
  1364. this.layer = element.getAttribute('layer');
  1365. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  1366. this.nodes = [];
  1367. this.transforms = [];
  1368. this.geometries = [];
  1369. this.cameras = [];
  1370. this.lights = [];
  1371. this.controllers = [];
  1372. this.matrix = new THREE.Matrix4();
  1373. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1374. var child = element.childNodes[ i ];
  1375. if ( child.nodeType != 1 ) continue;
  1376. switch ( child.nodeName ) {
  1377. case 'node':
  1378. this.nodes.push( ( new Node() ).parse( child ) );
  1379. break;
  1380. case 'instance_camera':
  1381. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1382. break;
  1383. case 'instance_controller':
  1384. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1385. break;
  1386. case 'instance_geometry':
  1387. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1388. break;
  1389. case 'instance_light':
  1390. this.lights.push( ( new InstanceLight() ).parse( child ) );
  1391. break;
  1392. case 'instance_node':
  1393. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1394. var iNode = getLibraryNode( url );
  1395. if ( iNode ) {
  1396. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1397. }
  1398. break;
  1399. case 'rotate':
  1400. case 'translate':
  1401. case 'scale':
  1402. case 'matrix':
  1403. case 'lookat':
  1404. case 'skew':
  1405. this.transforms.push( ( new Transform() ).parse( child ) );
  1406. break;
  1407. case 'extra':
  1408. break;
  1409. default:
  1410. console.log( child.nodeName );
  1411. break;
  1412. }
  1413. }
  1414. this.channels = getChannelsForNode( this );
  1415. bakeAnimations( this );
  1416. this.updateMatrix();
  1417. return this;
  1418. };
  1419. Node.prototype.updateMatrix = function () {
  1420. this.matrix.identity();
  1421. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1422. this.transforms[ i ].apply( this.matrix );
  1423. }
  1424. };
  1425. function Transform () {
  1426. this.sid = "";
  1427. this.type = "";
  1428. this.data = [];
  1429. this.obj = null;
  1430. };
  1431. Transform.prototype.parse = function ( element ) {
  1432. this.sid = element.getAttribute( 'sid' );
  1433. this.type = element.nodeName;
  1434. this.data = _floats( element.textContent );
  1435. this.convert();
  1436. return this;
  1437. };
  1438. Transform.prototype.convert = function () {
  1439. switch ( this.type ) {
  1440. case 'matrix':
  1441. this.obj = getConvertedMat4( this.data );
  1442. break;
  1443. case 'rotate':
  1444. this.angle = THREE.Math.degToRad( this.data[3] );
  1445. case 'translate':
  1446. fixCoords( this.data, -1 );
  1447. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1448. break;
  1449. case 'scale':
  1450. fixCoords( this.data, 1 );
  1451. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1452. break;
  1453. default:
  1454. console.log( 'Can not convert Transform of type ' + this.type );
  1455. break;
  1456. }
  1457. };
  1458. Transform.prototype.apply = function () {
  1459. var m1 = new THREE.Matrix4();
  1460. return function ( matrix ) {
  1461. switch ( this.type ) {
  1462. case 'matrix':
  1463. matrix.multiply( this.obj );
  1464. break;
  1465. case 'translate':
  1466. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  1467. break;
  1468. case 'rotate':
  1469. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  1470. break;
  1471. case 'scale':
  1472. matrix.scale( this.obj );
  1473. break;
  1474. }
  1475. };
  1476. }();
  1477. Transform.prototype.update = function ( data, member ) {
  1478. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1479. switch ( this.type ) {
  1480. case 'matrix':
  1481. if ( ! member ) {
  1482. this.obj.copy( data );
  1483. } else if ( member.length === 1 ) {
  1484. switch ( member[ 0 ] ) {
  1485. case 0:
  1486. this.obj.n11 = data[ 0 ];
  1487. this.obj.n21 = data[ 1 ];
  1488. this.obj.n31 = data[ 2 ];
  1489. this.obj.n41 = data[ 3 ];
  1490. break;
  1491. case 1:
  1492. this.obj.n12 = data[ 0 ];
  1493. this.obj.n22 = data[ 1 ];
  1494. this.obj.n32 = data[ 2 ];
  1495. this.obj.n42 = data[ 3 ];
  1496. break;
  1497. case 2:
  1498. this.obj.n13 = data[ 0 ];
  1499. this.obj.n23 = data[ 1 ];
  1500. this.obj.n33 = data[ 2 ];
  1501. this.obj.n43 = data[ 3 ];
  1502. break;
  1503. case 3:
  1504. this.obj.n14 = data[ 0 ];
  1505. this.obj.n24 = data[ 1 ];
  1506. this.obj.n34 = data[ 2 ];
  1507. this.obj.n44 = data[ 3 ];
  1508. break;
  1509. }
  1510. } else if ( member.length === 2 ) {
  1511. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1512. this.obj[ propName ] = data;
  1513. } else {
  1514. console.log('Incorrect addressing of matrix in transform.');
  1515. }
  1516. break;
  1517. case 'translate':
  1518. case 'scale':
  1519. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1520. member = members[ member[ 0 ] ];
  1521. }
  1522. switch ( member ) {
  1523. case 'X':
  1524. this.obj.x = data;
  1525. break;
  1526. case 'Y':
  1527. this.obj.y = data;
  1528. break;
  1529. case 'Z':
  1530. this.obj.z = data;
  1531. break;
  1532. default:
  1533. this.obj.x = data[ 0 ];
  1534. this.obj.y = data[ 1 ];
  1535. this.obj.z = data[ 2 ];
  1536. break;
  1537. }
  1538. break;
  1539. case 'rotate':
  1540. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1541. member = members[ member[ 0 ] ];
  1542. }
  1543. switch ( member ) {
  1544. case 'X':
  1545. this.obj.x = data;
  1546. break;
  1547. case 'Y':
  1548. this.obj.y = data;
  1549. break;
  1550. case 'Z':
  1551. this.obj.z = data;
  1552. break;
  1553. case 'ANGLE':
  1554. this.angle = THREE.Math.degToRad( data );
  1555. break;
  1556. default:
  1557. this.obj.x = data[ 0 ];
  1558. this.obj.y = data[ 1 ];
  1559. this.obj.z = data[ 2 ];
  1560. this.angle = THREE.Math.degToRad( data[ 3 ] );
  1561. break;
  1562. }
  1563. break;
  1564. }
  1565. };
  1566. function InstanceController() {
  1567. this.url = "";
  1568. this.skeleton = [];
  1569. this.instance_material = [];
  1570. };
  1571. InstanceController.prototype.parse = function ( element ) {
  1572. this.url = element.getAttribute('url').replace(/^#/, '');
  1573. this.skeleton = [];
  1574. this.instance_material = [];
  1575. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1576. var child = element.childNodes[ i ];
  1577. if ( child.nodeType !== 1 ) continue;
  1578. switch ( child.nodeName ) {
  1579. case 'skeleton':
  1580. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1581. break;
  1582. case 'bind_material':
  1583. var instances = child.querySelectorAll('instance_material');
  1584. for ( var j = 0; j < instances.length; j ++ ) {
  1585. var instance = instances[j];
  1586. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1587. }
  1588. break;
  1589. case 'extra':
  1590. break;
  1591. default:
  1592. break;
  1593. }
  1594. }
  1595. return this;
  1596. };
  1597. function InstanceMaterial () {
  1598. this.symbol = "";
  1599. this.target = "";
  1600. };
  1601. InstanceMaterial.prototype.parse = function ( element ) {
  1602. this.symbol = element.getAttribute('symbol');
  1603. this.target = element.getAttribute('target').replace(/^#/, '');
  1604. return this;
  1605. };
  1606. function InstanceGeometry() {
  1607. this.url = "";
  1608. this.instance_material = [];
  1609. };
  1610. InstanceGeometry.prototype.parse = function ( element ) {
  1611. this.url = element.getAttribute('url').replace(/^#/, '');
  1612. this.instance_material = [];
  1613. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1614. var child = element.childNodes[i];
  1615. if ( child.nodeType != 1 ) continue;
  1616. if ( child.nodeName === 'bind_material' ) {
  1617. var instances = child.querySelectorAll('instance_material');
  1618. for ( var j = 0; j < instances.length; j ++ ) {
  1619. var instance = instances[j];
  1620. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1621. }
  1622. break;
  1623. }
  1624. }
  1625. return this;
  1626. };
  1627. function Geometry() {
  1628. this.id = "";
  1629. this.mesh = null;
  1630. };
  1631. Geometry.prototype.parse = function ( element ) {
  1632. this.id = element.getAttribute('id');
  1633. extractDoubleSided( this, element );
  1634. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1635. var child = element.childNodes[i];
  1636. switch ( child.nodeName ) {
  1637. case 'mesh':
  1638. this.mesh = (new Mesh(this)).parse(child);
  1639. break;
  1640. case 'extra':
  1641. // console.log( child );
  1642. break;
  1643. default:
  1644. break;
  1645. }
  1646. }
  1647. return this;
  1648. };
  1649. function Mesh( geometry ) {
  1650. this.geometry = geometry.id;
  1651. this.primitives = [];
  1652. this.vertices = null;
  1653. this.geometry3js = null;
  1654. };
  1655. Mesh.prototype.parse = function ( element ) {
  1656. this.primitives = [];
  1657. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1658. var child = element.childNodes[ i ];
  1659. switch ( child.nodeName ) {
  1660. case 'source':
  1661. _source( child );
  1662. break;
  1663. case 'vertices':
  1664. this.vertices = ( new Vertices() ).parse( child );
  1665. break;
  1666. case 'linestrips':
  1667. this.primitives.push( ( new LineStrips().parse( child ) ) );
  1668. break;
  1669. case 'triangles':
  1670. this.primitives.push( ( new Triangles().parse( child ) ) );
  1671. break;
  1672. case 'polygons':
  1673. this.primitives.push( ( new Polygons().parse( child ) ) );
  1674. break;
  1675. case 'polylist':
  1676. this.primitives.push( ( new Polylist().parse( child ) ) );
  1677. break;
  1678. default:
  1679. break;
  1680. }
  1681. }
  1682. this.geometry3js = new THREE.Geometry();
  1683. if ( this.vertices === null ) {
  1684. // TODO (mrdoob): Study case when this is null (carrier.dae)
  1685. return this;
  1686. }
  1687. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1688. for ( var i = 0; i < vertexData.length; i += 3 ) {
  1689. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1690. }
  1691. for ( var i = 0; i < this.primitives.length; i ++ ) {
  1692. var primitive = this.primitives[ i ];
  1693. primitive.setVertices( this.vertices );
  1694. this.handlePrimitive( primitive, this.geometry3js );
  1695. }
  1696. if ( this.geometry3js.calcNormals ) {
  1697. this.geometry3js.computeVertexNormals();
  1698. delete this.geometry3js.calcNormals;
  1699. }
  1700. return this;
  1701. };
  1702. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  1703. if ( primitive instanceof LineStrips ) {
  1704. // TODO: Handle indices. Maybe easier with BufferGeometry?
  1705. geom.isLineStrip = true;
  1706. return;
  1707. }
  1708. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1709. var input, index, idx32;
  1710. var source, numParams;
  1711. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1712. var texture_sets = [];
  1713. for ( j = 0; j < inputs.length; j ++ ) {
  1714. input = inputs[ j ];
  1715. var offset = input.offset + 1;
  1716. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  1717. switch ( input.semantic ) {
  1718. case 'TEXCOORD':
  1719. texture_sets.push( input.set );
  1720. break;
  1721. }
  1722. }
  1723. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  1724. var p = pList[ pCount ], i = 0;
  1725. while ( i < p.length ) {
  1726. var vs = [];
  1727. var ns = [];
  1728. var ts = null;
  1729. var cs = [];
  1730. if ( primitive.vcount ) {
  1731. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1732. } else {
  1733. vcount = p.length / maxOffset;
  1734. }
  1735. for ( j = 0; j < vcount; j ++ ) {
  1736. for ( k = 0; k < inputs.length; k ++ ) {
  1737. input = inputs[ k ];
  1738. source = sources[ input.source ];
  1739. index = p[ i + ( j * maxOffset ) + input.offset ];
  1740. numParams = source.accessor.params.length;
  1741. idx32 = index * numParams;
  1742. switch ( input.semantic ) {
  1743. case 'VERTEX':
  1744. vs.push( index );
  1745. break;
  1746. case 'NORMAL':
  1747. ns.push( getConvertedVec3( source.data, idx32 ) );
  1748. break;
  1749. case 'TEXCOORD':
  1750. ts = ts || { };
  1751. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1752. // invert the V
  1753. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1754. break;
  1755. case 'COLOR':
  1756. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1757. break;
  1758. default:
  1759. break;
  1760. }
  1761. }
  1762. }
  1763. if ( ns.length === 0 ) {
  1764. // check the vertices inputs
  1765. input = this.vertices.input.NORMAL;
  1766. if ( input ) {
  1767. source = sources[ input.source ];
  1768. numParams = source.accessor.params.length;
  1769. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1770. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1771. }
  1772. } else {
  1773. geom.calcNormals = true;
  1774. }
  1775. }
  1776. if ( !ts ) {
  1777. ts = { };
  1778. // check the vertices inputs
  1779. input = this.vertices.input.TEXCOORD;
  1780. if ( input ) {
  1781. texture_sets.push( input.set );
  1782. source = sources[ input.source ];
  1783. numParams = source.accessor.params.length;
  1784. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1785. idx32 = vs[ ndx ] * numParams;
  1786. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1787. // invert the V
  1788. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1789. }
  1790. }
  1791. }
  1792. if ( cs.length === 0 ) {
  1793. // check the vertices inputs
  1794. input = this.vertices.input.COLOR;
  1795. if ( input ) {
  1796. source = sources[ input.source ];
  1797. numParams = source.accessor.params.length;
  1798. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1799. idx32 = vs[ ndx ] * numParams;
  1800. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1801. }
  1802. }
  1803. }
  1804. var face = null, faces = [], uv, uvArr;
  1805. if ( vcount === 3 ) {
  1806. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1807. } else if ( vcount === 4 ) {
  1808. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], [ ns[0], ns[1], ns[3]], cs.length ? [ cs[0], cs[1], cs[3]] : new THREE.Color() ) );
  1809. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], [ ns[1], ns[2], ns[3]], cs.length ? [ cs[1], cs[2], cs[3]] : new THREE.Color() ) );
  1810. } else if ( vcount > 4 && options.subdivideFaces ) {
  1811. var clr = cs.length ? cs : new THREE.Color(),
  1812. vec1, vec2, vec3, v1, v2, norm;
  1813. // subdivide into multiple Face3s
  1814. for ( k = 1; k < vcount - 1; ) {
  1815. // FIXME: normals don't seem to be quite right
  1816. <<<<<<< HEAD
  1817. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  1818. =======
  1819. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], [ ns[0], ns[k ++], ns[k] ], clr ) );
  1820. >>>>>>> 4501d5a51d49e2e709930188a02af8d3dec5da61
  1821. }
  1822. }
  1823. if ( faces.length ) {
  1824. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  1825. face = faces[ndx];
  1826. face.daeMaterial = primitive.material;
  1827. geom.faces.push( face );
  1828. for ( k = 0; k < texture_sets.length; k ++ ) {
  1829. uv = ts[ texture_sets[k] ];
  1830. if ( vcount > 4 ) {
  1831. // Grab the right UVs for the vertices in this face
  1832. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  1833. } else if ( vcount === 4 ) {
  1834. if ( ndx === 0 ) {
  1835. uvArr = [ uv[0], uv[1], uv[3] ];
  1836. } else {
  1837. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  1838. }
  1839. } else {
  1840. uvArr = [ uv[0], uv[1], uv[2] ];
  1841. }
  1842. if ( geom.faceVertexUvs[k] === undefined ) {
  1843. geom.faceVertexUvs[k] = [];
  1844. }
  1845. geom.faceVertexUvs[k].push( uvArr );
  1846. }
  1847. }
  1848. } else {
  1849. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1850. }
  1851. i += maxOffset * vcount;
  1852. }
  1853. }
  1854. };
  1855. function Polygons () {
  1856. this.material = "";
  1857. this.count = 0;
  1858. this.inputs = [];
  1859. this.vcount = null;
  1860. this.p = [];
  1861. this.geometry = new THREE.Geometry();
  1862. };
  1863. Polygons.prototype.setVertices = function ( vertices ) {
  1864. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1865. if ( this.inputs[ i ].source === vertices.id ) {
  1866. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1867. }
  1868. }
  1869. };
  1870. Polygons.prototype.parse = function ( element ) {
  1871. this.material = element.getAttribute( 'material' );
  1872. this.count = _attr_as_int( element, 'count', 0 );
  1873. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1874. var child = element.childNodes[ i ];
  1875. switch ( child.nodeName ) {
  1876. case 'input':
  1877. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1878. break;
  1879. case 'vcount':
  1880. this.vcount = _ints( child.textContent );
  1881. break;
  1882. case 'p':
  1883. this.p.push( _ints( child.textContent ) );
  1884. break;
  1885. case 'ph':
  1886. console.warn( 'polygon holes not yet supported!' );
  1887. break;
  1888. default:
  1889. break;
  1890. }
  1891. }
  1892. return this;
  1893. };
  1894. function Polylist () {
  1895. Polygons.call( this );
  1896. this.vcount = [];
  1897. };
  1898. Polylist.prototype = Object.create( Polygons.prototype );
  1899. Polylist.prototype.constructor = Polylist;
  1900. function LineStrips() {
  1901. Polygons.call( this );
  1902. this.vcount = 1;
  1903. };
  1904. LineStrips.prototype = Object.create( Polygons.prototype );
  1905. LineStrips.prototype.constructor = LineStrips;
  1906. function Triangles () {
  1907. Polygons.call( this );
  1908. this.vcount = 3;
  1909. };
  1910. Triangles.prototype = Object.create( Polygons.prototype );
  1911. Triangles.prototype.constructor = Triangles;
  1912. function Accessor() {
  1913. this.source = "";
  1914. this.count = 0;
  1915. this.stride = 0;
  1916. this.params = [];
  1917. };
  1918. Accessor.prototype.parse = function ( element ) {
  1919. this.params = [];
  1920. this.source = element.getAttribute( 'source' );
  1921. this.count = _attr_as_int( element, 'count', 0 );
  1922. this.stride = _attr_as_int( element, 'stride', 0 );
  1923. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1924. var child = element.childNodes[ i ];
  1925. if ( child.nodeName === 'param' ) {
  1926. var param = {};
  1927. param[ 'name' ] = child.getAttribute( 'name' );
  1928. param[ 'type' ] = child.getAttribute( 'type' );
  1929. this.params.push( param );
  1930. }
  1931. }
  1932. return this;
  1933. };
  1934. function Vertices() {
  1935. this.input = {};
  1936. };
  1937. Vertices.prototype.parse = function ( element ) {
  1938. this.id = element.getAttribute('id');
  1939. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1940. if ( element.childNodes[i].nodeName === 'input' ) {
  1941. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1942. this.input[ input.semantic ] = input;
  1943. }
  1944. }
  1945. return this;
  1946. };
  1947. function Input () {
  1948. this.semantic = "";
  1949. this.offset = 0;
  1950. this.source = "";
  1951. this.set = 0;
  1952. };
  1953. Input.prototype.parse = function ( element ) {
  1954. this.semantic = element.getAttribute('semantic');
  1955. this.source = element.getAttribute('source').replace(/^#/, '');
  1956. this.set = _attr_as_int(element, 'set', -1);
  1957. this.offset = _attr_as_int(element, 'offset', 0);
  1958. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  1959. this.set = 0;
  1960. }
  1961. return this;
  1962. };
  1963. function Source ( id ) {
  1964. this.id = id;
  1965. this.type = null;
  1966. };
  1967. Source.prototype.parse = function ( element ) {
  1968. this.id = element.getAttribute( 'id' );
  1969. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1970. var child = element.childNodes[i];
  1971. switch ( child.nodeName ) {
  1972. case 'bool_array':
  1973. this.data = _bools( child.textContent );
  1974. this.type = child.nodeName;
  1975. break;
  1976. case 'float_array':
  1977. this.data = _floats( child.textContent );
  1978. this.type = child.nodeName;
  1979. break;
  1980. case 'int_array':
  1981. this.data = _ints( child.textContent );
  1982. this.type = child.nodeName;
  1983. break;
  1984. case 'IDREF_array':
  1985. case 'Name_array':
  1986. this.data = _strings( child.textContent );
  1987. this.type = child.nodeName;
  1988. break;
  1989. case 'technique_common':
  1990. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1991. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  1992. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1993. break;
  1994. }
  1995. }
  1996. break;
  1997. default:
  1998. // console.log(child.nodeName);
  1999. break;
  2000. }
  2001. }
  2002. return this;
  2003. };
  2004. Source.prototype.read = function () {
  2005. var result = [];
  2006. //for (var i = 0; i < this.accessor.params.length; i++) {
  2007. var param = this.accessor.params[ 0 ];
  2008. //console.log(param.name + " " + param.type);
  2009. switch ( param.type ) {
  2010. case 'IDREF':
  2011. case 'Name': case 'name':
  2012. case 'float':
  2013. return this.data;
  2014. case 'float4x4':
  2015. for ( var j = 0; j < this.data.length; j += 16 ) {
  2016. var s = this.data.slice( j, j + 16 );
  2017. var m = getConvertedMat4( s );
  2018. result.push( m );
  2019. }
  2020. break;
  2021. default:
  2022. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  2023. break;
  2024. }
  2025. //}
  2026. return result;
  2027. };
  2028. function Material () {
  2029. this.id = "";
  2030. this.name = "";
  2031. this.instance_effect = null;
  2032. };
  2033. Material.prototype.parse = function ( element ) {
  2034. this.id = element.getAttribute( 'id' );
  2035. this.name = element.getAttribute( 'name' );
  2036. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2037. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  2038. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  2039. break;
  2040. }
  2041. }
  2042. return this;
  2043. };
  2044. function ColorOrTexture () {
  2045. this.color = new THREE.Color();
  2046. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  2047. this.color.a = 1.0;
  2048. this.texture = null;
  2049. this.texcoord = null;
  2050. this.texOpts = null;
  2051. };
  2052. ColorOrTexture.prototype.isColor = function () {
  2053. return ( this.texture === null );
  2054. };
  2055. ColorOrTexture.prototype.isTexture = function () {
  2056. return ( this.texture != null );
  2057. };
  2058. ColorOrTexture.prototype.parse = function ( element ) {
  2059. if (element.nodeName === 'transparent') {
  2060. this.opaque = element.getAttribute('opaque');
  2061. }
  2062. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2063. var child = element.childNodes[ i ];
  2064. if ( child.nodeType != 1 ) continue;
  2065. switch ( child.nodeName ) {
  2066. case 'color':
  2067. var rgba = _floats( child.textContent );
  2068. this.color = new THREE.Color();
  2069. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2070. this.color.a = rgba[3];
  2071. break;
  2072. case 'texture':
  2073. this.texture = child.getAttribute('texture');
  2074. this.texcoord = child.getAttribute('texcoord');
  2075. // Defaults from:
  2076. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  2077. this.texOpts = {
  2078. offsetU: 0,
  2079. offsetV: 0,
  2080. repeatU: 1,
  2081. repeatV: 1,
  2082. wrapU: 1,
  2083. wrapV: 1
  2084. };
  2085. this.parseTexture( child );
  2086. break;
  2087. default:
  2088. break;
  2089. }
  2090. }
  2091. return this;
  2092. };
  2093. ColorOrTexture.prototype.parseTexture = function ( element ) {
  2094. if ( ! element.childNodes ) return this;
  2095. // This should be supported by Maya, 3dsMax, and MotionBuilder
  2096. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  2097. element = element.childNodes[1];
  2098. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  2099. element = element.childNodes[1];
  2100. }
  2101. }
  2102. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2103. var child = element.childNodes[ i ];
  2104. switch ( child.nodeName ) {
  2105. case 'offsetU':
  2106. case 'offsetV':
  2107. case 'repeatU':
  2108. case 'repeatV':
  2109. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  2110. break;
  2111. case 'wrapU':
  2112. case 'wrapV':
  2113. // some dae have a value of true which becomes NaN via parseInt
  2114. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  2115. this.texOpts[ child.nodeName ] = 1;
  2116. } else {
  2117. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  2118. }
  2119. break;
  2120. default:
  2121. this.texOpts[ child.nodeName ] = child.textContent;
  2122. break;
  2123. }
  2124. }
  2125. return this;
  2126. };
  2127. function Shader ( type, effect ) {
  2128. this.type = type;
  2129. this.effect = effect;
  2130. this.material = null;
  2131. };
  2132. Shader.prototype.parse = function ( element ) {
  2133. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2134. var child = element.childNodes[ i ];
  2135. if ( child.nodeType != 1 ) continue;
  2136. switch ( child.nodeName ) {
  2137. case 'emission':
  2138. case 'diffuse':
  2139. case 'specular':
  2140. case 'transparent':
  2141. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  2142. break;
  2143. case 'bump':
  2144. // If 'bumptype' is 'heightfield', create a 'bump' property
  2145. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  2146. // (Default to 'bump')
  2147. var bumpType = child.getAttribute( 'bumptype' );
  2148. if ( bumpType ) {
  2149. if ( bumpType.toLowerCase() === "heightfield" ) {
  2150. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2151. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  2152. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  2153. } else {
  2154. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  2155. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2156. }
  2157. } else {
  2158. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  2159. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2160. }
  2161. break;
  2162. case 'shininess':
  2163. case 'reflectivity':
  2164. case 'index_of_refraction':
  2165. case 'transparency':
  2166. var f = child.querySelectorAll('float');
  2167. if ( f.length > 0 )
  2168. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  2169. break;
  2170. default:
  2171. break;
  2172. }
  2173. }
  2174. this.create();
  2175. return this;
  2176. };
  2177. Shader.prototype.create = function() {
  2178. var props = {};
  2179. var transparent = false;
  2180. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  2181. // convert transparent color RBG to average value
  2182. var transparentColor = this['transparent'];
  2183. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  2184. if (transparencyLevel > 0) {
  2185. transparent = true;
  2186. props[ 'transparent' ] = true;
  2187. props[ 'opacity' ] = 1 - transparencyLevel;
  2188. }
  2189. }
  2190. var keys = {
  2191. 'diffuse':'map',
  2192. 'ambient':'lightMap',
  2193. 'specular':'specularMap',
  2194. 'emission':'emissionMap',
  2195. 'bump':'bumpMap',
  2196. 'normal':'normalMap'
  2197. };
  2198. for ( var prop in this ) {
  2199. switch ( prop ) {
  2200. case 'ambient':
  2201. case 'emission':
  2202. case 'diffuse':
  2203. case 'specular':
  2204. case 'bump':
  2205. case 'normal':
  2206. var cot = this[ prop ];
  2207. if ( cot instanceof ColorOrTexture ) {
  2208. if ( cot.isTexture() ) {
  2209. var samplerId = cot.texture;
  2210. var surfaceId = this.effect.sampler[samplerId];
  2211. if ( surfaceId !== undefined && surfaceId.source !== undefined ) {
  2212. var surface = this.effect.surface[surfaceId.source];
  2213. if ( surface !== undefined ) {
  2214. var image = images[ surface.init_from ];
  2215. if ( image ) {
  2216. var url = baseUrl + image.init_from;
  2217. var texture;
  2218. var loader = THREE.Loader.Handlers.get( url );
  2219. if ( loader !== null ) {
  2220. texture = loader.load( url );
  2221. } else {
  2222. texture = new THREE.Texture();
  2223. loadTextureImage( texture, url );
  2224. }
  2225. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2226. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2227. texture.offset.x = cot.texOpts.offsetU;
  2228. texture.offset.y = cot.texOpts.offsetV;
  2229. texture.repeat.x = cot.texOpts.repeatU;
  2230. texture.repeat.y = cot.texOpts.repeatV;
  2231. props[keys[prop]] = texture;
  2232. // Texture with baked lighting?
  2233. if (prop === 'emission') props['emissive'] = 0xffffff;
  2234. }
  2235. }
  2236. }
  2237. } else if ( prop === 'diffuse' || !transparent ) {
  2238. if ( prop === 'emission' ) {
  2239. props[ 'emissive' ] = cot.color.getHex();
  2240. } else {
  2241. props[ prop ] = cot.color.getHex();
  2242. }
  2243. }
  2244. }
  2245. break;
  2246. case 'shininess':
  2247. props[ prop ] = this[ prop ];
  2248. break;
  2249. case 'reflectivity':
  2250. props[ prop ] = this[ prop ];
  2251. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  2252. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  2253. break;
  2254. case 'index_of_refraction':
  2255. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  2256. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  2257. break;
  2258. case 'transparency':
  2259. // gets figured out up top
  2260. break;
  2261. default:
  2262. break;
  2263. }
  2264. }
  2265. props[ 'shading' ] = preferredShading;
  2266. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  2267. switch ( this.type ) {
  2268. case 'constant':
  2269. if (props.emissive != undefined) props.color = props.emissive;
  2270. this.material = new THREE.MeshBasicMaterial( props );
  2271. break;
  2272. case 'phong':
  2273. case 'blinn':
  2274. if (props.diffuse != undefined) props.color = props.diffuse;
  2275. this.material = new THREE.MeshPhongMaterial( props );
  2276. break;
  2277. case 'lambert':
  2278. default:
  2279. if (props.diffuse != undefined) props.color = props.diffuse;
  2280. this.material = new THREE.MeshLambertMaterial( props );
  2281. break;
  2282. }
  2283. return this.material;
  2284. };
  2285. function Surface ( effect ) {
  2286. this.effect = effect;
  2287. this.init_from = null;
  2288. this.format = null;
  2289. };
  2290. Surface.prototype.parse = function ( element ) {
  2291. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2292. var child = element.childNodes[ i ];
  2293. if ( child.nodeType != 1 ) continue;
  2294. switch ( child.nodeName ) {
  2295. case 'init_from':
  2296. this.init_from = child.textContent;
  2297. break;
  2298. case 'format':
  2299. this.format = child.textContent;
  2300. break;
  2301. default:
  2302. console.log( "unhandled Surface prop: " + child.nodeName );
  2303. break;
  2304. }
  2305. }
  2306. return this;
  2307. };
  2308. function Sampler2D ( effect ) {
  2309. this.effect = effect;
  2310. this.source = null;
  2311. this.wrap_s = null;
  2312. this.wrap_t = null;
  2313. this.minfilter = null;
  2314. this.magfilter = null;
  2315. this.mipfilter = null;
  2316. };
  2317. Sampler2D.prototype.parse = function ( element ) {
  2318. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2319. var child = element.childNodes[ i ];
  2320. if ( child.nodeType != 1 ) continue;
  2321. switch ( child.nodeName ) {
  2322. case 'source':
  2323. this.source = child.textContent;
  2324. break;
  2325. case 'minfilter':
  2326. this.minfilter = child.textContent;
  2327. break;
  2328. case 'magfilter':
  2329. this.magfilter = child.textContent;
  2330. break;
  2331. case 'mipfilter':
  2332. this.mipfilter = child.textContent;
  2333. break;
  2334. case 'wrap_s':
  2335. this.wrap_s = child.textContent;
  2336. break;
  2337. case 'wrap_t':
  2338. this.wrap_t = child.textContent;
  2339. break;
  2340. default:
  2341. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  2342. break;
  2343. }
  2344. }
  2345. return this;
  2346. };
  2347. function Effect () {
  2348. this.id = "";
  2349. this.name = "";
  2350. this.shader = null;
  2351. this.surface = {};
  2352. this.sampler = {};
  2353. };
  2354. Effect.prototype.create = function () {
  2355. if ( this.shader === null ) {
  2356. return null;
  2357. }
  2358. };
  2359. Effect.prototype.parse = function ( element ) {
  2360. this.id = element.getAttribute( 'id' );
  2361. this.name = element.getAttribute( 'name' );
  2362. extractDoubleSided( this, element );
  2363. this.shader = null;
  2364. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2365. var child = element.childNodes[ i ];
  2366. if ( child.nodeType != 1 ) continue;
  2367. switch ( child.nodeName ) {
  2368. case 'profile_COMMON':
  2369. this.parseTechnique( this.parseProfileCOMMON( child ) );
  2370. break;
  2371. default:
  2372. break;
  2373. }
  2374. }
  2375. return this;
  2376. };
  2377. Effect.prototype.parseNewparam = function ( element ) {
  2378. var sid = element.getAttribute( 'sid' );
  2379. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2380. var child = element.childNodes[ i ];
  2381. if ( child.nodeType != 1 ) continue;
  2382. switch ( child.nodeName ) {
  2383. case 'surface':
  2384. this.surface[sid] = ( new Surface( this ) ).parse( child );
  2385. break;
  2386. case 'sampler2D':
  2387. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  2388. break;
  2389. case 'extra':
  2390. break;
  2391. default:
  2392. console.log( child.nodeName );
  2393. break;
  2394. }
  2395. }
  2396. };
  2397. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2398. var technique;
  2399. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2400. var child = element.childNodes[ i ];
  2401. if ( child.nodeType != 1 ) continue;
  2402. switch ( child.nodeName ) {
  2403. case 'profile_COMMON':
  2404. this.parseProfileCOMMON( child );
  2405. break;
  2406. case 'technique':
  2407. technique = child;
  2408. break;
  2409. case 'newparam':
  2410. this.parseNewparam( child );
  2411. break;
  2412. case 'image':
  2413. var _image = ( new _Image() ).parse( child );
  2414. images[ _image.id ] = _image;
  2415. break;
  2416. case 'extra':
  2417. break;
  2418. default:
  2419. console.log( child.nodeName );
  2420. break;
  2421. }
  2422. }
  2423. return technique;
  2424. };
  2425. Effect.prototype.parseTechnique = function ( element ) {
  2426. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2427. var child = element.childNodes[i];
  2428. if ( child.nodeType != 1 ) continue;
  2429. switch ( child.nodeName ) {
  2430. case 'constant':
  2431. case 'lambert':
  2432. case 'blinn':
  2433. case 'phong':
  2434. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2435. break;
  2436. case 'extra':
  2437. this.parseExtra(child);
  2438. break;
  2439. default:
  2440. break;
  2441. }
  2442. }
  2443. };
  2444. Effect.prototype.parseExtra = function ( element ) {
  2445. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2446. var child = element.childNodes[i];
  2447. if ( child.nodeType != 1 ) continue;
  2448. switch ( child.nodeName ) {
  2449. case 'technique':
  2450. this.parseExtraTechnique( child );
  2451. break;
  2452. default:
  2453. break;
  2454. }
  2455. }
  2456. };
  2457. Effect.prototype.parseExtraTechnique = function ( element ) {
  2458. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2459. var child = element.childNodes[i];
  2460. if ( child.nodeType != 1 ) continue;
  2461. switch ( child.nodeName ) {
  2462. case 'bump':
  2463. this.shader.parse( element );
  2464. break;
  2465. default:
  2466. break;
  2467. }
  2468. }
  2469. };
  2470. function InstanceEffect () {
  2471. this.url = "";
  2472. };
  2473. InstanceEffect.prototype.parse = function ( element ) {
  2474. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2475. return this;
  2476. };
  2477. function Animation() {
  2478. this.id = "";
  2479. this.name = "";
  2480. this.source = {};
  2481. this.sampler = [];
  2482. this.channel = [];
  2483. };
  2484. Animation.prototype.parse = function ( element ) {
  2485. this.id = element.getAttribute( 'id' );
  2486. this.name = element.getAttribute( 'name' );
  2487. this.source = {};
  2488. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2489. var child = element.childNodes[ i ];
  2490. if ( child.nodeType != 1 ) continue;
  2491. switch ( child.nodeName ) {
  2492. case 'animation':
  2493. var anim = ( new Animation() ).parse( child );
  2494. for ( var src in anim.source ) {
  2495. this.source[ src ] = anim.source[ src ];
  2496. }
  2497. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2498. this.channel.push( anim.channel[ j ] );
  2499. this.sampler.push( anim.sampler[ j ] );
  2500. }
  2501. break;
  2502. case 'source':
  2503. var src = ( new Source() ).parse( child );
  2504. this.source[ src.id ] = src;
  2505. break;
  2506. case 'sampler':
  2507. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2508. break;
  2509. case 'channel':
  2510. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2511. break;
  2512. default:
  2513. break;
  2514. }
  2515. }
  2516. return this;
  2517. };
  2518. function Channel( animation ) {
  2519. this.animation = animation;
  2520. this.source = "";
  2521. this.target = "";
  2522. this.fullSid = null;
  2523. this.sid = null;
  2524. this.dotSyntax = null;
  2525. this.arrSyntax = null;
  2526. this.arrIndices = null;
  2527. this.member = null;
  2528. };
  2529. Channel.prototype.parse = function ( element ) {
  2530. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2531. this.target = element.getAttribute( 'target' );
  2532. var parts = this.target.split( '/' );
  2533. var id = parts.shift();
  2534. var sid = parts.shift();
  2535. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2536. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2537. if ( dotSyntax ) {
  2538. parts = sid.split(".");
  2539. this.sid = parts.shift();
  2540. this.member = parts.shift();
  2541. } else if ( arrSyntax ) {
  2542. var arrIndices = sid.split("(");
  2543. this.sid = arrIndices.shift();
  2544. for (var j = 0; j < arrIndices.length; j ++ ) {
  2545. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2546. }
  2547. this.arrIndices = arrIndices;
  2548. } else {
  2549. this.sid = sid;
  2550. }
  2551. this.fullSid = sid;
  2552. this.dotSyntax = dotSyntax;
  2553. this.arrSyntax = arrSyntax;
  2554. return this;
  2555. };
  2556. function Sampler ( animation ) {
  2557. this.id = "";
  2558. this.animation = animation;
  2559. this.inputs = [];
  2560. this.input = null;
  2561. this.output = null;
  2562. this.strideOut = null;
  2563. this.interpolation = null;
  2564. this.startTime = null;
  2565. this.endTime = null;
  2566. this.duration = 0;
  2567. };
  2568. Sampler.prototype.parse = function ( element ) {
  2569. this.id = element.getAttribute( 'id' );
  2570. this.inputs = [];
  2571. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2572. var child = element.childNodes[ i ];
  2573. if ( child.nodeType != 1 ) continue;
  2574. switch ( child.nodeName ) {
  2575. case 'input':
  2576. this.inputs.push( (new Input()).parse( child ) );
  2577. break;
  2578. default:
  2579. break;
  2580. }
  2581. }
  2582. return this;
  2583. };
  2584. Sampler.prototype.create = function () {
  2585. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2586. var input = this.inputs[ i ];
  2587. var source = this.animation.source[ input.source ];
  2588. switch ( input.semantic ) {
  2589. case 'INPUT':
  2590. this.input = source.read();
  2591. break;
  2592. case 'OUTPUT':
  2593. this.output = source.read();
  2594. this.strideOut = source.accessor.stride;
  2595. break;
  2596. case 'INTERPOLATION':
  2597. this.interpolation = source.read();
  2598. break;
  2599. case 'IN_TANGENT':
  2600. break;
  2601. case 'OUT_TANGENT':
  2602. break;
  2603. default:
  2604. console.log(input.semantic);
  2605. break;
  2606. }
  2607. }
  2608. this.startTime = 0;
  2609. this.endTime = 0;
  2610. this.duration = 0;
  2611. if ( this.input.length ) {
  2612. this.startTime = 100000000;
  2613. this.endTime = -100000000;
  2614. for ( var i = 0; i < this.input.length; i ++ ) {
  2615. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2616. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2617. }
  2618. this.duration = this.endTime - this.startTime;
  2619. }
  2620. };
  2621. Sampler.prototype.getData = function ( type, ndx, member ) {
  2622. var data;
  2623. if ( type === 'matrix' && this.strideOut === 16 ) {
  2624. data = this.output[ ndx ];
  2625. } else if ( this.strideOut > 1 ) {
  2626. data = [];
  2627. ndx *= this.strideOut;
  2628. for ( var i = 0; i < this.strideOut; ++ i ) {
  2629. data[ i ] = this.output[ ndx + i ];
  2630. }
  2631. if ( this.strideOut === 3 ) {
  2632. switch ( type ) {
  2633. case 'rotate':
  2634. case 'translate':
  2635. fixCoords( data, -1 );
  2636. break;
  2637. case 'scale':
  2638. fixCoords( data, 1 );
  2639. break;
  2640. }
  2641. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2642. fixCoords( data, -1 );
  2643. }
  2644. } else {
  2645. data = this.output[ ndx ];
  2646. if ( member && type === 'translate' ) {
  2647. data = getConvertedTranslation( member, data );
  2648. }
  2649. }
  2650. return data;
  2651. };
  2652. function Key ( time ) {
  2653. this.targets = [];
  2654. this.time = time;
  2655. };
  2656. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2657. this.targets.push( {
  2658. sid: fullSid,
  2659. member: member,
  2660. transform: transform,
  2661. data: data
  2662. } );
  2663. };
  2664. Key.prototype.apply = function ( opt_sid ) {
  2665. for ( var i = 0; i < this.targets.length; ++ i ) {
  2666. var target = this.targets[ i ];
  2667. if ( !opt_sid || target.sid === opt_sid ) {
  2668. target.transform.update( target.data, target.member );
  2669. }
  2670. }
  2671. };
  2672. Key.prototype.getTarget = function ( fullSid ) {
  2673. for ( var i = 0; i < this.targets.length; ++ i ) {
  2674. if ( this.targets[ i ].sid === fullSid ) {
  2675. return this.targets[ i ];
  2676. }
  2677. }
  2678. return null;
  2679. };
  2680. Key.prototype.hasTarget = function ( fullSid ) {
  2681. for ( var i = 0; i < this.targets.length; ++ i ) {
  2682. if ( this.targets[ i ].sid === fullSid ) {
  2683. return true;
  2684. }
  2685. }
  2686. return false;
  2687. };
  2688. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2689. Key.prototype.interpolate = function ( nextKey, time ) {
  2690. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  2691. var target = this.targets[ i ],
  2692. nextTarget = nextKey.getTarget( target.sid ),
  2693. data;
  2694. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2695. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2696. nextData = nextTarget.data,
  2697. prevData = target.data;
  2698. if ( scale < 0 ) scale = 0;
  2699. if ( scale > 1 ) scale = 1;
  2700. if ( prevData.length ) {
  2701. data = [];
  2702. for ( var j = 0; j < prevData.length; ++ j ) {
  2703. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2704. }
  2705. } else {
  2706. data = prevData + ( nextData - prevData ) * scale;
  2707. }
  2708. } else {
  2709. data = target.data;
  2710. }
  2711. target.transform.update( data, target.member );
  2712. }
  2713. };
  2714. // Camera
  2715. function Camera() {
  2716. this.id = "";
  2717. this.name = "";
  2718. this.technique = "";
  2719. };
  2720. Camera.prototype.parse = function ( element ) {
  2721. this.id = element.getAttribute( 'id' );
  2722. this.name = element.getAttribute( 'name' );
  2723. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2724. var child = element.childNodes[ i ];
  2725. if ( child.nodeType != 1 ) continue;
  2726. switch ( child.nodeName ) {
  2727. case 'optics':
  2728. this.parseOptics( child );
  2729. break;
  2730. default:
  2731. break;
  2732. }
  2733. }
  2734. return this;
  2735. };
  2736. Camera.prototype.parseOptics = function ( element ) {
  2737. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2738. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  2739. var technique = element.childNodes[ i ];
  2740. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2741. this.technique = technique.childNodes[ j ].nodeName;
  2742. if ( this.technique === 'perspective' ) {
  2743. var perspective = technique.childNodes[ j ];
  2744. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2745. var param = perspective.childNodes[ k ];
  2746. switch ( param.nodeName ) {
  2747. case 'yfov':
  2748. this.yfov = param.textContent;
  2749. break;
  2750. case 'xfov':
  2751. this.xfov = param.textContent;
  2752. break;
  2753. case 'znear':
  2754. this.znear = param.textContent;
  2755. break;
  2756. case 'zfar':
  2757. this.zfar = param.textContent;
  2758. break;
  2759. case 'aspect_ratio':
  2760. this.aspect_ratio = param.textContent;
  2761. break;
  2762. }
  2763. }
  2764. } else if ( this.technique === 'orthographic' ) {
  2765. var orthographic = technique.childNodes[ j ];
  2766. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2767. var param = orthographic.childNodes[ k ];
  2768. switch ( param.nodeName ) {
  2769. case 'xmag':
  2770. this.xmag = param.textContent;
  2771. break;
  2772. case 'ymag':
  2773. this.ymag = param.textContent;
  2774. break;
  2775. case 'znear':
  2776. this.znear = param.textContent;
  2777. break;
  2778. case 'zfar':
  2779. this.zfar = param.textContent;
  2780. break;
  2781. case 'aspect_ratio':
  2782. this.aspect_ratio = param.textContent;
  2783. break;
  2784. }
  2785. }
  2786. }
  2787. }
  2788. }
  2789. }
  2790. return this;
  2791. };
  2792. function InstanceCamera() {
  2793. this.url = "";
  2794. };
  2795. InstanceCamera.prototype.parse = function ( element ) {
  2796. this.url = element.getAttribute('url').replace(/^#/, '');
  2797. return this;
  2798. };
  2799. // Light
  2800. function Light() {
  2801. this.id = "";
  2802. this.name = "";
  2803. this.technique = "";
  2804. };
  2805. Light.prototype.parse = function ( element ) {
  2806. this.id = element.getAttribute( 'id' );
  2807. this.name = element.getAttribute( 'name' );
  2808. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2809. var child = element.childNodes[ i ];
  2810. if ( child.nodeType != 1 ) continue;
  2811. switch ( child.nodeName ) {
  2812. case 'technique_common':
  2813. this.parseCommon( child );
  2814. break;
  2815. case 'technique':
  2816. this.parseTechnique( child );
  2817. break;
  2818. default:
  2819. break;
  2820. }
  2821. }
  2822. return this;
  2823. };
  2824. Light.prototype.parseCommon = function ( element ) {
  2825. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2826. switch ( element.childNodes[ i ].nodeName ) {
  2827. case 'directional':
  2828. case 'point':
  2829. case 'spot':
  2830. case 'ambient':
  2831. this.technique = element.childNodes[ i ].nodeName;
  2832. var light = element.childNodes[ i ];
  2833. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  2834. var child = light.childNodes[j];
  2835. switch ( child.nodeName ) {
  2836. case 'color':
  2837. var rgba = _floats( child.textContent );
  2838. this.color = new THREE.Color(0);
  2839. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2840. this.color.a = rgba[3];
  2841. break;
  2842. case 'falloff_angle':
  2843. this.falloff_angle = parseFloat( child.textContent );
  2844. break;
  2845. case 'quadratic_attenuation':
  2846. var f = parseFloat( child.textContent );
  2847. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  2848. }
  2849. }
  2850. }
  2851. }
  2852. return this;
  2853. };
  2854. Light.prototype.parseTechnique = function ( element ) {
  2855. this.profile = element.getAttribute( 'profile' );
  2856. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2857. var child = element.childNodes[ i ];
  2858. switch ( child.nodeName ) {
  2859. case 'intensity':
  2860. this.intensity = parseFloat(child.textContent);
  2861. break;
  2862. }
  2863. }
  2864. return this;
  2865. };
  2866. function InstanceLight() {
  2867. this.url = "";
  2868. };
  2869. InstanceLight.prototype.parse = function ( element ) {
  2870. this.url = element.getAttribute('url').replace(/^#/, '');
  2871. return this;
  2872. };
  2873. function KinematicsModel( ) {
  2874. this.id = '';
  2875. this.name = '';
  2876. this.joints = [];
  2877. this.links = [];
  2878. }
  2879. KinematicsModel.prototype.parse = function( element ) {
  2880. this.id = element.getAttribute('id');
  2881. this.name = element.getAttribute('name');
  2882. this.joints = [];
  2883. this.links = [];
  2884. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2885. var child = element.childNodes[ i ];
  2886. if ( child.nodeType != 1 ) continue;
  2887. switch ( child.nodeName ) {
  2888. case 'technique_common':
  2889. this.parseCommon(child);
  2890. break;
  2891. default:
  2892. break;
  2893. }
  2894. }
  2895. return this;
  2896. };
  2897. KinematicsModel.prototype.parseCommon = function( element ) {
  2898. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2899. var child = element.childNodes[ i ];
  2900. if ( child.nodeType != 1 ) continue;
  2901. switch ( element.childNodes[ i ].nodeName ) {
  2902. case 'joint':
  2903. this.joints.push( (new Joint()).parse(child) );
  2904. break;
  2905. case 'link':
  2906. this.links.push( (new Link()).parse(child) );
  2907. break;
  2908. default:
  2909. break;
  2910. }
  2911. }
  2912. return this;
  2913. };
  2914. function Joint( ) {
  2915. this.sid = '';
  2916. this.name = '';
  2917. this.axis = new THREE.Vector3();
  2918. this.limits = {
  2919. min: 0,
  2920. max: 0
  2921. };
  2922. this.type = '';
  2923. this.static = false;
  2924. this.zeroPosition = 0.0;
  2925. this.middlePosition = 0.0;
  2926. }
  2927. Joint.prototype.parse = function( element ) {
  2928. this.sid = element.getAttribute('sid');
  2929. this.name = element.getAttribute('name');
  2930. this.axis = new THREE.Vector3();
  2931. this.limits = {
  2932. min: 0,
  2933. max: 0
  2934. };
  2935. this.type = '';
  2936. this.static = false;
  2937. this.zeroPosition = 0.0;
  2938. this.middlePosition = 0.0;
  2939. var axisElement = element.querySelector('axis');
  2940. var _axis = _floats(axisElement.textContent);
  2941. this.axis = getConvertedVec3(_axis, 0);
  2942. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  2943. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  2944. this.limits = {
  2945. min: min,
  2946. max: max
  2947. };
  2948. var jointTypes = [ 'prismatic', 'revolute' ];
  2949. for (var i = 0; i < jointTypes.length; i ++ ) {
  2950. var type = jointTypes[ i ];
  2951. var jointElement = element.querySelector(type);
  2952. if ( jointElement ) {
  2953. this.type = type;
  2954. }
  2955. }
  2956. // if the min is equal to or somehow greater than the max, consider the joint static
  2957. if ( this.limits.min >= this.limits.max ) {
  2958. this.static = true;
  2959. }
  2960. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  2961. return this;
  2962. };
  2963. function Link( ) {
  2964. this.sid = '';
  2965. this.name = '';
  2966. this.transforms = [];
  2967. this.attachments = [];
  2968. }
  2969. Link.prototype.parse = function( element ) {
  2970. this.sid = element.getAttribute('sid');
  2971. this.name = element.getAttribute('name');
  2972. this.transforms = [];
  2973. this.attachments = [];
  2974. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2975. var child = element.childNodes[ i ];
  2976. if ( child.nodeType != 1 ) continue;
  2977. switch ( child.nodeName ) {
  2978. case 'attachment_full':
  2979. this.attachments.push( (new Attachment()).parse(child) );
  2980. break;
  2981. case 'rotate':
  2982. case 'translate':
  2983. case 'matrix':
  2984. this.transforms.push( (new Transform()).parse(child) );
  2985. break;
  2986. default:
  2987. break;
  2988. }
  2989. }
  2990. return this;
  2991. };
  2992. function Attachment( ) {
  2993. this.joint = '';
  2994. this.transforms = [];
  2995. this.links = [];
  2996. }
  2997. Attachment.prototype.parse = function( element ) {
  2998. this.joint = element.getAttribute('joint').split('/').pop();
  2999. this.links = [];
  3000. for (var i = 0; i < element.childNodes.length; i ++ ) {
  3001. var child = element.childNodes[ i ];
  3002. if ( child.nodeType != 1 ) continue;
  3003. switch ( child.nodeName ) {
  3004. case 'link':
  3005. this.links.push( (new Link()).parse(child) );
  3006. break;
  3007. case 'rotate':
  3008. case 'translate':
  3009. case 'matrix':
  3010. this.transforms.push( (new Transform()).parse(child) );
  3011. break;
  3012. default:
  3013. break;
  3014. }
  3015. }
  3016. return this;
  3017. };
  3018. function _source( element ) {
  3019. var id = element.getAttribute( 'id' );
  3020. if ( sources[ id ] != undefined ) {
  3021. return sources[ id ];
  3022. }
  3023. sources[ id ] = ( new Source(id )).parse( element );
  3024. return sources[ id ];
  3025. };
  3026. function _nsResolver( nsPrefix ) {
  3027. if ( nsPrefix === "dae" ) {
  3028. return "http://www.collada.org/2005/11/COLLADASchema";
  3029. }
  3030. return null;
  3031. };
  3032. function _bools( str ) {
  3033. var raw = _strings( str );
  3034. var data = [];
  3035. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3036. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  3037. }
  3038. return data;
  3039. };
  3040. function _floats( str ) {
  3041. var raw = _strings(str);
  3042. var data = [];
  3043. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3044. data.push( parseFloat( raw[ i ] ) );
  3045. }
  3046. return data;
  3047. };
  3048. function _ints( str ) {
  3049. var raw = _strings( str );
  3050. var data = [];
  3051. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3052. data.push( parseInt( raw[ i ], 10 ) );
  3053. }
  3054. return data;
  3055. };
  3056. function _strings( str ) {
  3057. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  3058. };
  3059. function _trimString( str ) {
  3060. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  3061. };
  3062. function _attr_as_float( element, name, defaultValue ) {
  3063. if ( element.hasAttribute( name ) ) {
  3064. return parseFloat( element.getAttribute( name ) );
  3065. } else {
  3066. return defaultValue;
  3067. }
  3068. };
  3069. function _attr_as_int( element, name, defaultValue ) {
  3070. if ( element.hasAttribute( name ) ) {
  3071. return parseInt( element.getAttribute( name ), 10) ;
  3072. } else {
  3073. return defaultValue;
  3074. }
  3075. };
  3076. function _attr_as_string( element, name, defaultValue ) {
  3077. if ( element.hasAttribute( name ) ) {
  3078. return element.getAttribute( name );
  3079. } else {
  3080. return defaultValue;
  3081. }
  3082. };
  3083. function _format_float( f, num ) {
  3084. if ( f === undefined ) {
  3085. var s = '0.';
  3086. while ( s.length < num + 2 ) {
  3087. s += '0';
  3088. }
  3089. return s;
  3090. }
  3091. num = num || 2;
  3092. var parts = f.toString().split( '.' );
  3093. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  3094. while ( parts[ 1 ].length < num ) {
  3095. parts[ 1 ] += '0';
  3096. }
  3097. return parts.join( '.' );
  3098. };
  3099. function loadTextureImage ( texture, url ) {
  3100. loader = new THREE.ImageLoader();
  3101. loader.load( url, function ( image ) {
  3102. texture.image = image;
  3103. texture.needsUpdate = true;
  3104. } );
  3105. };
  3106. function extractDoubleSided( obj, element ) {
  3107. obj.doubleSided = false;
  3108. var node = element.querySelectorAll('extra double_sided')[0];
  3109. if ( node ) {
  3110. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  3111. obj.doubleSided = true;
  3112. }
  3113. }
  3114. };
  3115. // Up axis conversion
  3116. function setUpConversion() {
  3117. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3118. upConversion = null;
  3119. } else {
  3120. switch ( colladaUp ) {
  3121. case 'X':
  3122. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  3123. break;
  3124. case 'Y':
  3125. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  3126. break;
  3127. case 'Z':
  3128. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  3129. break;
  3130. }
  3131. }
  3132. };
  3133. function fixCoords( data, sign ) {
  3134. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3135. return;
  3136. }
  3137. switch ( upConversion ) {
  3138. case 'XtoY':
  3139. var tmp = data[ 0 ];
  3140. data[ 0 ] = sign * data[ 1 ];
  3141. data[ 1 ] = tmp;
  3142. break;
  3143. case 'XtoZ':
  3144. var tmp = data[ 2 ];
  3145. data[ 2 ] = data[ 1 ];
  3146. data[ 1 ] = data[ 0 ];
  3147. data[ 0 ] = tmp;
  3148. break;
  3149. case 'YtoX':
  3150. var tmp = data[ 0 ];
  3151. data[ 0 ] = data[ 1 ];
  3152. data[ 1 ] = sign * tmp;
  3153. break;
  3154. case 'YtoZ':
  3155. var tmp = data[ 1 ];
  3156. data[ 1 ] = sign * data[ 2 ];
  3157. data[ 2 ] = tmp;
  3158. break;
  3159. case 'ZtoX':
  3160. var tmp = data[ 0 ];
  3161. data[ 0 ] = data[ 1 ];
  3162. data[ 1 ] = data[ 2 ];
  3163. data[ 2 ] = tmp;
  3164. break;
  3165. case 'ZtoY':
  3166. var tmp = data[ 1 ];
  3167. data[ 1 ] = data[ 2 ];
  3168. data[ 2 ] = sign * tmp;
  3169. break;
  3170. }
  3171. };
  3172. function getConvertedTranslation( axis, data ) {
  3173. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3174. return data;
  3175. }
  3176. switch ( axis ) {
  3177. case 'X':
  3178. data = upConversion === 'XtoY' ? data * -1 : data;
  3179. break;
  3180. case 'Y':
  3181. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  3182. break;
  3183. case 'Z':
  3184. data = upConversion === 'ZtoY' ? data * -1 : data ;
  3185. break;
  3186. default:
  3187. break;
  3188. }
  3189. return data;
  3190. };
  3191. function getConvertedVec3( data, offset ) {
  3192. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  3193. fixCoords( arr, -1 );
  3194. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  3195. };
  3196. function getConvertedMat4( data ) {
  3197. if ( options.convertUpAxis ) {
  3198. // First fix rotation and scale
  3199. // Columns first
  3200. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  3201. fixCoords( arr, -1 );
  3202. data[ 0 ] = arr[ 0 ];
  3203. data[ 4 ] = arr[ 1 ];
  3204. data[ 8 ] = arr[ 2 ];
  3205. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  3206. fixCoords( arr, -1 );
  3207. data[ 1 ] = arr[ 0 ];
  3208. data[ 5 ] = arr[ 1 ];
  3209. data[ 9 ] = arr[ 2 ];
  3210. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  3211. fixCoords( arr, -1 );
  3212. data[ 2 ] = arr[ 0 ];
  3213. data[ 6 ] = arr[ 1 ];
  3214. data[ 10 ] = arr[ 2 ];
  3215. // Rows second
  3216. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  3217. fixCoords( arr, -1 );
  3218. data[ 0 ] = arr[ 0 ];
  3219. data[ 1 ] = arr[ 1 ];
  3220. data[ 2 ] = arr[ 2 ];
  3221. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  3222. fixCoords( arr, -1 );
  3223. data[ 4 ] = arr[ 0 ];
  3224. data[ 5 ] = arr[ 1 ];
  3225. data[ 6 ] = arr[ 2 ];
  3226. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  3227. fixCoords( arr, -1 );
  3228. data[ 8 ] = arr[ 0 ];
  3229. data[ 9 ] = arr[ 1 ];
  3230. data[ 10 ] = arr[ 2 ];
  3231. // Now fix translation
  3232. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  3233. fixCoords( arr, -1 );
  3234. data[ 3 ] = arr[ 0 ];
  3235. data[ 7 ] = arr[ 1 ];
  3236. data[ 11 ] = arr[ 2 ];
  3237. }
  3238. return new THREE.Matrix4().set(
  3239. data[0], data[1], data[2], data[3],
  3240. data[4], data[5], data[6], data[7],
  3241. data[8], data[9], data[10], data[11],
  3242. data[12], data[13], data[14], data[15]
  3243. );
  3244. };
  3245. function getConvertedIndex( index ) {
  3246. if ( index > -1 && index < 3 ) {
  3247. var members = [ 'X', 'Y', 'Z' ],
  3248. indices = { X: 0, Y: 1, Z: 2 };
  3249. index = getConvertedMember( members[ index ] );
  3250. index = indices[ index ];
  3251. }
  3252. return index;
  3253. };
  3254. function getConvertedMember( member ) {
  3255. if ( options.convertUpAxis ) {
  3256. switch ( member ) {
  3257. case 'X':
  3258. switch ( upConversion ) {
  3259. case 'XtoY':
  3260. case 'XtoZ':
  3261. case 'YtoX':
  3262. member = 'Y';
  3263. break;
  3264. case 'ZtoX':
  3265. member = 'Z';
  3266. break;
  3267. }
  3268. break;
  3269. case 'Y':
  3270. switch ( upConversion ) {
  3271. case 'XtoY':
  3272. case 'YtoX':
  3273. case 'ZtoX':
  3274. member = 'X';
  3275. break;
  3276. case 'XtoZ':
  3277. case 'YtoZ':
  3278. case 'ZtoY':
  3279. member = 'Z';
  3280. break;
  3281. }
  3282. break;
  3283. case 'Z':
  3284. switch ( upConversion ) {
  3285. case 'XtoZ':
  3286. member = 'X';
  3287. break;
  3288. case 'YtoZ':
  3289. case 'ZtoX':
  3290. case 'ZtoY':
  3291. member = 'Y';
  3292. break;
  3293. }
  3294. break;
  3295. }
  3296. }
  3297. return member;
  3298. };
  3299. return {
  3300. load: load,
  3301. parse: parse,
  3302. setPreferredShading: setPreferredShading,
  3303. applySkin: applySkin,
  3304. geometries : geometries,
  3305. options: options
  3306. };
  3307. };