ColladaLoader.js 77 KB

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