ColladaLoader.js 77 KB

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