ColladaLoader.js 78 KB

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