ColladaLoader.js 77 KB

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