ColladaLoader.js 80 KB

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