ColladaLoader.js 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821
  1. ( function () {
  2. class ColladaLoader extends THREE.Loader {
  3. constructor( manager ) {
  4. super( manager );
  5. }
  6. load( url, onLoad, onProgress, onError ) {
  7. const scope = this;
  8. const path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  9. const loader = new THREE.FileLoader( scope.manager );
  10. loader.setPath( scope.path );
  11. loader.setRequestHeader( scope.requestHeader );
  12. loader.setWithCredentials( scope.withCredentials );
  13. loader.load( url, function ( text ) {
  14. try {
  15. onLoad( scope.parse( text, path ) );
  16. } catch ( e ) {
  17. if ( onError ) {
  18. onError( e );
  19. } else {
  20. console.error( e );
  21. }
  22. scope.manager.itemError( url );
  23. }
  24. }, onProgress, onError );
  25. }
  26. parse( text, path ) {
  27. function getElementsByTagName( xml, name ) {
  28. // Non recursive xml.getElementsByTagName() ...
  29. const array = [];
  30. const childNodes = xml.childNodes;
  31. for ( let i = 0, l = childNodes.length; i < l; i ++ ) {
  32. const child = childNodes[ i ];
  33. if ( child.nodeName === name ) {
  34. array.push( child );
  35. }
  36. }
  37. return array;
  38. }
  39. function parseStrings( text ) {
  40. if ( text.length === 0 ) return [];
  41. const parts = text.trim().split( /\s+/ );
  42. const array = new Array( parts.length );
  43. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  44. array[ i ] = parts[ i ];
  45. }
  46. return array;
  47. }
  48. function parseFloats( text ) {
  49. if ( text.length === 0 ) return [];
  50. const parts = text.trim().split( /\s+/ );
  51. const array = new Array( parts.length );
  52. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  53. array[ i ] = parseFloat( parts[ i ] );
  54. }
  55. return array;
  56. }
  57. function parseInts( text ) {
  58. if ( text.length === 0 ) return [];
  59. const parts = text.trim().split( /\s+/ );
  60. const array = new Array( parts.length );
  61. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  62. array[ i ] = parseInt( parts[ i ] );
  63. }
  64. return array;
  65. }
  66. function parseId( text ) {
  67. return text.substring( 1 );
  68. }
  69. function generateId() {
  70. return 'three_default_' + count ++;
  71. }
  72. function isEmpty( object ) {
  73. return Object.keys( object ).length === 0;
  74. } // asset
  75. function parseAsset( xml ) {
  76. return {
  77. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  78. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  79. };
  80. }
  81. function parseAssetUnit( xml ) {
  82. if ( xml !== undefined && xml.hasAttribute( 'meter' ) === true ) {
  83. return parseFloat( xml.getAttribute( 'meter' ) );
  84. } else {
  85. return 1; // default 1 meter
  86. }
  87. }
  88. function parseAssetUpAxis( xml ) {
  89. return xml !== undefined ? xml.textContent : 'Y_UP';
  90. } // library
  91. function parseLibrary( xml, libraryName, nodeName, parser ) {
  92. const library = getElementsByTagName( xml, libraryName )[ 0 ];
  93. if ( library !== undefined ) {
  94. const elements = getElementsByTagName( library, nodeName );
  95. for ( let i = 0; i < elements.length; i ++ ) {
  96. parser( elements[ i ] );
  97. }
  98. }
  99. }
  100. function buildLibrary( data, builder ) {
  101. for ( const name in data ) {
  102. const object = data[ name ];
  103. object.build = builder( data[ name ] );
  104. }
  105. } // get
  106. function getBuild( data, builder ) {
  107. if ( data.build !== undefined ) return data.build;
  108. data.build = builder( data );
  109. return data.build;
  110. } // animation
  111. function parseAnimation( xml ) {
  112. const data = {
  113. sources: {},
  114. samplers: {},
  115. channels: {}
  116. };
  117. let hasChildren = false;
  118. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  119. const child = xml.childNodes[ i ];
  120. if ( child.nodeType !== 1 ) continue;
  121. let id;
  122. switch ( child.nodeName ) {
  123. case 'source':
  124. id = child.getAttribute( 'id' );
  125. data.sources[ id ] = parseSource( child );
  126. break;
  127. case 'sampler':
  128. id = child.getAttribute( 'id' );
  129. data.samplers[ id ] = parseAnimationSampler( child );
  130. break;
  131. case 'channel':
  132. id = child.getAttribute( 'target' );
  133. data.channels[ id ] = parseAnimationChannel( child );
  134. break;
  135. case 'animation':
  136. // hierarchy of related animations
  137. parseAnimation( child );
  138. hasChildren = true;
  139. break;
  140. default:
  141. console.log( child );
  142. }
  143. }
  144. if ( hasChildren === false ) {
  145. // since 'id' attributes can be optional, it's necessary to generate a UUID for unqiue assignment
  146. library.animations[ xml.getAttribute( 'id' ) || THREE.MathUtils.generateUUID() ] = data;
  147. }
  148. }
  149. function parseAnimationSampler( xml ) {
  150. const data = {
  151. inputs: {}
  152. };
  153. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  154. const child = xml.childNodes[ i ];
  155. if ( child.nodeType !== 1 ) continue;
  156. switch ( child.nodeName ) {
  157. case 'input':
  158. const id = parseId( child.getAttribute( 'source' ) );
  159. const semantic = child.getAttribute( 'semantic' );
  160. data.inputs[ semantic ] = id;
  161. break;
  162. }
  163. }
  164. return data;
  165. }
  166. function parseAnimationChannel( xml ) {
  167. const data = {};
  168. const target = xml.getAttribute( 'target' ); // parsing SID Addressing Syntax
  169. let parts = target.split( '/' );
  170. const id = parts.shift();
  171. let sid = parts.shift(); // check selection syntax
  172. const arraySyntax = sid.indexOf( '(' ) !== - 1;
  173. const memberSyntax = sid.indexOf( '.' ) !== - 1;
  174. if ( memberSyntax ) {
  175. // member selection access
  176. parts = sid.split( '.' );
  177. sid = parts.shift();
  178. data.member = parts.shift();
  179. } else if ( arraySyntax ) {
  180. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  181. const indices = sid.split( '(' );
  182. sid = indices.shift();
  183. for ( let i = 0; i < indices.length; i ++ ) {
  184. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  185. }
  186. data.indices = indices;
  187. }
  188. data.id = id;
  189. data.sid = sid;
  190. data.arraySyntax = arraySyntax;
  191. data.memberSyntax = memberSyntax;
  192. data.sampler = parseId( xml.getAttribute( 'source' ) );
  193. return data;
  194. }
  195. function buildAnimation( data ) {
  196. const tracks = [];
  197. const channels = data.channels;
  198. const samplers = data.samplers;
  199. const sources = data.sources;
  200. for ( const target in channels ) {
  201. if ( channels.hasOwnProperty( target ) ) {
  202. const channel = channels[ target ];
  203. const sampler = samplers[ channel.sampler ];
  204. const inputId = sampler.inputs.INPUT;
  205. const outputId = sampler.inputs.OUTPUT;
  206. const inputSource = sources[ inputId ];
  207. const outputSource = sources[ outputId ];
  208. const animation = buildAnimationChannel( channel, inputSource, outputSource );
  209. createKeyframeTracks( animation, tracks );
  210. }
  211. }
  212. return tracks;
  213. }
  214. function getAnimation( id ) {
  215. return getBuild( library.animations[ id ], buildAnimation );
  216. }
  217. function buildAnimationChannel( channel, inputSource, outputSource ) {
  218. const node = library.nodes[ channel.id ];
  219. const object3D = getNode( node.id );
  220. const transform = node.transforms[ channel.sid ];
  221. const defaultMatrix = node.matrix.clone().transpose();
  222. let time, stride;
  223. let i, il, j, jl;
  224. const data = {}; // the collada spec allows the animation of data in various ways.
  225. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  226. switch ( transform ) {
  227. case 'matrix':
  228. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  229. time = inputSource.array[ i ];
  230. stride = i * outputSource.stride;
  231. if ( data[ time ] === undefined ) data[ time ] = {};
  232. if ( channel.arraySyntax === true ) {
  233. const value = outputSource.array[ stride ];
  234. const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  235. data[ time ][ index ] = value;
  236. } else {
  237. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  238. data[ time ][ j ] = outputSource.array[ stride + j ];
  239. }
  240. }
  241. }
  242. break;
  243. case 'translate':
  244. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  245. break;
  246. case 'rotate':
  247. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  248. break;
  249. case 'scale':
  250. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  251. break;
  252. }
  253. const keyframes = prepareAnimationData( data, defaultMatrix );
  254. const animation = {
  255. name: object3D.uuid,
  256. keyframes: keyframes
  257. };
  258. return animation;
  259. }
  260. function prepareAnimationData( data, defaultMatrix ) {
  261. const keyframes = []; // transfer data into a sortable array
  262. for ( const time in data ) {
  263. keyframes.push( {
  264. time: parseFloat( time ),
  265. value: data[ time ]
  266. } );
  267. } // ensure keyframes are sorted by time
  268. keyframes.sort( ascending ); // now we clean up all animation data, so we can use them for keyframe tracks
  269. for ( let i = 0; i < 16; i ++ ) {
  270. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  271. }
  272. return keyframes; // array sort function
  273. function ascending( a, b ) {
  274. return a.time - b.time;
  275. }
  276. }
  277. const position = new THREE.Vector3();
  278. const scale = new THREE.Vector3();
  279. const quaternion = new THREE.Quaternion();
  280. function createKeyframeTracks( animation, tracks ) {
  281. const keyframes = animation.keyframes;
  282. const name = animation.name;
  283. const times = [];
  284. const positionData = [];
  285. const quaternionData = [];
  286. const scaleData = [];
  287. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  288. const keyframe = keyframes[ i ];
  289. const time = keyframe.time;
  290. const value = keyframe.value;
  291. matrix.fromArray( value ).transpose();
  292. matrix.decompose( position, quaternion, scale );
  293. times.push( time );
  294. positionData.push( position.x, position.y, position.z );
  295. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  296. scaleData.push( scale.x, scale.y, scale.z );
  297. }
  298. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  299. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  300. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  301. return tracks;
  302. }
  303. function transformAnimationData( keyframes, property, defaultValue ) {
  304. let keyframe;
  305. let empty = true;
  306. let i, l; // check, if values of a property are missing in our keyframes
  307. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  308. keyframe = keyframes[ i ];
  309. if ( keyframe.value[ property ] === undefined ) {
  310. keyframe.value[ property ] = null; // mark as missing
  311. } else {
  312. empty = false;
  313. }
  314. }
  315. if ( empty === true ) {
  316. // no values at all, so we set a default value
  317. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  318. keyframe = keyframes[ i ];
  319. keyframe.value[ property ] = defaultValue;
  320. }
  321. } else {
  322. // filling gaps
  323. createMissingKeyframes( keyframes, property );
  324. }
  325. }
  326. function createMissingKeyframes( keyframes, property ) {
  327. let prev, next;
  328. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  329. const keyframe = keyframes[ i ];
  330. if ( keyframe.value[ property ] === null ) {
  331. prev = getPrev( keyframes, i, property );
  332. next = getNext( keyframes, i, property );
  333. if ( prev === null ) {
  334. keyframe.value[ property ] = next.value[ property ];
  335. continue;
  336. }
  337. if ( next === null ) {
  338. keyframe.value[ property ] = prev.value[ property ];
  339. continue;
  340. }
  341. interpolate( keyframe, prev, next, property );
  342. }
  343. }
  344. }
  345. function getPrev( keyframes, i, property ) {
  346. while ( i >= 0 ) {
  347. const keyframe = keyframes[ i ];
  348. if ( keyframe.value[ property ] !== null ) return keyframe;
  349. i --;
  350. }
  351. return null;
  352. }
  353. function getNext( keyframes, i, property ) {
  354. while ( i < keyframes.length ) {
  355. const keyframe = keyframes[ i ];
  356. if ( keyframe.value[ property ] !== null ) return keyframe;
  357. i ++;
  358. }
  359. return null;
  360. }
  361. function interpolate( key, prev, next, property ) {
  362. if ( next.time - prev.time === 0 ) {
  363. key.value[ property ] = prev.value[ property ];
  364. return;
  365. }
  366. key.value[ property ] = ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) + prev.value[ property ];
  367. } // animation clips
  368. function parseAnimationClip( xml ) {
  369. const data = {
  370. name: xml.getAttribute( 'id' ) || 'default',
  371. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  372. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  373. animations: []
  374. };
  375. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  376. const child = xml.childNodes[ i ];
  377. if ( child.nodeType !== 1 ) continue;
  378. switch ( child.nodeName ) {
  379. case 'instance_animation':
  380. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  381. break;
  382. }
  383. }
  384. library.clips[ xml.getAttribute( 'id' ) ] = data;
  385. }
  386. function buildAnimationClip( data ) {
  387. const tracks = [];
  388. const name = data.name;
  389. const duration = data.end - data.start || - 1;
  390. const animations = data.animations;
  391. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  392. const animationTracks = getAnimation( animations[ i ] );
  393. for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  394. tracks.push( animationTracks[ j ] );
  395. }
  396. }
  397. return new THREE.AnimationClip( name, duration, tracks );
  398. }
  399. function getAnimationClip( id ) {
  400. return getBuild( library.clips[ id ], buildAnimationClip );
  401. } // controller
  402. function parseController( xml ) {
  403. const data = {};
  404. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  405. const child = xml.childNodes[ i ];
  406. if ( child.nodeType !== 1 ) continue;
  407. switch ( child.nodeName ) {
  408. case 'skin':
  409. // there is exactly one skin per controller
  410. data.id = parseId( child.getAttribute( 'source' ) );
  411. data.skin = parseSkin( child );
  412. break;
  413. case 'morph':
  414. data.id = parseId( child.getAttribute( 'source' ) );
  415. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  416. break;
  417. }
  418. }
  419. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  420. }
  421. function parseSkin( xml ) {
  422. const data = {
  423. sources: {}
  424. };
  425. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  426. const child = xml.childNodes[ i ];
  427. if ( child.nodeType !== 1 ) continue;
  428. switch ( child.nodeName ) {
  429. case 'bind_shape_matrix':
  430. data.bindShapeMatrix = parseFloats( child.textContent );
  431. break;
  432. case 'source':
  433. const id = child.getAttribute( 'id' );
  434. data.sources[ id ] = parseSource( child );
  435. break;
  436. case 'joints':
  437. data.joints = parseJoints( child );
  438. break;
  439. case 'vertex_weights':
  440. data.vertexWeights = parseVertexWeights( child );
  441. break;
  442. }
  443. }
  444. return data;
  445. }
  446. function parseJoints( xml ) {
  447. const data = {
  448. inputs: {}
  449. };
  450. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  451. const child = xml.childNodes[ i ];
  452. if ( child.nodeType !== 1 ) continue;
  453. switch ( child.nodeName ) {
  454. case 'input':
  455. const semantic = child.getAttribute( 'semantic' );
  456. const id = parseId( child.getAttribute( 'source' ) );
  457. data.inputs[ semantic ] = id;
  458. break;
  459. }
  460. }
  461. return data;
  462. }
  463. function parseVertexWeights( xml ) {
  464. const data = {
  465. inputs: {}
  466. };
  467. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  468. const child = xml.childNodes[ i ];
  469. if ( child.nodeType !== 1 ) continue;
  470. switch ( child.nodeName ) {
  471. case 'input':
  472. const semantic = child.getAttribute( 'semantic' );
  473. const id = parseId( child.getAttribute( 'source' ) );
  474. const offset = parseInt( child.getAttribute( 'offset' ) );
  475. data.inputs[ semantic ] = {
  476. id: id,
  477. offset: offset
  478. };
  479. break;
  480. case 'vcount':
  481. data.vcount = parseInts( child.textContent );
  482. break;
  483. case 'v':
  484. data.v = parseInts( child.textContent );
  485. break;
  486. }
  487. }
  488. return data;
  489. }
  490. function buildController( data ) {
  491. const build = {
  492. id: data.id
  493. };
  494. const geometry = library.geometries[ build.id ];
  495. if ( data.skin !== undefined ) {
  496. build.skin = buildSkin( data.skin ); // we enhance the 'sources' property of the corresponding geometry with our skin data
  497. geometry.sources.skinIndices = build.skin.indices;
  498. geometry.sources.skinWeights = build.skin.weights;
  499. }
  500. return build;
  501. }
  502. function buildSkin( data ) {
  503. const BONE_LIMIT = 4;
  504. const build = {
  505. joints: [],
  506. // this must be an array to preserve the joint order
  507. indices: {
  508. array: [],
  509. stride: BONE_LIMIT
  510. },
  511. weights: {
  512. array: [],
  513. stride: BONE_LIMIT
  514. }
  515. };
  516. const sources = data.sources;
  517. const vertexWeights = data.vertexWeights;
  518. const vcount = vertexWeights.vcount;
  519. const v = vertexWeights.v;
  520. const jointOffset = vertexWeights.inputs.JOINT.offset;
  521. const weightOffset = vertexWeights.inputs.WEIGHT.offset;
  522. const jointSource = data.sources[ data.joints.inputs.JOINT ];
  523. const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  524. const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  525. let stride = 0;
  526. let i, j, l; // procces skin data for each vertex
  527. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  528. const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  529. const vertexSkinData = [];
  530. for ( j = 0; j < jointCount; j ++ ) {
  531. const skinIndex = v[ stride + jointOffset ];
  532. const weightId = v[ stride + weightOffset ];
  533. const skinWeight = weights[ weightId ];
  534. vertexSkinData.push( {
  535. index: skinIndex,
  536. weight: skinWeight
  537. } );
  538. stride += 2;
  539. } // we sort the joints in descending order based on the weights.
  540. // this ensures, we only procced the most important joints of the vertex
  541. vertexSkinData.sort( descending ); // now we provide for each vertex a set of four index and weight values.
  542. // the order of the skin data matches the order of vertices
  543. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  544. const d = vertexSkinData[ j ];
  545. if ( d !== undefined ) {
  546. build.indices.array.push( d.index );
  547. build.weights.array.push( d.weight );
  548. } else {
  549. build.indices.array.push( 0 );
  550. build.weights.array.push( 0 );
  551. }
  552. }
  553. } // setup bind matrix
  554. if ( data.bindShapeMatrix ) {
  555. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  556. } else {
  557. build.bindMatrix = new THREE.Matrix4().identity();
  558. } // process bones and inverse bind matrix data
  559. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  560. const name = jointSource.array[ i ];
  561. const boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  562. build.joints.push( {
  563. name: name,
  564. boneInverse: boneInverse
  565. } );
  566. }
  567. return build; // array sort function
  568. function descending( a, b ) {
  569. return b.weight - a.weight;
  570. }
  571. }
  572. function getController( id ) {
  573. return getBuild( library.controllers[ id ], buildController );
  574. } // image
  575. function parseImage( xml ) {
  576. const data = {
  577. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  578. };
  579. library.images[ xml.getAttribute( 'id' ) ] = data;
  580. }
  581. function buildImage( data ) {
  582. if ( data.build !== undefined ) return data.build;
  583. return data.init_from;
  584. }
  585. function getImage( id ) {
  586. const data = library.images[ id ];
  587. if ( data !== undefined ) {
  588. return getBuild( data, buildImage );
  589. }
  590. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  591. return null;
  592. } // effect
  593. function parseEffect( xml ) {
  594. const data = {};
  595. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  596. const child = xml.childNodes[ i ];
  597. if ( child.nodeType !== 1 ) continue;
  598. switch ( child.nodeName ) {
  599. case 'profile_COMMON':
  600. data.profile = parseEffectProfileCOMMON( child );
  601. break;
  602. }
  603. }
  604. library.effects[ xml.getAttribute( 'id' ) ] = data;
  605. }
  606. function parseEffectProfileCOMMON( xml ) {
  607. const data = {
  608. surfaces: {},
  609. samplers: {}
  610. };
  611. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  612. const child = xml.childNodes[ i ];
  613. if ( child.nodeType !== 1 ) continue;
  614. switch ( child.nodeName ) {
  615. case 'newparam':
  616. parseEffectNewparam( child, data );
  617. break;
  618. case 'technique':
  619. data.technique = parseEffectTechnique( child );
  620. break;
  621. case 'extra':
  622. data.extra = parseEffectExtra( child );
  623. break;
  624. }
  625. }
  626. return data;
  627. }
  628. function parseEffectNewparam( xml, data ) {
  629. const sid = xml.getAttribute( 'sid' );
  630. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  631. const child = xml.childNodes[ i ];
  632. if ( child.nodeType !== 1 ) continue;
  633. switch ( child.nodeName ) {
  634. case 'surface':
  635. data.surfaces[ sid ] = parseEffectSurface( child );
  636. break;
  637. case 'sampler2D':
  638. data.samplers[ sid ] = parseEffectSampler( child );
  639. break;
  640. }
  641. }
  642. }
  643. function parseEffectSurface( xml ) {
  644. const data = {};
  645. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  646. const child = xml.childNodes[ i ];
  647. if ( child.nodeType !== 1 ) continue;
  648. switch ( child.nodeName ) {
  649. case 'init_from':
  650. data.init_from = child.textContent;
  651. break;
  652. }
  653. }
  654. return data;
  655. }
  656. function parseEffectSampler( xml ) {
  657. const data = {};
  658. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  659. const child = xml.childNodes[ i ];
  660. if ( child.nodeType !== 1 ) continue;
  661. switch ( child.nodeName ) {
  662. case 'source':
  663. data.source = child.textContent;
  664. break;
  665. }
  666. }
  667. return data;
  668. }
  669. function parseEffectTechnique( xml ) {
  670. const data = {};
  671. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  672. const child = xml.childNodes[ i ];
  673. if ( child.nodeType !== 1 ) continue;
  674. switch ( child.nodeName ) {
  675. case 'constant':
  676. case 'lambert':
  677. case 'blinn':
  678. case 'phong':
  679. data.type = child.nodeName;
  680. data.parameters = parseEffectParameters( child );
  681. break;
  682. case 'extra':
  683. data.extra = parseEffectExtra( child );
  684. break;
  685. }
  686. }
  687. return data;
  688. }
  689. function parseEffectParameters( xml ) {
  690. const data = {};
  691. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  692. const child = xml.childNodes[ i ];
  693. if ( child.nodeType !== 1 ) continue;
  694. switch ( child.nodeName ) {
  695. case 'emission':
  696. case 'diffuse':
  697. case 'specular':
  698. case 'bump':
  699. case 'ambient':
  700. case 'shininess':
  701. case 'transparency':
  702. data[ child.nodeName ] = parseEffectParameter( child );
  703. break;
  704. case 'transparent':
  705. data[ child.nodeName ] = {
  706. opaque: child.hasAttribute( 'opaque' ) ? child.getAttribute( 'opaque' ) : 'A_ONE',
  707. data: parseEffectParameter( child )
  708. };
  709. break;
  710. }
  711. }
  712. return data;
  713. }
  714. function parseEffectParameter( xml ) {
  715. const data = {};
  716. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  717. const child = xml.childNodes[ i ];
  718. if ( child.nodeType !== 1 ) continue;
  719. switch ( child.nodeName ) {
  720. case 'color':
  721. data[ child.nodeName ] = parseFloats( child.textContent );
  722. break;
  723. case 'float':
  724. data[ child.nodeName ] = parseFloat( child.textContent );
  725. break;
  726. case 'texture':
  727. data[ child.nodeName ] = {
  728. id: child.getAttribute( 'texture' ),
  729. extra: parseEffectParameterTexture( child )
  730. };
  731. break;
  732. }
  733. }
  734. return data;
  735. }
  736. function parseEffectParameterTexture( xml ) {
  737. const data = {
  738. technique: {}
  739. };
  740. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  741. const child = xml.childNodes[ i ];
  742. if ( child.nodeType !== 1 ) continue;
  743. switch ( child.nodeName ) {
  744. case 'extra':
  745. parseEffectParameterTextureExtra( child, data );
  746. break;
  747. }
  748. }
  749. return data;
  750. }
  751. function parseEffectParameterTextureExtra( xml, data ) {
  752. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  753. const child = xml.childNodes[ i ];
  754. if ( child.nodeType !== 1 ) continue;
  755. switch ( child.nodeName ) {
  756. case 'technique':
  757. parseEffectParameterTextureExtraTechnique( child, data );
  758. break;
  759. }
  760. }
  761. }
  762. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  763. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  764. const child = xml.childNodes[ i ];
  765. if ( child.nodeType !== 1 ) continue;
  766. switch ( child.nodeName ) {
  767. case 'repeatU':
  768. case 'repeatV':
  769. case 'offsetU':
  770. case 'offsetV':
  771. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  772. break;
  773. case 'wrapU':
  774. case 'wrapV':
  775. // some files have values for wrapU/wrapV which become NaN via parseInt
  776. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  777. data.technique[ child.nodeName ] = 1;
  778. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  779. data.technique[ child.nodeName ] = 0;
  780. } else {
  781. data.technique[ child.nodeName ] = parseInt( child.textContent );
  782. }
  783. break;
  784. case 'bump':
  785. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  786. break;
  787. }
  788. }
  789. }
  790. function parseEffectExtra( xml ) {
  791. const data = {};
  792. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  793. const child = xml.childNodes[ i ];
  794. if ( child.nodeType !== 1 ) continue;
  795. switch ( child.nodeName ) {
  796. case 'technique':
  797. data.technique = parseEffectExtraTechnique( child );
  798. break;
  799. }
  800. }
  801. return data;
  802. }
  803. function parseEffectExtraTechnique( xml ) {
  804. const data = {};
  805. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  806. const child = xml.childNodes[ i ];
  807. if ( child.nodeType !== 1 ) continue;
  808. switch ( child.nodeName ) {
  809. case 'double_sided':
  810. data[ child.nodeName ] = parseInt( child.textContent );
  811. break;
  812. case 'bump':
  813. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  814. break;
  815. }
  816. }
  817. return data;
  818. }
  819. function parseEffectExtraTechniqueBump( xml ) {
  820. const data = {};
  821. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  822. const child = xml.childNodes[ i ];
  823. if ( child.nodeType !== 1 ) continue;
  824. switch ( child.nodeName ) {
  825. case 'texture':
  826. data[ child.nodeName ] = {
  827. id: child.getAttribute( 'texture' ),
  828. texcoord: child.getAttribute( 'texcoord' ),
  829. extra: parseEffectParameterTexture( child )
  830. };
  831. break;
  832. }
  833. }
  834. return data;
  835. }
  836. function buildEffect( data ) {
  837. return data;
  838. }
  839. function getEffect( id ) {
  840. return getBuild( library.effects[ id ], buildEffect );
  841. } // material
  842. function parseMaterial( xml ) {
  843. const data = {
  844. name: xml.getAttribute( 'name' )
  845. };
  846. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  847. const child = xml.childNodes[ i ];
  848. if ( child.nodeType !== 1 ) continue;
  849. switch ( child.nodeName ) {
  850. case 'instance_effect':
  851. data.url = parseId( child.getAttribute( 'url' ) );
  852. break;
  853. }
  854. }
  855. library.materials[ xml.getAttribute( 'id' ) ] = data;
  856. }
  857. function getTextureLoader( image ) {
  858. let loader;
  859. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  860. extension = extension.toLowerCase();
  861. switch ( extension ) {
  862. case 'tga':
  863. loader = tgaLoader;
  864. break;
  865. default:
  866. loader = textureLoader;
  867. }
  868. return loader;
  869. }
  870. function buildMaterial( data ) {
  871. const effect = getEffect( data.url );
  872. const technique = effect.profile.technique;
  873. let material;
  874. switch ( technique.type ) {
  875. case 'phong':
  876. case 'blinn':
  877. material = new THREE.MeshPhongMaterial();
  878. break;
  879. case 'lambert':
  880. material = new THREE.MeshLambertMaterial();
  881. break;
  882. default:
  883. material = new THREE.MeshBasicMaterial();
  884. break;
  885. }
  886. material.name = data.name || '';
  887. function getTexture( textureObject, encoding = null ) {
  888. const sampler = effect.profile.samplers[ textureObject.id ];
  889. let image = null; // get image
  890. if ( sampler !== undefined ) {
  891. const surface = effect.profile.surfaces[ sampler.source ];
  892. image = getImage( surface.init_from );
  893. } else {
  894. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  895. image = getImage( textureObject.id );
  896. } // create texture if image is avaiable
  897. if ( image !== null ) {
  898. const loader = getTextureLoader( image );
  899. if ( loader !== undefined ) {
  900. const texture = loader.load( image );
  901. const extra = textureObject.extra;
  902. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  903. const technique = extra.technique;
  904. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  905. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  906. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  907. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  908. } else {
  909. texture.wrapS = THREE.RepeatWrapping;
  910. texture.wrapT = THREE.RepeatWrapping;
  911. }
  912. if ( encoding !== null ) {
  913. texture.encoding = encoding;
  914. }
  915. return texture;
  916. } else {
  917. console.warn( 'THREE.ColladaLoader: THREE.Loader for texture %s not found.', image );
  918. return null;
  919. }
  920. } else {
  921. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  922. return null;
  923. }
  924. }
  925. const parameters = technique.parameters;
  926. for ( const key in parameters ) {
  927. const parameter = parameters[ key ];
  928. switch ( key ) {
  929. case 'diffuse':
  930. if ( parameter.color ) material.color.fromArray( parameter.color );
  931. if ( parameter.texture ) material.map = getTexture( parameter.texture, THREE.sRGBEncoding );
  932. break;
  933. case 'specular':
  934. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  935. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  936. break;
  937. case 'bump':
  938. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  939. break;
  940. case 'ambient':
  941. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture, THREE.sRGBEncoding );
  942. break;
  943. case 'shininess':
  944. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  945. break;
  946. case 'emission':
  947. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  948. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture, THREE.sRGBEncoding );
  949. break;
  950. }
  951. }
  952. material.color.convertSRGBToLinear();
  953. if ( material.specular ) material.specular.convertSRGBToLinear();
  954. if ( material.emissive ) material.emissive.convertSRGBToLinear(); //
  955. let transparent = parameters[ 'transparent' ];
  956. let transparency = parameters[ 'transparency' ]; // <transparency> does not exist but <transparent>
  957. if ( transparency === undefined && transparent ) {
  958. transparency = {
  959. float: 1
  960. };
  961. } // <transparent> does not exist but <transparency>
  962. if ( transparent === undefined && transparency ) {
  963. transparent = {
  964. opaque: 'A_ONE',
  965. data: {
  966. color: [ 1, 1, 1, 1 ]
  967. }
  968. };
  969. }
  970. if ( transparent && transparency ) {
  971. // handle case if a texture exists but no color
  972. if ( transparent.data.texture ) {
  973. // we do not set an alpha map (see #13792)
  974. material.transparent = true;
  975. } else {
  976. const color = transparent.data.color;
  977. switch ( transparent.opaque ) {
  978. case 'A_ONE':
  979. material.opacity = color[ 3 ] * transparency.float;
  980. break;
  981. case 'RGB_ZERO':
  982. material.opacity = 1 - color[ 0 ] * transparency.float;
  983. break;
  984. case 'A_ZERO':
  985. material.opacity = 1 - color[ 3 ] * transparency.float;
  986. break;
  987. case 'RGB_ONE':
  988. material.opacity = color[ 0 ] * transparency.float;
  989. break;
  990. default:
  991. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  992. }
  993. if ( material.opacity < 1 ) material.transparent = true;
  994. }
  995. } //
  996. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  997. const techniques = technique.extra.technique;
  998. for ( const k in techniques ) {
  999. const v = techniques[ k ];
  1000. switch ( k ) {
  1001. case 'double_sided':
  1002. material.side = v === 1 ? THREE.DoubleSide : THREE.FrontSide;
  1003. break;
  1004. case 'bump':
  1005. material.normalMap = getTexture( v.texture );
  1006. material.normalScale = new THREE.Vector2( 1, 1 );
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. return material;
  1012. }
  1013. function getMaterial( id ) {
  1014. return getBuild( library.materials[ id ], buildMaterial );
  1015. } // camera
  1016. function parseCamera( xml ) {
  1017. const data = {
  1018. name: xml.getAttribute( 'name' )
  1019. };
  1020. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1021. const child = xml.childNodes[ i ];
  1022. if ( child.nodeType !== 1 ) continue;
  1023. switch ( child.nodeName ) {
  1024. case 'optics':
  1025. data.optics = parseCameraOptics( child );
  1026. break;
  1027. }
  1028. }
  1029. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  1030. }
  1031. function parseCameraOptics( xml ) {
  1032. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1033. const child = xml.childNodes[ i ];
  1034. switch ( child.nodeName ) {
  1035. case 'technique_common':
  1036. return parseCameraTechnique( child );
  1037. }
  1038. }
  1039. return {};
  1040. }
  1041. function parseCameraTechnique( xml ) {
  1042. const data = {};
  1043. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1044. const child = xml.childNodes[ i ];
  1045. switch ( child.nodeName ) {
  1046. case 'perspective':
  1047. case 'orthographic':
  1048. data.technique = child.nodeName;
  1049. data.parameters = parseCameraParameters( child );
  1050. break;
  1051. }
  1052. }
  1053. return data;
  1054. }
  1055. function parseCameraParameters( xml ) {
  1056. const data = {};
  1057. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1058. const child = xml.childNodes[ i ];
  1059. switch ( child.nodeName ) {
  1060. case 'xfov':
  1061. case 'yfov':
  1062. case 'xmag':
  1063. case 'ymag':
  1064. case 'znear':
  1065. case 'zfar':
  1066. case 'aspect_ratio':
  1067. data[ child.nodeName ] = parseFloat( child.textContent );
  1068. break;
  1069. }
  1070. }
  1071. return data;
  1072. }
  1073. function buildCamera( data ) {
  1074. let camera;
  1075. switch ( data.optics.technique ) {
  1076. case 'perspective':
  1077. camera = new THREE.PerspectiveCamera( data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar );
  1078. break;
  1079. case 'orthographic':
  1080. let ymag = data.optics.parameters.ymag;
  1081. let xmag = data.optics.parameters.xmag;
  1082. const aspectRatio = data.optics.parameters.aspect_ratio;
  1083. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1084. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1085. xmag *= 0.5;
  1086. ymag *= 0.5;
  1087. camera = new THREE.OrthographicCamera( - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1088. data.optics.parameters.znear, data.optics.parameters.zfar );
  1089. break;
  1090. default:
  1091. camera = new THREE.PerspectiveCamera();
  1092. break;
  1093. }
  1094. camera.name = data.name || '';
  1095. return camera;
  1096. }
  1097. function getCamera( id ) {
  1098. const data = library.cameras[ id ];
  1099. if ( data !== undefined ) {
  1100. return getBuild( data, buildCamera );
  1101. }
  1102. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1103. return null;
  1104. } // light
  1105. function parseLight( xml ) {
  1106. let data = {};
  1107. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1108. const child = xml.childNodes[ i ];
  1109. if ( child.nodeType !== 1 ) continue;
  1110. switch ( child.nodeName ) {
  1111. case 'technique_common':
  1112. data = parseLightTechnique( child );
  1113. break;
  1114. }
  1115. }
  1116. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1117. }
  1118. function parseLightTechnique( xml ) {
  1119. const data = {};
  1120. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1121. const child = xml.childNodes[ i ];
  1122. if ( child.nodeType !== 1 ) continue;
  1123. switch ( child.nodeName ) {
  1124. case 'directional':
  1125. case 'point':
  1126. case 'spot':
  1127. case 'ambient':
  1128. data.technique = child.nodeName;
  1129. data.parameters = parseLightParameters( child );
  1130. }
  1131. }
  1132. return data;
  1133. }
  1134. function parseLightParameters( xml ) {
  1135. const data = {};
  1136. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1137. const child = xml.childNodes[ i ];
  1138. if ( child.nodeType !== 1 ) continue;
  1139. switch ( child.nodeName ) {
  1140. case 'color':
  1141. const array = parseFloats( child.textContent );
  1142. data.color = new THREE.Color().fromArray( array ).convertSRGBToLinear();
  1143. break;
  1144. case 'falloff_angle':
  1145. data.falloffAngle = parseFloat( child.textContent );
  1146. break;
  1147. case 'quadratic_attenuation':
  1148. const f = parseFloat( child.textContent );
  1149. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1150. break;
  1151. }
  1152. }
  1153. return data;
  1154. }
  1155. function buildLight( data ) {
  1156. let light;
  1157. switch ( data.technique ) {
  1158. case 'directional':
  1159. light = new THREE.DirectionalLight();
  1160. break;
  1161. case 'point':
  1162. light = new THREE.PointLight();
  1163. break;
  1164. case 'spot':
  1165. light = new THREE.SpotLight();
  1166. break;
  1167. case 'ambient':
  1168. light = new THREE.AmbientLight();
  1169. break;
  1170. }
  1171. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1172. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1173. return light;
  1174. }
  1175. function getLight( id ) {
  1176. const data = library.lights[ id ];
  1177. if ( data !== undefined ) {
  1178. return getBuild( data, buildLight );
  1179. }
  1180. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1181. return null;
  1182. } // geometry
  1183. function parseGeometry( xml ) {
  1184. const data = {
  1185. name: xml.getAttribute( 'name' ),
  1186. sources: {},
  1187. vertices: {},
  1188. primitives: []
  1189. };
  1190. const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1191. if ( mesh === undefined ) return;
  1192. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1193. const child = mesh.childNodes[ i ];
  1194. if ( child.nodeType !== 1 ) continue;
  1195. const id = child.getAttribute( 'id' );
  1196. switch ( child.nodeName ) {
  1197. case 'source':
  1198. data.sources[ id ] = parseSource( child );
  1199. break;
  1200. case 'vertices':
  1201. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1202. data.vertices = parseGeometryVertices( child );
  1203. break;
  1204. case 'polygons':
  1205. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1206. break;
  1207. case 'lines':
  1208. case 'linestrips':
  1209. case 'polylist':
  1210. case 'triangles':
  1211. data.primitives.push( parseGeometryPrimitive( child ) );
  1212. break;
  1213. default:
  1214. console.log( child );
  1215. }
  1216. }
  1217. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1218. }
  1219. function parseSource( xml ) {
  1220. const data = {
  1221. array: [],
  1222. stride: 3
  1223. };
  1224. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1225. const child = xml.childNodes[ i ];
  1226. if ( child.nodeType !== 1 ) continue;
  1227. switch ( child.nodeName ) {
  1228. case 'float_array':
  1229. data.array = parseFloats( child.textContent );
  1230. break;
  1231. case 'Name_array':
  1232. data.array = parseStrings( child.textContent );
  1233. break;
  1234. case 'technique_common':
  1235. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1236. if ( accessor !== undefined ) {
  1237. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1238. }
  1239. break;
  1240. }
  1241. }
  1242. return data;
  1243. }
  1244. function parseGeometryVertices( xml ) {
  1245. const data = {};
  1246. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1247. const child = xml.childNodes[ i ];
  1248. if ( child.nodeType !== 1 ) continue;
  1249. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1250. }
  1251. return data;
  1252. }
  1253. function parseGeometryPrimitive( xml ) {
  1254. const primitive = {
  1255. type: xml.nodeName,
  1256. material: xml.getAttribute( 'material' ),
  1257. count: parseInt( xml.getAttribute( 'count' ) ),
  1258. inputs: {},
  1259. stride: 0,
  1260. hasUV: false
  1261. };
  1262. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1263. const child = xml.childNodes[ i ];
  1264. if ( child.nodeType !== 1 ) continue;
  1265. switch ( child.nodeName ) {
  1266. case 'input':
  1267. const id = parseId( child.getAttribute( 'source' ) );
  1268. const semantic = child.getAttribute( 'semantic' );
  1269. const offset = parseInt( child.getAttribute( 'offset' ) );
  1270. const set = parseInt( child.getAttribute( 'set' ) );
  1271. const inputname = set > 0 ? semantic + set : semantic;
  1272. primitive.inputs[ inputname ] = {
  1273. id: id,
  1274. offset: offset
  1275. };
  1276. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1277. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1278. break;
  1279. case 'vcount':
  1280. primitive.vcount = parseInts( child.textContent );
  1281. break;
  1282. case 'p':
  1283. primitive.p = parseInts( child.textContent );
  1284. break;
  1285. }
  1286. }
  1287. return primitive;
  1288. }
  1289. function groupPrimitives( primitives ) {
  1290. const build = {};
  1291. for ( let i = 0; i < primitives.length; i ++ ) {
  1292. const primitive = primitives[ i ];
  1293. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1294. build[ primitive.type ].push( primitive );
  1295. }
  1296. return build;
  1297. }
  1298. function checkUVCoordinates( primitives ) {
  1299. let count = 0;
  1300. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1301. const primitive = primitives[ i ];
  1302. if ( primitive.hasUV === true ) {
  1303. count ++;
  1304. }
  1305. }
  1306. if ( count > 0 && count < primitives.length ) {
  1307. primitives.uvsNeedsFix = true;
  1308. }
  1309. }
  1310. function buildGeometry( data ) {
  1311. const build = {};
  1312. const sources = data.sources;
  1313. const vertices = data.vertices;
  1314. const primitives = data.primitives;
  1315. if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives
  1316. // first, we group all primitives by their type
  1317. const groupedPrimitives = groupPrimitives( primitives );
  1318. for ( const type in groupedPrimitives ) {
  1319. const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1320. checkUVCoordinates( primitiveType ); // third, create a buffer geometry for each type of primitives
  1321. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1322. }
  1323. return build;
  1324. }
  1325. function buildGeometryType( primitives, sources, vertices ) {
  1326. const build = {};
  1327. const position = {
  1328. array: [],
  1329. stride: 0
  1330. };
  1331. const normal = {
  1332. array: [],
  1333. stride: 0
  1334. };
  1335. const uv = {
  1336. array: [],
  1337. stride: 0
  1338. };
  1339. const uv2 = {
  1340. array: [],
  1341. stride: 0
  1342. };
  1343. const color = {
  1344. array: [],
  1345. stride: 0
  1346. };
  1347. const skinIndex = {
  1348. array: [],
  1349. stride: 4
  1350. };
  1351. const skinWeight = {
  1352. array: [],
  1353. stride: 4
  1354. };
  1355. const geometry = new THREE.BufferGeometry();
  1356. const materialKeys = [];
  1357. let start = 0;
  1358. for ( let p = 0; p < primitives.length; p ++ ) {
  1359. const primitive = primitives[ p ];
  1360. const inputs = primitive.inputs; // groups
  1361. let count = 0;
  1362. switch ( primitive.type ) {
  1363. case 'lines':
  1364. case 'linestrips':
  1365. count = primitive.count * 2;
  1366. break;
  1367. case 'triangles':
  1368. count = primitive.count * 3;
  1369. break;
  1370. case 'polylist':
  1371. for ( let g = 0; g < primitive.count; g ++ ) {
  1372. const vc = primitive.vcount[ g ];
  1373. switch ( vc ) {
  1374. case 3:
  1375. count += 3; // single triangle
  1376. break;
  1377. case 4:
  1378. count += 6; // quad, subdivided into two triangles
  1379. break;
  1380. default:
  1381. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1382. break;
  1383. }
  1384. }
  1385. break;
  1386. default:
  1387. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  1388. }
  1389. geometry.addGroup( start, count, p );
  1390. start += count; // material
  1391. if ( primitive.material ) {
  1392. materialKeys.push( primitive.material );
  1393. } // geometry data
  1394. for ( const name in inputs ) {
  1395. const input = inputs[ name ];
  1396. switch ( name ) {
  1397. case 'VERTEX':
  1398. for ( const key in vertices ) {
  1399. const id = vertices[ key ];
  1400. switch ( key ) {
  1401. case 'POSITION':
  1402. const prevLength = position.array.length;
  1403. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1404. position.stride = sources[ id ].stride;
  1405. if ( sources.skinWeights && sources.skinIndices ) {
  1406. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1407. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1408. } // see #3803
  1409. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1410. const count = ( position.array.length - prevLength ) / position.stride;
  1411. for ( let i = 0; i < count; i ++ ) {
  1412. // fill missing uv coordinates
  1413. uv.array.push( 0, 0 );
  1414. }
  1415. }
  1416. break;
  1417. case 'NORMAL':
  1418. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1419. normal.stride = sources[ id ].stride;
  1420. break;
  1421. case 'COLOR':
  1422. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1423. color.stride = sources[ id ].stride;
  1424. break;
  1425. case 'TEXCOORD':
  1426. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1427. uv.stride = sources[ id ].stride;
  1428. break;
  1429. case 'TEXCOORD1':
  1430. buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
  1431. uv.stride = sources[ id ].stride;
  1432. break;
  1433. default:
  1434. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1435. }
  1436. }
  1437. break;
  1438. case 'NORMAL':
  1439. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1440. normal.stride = sources[ input.id ].stride;
  1441. break;
  1442. case 'COLOR':
  1443. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array, true );
  1444. color.stride = sources[ input.id ].stride;
  1445. break;
  1446. case 'TEXCOORD':
  1447. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1448. uv.stride = sources[ input.id ].stride;
  1449. break;
  1450. case 'TEXCOORD1':
  1451. buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
  1452. uv2.stride = sources[ input.id ].stride;
  1453. break;
  1454. }
  1455. }
  1456. } // build geometry
  1457. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  1458. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  1459. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  1460. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  1461. if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new THREE.Float32BufferAttribute( uv2.array, uv2.stride ) );
  1462. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1463. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1464. build.data = geometry;
  1465. build.type = primitives[ 0 ].type;
  1466. build.materialKeys = materialKeys;
  1467. return build;
  1468. }
  1469. function buildGeometryData( primitive, source, offset, array, isColor = false ) {
  1470. const indices = primitive.p;
  1471. const stride = primitive.stride;
  1472. const vcount = primitive.vcount;
  1473. function pushVector( i ) {
  1474. let index = indices[ i + offset ] * sourceStride;
  1475. const length = index + sourceStride;
  1476. for ( ; index < length; index ++ ) {
  1477. array.push( sourceArray[ index ] );
  1478. }
  1479. if ( isColor ) {
  1480. // convert the vertex colors from srgb to linear if present
  1481. const startIndex = array.length - sourceStride - 1;
  1482. tempColor.setRGB( array[ startIndex + 0 ], array[ startIndex + 1 ], array[ startIndex + 2 ] ).convertSRGBToLinear();
  1483. array[ startIndex + 0 ] = tempColor.r;
  1484. array[ startIndex + 1 ] = tempColor.g;
  1485. array[ startIndex + 2 ] = tempColor.b;
  1486. }
  1487. }
  1488. const sourceArray = source.array;
  1489. const sourceStride = source.stride;
  1490. if ( primitive.vcount !== undefined ) {
  1491. let index = 0;
  1492. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1493. const count = vcount[ i ];
  1494. if ( count === 4 ) {
  1495. const a = index + stride * 0;
  1496. const b = index + stride * 1;
  1497. const c = index + stride * 2;
  1498. const d = index + stride * 3;
  1499. pushVector( a );
  1500. pushVector( b );
  1501. pushVector( d );
  1502. pushVector( b );
  1503. pushVector( c );
  1504. pushVector( d );
  1505. } else if ( count === 3 ) {
  1506. const a = index + stride * 0;
  1507. const b = index + stride * 1;
  1508. const c = index + stride * 2;
  1509. pushVector( a );
  1510. pushVector( b );
  1511. pushVector( c );
  1512. } else if ( count > 4 ) {
  1513. for ( let k = 1, kl = count - 2; k <= kl; k ++ ) {
  1514. const a = index + stride * 0;
  1515. const b = index + stride * k;
  1516. const c = index + stride * ( k + 1 );
  1517. pushVector( a );
  1518. pushVector( b );
  1519. pushVector( c );
  1520. }
  1521. }
  1522. index += stride * count;
  1523. }
  1524. } else {
  1525. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1526. pushVector( i );
  1527. }
  1528. }
  1529. }
  1530. function getGeometry( id ) {
  1531. return getBuild( library.geometries[ id ], buildGeometry );
  1532. } // kinematics
  1533. function parseKinematicsModel( xml ) {
  1534. const data = {
  1535. name: xml.getAttribute( 'name' ) || '',
  1536. joints: {},
  1537. links: []
  1538. };
  1539. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1540. const child = xml.childNodes[ i ];
  1541. if ( child.nodeType !== 1 ) continue;
  1542. switch ( child.nodeName ) {
  1543. case 'technique_common':
  1544. parseKinematicsTechniqueCommon( child, data );
  1545. break;
  1546. }
  1547. }
  1548. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1549. }
  1550. function buildKinematicsModel( data ) {
  1551. if ( data.build !== undefined ) return data.build;
  1552. return data;
  1553. }
  1554. function getKinematicsModel( id ) {
  1555. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1556. }
  1557. function parseKinematicsTechniqueCommon( xml, data ) {
  1558. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1559. const child = xml.childNodes[ i ];
  1560. if ( child.nodeType !== 1 ) continue;
  1561. switch ( child.nodeName ) {
  1562. case 'joint':
  1563. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1564. break;
  1565. case 'link':
  1566. data.links.push( parseKinematicsLink( child ) );
  1567. break;
  1568. }
  1569. }
  1570. }
  1571. function parseKinematicsJoint( xml ) {
  1572. let data;
  1573. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1574. const child = xml.childNodes[ i ];
  1575. if ( child.nodeType !== 1 ) continue;
  1576. switch ( child.nodeName ) {
  1577. case 'prismatic':
  1578. case 'revolute':
  1579. data = parseKinematicsJointParameter( child );
  1580. break;
  1581. }
  1582. }
  1583. return data;
  1584. }
  1585. function parseKinematicsJointParameter( xml ) {
  1586. const data = {
  1587. sid: xml.getAttribute( 'sid' ),
  1588. name: xml.getAttribute( 'name' ) || '',
  1589. axis: new THREE.Vector3(),
  1590. limits: {
  1591. min: 0,
  1592. max: 0
  1593. },
  1594. type: xml.nodeName,
  1595. static: false,
  1596. zeroPosition: 0,
  1597. middlePosition: 0
  1598. };
  1599. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1600. const child = xml.childNodes[ i ];
  1601. if ( child.nodeType !== 1 ) continue;
  1602. switch ( child.nodeName ) {
  1603. case 'axis':
  1604. const array = parseFloats( child.textContent );
  1605. data.axis.fromArray( array );
  1606. break;
  1607. case 'limits':
  1608. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1609. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1610. data.limits.max = parseFloat( max.textContent );
  1611. data.limits.min = parseFloat( min.textContent );
  1612. break;
  1613. }
  1614. } // if min is equal to or greater than max, consider the joint static
  1615. if ( data.limits.min >= data.limits.max ) {
  1616. data.static = true;
  1617. } // calculate middle position
  1618. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1619. return data;
  1620. }
  1621. function parseKinematicsLink( xml ) {
  1622. const data = {
  1623. sid: xml.getAttribute( 'sid' ),
  1624. name: xml.getAttribute( 'name' ) || '',
  1625. attachments: [],
  1626. transforms: []
  1627. };
  1628. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1629. const child = xml.childNodes[ i ];
  1630. if ( child.nodeType !== 1 ) continue;
  1631. switch ( child.nodeName ) {
  1632. case 'attachment_full':
  1633. data.attachments.push( parseKinematicsAttachment( child ) );
  1634. break;
  1635. case 'matrix':
  1636. case 'translate':
  1637. case 'rotate':
  1638. data.transforms.push( parseKinematicsTransform( child ) );
  1639. break;
  1640. }
  1641. }
  1642. return data;
  1643. }
  1644. function parseKinematicsAttachment( xml ) {
  1645. const data = {
  1646. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1647. transforms: [],
  1648. links: []
  1649. };
  1650. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1651. const child = xml.childNodes[ i ];
  1652. if ( child.nodeType !== 1 ) continue;
  1653. switch ( child.nodeName ) {
  1654. case 'link':
  1655. data.links.push( parseKinematicsLink( child ) );
  1656. break;
  1657. case 'matrix':
  1658. case 'translate':
  1659. case 'rotate':
  1660. data.transforms.push( parseKinematicsTransform( child ) );
  1661. break;
  1662. }
  1663. }
  1664. return data;
  1665. }
  1666. function parseKinematicsTransform( xml ) {
  1667. const data = {
  1668. type: xml.nodeName
  1669. };
  1670. const array = parseFloats( xml.textContent );
  1671. switch ( data.type ) {
  1672. case 'matrix':
  1673. data.obj = new THREE.Matrix4();
  1674. data.obj.fromArray( array ).transpose();
  1675. break;
  1676. case 'translate':
  1677. data.obj = new THREE.Vector3();
  1678. data.obj.fromArray( array );
  1679. break;
  1680. case 'rotate':
  1681. data.obj = new THREE.Vector3();
  1682. data.obj.fromArray( array );
  1683. data.angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1684. break;
  1685. }
  1686. return data;
  1687. } // physics
  1688. function parsePhysicsModel( xml ) {
  1689. const data = {
  1690. name: xml.getAttribute( 'name' ) || '',
  1691. rigidBodies: {}
  1692. };
  1693. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1694. const child = xml.childNodes[ i ];
  1695. if ( child.nodeType !== 1 ) continue;
  1696. switch ( child.nodeName ) {
  1697. case 'rigid_body':
  1698. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1699. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1700. break;
  1701. }
  1702. }
  1703. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1704. }
  1705. function parsePhysicsRigidBody( xml, data ) {
  1706. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1707. const child = xml.childNodes[ i ];
  1708. if ( child.nodeType !== 1 ) continue;
  1709. switch ( child.nodeName ) {
  1710. case 'technique_common':
  1711. parsePhysicsTechniqueCommon( child, data );
  1712. break;
  1713. }
  1714. }
  1715. }
  1716. function parsePhysicsTechniqueCommon( xml, data ) {
  1717. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1718. const child = xml.childNodes[ i ];
  1719. if ( child.nodeType !== 1 ) continue;
  1720. switch ( child.nodeName ) {
  1721. case 'inertia':
  1722. data.inertia = parseFloats( child.textContent );
  1723. break;
  1724. case 'mass':
  1725. data.mass = parseFloats( child.textContent )[ 0 ];
  1726. break;
  1727. }
  1728. }
  1729. } // scene
  1730. function parseKinematicsScene( xml ) {
  1731. const data = {
  1732. bindJointAxis: []
  1733. };
  1734. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1735. const child = xml.childNodes[ i ];
  1736. if ( child.nodeType !== 1 ) continue;
  1737. switch ( child.nodeName ) {
  1738. case 'bind_joint_axis':
  1739. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1740. break;
  1741. }
  1742. }
  1743. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1744. }
  1745. function parseKinematicsBindJointAxis( xml ) {
  1746. const data = {
  1747. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1748. };
  1749. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1750. const child = xml.childNodes[ i ];
  1751. if ( child.nodeType !== 1 ) continue;
  1752. switch ( child.nodeName ) {
  1753. case 'axis':
  1754. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1755. data.axis = param.textContent;
  1756. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1757. data.jointIndex = tmpJointIndex.substring( 0, tmpJointIndex.length - 1 );
  1758. break;
  1759. }
  1760. }
  1761. return data;
  1762. }
  1763. function buildKinematicsScene( data ) {
  1764. if ( data.build !== undefined ) return data.build;
  1765. return data;
  1766. }
  1767. function getKinematicsScene( id ) {
  1768. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1769. }
  1770. function setupKinematics() {
  1771. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1772. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1773. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1774. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1775. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1776. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1777. const visualScene = getVisualScene( visualSceneId );
  1778. const bindJointAxis = kinematicsScene.bindJointAxis;
  1779. const jointMap = {};
  1780. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1781. const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1782. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1783. if ( targetElement ) {
  1784. // get the parent of the transform element
  1785. const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene
  1786. connect( axis.jointIndex, parentVisualElement );
  1787. }
  1788. }
  1789. function connect( jointIndex, visualElement ) {
  1790. const visualElementName = visualElement.getAttribute( 'name' );
  1791. const joint = kinematicsModel.joints[ jointIndex ];
  1792. visualScene.traverse( function ( object ) {
  1793. if ( object.name === visualElementName ) {
  1794. jointMap[ jointIndex ] = {
  1795. object: object,
  1796. transforms: buildTransformList( visualElement ),
  1797. joint: joint,
  1798. position: joint.zeroPosition
  1799. };
  1800. }
  1801. } );
  1802. }
  1803. const m0 = new THREE.Matrix4();
  1804. kinematics = {
  1805. joints: kinematicsModel && kinematicsModel.joints,
  1806. getJointValue: function ( jointIndex ) {
  1807. const jointData = jointMap[ jointIndex ];
  1808. if ( jointData ) {
  1809. return jointData.position;
  1810. } else {
  1811. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1812. }
  1813. },
  1814. setJointValue: function ( jointIndex, value ) {
  1815. const jointData = jointMap[ jointIndex ];
  1816. if ( jointData ) {
  1817. const joint = jointData.joint;
  1818. if ( value > joint.limits.max || value < joint.limits.min ) {
  1819. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1820. } else if ( joint.static ) {
  1821. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1822. } else {
  1823. const object = jointData.object;
  1824. const axis = joint.axis;
  1825. const transforms = jointData.transforms;
  1826. matrix.identity(); // each update, we have to apply all transforms in the correct order
  1827. for ( let i = 0; i < transforms.length; i ++ ) {
  1828. const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value
  1829. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1830. switch ( joint.type ) {
  1831. case 'revolute':
  1832. matrix.multiply( m0.makeRotationAxis( axis, THREE.MathUtils.degToRad( value ) ) );
  1833. break;
  1834. case 'prismatic':
  1835. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1836. break;
  1837. default:
  1838. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1839. break;
  1840. }
  1841. } else {
  1842. switch ( transform.type ) {
  1843. case 'matrix':
  1844. matrix.multiply( transform.obj );
  1845. break;
  1846. case 'translate':
  1847. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1848. break;
  1849. case 'scale':
  1850. matrix.scale( transform.obj );
  1851. break;
  1852. case 'rotate':
  1853. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1854. break;
  1855. }
  1856. }
  1857. }
  1858. object.matrix.copy( matrix );
  1859. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1860. jointMap[ jointIndex ].position = value;
  1861. }
  1862. } else {
  1863. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1864. }
  1865. }
  1866. };
  1867. }
  1868. function buildTransformList( node ) {
  1869. const transforms = [];
  1870. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1871. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1872. const child = xml.childNodes[ i ];
  1873. if ( child.nodeType !== 1 ) continue;
  1874. let array, vector;
  1875. switch ( child.nodeName ) {
  1876. case 'matrix':
  1877. array = parseFloats( child.textContent );
  1878. const matrix = new THREE.Matrix4().fromArray( array ).transpose();
  1879. transforms.push( {
  1880. sid: child.getAttribute( 'sid' ),
  1881. type: child.nodeName,
  1882. obj: matrix
  1883. } );
  1884. break;
  1885. case 'translate':
  1886. case 'scale':
  1887. array = parseFloats( child.textContent );
  1888. vector = new THREE.Vector3().fromArray( array );
  1889. transforms.push( {
  1890. sid: child.getAttribute( 'sid' ),
  1891. type: child.nodeName,
  1892. obj: vector
  1893. } );
  1894. break;
  1895. case 'rotate':
  1896. array = parseFloats( child.textContent );
  1897. vector = new THREE.Vector3().fromArray( array );
  1898. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1899. transforms.push( {
  1900. sid: child.getAttribute( 'sid' ),
  1901. type: child.nodeName,
  1902. obj: vector,
  1903. angle: angle
  1904. } );
  1905. break;
  1906. }
  1907. }
  1908. return transforms;
  1909. } // nodes
  1910. function prepareNodes( xml ) {
  1911. const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes
  1912. for ( let i = 0; i < elements.length; i ++ ) {
  1913. const element = elements[ i ];
  1914. if ( element.hasAttribute( 'id' ) === false ) {
  1915. element.setAttribute( 'id', generateId() );
  1916. }
  1917. }
  1918. }
  1919. const matrix = new THREE.Matrix4();
  1920. const vector = new THREE.Vector3();
  1921. function parseNode( xml ) {
  1922. const data = {
  1923. name: xml.getAttribute( 'name' ) || '',
  1924. type: xml.getAttribute( 'type' ),
  1925. id: xml.getAttribute( 'id' ),
  1926. sid: xml.getAttribute( 'sid' ),
  1927. matrix: new THREE.Matrix4(),
  1928. nodes: [],
  1929. instanceCameras: [],
  1930. instanceControllers: [],
  1931. instanceLights: [],
  1932. instanceGeometries: [],
  1933. instanceNodes: [],
  1934. transforms: {}
  1935. };
  1936. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1937. const child = xml.childNodes[ i ];
  1938. if ( child.nodeType !== 1 ) continue;
  1939. let array;
  1940. switch ( child.nodeName ) {
  1941. case 'node':
  1942. data.nodes.push( child.getAttribute( 'id' ) );
  1943. parseNode( child );
  1944. break;
  1945. case 'instance_camera':
  1946. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  1947. break;
  1948. case 'instance_controller':
  1949. data.instanceControllers.push( parseNodeInstance( child ) );
  1950. break;
  1951. case 'instance_light':
  1952. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  1953. break;
  1954. case 'instance_geometry':
  1955. data.instanceGeometries.push( parseNodeInstance( child ) );
  1956. break;
  1957. case 'instance_node':
  1958. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  1959. break;
  1960. case 'matrix':
  1961. array = parseFloats( child.textContent );
  1962. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  1963. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1964. break;
  1965. case 'translate':
  1966. array = parseFloats( child.textContent );
  1967. vector.fromArray( array );
  1968. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  1969. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1970. break;
  1971. case 'rotate':
  1972. array = parseFloats( child.textContent );
  1973. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1974. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  1975. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1976. break;
  1977. case 'scale':
  1978. array = parseFloats( child.textContent );
  1979. data.matrix.scale( vector.fromArray( array ) );
  1980. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1981. break;
  1982. case 'extra':
  1983. break;
  1984. default:
  1985. console.log( child );
  1986. }
  1987. }
  1988. if ( hasNode( data.id ) ) {
  1989. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  1990. } else {
  1991. library.nodes[ data.id ] = data;
  1992. }
  1993. return data;
  1994. }
  1995. function parseNodeInstance( xml ) {
  1996. const data = {
  1997. id: parseId( xml.getAttribute( 'url' ) ),
  1998. materials: {},
  1999. skeletons: []
  2000. };
  2001. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  2002. const child = xml.childNodes[ i ];
  2003. switch ( child.nodeName ) {
  2004. case 'bind_material':
  2005. const instances = child.getElementsByTagName( 'instance_material' );
  2006. for ( let j = 0; j < instances.length; j ++ ) {
  2007. const instance = instances[ j ];
  2008. const symbol = instance.getAttribute( 'symbol' );
  2009. const target = instance.getAttribute( 'target' );
  2010. data.materials[ symbol ] = parseId( target );
  2011. }
  2012. break;
  2013. case 'skeleton':
  2014. data.skeletons.push( parseId( child.textContent ) );
  2015. break;
  2016. default:
  2017. break;
  2018. }
  2019. }
  2020. return data;
  2021. }
  2022. function buildSkeleton( skeletons, joints ) {
  2023. const boneData = [];
  2024. const sortedBoneData = [];
  2025. let i, j, data; // a skeleton can have multiple root bones. collada expresses this
  2026. // situtation with multiple "skeleton" tags per controller instance
  2027. for ( i = 0; i < skeletons.length; i ++ ) {
  2028. const skeleton = skeletons[ i ];
  2029. let root;
  2030. if ( hasNode( skeleton ) ) {
  2031. root = getNode( skeleton );
  2032. buildBoneHierarchy( root, joints, boneData );
  2033. } else if ( hasVisualScene( skeleton ) ) {
  2034. // handle case where the skeleton refers to the visual scene (#13335)
  2035. const visualScene = library.visualScenes[ skeleton ];
  2036. const children = visualScene.children;
  2037. for ( let j = 0; j < children.length; j ++ ) {
  2038. const child = children[ j ];
  2039. if ( child.type === 'JOINT' ) {
  2040. const root = getNode( child.id );
  2041. buildBoneHierarchy( root, joints, boneData );
  2042. }
  2043. }
  2044. } else {
  2045. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  2046. }
  2047. } // sort bone data (the order is defined in the corresponding controller)
  2048. for ( i = 0; i < joints.length; i ++ ) {
  2049. for ( j = 0; j < boneData.length; j ++ ) {
  2050. data = boneData[ j ];
  2051. if ( data.bone.name === joints[ i ].name ) {
  2052. sortedBoneData[ i ] = data;
  2053. data.processed = true;
  2054. break;
  2055. }
  2056. }
  2057. } // add unprocessed bone data at the end of the list
  2058. for ( i = 0; i < boneData.length; i ++ ) {
  2059. data = boneData[ i ];
  2060. if ( data.processed === false ) {
  2061. sortedBoneData.push( data );
  2062. data.processed = true;
  2063. }
  2064. } // setup arrays for skeleton creation
  2065. const bones = [];
  2066. const boneInverses = [];
  2067. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2068. data = sortedBoneData[ i ];
  2069. bones.push( data.bone );
  2070. boneInverses.push( data.boneInverse );
  2071. }
  2072. return new THREE.Skeleton( bones, boneInverses );
  2073. }
  2074. function buildBoneHierarchy( root, joints, boneData ) {
  2075. // setup bone data from visual scene
  2076. root.traverse( function ( object ) {
  2077. if ( object.isBone === true ) {
  2078. let boneInverse; // retrieve the boneInverse from the controller data
  2079. for ( let i = 0; i < joints.length; i ++ ) {
  2080. const joint = joints[ i ];
  2081. if ( joint.name === object.name ) {
  2082. boneInverse = joint.boneInverse;
  2083. break;
  2084. }
  2085. }
  2086. if ( boneInverse === undefined ) {
  2087. // Unfortunately, there can be joints in the visual scene that are not part of the
  2088. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2089. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2090. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2091. // ensure a correct animation of the model.
  2092. boneInverse = new THREE.Matrix4();
  2093. }
  2094. boneData.push( {
  2095. bone: object,
  2096. boneInverse: boneInverse,
  2097. processed: false
  2098. } );
  2099. }
  2100. } );
  2101. }
  2102. function buildNode( data ) {
  2103. const objects = [];
  2104. const matrix = data.matrix;
  2105. const nodes = data.nodes;
  2106. const type = data.type;
  2107. const instanceCameras = data.instanceCameras;
  2108. const instanceControllers = data.instanceControllers;
  2109. const instanceLights = data.instanceLights;
  2110. const instanceGeometries = data.instanceGeometries;
  2111. const instanceNodes = data.instanceNodes; // nodes
  2112. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2113. objects.push( getNode( nodes[ i ] ) );
  2114. } // instance cameras
  2115. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2116. const instanceCamera = getCamera( instanceCameras[ i ] );
  2117. if ( instanceCamera !== null ) {
  2118. objects.push( instanceCamera.clone() );
  2119. }
  2120. } // instance controllers
  2121. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2122. const instance = instanceControllers[ i ];
  2123. const controller = getController( instance.id );
  2124. const geometries = getGeometry( controller.id );
  2125. const newObjects = buildObjects( geometries, instance.materials );
  2126. const skeletons = instance.skeletons;
  2127. const joints = controller.skin.joints;
  2128. const skeleton = buildSkeleton( skeletons, joints );
  2129. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2130. const object = newObjects[ j ];
  2131. if ( object.isSkinnedMesh ) {
  2132. object.bind( skeleton, controller.skin.bindMatrix );
  2133. object.normalizeSkinWeights();
  2134. }
  2135. objects.push( object );
  2136. }
  2137. } // instance lights
  2138. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2139. const instanceLight = getLight( instanceLights[ i ] );
  2140. if ( instanceLight !== null ) {
  2141. objects.push( instanceLight.clone() );
  2142. }
  2143. } // instance geometries
  2144. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2145. const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds.
  2146. // this is the case when primitives are combined like triangles and lines
  2147. const geometries = getGeometry( instance.id );
  2148. const newObjects = buildObjects( geometries, instance.materials );
  2149. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2150. objects.push( newObjects[ j ] );
  2151. }
  2152. } // instance nodes
  2153. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2154. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2155. }
  2156. let object;
  2157. if ( nodes.length === 0 && objects.length === 1 ) {
  2158. object = objects[ 0 ];
  2159. } else {
  2160. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2161. for ( let i = 0; i < objects.length; i ++ ) {
  2162. object.add( objects[ i ] );
  2163. }
  2164. }
  2165. object.name = type === 'JOINT' ? data.sid : data.name;
  2166. object.matrix.copy( matrix );
  2167. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2168. return object;
  2169. }
  2170. const fallbackMaterial = new THREE.MeshBasicMaterial( {
  2171. color: 0xff00ff
  2172. } );
  2173. function resolveMaterialBinding( keys, instanceMaterials ) {
  2174. const materials = [];
  2175. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2176. const id = instanceMaterials[ keys[ i ] ];
  2177. if ( id === undefined ) {
  2178. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2179. materials.push( fallbackMaterial );
  2180. } else {
  2181. materials.push( getMaterial( id ) );
  2182. }
  2183. }
  2184. return materials;
  2185. }
  2186. function buildObjects( geometries, instanceMaterials ) {
  2187. const objects = [];
  2188. for ( const type in geometries ) {
  2189. const geometry = geometries[ type ];
  2190. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined
  2191. if ( materials.length === 0 ) {
  2192. if ( type === 'lines' || type === 'linestrips' ) {
  2193. materials.push( new THREE.LineBasicMaterial() );
  2194. } else {
  2195. materials.push( new THREE.MeshPhongMaterial() );
  2196. }
  2197. } // regard skinning
  2198. const skinning = geometry.data.attributes.skinIndex !== undefined; // choose between a single or multi materials (material array)
  2199. const material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object
  2200. let object;
  2201. switch ( type ) {
  2202. case 'lines':
  2203. object = new THREE.LineSegments( geometry.data, material );
  2204. break;
  2205. case 'linestrips':
  2206. object = new THREE.Line( geometry.data, material );
  2207. break;
  2208. case 'triangles':
  2209. case 'polylist':
  2210. if ( skinning ) {
  2211. object = new THREE.SkinnedMesh( geometry.data, material );
  2212. } else {
  2213. object = new THREE.Mesh( geometry.data, material );
  2214. }
  2215. break;
  2216. }
  2217. objects.push( object );
  2218. }
  2219. return objects;
  2220. }
  2221. function hasNode( id ) {
  2222. return library.nodes[ id ] !== undefined;
  2223. }
  2224. function getNode( id ) {
  2225. return getBuild( library.nodes[ id ], buildNode );
  2226. } // visual scenes
  2227. function parseVisualScene( xml ) {
  2228. const data = {
  2229. name: xml.getAttribute( 'name' ),
  2230. children: []
  2231. };
  2232. prepareNodes( xml );
  2233. const elements = getElementsByTagName( xml, 'node' );
  2234. for ( let i = 0; i < elements.length; i ++ ) {
  2235. data.children.push( parseNode( elements[ i ] ) );
  2236. }
  2237. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2238. }
  2239. function buildVisualScene( data ) {
  2240. const group = new THREE.Group();
  2241. group.name = data.name;
  2242. const children = data.children;
  2243. for ( let i = 0; i < children.length; i ++ ) {
  2244. const child = children[ i ];
  2245. group.add( getNode( child.id ) );
  2246. }
  2247. return group;
  2248. }
  2249. function hasVisualScene( id ) {
  2250. return library.visualScenes[ id ] !== undefined;
  2251. }
  2252. function getVisualScene( id ) {
  2253. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2254. } // scenes
  2255. function parseScene( xml ) {
  2256. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2257. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2258. }
  2259. function setupAnimations() {
  2260. const clips = library.clips;
  2261. if ( isEmpty( clips ) === true ) {
  2262. if ( isEmpty( library.animations ) === false ) {
  2263. // if there are animations but no clips, we create a default clip for playback
  2264. const tracks = [];
  2265. for ( const id in library.animations ) {
  2266. const animationTracks = getAnimation( id );
  2267. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2268. tracks.push( animationTracks[ i ] );
  2269. }
  2270. }
  2271. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  2272. }
  2273. } else {
  2274. for ( const id in clips ) {
  2275. animations.push( getAnimationClip( id ) );
  2276. }
  2277. }
  2278. } // convert the parser error element into text with each child elements text
  2279. // separated by new lines.
  2280. function parserErrorToText( parserError ) {
  2281. let result = '';
  2282. const stack = [ parserError ];
  2283. while ( stack.length ) {
  2284. const node = stack.shift();
  2285. if ( node.nodeType === Node.TEXT_NODE ) {
  2286. result += node.textContent;
  2287. } else {
  2288. result += '\n';
  2289. stack.push.apply( stack, node.childNodes );
  2290. }
  2291. }
  2292. return result.trim();
  2293. }
  2294. if ( text.length === 0 ) {
  2295. return {
  2296. scene: new THREE.Scene()
  2297. };
  2298. }
  2299. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2300. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2301. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2302. if ( parserError !== undefined ) {
  2303. // Chrome will return parser error with a div in it
  2304. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2305. let errorText;
  2306. if ( errorElement ) {
  2307. errorText = errorElement.textContent;
  2308. } else {
  2309. errorText = parserErrorToText( parserError );
  2310. }
  2311. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2312. return null;
  2313. } // metadata
  2314. const version = collada.getAttribute( 'version' );
  2315. console.log( 'THREE.ColladaLoader: File version', version );
  2316. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2317. const textureLoader = new THREE.TextureLoader( this.manager );
  2318. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2319. let tgaLoader;
  2320. if ( THREE.TGALoader ) {
  2321. tgaLoader = new THREE.TGALoader( this.manager );
  2322. tgaLoader.setPath( this.resourcePath || path );
  2323. } //
  2324. const tempColor = new THREE.Color();
  2325. const animations = [];
  2326. let kinematics = {};
  2327. let count = 0; //
  2328. const library = {
  2329. animations: {},
  2330. clips: {},
  2331. controllers: {},
  2332. images: {},
  2333. effects: {},
  2334. materials: {},
  2335. cameras: {},
  2336. lights: {},
  2337. geometries: {},
  2338. nodes: {},
  2339. visualScenes: {},
  2340. kinematicsModels: {},
  2341. physicsModels: {},
  2342. kinematicsScenes: {}
  2343. };
  2344. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2345. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2346. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2347. parseLibrary( collada, 'library_images', 'image', parseImage );
  2348. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2349. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2350. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2351. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2352. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2353. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2354. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2355. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2356. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2357. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2358. buildLibrary( library.animations, buildAnimation );
  2359. buildLibrary( library.clips, buildAnimationClip );
  2360. buildLibrary( library.controllers, buildController );
  2361. buildLibrary( library.images, buildImage );
  2362. buildLibrary( library.effects, buildEffect );
  2363. buildLibrary( library.materials, buildMaterial );
  2364. buildLibrary( library.cameras, buildCamera );
  2365. buildLibrary( library.lights, buildLight );
  2366. buildLibrary( library.geometries, buildGeometry );
  2367. buildLibrary( library.visualScenes, buildVisualScene );
  2368. setupAnimations();
  2369. setupKinematics();
  2370. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2371. scene.animations = animations;
  2372. if ( asset.upAxis === 'Z_UP' ) {
  2373. console.warn( 'THREE.ColladaLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted, see #24289.' );
  2374. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  2375. }
  2376. scene.scale.multiplyScalar( asset.unit );
  2377. return {
  2378. get animations() {
  2379. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2380. return animations;
  2381. },
  2382. kinematics: kinematics,
  2383. library: library,
  2384. scene: scene
  2385. };
  2386. }
  2387. }
  2388. THREE.ColladaLoader = ColladaLoader;
  2389. } )();