ColladaLoader.js 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753
  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. }
  683. }
  684. return data;
  685. }
  686. function parseEffectParameters( xml ) {
  687. const data = {};
  688. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  689. const child = xml.childNodes[ i ];
  690. if ( child.nodeType !== 1 ) continue;
  691. switch ( child.nodeName ) {
  692. case 'emission':
  693. case 'diffuse':
  694. case 'specular':
  695. case 'bump':
  696. case 'ambient':
  697. case 'shininess':
  698. case 'transparency':
  699. data[ child.nodeName ] = parseEffectParameter( child );
  700. break;
  701. case 'transparent':
  702. data[ child.nodeName ] = {
  703. opaque: child.getAttribute( 'opaque' ),
  704. data: parseEffectParameter( child )
  705. };
  706. break;
  707. }
  708. }
  709. return data;
  710. }
  711. function parseEffectParameter( xml ) {
  712. const data = {};
  713. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  714. const child = xml.childNodes[ i ];
  715. if ( child.nodeType !== 1 ) continue;
  716. switch ( child.nodeName ) {
  717. case 'color':
  718. data[ child.nodeName ] = parseFloats( child.textContent );
  719. break;
  720. case 'float':
  721. data[ child.nodeName ] = parseFloat( child.textContent );
  722. break;
  723. case 'texture':
  724. data[ child.nodeName ] = {
  725. id: child.getAttribute( 'texture' ),
  726. extra: parseEffectParameterTexture( child )
  727. };
  728. break;
  729. }
  730. }
  731. return data;
  732. }
  733. function parseEffectParameterTexture( xml ) {
  734. const data = {
  735. technique: {}
  736. };
  737. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  738. const child = xml.childNodes[ i ];
  739. if ( child.nodeType !== 1 ) continue;
  740. switch ( child.nodeName ) {
  741. case 'extra':
  742. parseEffectParameterTextureExtra( child, data );
  743. break;
  744. }
  745. }
  746. return data;
  747. }
  748. function parseEffectParameterTextureExtra( xml, data ) {
  749. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  750. const child = xml.childNodes[ i ];
  751. if ( child.nodeType !== 1 ) continue;
  752. switch ( child.nodeName ) {
  753. case 'technique':
  754. parseEffectParameterTextureExtraTechnique( child, data );
  755. break;
  756. }
  757. }
  758. }
  759. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  760. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  761. const child = xml.childNodes[ i ];
  762. if ( child.nodeType !== 1 ) continue;
  763. switch ( child.nodeName ) {
  764. case 'repeatU':
  765. case 'repeatV':
  766. case 'offsetU':
  767. case 'offsetV':
  768. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  769. break;
  770. case 'wrapU':
  771. case 'wrapV':
  772. // some files have values for wrapU/wrapV which become NaN via parseInt
  773. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  774. data.technique[ child.nodeName ] = 1;
  775. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  776. data.technique[ child.nodeName ] = 0;
  777. } else {
  778. data.technique[ child.nodeName ] = parseInt( child.textContent );
  779. }
  780. break;
  781. }
  782. }
  783. }
  784. function parseEffectExtra( xml ) {
  785. const data = {};
  786. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  787. const child = xml.childNodes[ i ];
  788. if ( child.nodeType !== 1 ) continue;
  789. switch ( child.nodeName ) {
  790. case 'technique':
  791. data.technique = parseEffectExtraTechnique( child );
  792. break;
  793. }
  794. }
  795. return data;
  796. }
  797. function parseEffectExtraTechnique( xml ) {
  798. const data = {};
  799. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  800. const child = xml.childNodes[ i ];
  801. if ( child.nodeType !== 1 ) continue;
  802. switch ( child.nodeName ) {
  803. case 'double_sided':
  804. data[ child.nodeName ] = parseInt( child.textContent );
  805. break;
  806. }
  807. }
  808. return data;
  809. }
  810. function buildEffect( data ) {
  811. return data;
  812. }
  813. function getEffect( id ) {
  814. return getBuild( library.effects[ id ], buildEffect );
  815. } // material
  816. function parseMaterial( xml ) {
  817. const data = {
  818. name: xml.getAttribute( 'name' )
  819. };
  820. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  821. const child = xml.childNodes[ i ];
  822. if ( child.nodeType !== 1 ) continue;
  823. switch ( child.nodeName ) {
  824. case 'instance_effect':
  825. data.url = parseId( child.getAttribute( 'url' ) );
  826. break;
  827. }
  828. }
  829. library.materials[ xml.getAttribute( 'id' ) ] = data;
  830. }
  831. function getTextureLoader( image ) {
  832. let loader;
  833. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  834. extension = extension.toLowerCase();
  835. switch ( extension ) {
  836. case 'tga':
  837. loader = tgaLoader;
  838. break;
  839. default:
  840. loader = textureLoader;
  841. }
  842. return loader;
  843. }
  844. function buildMaterial( data ) {
  845. const effect = getEffect( data.url );
  846. const technique = effect.profile.technique;
  847. const extra = effect.profile.extra;
  848. let material;
  849. switch ( technique.type ) {
  850. case 'phong':
  851. case 'blinn':
  852. material = new THREE.MeshPhongMaterial();
  853. break;
  854. case 'lambert':
  855. material = new THREE.MeshLambertMaterial();
  856. break;
  857. default:
  858. material = new THREE.MeshBasicMaterial();
  859. break;
  860. }
  861. material.name = data.name || '';
  862. function getTexture( textureObject ) {
  863. const sampler = effect.profile.samplers[ textureObject.id ];
  864. let image = null; // get image
  865. if ( sampler !== undefined ) {
  866. const surface = effect.profile.surfaces[ sampler.source ];
  867. image = getImage( surface.init_from );
  868. } else {
  869. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  870. image = getImage( textureObject.id );
  871. } // create texture if image is avaiable
  872. if ( image !== null ) {
  873. const loader = getTextureLoader( image );
  874. if ( loader !== undefined ) {
  875. const texture = loader.load( image );
  876. const extra = textureObject.extra;
  877. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  878. const technique = extra.technique;
  879. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  880. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  881. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  882. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  883. } else {
  884. texture.wrapS = THREE.RepeatWrapping;
  885. texture.wrapT = THREE.RepeatWrapping;
  886. }
  887. return texture;
  888. } else {
  889. console.warn( 'THREE.ColladaLoader: THREE.Loader for texture %s not found.', image );
  890. return null;
  891. }
  892. } else {
  893. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  894. return null;
  895. }
  896. }
  897. const parameters = technique.parameters;
  898. for ( const key in parameters ) {
  899. const parameter = parameters[ key ];
  900. switch ( key ) {
  901. case 'diffuse':
  902. if ( parameter.color ) material.color.fromArray( parameter.color );
  903. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  904. break;
  905. case 'specular':
  906. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  907. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  908. break;
  909. case 'bump':
  910. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  911. break;
  912. case 'ambient':
  913. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture );
  914. break;
  915. case 'shininess':
  916. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  917. break;
  918. case 'emission':
  919. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  920. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  921. break;
  922. }
  923. } //
  924. let transparent = parameters[ 'transparent' ];
  925. let transparency = parameters[ 'transparency' ]; // <transparency> does not exist but <transparent>
  926. if ( transparency === undefined && transparent ) {
  927. transparency = {
  928. float: 1
  929. };
  930. } // <transparent> does not exist but <transparency>
  931. if ( transparent === undefined && transparency ) {
  932. transparent = {
  933. opaque: 'A_ONE',
  934. data: {
  935. color: [ 1, 1, 1, 1 ]
  936. }
  937. };
  938. }
  939. if ( transparent && transparency ) {
  940. // handle case if a texture exists but no color
  941. if ( transparent.data.texture ) {
  942. // we do not set an alpha map (see #13792)
  943. material.transparent = true;
  944. } else {
  945. const color = transparent.data.color;
  946. switch ( transparent.opaque ) {
  947. case 'A_ONE':
  948. material.opacity = color[ 3 ] * transparency.float;
  949. break;
  950. case 'RGB_ZERO':
  951. material.opacity = 1 - color[ 0 ] * transparency.float;
  952. break;
  953. case 'A_ZERO':
  954. material.opacity = 1 - color[ 3 ] * transparency.float;
  955. break;
  956. case 'RGB_ONE':
  957. material.opacity = color[ 0 ] * transparency.float;
  958. break;
  959. default:
  960. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  961. }
  962. if ( material.opacity < 1 ) material.transparent = true;
  963. }
  964. } //
  965. if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
  966. material.side = THREE.DoubleSide;
  967. }
  968. return material;
  969. }
  970. function getMaterial( id ) {
  971. return getBuild( library.materials[ id ], buildMaterial );
  972. } // camera
  973. function parseCamera( xml ) {
  974. const data = {
  975. name: xml.getAttribute( 'name' )
  976. };
  977. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  978. const child = xml.childNodes[ i ];
  979. if ( child.nodeType !== 1 ) continue;
  980. switch ( child.nodeName ) {
  981. case 'optics':
  982. data.optics = parseCameraOptics( child );
  983. break;
  984. }
  985. }
  986. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  987. }
  988. function parseCameraOptics( xml ) {
  989. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  990. const child = xml.childNodes[ i ];
  991. switch ( child.nodeName ) {
  992. case 'technique_common':
  993. return parseCameraTechnique( child );
  994. }
  995. }
  996. return {};
  997. }
  998. function parseCameraTechnique( xml ) {
  999. const data = {};
  1000. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1001. const child = xml.childNodes[ i ];
  1002. switch ( child.nodeName ) {
  1003. case 'perspective':
  1004. case 'orthographic':
  1005. data.technique = child.nodeName;
  1006. data.parameters = parseCameraParameters( child );
  1007. break;
  1008. }
  1009. }
  1010. return data;
  1011. }
  1012. function parseCameraParameters( xml ) {
  1013. const data = {};
  1014. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1015. const child = xml.childNodes[ i ];
  1016. switch ( child.nodeName ) {
  1017. case 'xfov':
  1018. case 'yfov':
  1019. case 'xmag':
  1020. case 'ymag':
  1021. case 'znear':
  1022. case 'zfar':
  1023. case 'aspect_ratio':
  1024. data[ child.nodeName ] = parseFloat( child.textContent );
  1025. break;
  1026. }
  1027. }
  1028. return data;
  1029. }
  1030. function buildCamera( data ) {
  1031. let camera;
  1032. switch ( data.optics.technique ) {
  1033. case 'perspective':
  1034. camera = new THREE.PerspectiveCamera( data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar );
  1035. break;
  1036. case 'orthographic':
  1037. let ymag = data.optics.parameters.ymag;
  1038. let xmag = data.optics.parameters.xmag;
  1039. const aspectRatio = data.optics.parameters.aspect_ratio;
  1040. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1041. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1042. xmag *= 0.5;
  1043. ymag *= 0.5;
  1044. camera = new THREE.OrthographicCamera( - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1045. data.optics.parameters.znear, data.optics.parameters.zfar );
  1046. break;
  1047. default:
  1048. camera = new THREE.PerspectiveCamera();
  1049. break;
  1050. }
  1051. camera.name = data.name || '';
  1052. return camera;
  1053. }
  1054. function getCamera( id ) {
  1055. const data = library.cameras[ id ];
  1056. if ( data !== undefined ) {
  1057. return getBuild( data, buildCamera );
  1058. }
  1059. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1060. return null;
  1061. } // light
  1062. function parseLight( xml ) {
  1063. let data = {};
  1064. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1065. const child = xml.childNodes[ i ];
  1066. if ( child.nodeType !== 1 ) continue;
  1067. switch ( child.nodeName ) {
  1068. case 'technique_common':
  1069. data = parseLightTechnique( child );
  1070. break;
  1071. }
  1072. }
  1073. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1074. }
  1075. function parseLightTechnique( xml ) {
  1076. const data = {};
  1077. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1078. const child = xml.childNodes[ i ];
  1079. if ( child.nodeType !== 1 ) continue;
  1080. switch ( child.nodeName ) {
  1081. case 'directional':
  1082. case 'point':
  1083. case 'spot':
  1084. case 'ambient':
  1085. data.technique = child.nodeName;
  1086. data.parameters = parseLightParameters( child );
  1087. }
  1088. }
  1089. return data;
  1090. }
  1091. function parseLightParameters( xml ) {
  1092. const data = {};
  1093. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1094. const child = xml.childNodes[ i ];
  1095. if ( child.nodeType !== 1 ) continue;
  1096. switch ( child.nodeName ) {
  1097. case 'color':
  1098. const array = parseFloats( child.textContent );
  1099. data.color = new THREE.Color().fromArray( array );
  1100. break;
  1101. case 'falloff_angle':
  1102. data.falloffAngle = parseFloat( child.textContent );
  1103. break;
  1104. case 'quadratic_attenuation':
  1105. const f = parseFloat( child.textContent );
  1106. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1107. break;
  1108. }
  1109. }
  1110. return data;
  1111. }
  1112. function buildLight( data ) {
  1113. let light;
  1114. switch ( data.technique ) {
  1115. case 'directional':
  1116. light = new THREE.DirectionalLight();
  1117. break;
  1118. case 'point':
  1119. light = new THREE.PointLight();
  1120. break;
  1121. case 'spot':
  1122. light = new THREE.SpotLight();
  1123. break;
  1124. case 'ambient':
  1125. light = new THREE.AmbientLight();
  1126. break;
  1127. }
  1128. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1129. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1130. return light;
  1131. }
  1132. function getLight( id ) {
  1133. const data = library.lights[ id ];
  1134. if ( data !== undefined ) {
  1135. return getBuild( data, buildLight );
  1136. }
  1137. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1138. return null;
  1139. } // geometry
  1140. function parseGeometry( xml ) {
  1141. const data = {
  1142. name: xml.getAttribute( 'name' ),
  1143. sources: {},
  1144. vertices: {},
  1145. primitives: []
  1146. };
  1147. 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
  1148. if ( mesh === undefined ) return;
  1149. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1150. const child = mesh.childNodes[ i ];
  1151. if ( child.nodeType !== 1 ) continue;
  1152. const id = child.getAttribute( 'id' );
  1153. switch ( child.nodeName ) {
  1154. case 'source':
  1155. data.sources[ id ] = parseSource( child );
  1156. break;
  1157. case 'vertices':
  1158. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1159. data.vertices = parseGeometryVertices( child );
  1160. break;
  1161. case 'polygons':
  1162. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1163. break;
  1164. case 'lines':
  1165. case 'linestrips':
  1166. case 'polylist':
  1167. case 'triangles':
  1168. data.primitives.push( parseGeometryPrimitive( child ) );
  1169. break;
  1170. default:
  1171. console.log( child );
  1172. }
  1173. }
  1174. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1175. }
  1176. function parseSource( xml ) {
  1177. const data = {
  1178. array: [],
  1179. stride: 3
  1180. };
  1181. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1182. const child = xml.childNodes[ i ];
  1183. if ( child.nodeType !== 1 ) continue;
  1184. switch ( child.nodeName ) {
  1185. case 'float_array':
  1186. data.array = parseFloats( child.textContent );
  1187. break;
  1188. case 'Name_array':
  1189. data.array = parseStrings( child.textContent );
  1190. break;
  1191. case 'technique_common':
  1192. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1193. if ( accessor !== undefined ) {
  1194. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1195. }
  1196. break;
  1197. }
  1198. }
  1199. return data;
  1200. }
  1201. function parseGeometryVertices( xml ) {
  1202. const data = {};
  1203. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1204. const child = xml.childNodes[ i ];
  1205. if ( child.nodeType !== 1 ) continue;
  1206. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1207. }
  1208. return data;
  1209. }
  1210. function parseGeometryPrimitive( xml ) {
  1211. const primitive = {
  1212. type: xml.nodeName,
  1213. material: xml.getAttribute( 'material' ),
  1214. count: parseInt( xml.getAttribute( 'count' ) ),
  1215. inputs: {},
  1216. stride: 0,
  1217. hasUV: false
  1218. };
  1219. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1220. const child = xml.childNodes[ i ];
  1221. if ( child.nodeType !== 1 ) continue;
  1222. switch ( child.nodeName ) {
  1223. case 'input':
  1224. const id = parseId( child.getAttribute( 'source' ) );
  1225. const semantic = child.getAttribute( 'semantic' );
  1226. const offset = parseInt( child.getAttribute( 'offset' ) );
  1227. const set = parseInt( child.getAttribute( 'set' ) );
  1228. const inputname = set > 0 ? semantic + set : semantic;
  1229. primitive.inputs[ inputname ] = {
  1230. id: id,
  1231. offset: offset
  1232. };
  1233. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1234. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1235. break;
  1236. case 'vcount':
  1237. primitive.vcount = parseInts( child.textContent );
  1238. break;
  1239. case 'p':
  1240. primitive.p = parseInts( child.textContent );
  1241. break;
  1242. }
  1243. }
  1244. return primitive;
  1245. }
  1246. function groupPrimitives( primitives ) {
  1247. const build = {};
  1248. for ( let i = 0; i < primitives.length; i ++ ) {
  1249. const primitive = primitives[ i ];
  1250. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1251. build[ primitive.type ].push( primitive );
  1252. }
  1253. return build;
  1254. }
  1255. function checkUVCoordinates( primitives ) {
  1256. let count = 0;
  1257. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1258. const primitive = primitives[ i ];
  1259. if ( primitive.hasUV === true ) {
  1260. count ++;
  1261. }
  1262. }
  1263. if ( count > 0 && count < primitives.length ) {
  1264. primitives.uvsNeedsFix = true;
  1265. }
  1266. }
  1267. function buildGeometry( data ) {
  1268. const build = {};
  1269. const sources = data.sources;
  1270. const vertices = data.vertices;
  1271. const primitives = data.primitives;
  1272. if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives
  1273. // first, we group all primitives by their type
  1274. const groupedPrimitives = groupPrimitives( primitives );
  1275. for ( const type in groupedPrimitives ) {
  1276. const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1277. checkUVCoordinates( primitiveType ); // third, create a buffer geometry for each type of primitives
  1278. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1279. }
  1280. return build;
  1281. }
  1282. function buildGeometryType( primitives, sources, vertices ) {
  1283. const build = {};
  1284. const position = {
  1285. array: [],
  1286. stride: 0
  1287. };
  1288. const normal = {
  1289. array: [],
  1290. stride: 0
  1291. };
  1292. const uv = {
  1293. array: [],
  1294. stride: 0
  1295. };
  1296. const uv2 = {
  1297. array: [],
  1298. stride: 0
  1299. };
  1300. const color = {
  1301. array: [],
  1302. stride: 0
  1303. };
  1304. const skinIndex = {
  1305. array: [],
  1306. stride: 4
  1307. };
  1308. const skinWeight = {
  1309. array: [],
  1310. stride: 4
  1311. };
  1312. const geometry = new THREE.BufferGeometry();
  1313. const materialKeys = [];
  1314. let start = 0;
  1315. for ( let p = 0; p < primitives.length; p ++ ) {
  1316. const primitive = primitives[ p ];
  1317. const inputs = primitive.inputs; // groups
  1318. let count = 0;
  1319. switch ( primitive.type ) {
  1320. case 'lines':
  1321. case 'linestrips':
  1322. count = primitive.count * 2;
  1323. break;
  1324. case 'triangles':
  1325. count = primitive.count * 3;
  1326. break;
  1327. case 'polylist':
  1328. for ( let g = 0; g < primitive.count; g ++ ) {
  1329. const vc = primitive.vcount[ g ];
  1330. switch ( vc ) {
  1331. case 3:
  1332. count += 3; // single triangle
  1333. break;
  1334. case 4:
  1335. count += 6; // quad, subdivided into two triangles
  1336. break;
  1337. default:
  1338. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1339. break;
  1340. }
  1341. }
  1342. break;
  1343. default:
  1344. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  1345. }
  1346. geometry.addGroup( start, count, p );
  1347. start += count; // material
  1348. if ( primitive.material ) {
  1349. materialKeys.push( primitive.material );
  1350. } // geometry data
  1351. for ( const name in inputs ) {
  1352. const input = inputs[ name ];
  1353. switch ( name ) {
  1354. case 'VERTEX':
  1355. for ( const key in vertices ) {
  1356. const id = vertices[ key ];
  1357. switch ( key ) {
  1358. case 'POSITION':
  1359. const prevLength = position.array.length;
  1360. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1361. position.stride = sources[ id ].stride;
  1362. if ( sources.skinWeights && sources.skinIndices ) {
  1363. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1364. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1365. } // see #3803
  1366. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1367. const count = ( position.array.length - prevLength ) / position.stride;
  1368. for ( let i = 0; i < count; i ++ ) {
  1369. // fill missing uv coordinates
  1370. uv.array.push( 0, 0 );
  1371. }
  1372. }
  1373. break;
  1374. case 'NORMAL':
  1375. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1376. normal.stride = sources[ id ].stride;
  1377. break;
  1378. case 'COLOR':
  1379. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1380. color.stride = sources[ id ].stride;
  1381. break;
  1382. case 'TEXCOORD':
  1383. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1384. uv.stride = sources[ id ].stride;
  1385. break;
  1386. case 'TEXCOORD1':
  1387. buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
  1388. uv.stride = sources[ id ].stride;
  1389. break;
  1390. default:
  1391. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1392. }
  1393. }
  1394. break;
  1395. case 'NORMAL':
  1396. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1397. normal.stride = sources[ input.id ].stride;
  1398. break;
  1399. case 'COLOR':
  1400. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  1401. color.stride = sources[ input.id ].stride;
  1402. break;
  1403. case 'TEXCOORD':
  1404. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1405. uv.stride = sources[ input.id ].stride;
  1406. break;
  1407. case 'TEXCOORD1':
  1408. buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
  1409. uv2.stride = sources[ input.id ].stride;
  1410. break;
  1411. }
  1412. }
  1413. } // build geometry
  1414. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  1415. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  1416. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  1417. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  1418. if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new THREE.Float32BufferAttribute( uv2.array, uv2.stride ) );
  1419. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1420. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1421. build.data = geometry;
  1422. build.type = primitives[ 0 ].type;
  1423. build.materialKeys = materialKeys;
  1424. return build;
  1425. }
  1426. function buildGeometryData( primitive, source, offset, array ) {
  1427. const indices = primitive.p;
  1428. const stride = primitive.stride;
  1429. const vcount = primitive.vcount;
  1430. function pushVector( i ) {
  1431. let index = indices[ i + offset ] * sourceStride;
  1432. const length = index + sourceStride;
  1433. for ( ; index < length; index ++ ) {
  1434. array.push( sourceArray[ index ] );
  1435. }
  1436. }
  1437. const sourceArray = source.array;
  1438. const sourceStride = source.stride;
  1439. if ( primitive.vcount !== undefined ) {
  1440. let index = 0;
  1441. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1442. const count = vcount[ i ];
  1443. if ( count === 4 ) {
  1444. const a = index + stride * 0;
  1445. const b = index + stride * 1;
  1446. const c = index + stride * 2;
  1447. const d = index + stride * 3;
  1448. pushVector( a );
  1449. pushVector( b );
  1450. pushVector( d );
  1451. pushVector( b );
  1452. pushVector( c );
  1453. pushVector( d );
  1454. } else if ( count === 3 ) {
  1455. const a = index + stride * 0;
  1456. const b = index + stride * 1;
  1457. const c = index + stride * 2;
  1458. pushVector( a );
  1459. pushVector( b );
  1460. pushVector( c );
  1461. } else if ( count > 4 ) {
  1462. for ( let k = 1, kl = count - 2; k <= kl; k ++ ) {
  1463. const a = index + stride * 0;
  1464. const b = index + stride * k;
  1465. const c = index + stride * ( k + 1 );
  1466. pushVector( a );
  1467. pushVector( b );
  1468. pushVector( c );
  1469. }
  1470. }
  1471. index += stride * count;
  1472. }
  1473. } else {
  1474. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1475. pushVector( i );
  1476. }
  1477. }
  1478. }
  1479. function getGeometry( id ) {
  1480. return getBuild( library.geometries[ id ], buildGeometry );
  1481. } // kinematics
  1482. function parseKinematicsModel( xml ) {
  1483. const data = {
  1484. name: xml.getAttribute( 'name' ) || '',
  1485. joints: {},
  1486. links: []
  1487. };
  1488. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1489. const child = xml.childNodes[ i ];
  1490. if ( child.nodeType !== 1 ) continue;
  1491. switch ( child.nodeName ) {
  1492. case 'technique_common':
  1493. parseKinematicsTechniqueCommon( child, data );
  1494. break;
  1495. }
  1496. }
  1497. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1498. }
  1499. function buildKinematicsModel( data ) {
  1500. if ( data.build !== undefined ) return data.build;
  1501. return data;
  1502. }
  1503. function getKinematicsModel( id ) {
  1504. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1505. }
  1506. function parseKinematicsTechniqueCommon( xml, data ) {
  1507. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1508. const child = xml.childNodes[ i ];
  1509. if ( child.nodeType !== 1 ) continue;
  1510. switch ( child.nodeName ) {
  1511. case 'joint':
  1512. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1513. break;
  1514. case 'link':
  1515. data.links.push( parseKinematicsLink( child ) );
  1516. break;
  1517. }
  1518. }
  1519. }
  1520. function parseKinematicsJoint( xml ) {
  1521. let data;
  1522. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1523. const child = xml.childNodes[ i ];
  1524. if ( child.nodeType !== 1 ) continue;
  1525. switch ( child.nodeName ) {
  1526. case 'prismatic':
  1527. case 'revolute':
  1528. data = parseKinematicsJointParameter( child );
  1529. break;
  1530. }
  1531. }
  1532. return data;
  1533. }
  1534. function parseKinematicsJointParameter( xml ) {
  1535. const data = {
  1536. sid: xml.getAttribute( 'sid' ),
  1537. name: xml.getAttribute( 'name' ) || '',
  1538. axis: new THREE.Vector3(),
  1539. limits: {
  1540. min: 0,
  1541. max: 0
  1542. },
  1543. type: xml.nodeName,
  1544. static: false,
  1545. zeroPosition: 0,
  1546. middlePosition: 0
  1547. };
  1548. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1549. const child = xml.childNodes[ i ];
  1550. if ( child.nodeType !== 1 ) continue;
  1551. switch ( child.nodeName ) {
  1552. case 'axis':
  1553. const array = parseFloats( child.textContent );
  1554. data.axis.fromArray( array );
  1555. break;
  1556. case 'limits':
  1557. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1558. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1559. data.limits.max = parseFloat( max.textContent );
  1560. data.limits.min = parseFloat( min.textContent );
  1561. break;
  1562. }
  1563. } // if min is equal to or greater than max, consider the joint static
  1564. if ( data.limits.min >= data.limits.max ) {
  1565. data.static = true;
  1566. } // calculate middle position
  1567. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1568. return data;
  1569. }
  1570. function parseKinematicsLink( xml ) {
  1571. const data = {
  1572. sid: xml.getAttribute( 'sid' ),
  1573. name: xml.getAttribute( 'name' ) || '',
  1574. attachments: [],
  1575. transforms: []
  1576. };
  1577. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1578. const child = xml.childNodes[ i ];
  1579. if ( child.nodeType !== 1 ) continue;
  1580. switch ( child.nodeName ) {
  1581. case 'attachment_full':
  1582. data.attachments.push( parseKinematicsAttachment( child ) );
  1583. break;
  1584. case 'matrix':
  1585. case 'translate':
  1586. case 'rotate':
  1587. data.transforms.push( parseKinematicsTransform( child ) );
  1588. break;
  1589. }
  1590. }
  1591. return data;
  1592. }
  1593. function parseKinematicsAttachment( xml ) {
  1594. const data = {
  1595. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1596. transforms: [],
  1597. links: []
  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 'link':
  1604. data.links.push( parseKinematicsLink( child ) );
  1605. break;
  1606. case 'matrix':
  1607. case 'translate':
  1608. case 'rotate':
  1609. data.transforms.push( parseKinematicsTransform( child ) );
  1610. break;
  1611. }
  1612. }
  1613. return data;
  1614. }
  1615. function parseKinematicsTransform( xml ) {
  1616. const data = {
  1617. type: xml.nodeName
  1618. };
  1619. const array = parseFloats( xml.textContent );
  1620. switch ( data.type ) {
  1621. case 'matrix':
  1622. data.obj = new THREE.Matrix4();
  1623. data.obj.fromArray( array ).transpose();
  1624. break;
  1625. case 'translate':
  1626. data.obj = new THREE.Vector3();
  1627. data.obj.fromArray( array );
  1628. break;
  1629. case 'rotate':
  1630. data.obj = new THREE.Vector3();
  1631. data.obj.fromArray( array );
  1632. data.angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1633. break;
  1634. }
  1635. return data;
  1636. } // physics
  1637. function parsePhysicsModel( xml ) {
  1638. const data = {
  1639. name: xml.getAttribute( 'name' ) || '',
  1640. rigidBodies: {}
  1641. };
  1642. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1643. const child = xml.childNodes[ i ];
  1644. if ( child.nodeType !== 1 ) continue;
  1645. switch ( child.nodeName ) {
  1646. case 'rigid_body':
  1647. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1648. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1649. break;
  1650. }
  1651. }
  1652. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1653. }
  1654. function parsePhysicsRigidBody( xml, data ) {
  1655. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1656. const child = xml.childNodes[ i ];
  1657. if ( child.nodeType !== 1 ) continue;
  1658. switch ( child.nodeName ) {
  1659. case 'technique_common':
  1660. parsePhysicsTechniqueCommon( child, data );
  1661. break;
  1662. }
  1663. }
  1664. }
  1665. function parsePhysicsTechniqueCommon( xml, data ) {
  1666. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1667. const child = xml.childNodes[ i ];
  1668. if ( child.nodeType !== 1 ) continue;
  1669. switch ( child.nodeName ) {
  1670. case 'inertia':
  1671. data.inertia = parseFloats( child.textContent );
  1672. break;
  1673. case 'mass':
  1674. data.mass = parseFloats( child.textContent )[ 0 ];
  1675. break;
  1676. }
  1677. }
  1678. } // scene
  1679. function parseKinematicsScene( xml ) {
  1680. const data = {
  1681. bindJointAxis: []
  1682. };
  1683. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1684. const child = xml.childNodes[ i ];
  1685. if ( child.nodeType !== 1 ) continue;
  1686. switch ( child.nodeName ) {
  1687. case 'bind_joint_axis':
  1688. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1689. break;
  1690. }
  1691. }
  1692. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1693. }
  1694. function parseKinematicsBindJointAxis( xml ) {
  1695. const data = {
  1696. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1697. };
  1698. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1699. const child = xml.childNodes[ i ];
  1700. if ( child.nodeType !== 1 ) continue;
  1701. switch ( child.nodeName ) {
  1702. case 'axis':
  1703. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1704. data.axis = param.textContent;
  1705. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1706. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  1707. break;
  1708. }
  1709. }
  1710. return data;
  1711. }
  1712. function buildKinematicsScene( data ) {
  1713. if ( data.build !== undefined ) return data.build;
  1714. return data;
  1715. }
  1716. function getKinematicsScene( id ) {
  1717. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1718. }
  1719. function setupKinematics() {
  1720. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1721. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1722. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1723. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1724. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1725. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1726. const visualScene = getVisualScene( visualSceneId );
  1727. const bindJointAxis = kinematicsScene.bindJointAxis;
  1728. const jointMap = {};
  1729. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1730. const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1731. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1732. if ( targetElement ) {
  1733. // get the parent of the transform element
  1734. const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene
  1735. connect( axis.jointIndex, parentVisualElement );
  1736. }
  1737. }
  1738. function connect( jointIndex, visualElement ) {
  1739. const visualElementName = visualElement.getAttribute( 'name' );
  1740. const joint = kinematicsModel.joints[ jointIndex ];
  1741. visualScene.traverse( function ( object ) {
  1742. if ( object.name === visualElementName ) {
  1743. jointMap[ jointIndex ] = {
  1744. object: object,
  1745. transforms: buildTransformList( visualElement ),
  1746. joint: joint,
  1747. position: joint.zeroPosition
  1748. };
  1749. }
  1750. } );
  1751. }
  1752. const m0 = new THREE.Matrix4();
  1753. kinematics = {
  1754. joints: kinematicsModel && kinematicsModel.joints,
  1755. getJointValue: function ( jointIndex ) {
  1756. const jointData = jointMap[ jointIndex ];
  1757. if ( jointData ) {
  1758. return jointData.position;
  1759. } else {
  1760. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1761. }
  1762. },
  1763. setJointValue: function ( jointIndex, value ) {
  1764. const jointData = jointMap[ jointIndex ];
  1765. if ( jointData ) {
  1766. const joint = jointData.joint;
  1767. if ( value > joint.limits.max || value < joint.limits.min ) {
  1768. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1769. } else if ( joint.static ) {
  1770. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1771. } else {
  1772. const object = jointData.object;
  1773. const axis = joint.axis;
  1774. const transforms = jointData.transforms;
  1775. matrix.identity(); // each update, we have to apply all transforms in the correct order
  1776. for ( let i = 0; i < transforms.length; i ++ ) {
  1777. const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value
  1778. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1779. switch ( joint.type ) {
  1780. case 'revolute':
  1781. matrix.multiply( m0.makeRotationAxis( axis, THREE.MathUtils.degToRad( value ) ) );
  1782. break;
  1783. case 'prismatic':
  1784. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1785. break;
  1786. default:
  1787. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1788. break;
  1789. }
  1790. } else {
  1791. switch ( transform.type ) {
  1792. case 'matrix':
  1793. matrix.multiply( transform.obj );
  1794. break;
  1795. case 'translate':
  1796. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1797. break;
  1798. case 'scale':
  1799. matrix.scale( transform.obj );
  1800. break;
  1801. case 'rotate':
  1802. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1803. break;
  1804. }
  1805. }
  1806. }
  1807. object.matrix.copy( matrix );
  1808. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1809. jointMap[ jointIndex ].position = value;
  1810. }
  1811. } else {
  1812. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1813. }
  1814. }
  1815. };
  1816. }
  1817. function buildTransformList( node ) {
  1818. const transforms = [];
  1819. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1820. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1821. const child = xml.childNodes[ i ];
  1822. if ( child.nodeType !== 1 ) continue;
  1823. let array, vector;
  1824. switch ( child.nodeName ) {
  1825. case 'matrix':
  1826. array = parseFloats( child.textContent );
  1827. const matrix = new THREE.Matrix4().fromArray( array ).transpose();
  1828. transforms.push( {
  1829. sid: child.getAttribute( 'sid' ),
  1830. type: child.nodeName,
  1831. obj: matrix
  1832. } );
  1833. break;
  1834. case 'translate':
  1835. case 'scale':
  1836. array = parseFloats( child.textContent );
  1837. vector = new THREE.Vector3().fromArray( array );
  1838. transforms.push( {
  1839. sid: child.getAttribute( 'sid' ),
  1840. type: child.nodeName,
  1841. obj: vector
  1842. } );
  1843. break;
  1844. case 'rotate':
  1845. array = parseFloats( child.textContent );
  1846. vector = new THREE.Vector3().fromArray( array );
  1847. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1848. transforms.push( {
  1849. sid: child.getAttribute( 'sid' ),
  1850. type: child.nodeName,
  1851. obj: vector,
  1852. angle: angle
  1853. } );
  1854. break;
  1855. }
  1856. }
  1857. return transforms;
  1858. } // nodes
  1859. function prepareNodes( xml ) {
  1860. const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes
  1861. for ( let i = 0; i < elements.length; i ++ ) {
  1862. const element = elements[ i ];
  1863. if ( element.hasAttribute( 'id' ) === false ) {
  1864. element.setAttribute( 'id', generateId() );
  1865. }
  1866. }
  1867. }
  1868. const matrix = new THREE.Matrix4();
  1869. const vector = new THREE.Vector3();
  1870. function parseNode( xml ) {
  1871. const data = {
  1872. name: xml.getAttribute( 'name' ) || '',
  1873. type: xml.getAttribute( 'type' ),
  1874. id: xml.getAttribute( 'id' ),
  1875. sid: xml.getAttribute( 'sid' ),
  1876. matrix: new THREE.Matrix4(),
  1877. nodes: [],
  1878. instanceCameras: [],
  1879. instanceControllers: [],
  1880. instanceLights: [],
  1881. instanceGeometries: [],
  1882. instanceNodes: [],
  1883. transforms: {}
  1884. };
  1885. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1886. const child = xml.childNodes[ i ];
  1887. if ( child.nodeType !== 1 ) continue;
  1888. let array;
  1889. switch ( child.nodeName ) {
  1890. case 'node':
  1891. data.nodes.push( child.getAttribute( 'id' ) );
  1892. parseNode( child );
  1893. break;
  1894. case 'instance_camera':
  1895. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  1896. break;
  1897. case 'instance_controller':
  1898. data.instanceControllers.push( parseNodeInstance( child ) );
  1899. break;
  1900. case 'instance_light':
  1901. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  1902. break;
  1903. case 'instance_geometry':
  1904. data.instanceGeometries.push( parseNodeInstance( child ) );
  1905. break;
  1906. case 'instance_node':
  1907. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  1908. break;
  1909. case 'matrix':
  1910. array = parseFloats( child.textContent );
  1911. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  1912. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1913. break;
  1914. case 'translate':
  1915. array = parseFloats( child.textContent );
  1916. vector.fromArray( array );
  1917. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  1918. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1919. break;
  1920. case 'rotate':
  1921. array = parseFloats( child.textContent );
  1922. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1923. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  1924. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1925. break;
  1926. case 'scale':
  1927. array = parseFloats( child.textContent );
  1928. data.matrix.scale( vector.fromArray( array ) );
  1929. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1930. break;
  1931. case 'extra':
  1932. break;
  1933. default:
  1934. console.log( child );
  1935. }
  1936. }
  1937. if ( hasNode( data.id ) ) {
  1938. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  1939. } else {
  1940. library.nodes[ data.id ] = data;
  1941. }
  1942. return data;
  1943. }
  1944. function parseNodeInstance( xml ) {
  1945. const data = {
  1946. id: parseId( xml.getAttribute( 'url' ) ),
  1947. materials: {},
  1948. skeletons: []
  1949. };
  1950. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1951. const child = xml.childNodes[ i ];
  1952. switch ( child.nodeName ) {
  1953. case 'bind_material':
  1954. const instances = child.getElementsByTagName( 'instance_material' );
  1955. for ( let j = 0; j < instances.length; j ++ ) {
  1956. const instance = instances[ j ];
  1957. const symbol = instance.getAttribute( 'symbol' );
  1958. const target = instance.getAttribute( 'target' );
  1959. data.materials[ symbol ] = parseId( target );
  1960. }
  1961. break;
  1962. case 'skeleton':
  1963. data.skeletons.push( parseId( child.textContent ) );
  1964. break;
  1965. default:
  1966. break;
  1967. }
  1968. }
  1969. return data;
  1970. }
  1971. function buildSkeleton( skeletons, joints ) {
  1972. const boneData = [];
  1973. const sortedBoneData = [];
  1974. let i, j, data; // a skeleton can have multiple root bones. collada expresses this
  1975. // situtation with multiple "skeleton" tags per controller instance
  1976. for ( i = 0; i < skeletons.length; i ++ ) {
  1977. const skeleton = skeletons[ i ];
  1978. let root;
  1979. if ( hasNode( skeleton ) ) {
  1980. root = getNode( skeleton );
  1981. buildBoneHierarchy( root, joints, boneData );
  1982. } else if ( hasVisualScene( skeleton ) ) {
  1983. // handle case where the skeleton refers to the visual scene (#13335)
  1984. const visualScene = library.visualScenes[ skeleton ];
  1985. const children = visualScene.children;
  1986. for ( let j = 0; j < children.length; j ++ ) {
  1987. const child = children[ j ];
  1988. if ( child.type === 'JOINT' ) {
  1989. const root = getNode( child.id );
  1990. buildBoneHierarchy( root, joints, boneData );
  1991. }
  1992. }
  1993. } else {
  1994. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  1995. }
  1996. } // sort bone data (the order is defined in the corresponding controller)
  1997. for ( i = 0; i < joints.length; i ++ ) {
  1998. for ( j = 0; j < boneData.length; j ++ ) {
  1999. data = boneData[ j ];
  2000. if ( data.bone.name === joints[ i ].name ) {
  2001. sortedBoneData[ i ] = data;
  2002. data.processed = true;
  2003. break;
  2004. }
  2005. }
  2006. } // add unprocessed bone data at the end of the list
  2007. for ( i = 0; i < boneData.length; i ++ ) {
  2008. data = boneData[ i ];
  2009. if ( data.processed === false ) {
  2010. sortedBoneData.push( data );
  2011. data.processed = true;
  2012. }
  2013. } // setup arrays for skeleton creation
  2014. const bones = [];
  2015. const boneInverses = [];
  2016. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2017. data = sortedBoneData[ i ];
  2018. bones.push( data.bone );
  2019. boneInverses.push( data.boneInverse );
  2020. }
  2021. return new THREE.Skeleton( bones, boneInverses );
  2022. }
  2023. function buildBoneHierarchy( root, joints, boneData ) {
  2024. // setup bone data from visual scene
  2025. root.traverse( function ( object ) {
  2026. if ( object.isBone === true ) {
  2027. let boneInverse; // retrieve the boneInverse from the controller data
  2028. for ( let i = 0; i < joints.length; i ++ ) {
  2029. const joint = joints[ i ];
  2030. if ( joint.name === object.name ) {
  2031. boneInverse = joint.boneInverse;
  2032. break;
  2033. }
  2034. }
  2035. if ( boneInverse === undefined ) {
  2036. // Unfortunately, there can be joints in the visual scene that are not part of the
  2037. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2038. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2039. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2040. // ensure a correct animation of the model.
  2041. boneInverse = new THREE.Matrix4();
  2042. }
  2043. boneData.push( {
  2044. bone: object,
  2045. boneInverse: boneInverse,
  2046. processed: false
  2047. } );
  2048. }
  2049. } );
  2050. }
  2051. function buildNode( data ) {
  2052. const objects = [];
  2053. const matrix = data.matrix;
  2054. const nodes = data.nodes;
  2055. const type = data.type;
  2056. const instanceCameras = data.instanceCameras;
  2057. const instanceControllers = data.instanceControllers;
  2058. const instanceLights = data.instanceLights;
  2059. const instanceGeometries = data.instanceGeometries;
  2060. const instanceNodes = data.instanceNodes; // nodes
  2061. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2062. objects.push( getNode( nodes[ i ] ) );
  2063. } // instance cameras
  2064. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2065. const instanceCamera = getCamera( instanceCameras[ i ] );
  2066. if ( instanceCamera !== null ) {
  2067. objects.push( instanceCamera.clone() );
  2068. }
  2069. } // instance controllers
  2070. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2071. const instance = instanceControllers[ i ];
  2072. const controller = getController( instance.id );
  2073. const geometries = getGeometry( controller.id );
  2074. const newObjects = buildObjects( geometries, instance.materials );
  2075. const skeletons = instance.skeletons;
  2076. const joints = controller.skin.joints;
  2077. const skeleton = buildSkeleton( skeletons, joints );
  2078. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2079. const object = newObjects[ j ];
  2080. if ( object.isSkinnedMesh ) {
  2081. object.bind( skeleton, controller.skin.bindMatrix );
  2082. object.normalizeSkinWeights();
  2083. }
  2084. objects.push( object );
  2085. }
  2086. } // instance lights
  2087. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2088. const instanceLight = getLight( instanceLights[ i ] );
  2089. if ( instanceLight !== null ) {
  2090. objects.push( instanceLight.clone() );
  2091. }
  2092. } // instance geometries
  2093. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2094. const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds.
  2095. // this is the case when primitives are combined like triangles and lines
  2096. const geometries = getGeometry( instance.id );
  2097. const newObjects = buildObjects( geometries, instance.materials );
  2098. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2099. objects.push( newObjects[ j ] );
  2100. }
  2101. } // instance nodes
  2102. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2103. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2104. }
  2105. let object;
  2106. if ( nodes.length === 0 && objects.length === 1 ) {
  2107. object = objects[ 0 ];
  2108. } else {
  2109. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2110. for ( let i = 0; i < objects.length; i ++ ) {
  2111. object.add( objects[ i ] );
  2112. }
  2113. }
  2114. object.name = type === 'JOINT' ? data.sid : data.name;
  2115. object.matrix.copy( matrix );
  2116. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2117. return object;
  2118. }
  2119. const fallbackMaterial = new THREE.MeshBasicMaterial( {
  2120. color: 0xff00ff
  2121. } );
  2122. function resolveMaterialBinding( keys, instanceMaterials ) {
  2123. const materials = [];
  2124. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2125. const id = instanceMaterials[ keys[ i ] ];
  2126. if ( id === undefined ) {
  2127. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2128. materials.push( fallbackMaterial );
  2129. } else {
  2130. materials.push( getMaterial( id ) );
  2131. }
  2132. }
  2133. return materials;
  2134. }
  2135. function buildObjects( geometries, instanceMaterials ) {
  2136. const objects = [];
  2137. for ( const type in geometries ) {
  2138. const geometry = geometries[ type ];
  2139. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined
  2140. if ( materials.length === 0 ) {
  2141. if ( type === 'lines' || type === 'linestrips' ) {
  2142. materials.push( new THREE.LineBasicMaterial() );
  2143. } else {
  2144. materials.push( new THREE.MeshPhongMaterial() );
  2145. }
  2146. } // regard skinning
  2147. const skinning = geometry.data.attributes.skinIndex !== undefined;
  2148. if ( skinning ) {
  2149. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  2150. materials[ i ].skinning = true;
  2151. }
  2152. } // choose between a single or multi materials (material array)
  2153. const material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object
  2154. let object;
  2155. switch ( type ) {
  2156. case 'lines':
  2157. object = new THREE.LineSegments( geometry.data, material );
  2158. break;
  2159. case 'linestrips':
  2160. object = new THREE.Line( geometry.data, material );
  2161. break;
  2162. case 'triangles':
  2163. case 'polylist':
  2164. if ( skinning ) {
  2165. object = new THREE.SkinnedMesh( geometry.data, material );
  2166. } else {
  2167. object = new THREE.Mesh( geometry.data, material );
  2168. }
  2169. break;
  2170. }
  2171. objects.push( object );
  2172. }
  2173. return objects;
  2174. }
  2175. function hasNode( id ) {
  2176. return library.nodes[ id ] !== undefined;
  2177. }
  2178. function getNode( id ) {
  2179. return getBuild( library.nodes[ id ], buildNode );
  2180. } // visual scenes
  2181. function parseVisualScene( xml ) {
  2182. const data = {
  2183. name: xml.getAttribute( 'name' ),
  2184. children: []
  2185. };
  2186. prepareNodes( xml );
  2187. const elements = getElementsByTagName( xml, 'node' );
  2188. for ( let i = 0; i < elements.length; i ++ ) {
  2189. data.children.push( parseNode( elements[ i ] ) );
  2190. }
  2191. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2192. }
  2193. function buildVisualScene( data ) {
  2194. const group = new THREE.Group();
  2195. group.name = data.name;
  2196. const children = data.children;
  2197. for ( let i = 0; i < children.length; i ++ ) {
  2198. const child = children[ i ];
  2199. group.add( getNode( child.id ) );
  2200. }
  2201. return group;
  2202. }
  2203. function hasVisualScene( id ) {
  2204. return library.visualScenes[ id ] !== undefined;
  2205. }
  2206. function getVisualScene( id ) {
  2207. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2208. } // scenes
  2209. function parseScene( xml ) {
  2210. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2211. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2212. }
  2213. function setupAnimations() {
  2214. const clips = library.clips;
  2215. if ( isEmpty( clips ) === true ) {
  2216. if ( isEmpty( library.animations ) === false ) {
  2217. // if there are animations but no clips, we create a default clip for playback
  2218. const tracks = [];
  2219. for ( const id in library.animations ) {
  2220. const animationTracks = getAnimation( id );
  2221. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2222. tracks.push( animationTracks[ i ] );
  2223. }
  2224. }
  2225. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  2226. }
  2227. } else {
  2228. for ( const id in clips ) {
  2229. animations.push( getAnimationClip( id ) );
  2230. }
  2231. }
  2232. } // convert the parser error element into text with each child elements text
  2233. // separated by new lines.
  2234. function parserErrorToText( parserError ) {
  2235. let result = '';
  2236. const stack = [ parserError ];
  2237. while ( stack.length ) {
  2238. const node = stack.shift();
  2239. if ( node.nodeType === Node.TEXT_NODE ) {
  2240. result += node.textContent;
  2241. } else {
  2242. result += '\n';
  2243. stack.push.apply( stack, node.childNodes );
  2244. }
  2245. }
  2246. return result.trim();
  2247. }
  2248. if ( text.length === 0 ) {
  2249. return {
  2250. scene: new THREE.Scene()
  2251. };
  2252. }
  2253. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2254. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2255. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2256. if ( parserError !== undefined ) {
  2257. // Chrome will return parser error with a div in it
  2258. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2259. let errorText;
  2260. if ( errorElement ) {
  2261. errorText = errorElement.textContent;
  2262. } else {
  2263. errorText = parserErrorToText( parserError );
  2264. }
  2265. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2266. return null;
  2267. } // metadata
  2268. const version = collada.getAttribute( 'version' );
  2269. console.log( 'THREE.ColladaLoader: File version', version );
  2270. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2271. const textureLoader = new THREE.TextureLoader( this.manager );
  2272. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2273. let tgaLoader;
  2274. if ( THREE.TGALoader ) {
  2275. tgaLoader = new THREE.TGALoader( this.manager );
  2276. tgaLoader.setPath( this.resourcePath || path );
  2277. } //
  2278. const animations = [];
  2279. let kinematics = {};
  2280. let count = 0; //
  2281. const library = {
  2282. animations: {},
  2283. clips: {},
  2284. controllers: {},
  2285. images: {},
  2286. effects: {},
  2287. materials: {},
  2288. cameras: {},
  2289. lights: {},
  2290. geometries: {},
  2291. nodes: {},
  2292. visualScenes: {},
  2293. kinematicsModels: {},
  2294. physicsModels: {},
  2295. kinematicsScenes: {}
  2296. };
  2297. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2298. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2299. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2300. parseLibrary( collada, 'library_images', 'image', parseImage );
  2301. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2302. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2303. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2304. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2305. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2306. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2307. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2308. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2309. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2310. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2311. buildLibrary( library.animations, buildAnimation );
  2312. buildLibrary( library.clips, buildAnimationClip );
  2313. buildLibrary( library.controllers, buildController );
  2314. buildLibrary( library.images, buildImage );
  2315. buildLibrary( library.effects, buildEffect );
  2316. buildLibrary( library.materials, buildMaterial );
  2317. buildLibrary( library.cameras, buildCamera );
  2318. buildLibrary( library.lights, buildLight );
  2319. buildLibrary( library.geometries, buildGeometry );
  2320. buildLibrary( library.visualScenes, buildVisualScene );
  2321. setupAnimations();
  2322. setupKinematics();
  2323. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2324. scene.animations = animations;
  2325. if ( asset.upAxis === 'Z_UP' ) {
  2326. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  2327. }
  2328. scene.scale.multiplyScalar( asset.unit );
  2329. return {
  2330. get animations() {
  2331. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2332. return animations;
  2333. },
  2334. kinematics: kinematics,
  2335. library: library,
  2336. scene: scene
  2337. };
  2338. }
  2339. }
  2340. THREE.ColladaLoader = ColladaLoader;
  2341. } )();