ColladaLoader.js 78 KB

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