ColladaLoader.js 80 KB

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