ColladaLoader.js 81 KB

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