ColladaLoader.js 77 KB

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