ColladaComposer.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. import {
  2. AmbientLight,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. ClampToEdgeWrapping,
  7. Color,
  8. ColorManagement,
  9. DirectionalLight,
  10. DoubleSide,
  11. Float32BufferAttribute,
  12. FrontSide,
  13. Group,
  14. Line,
  15. LineBasicMaterial,
  16. LineSegments,
  17. Loader,
  18. MathUtils,
  19. Matrix4,
  20. Mesh,
  21. MeshBasicMaterial,
  22. MeshLambertMaterial,
  23. MeshPhongMaterial,
  24. OrthographicCamera,
  25. PerspectiveCamera,
  26. PointLight,
  27. Quaternion,
  28. QuaternionKeyframeTrack,
  29. RepeatWrapping,
  30. Skeleton,
  31. SkinnedMesh,
  32. SpotLight,
  33. Vector2,
  34. Vector3,
  35. VectorKeyframeTrack,
  36. SRGBColorSpace
  37. } from 'three';
  38. import { getElementsByTagName, parseFloats } from './ColladaParser.js';
  39. /**
  40. * ColladaComposer converts parsed library data into Three.js objects.
  41. */
  42. class ColladaComposer {
  43. constructor( library, collada, textureLoader, tgaLoader ) {
  44. this.library = library;
  45. this.collada = collada;
  46. this.textureLoader = textureLoader;
  47. this.tgaLoader = tgaLoader;
  48. this.tempColor = new Color();
  49. this.animations = [];
  50. this.kinematics = {};
  51. // Reusable objects for animation
  52. this.position = new Vector3();
  53. this.scale = new Vector3();
  54. this.quaternion = new Quaternion();
  55. this.matrix = new Matrix4();
  56. }
  57. compose() {
  58. const library = this.library;
  59. this.buildLibrary( library.animations, this.buildAnimation.bind( this ) );
  60. this.buildLibrary( library.clips, this.buildAnimationClip.bind( this ) );
  61. this.buildLibrary( library.controllers, this.buildController.bind( this ) );
  62. this.buildLibrary( library.images, this.buildImage.bind( this ) );
  63. this.buildLibrary( library.effects, this.buildEffect.bind( this ) );
  64. this.buildLibrary( library.materials, this.buildMaterial.bind( this ) );
  65. this.buildLibrary( library.cameras, this.buildCamera.bind( this ) );
  66. this.buildLibrary( library.lights, this.buildLight.bind( this ) );
  67. this.buildLibrary( library.geometries, this.buildGeometry.bind( this ) );
  68. this.buildLibrary( library.visualScenes, this.buildVisualScene.bind( this ) );
  69. this.setupAnimations();
  70. this.setupKinematics();
  71. const scene = this.parseScene( getElementsByTagName( this.collada, 'scene' )[ 0 ] );
  72. scene.animations = this.animations;
  73. return {
  74. scene: scene,
  75. animations: this.animations,
  76. kinematics: this.kinematics
  77. };
  78. }
  79. buildLibrary( data, builder ) {
  80. for ( const name in data ) {
  81. const object = data[ name ];
  82. object.build = builder( data[ name ] );
  83. }
  84. }
  85. // get
  86. getBuild( data, builder ) {
  87. if ( data.build !== undefined ) return data.build;
  88. data.build = builder( data );
  89. return data.build;
  90. }
  91. isEmpty( object ) {
  92. return Object.keys( object ).length === 0;
  93. }
  94. // animation
  95. buildAnimation( data ) {
  96. const tracks = [];
  97. const channels = data.channels;
  98. const samplers = data.samplers;
  99. const sources = data.sources;
  100. for ( const target in channels ) {
  101. if ( channels.hasOwnProperty( target ) ) {
  102. const channel = channels[ target ];
  103. const sampler = samplers[ channel.sampler ];
  104. const inputId = sampler.inputs.INPUT;
  105. const outputId = sampler.inputs.OUTPUT;
  106. const inputSource = sources[ inputId ];
  107. const outputSource = sources[ outputId ];
  108. const animation = this.buildAnimationChannel( channel, inputSource, outputSource );
  109. this.createKeyframeTracks( animation, tracks );
  110. }
  111. }
  112. return tracks;
  113. }
  114. getAnimation( id ) {
  115. return this.getBuild( this.library.animations[ id ], this.buildAnimation.bind( this ) );
  116. }
  117. buildAnimationChannel( channel, inputSource, outputSource ) {
  118. const node = this.library.nodes[ channel.id ];
  119. const object3D = this.getNode( node.id );
  120. const transform = node.transforms[ channel.sid ];
  121. const defaultMatrix = node.matrix.clone().transpose();
  122. let time, stride;
  123. let i, il, j, jl;
  124. const data = {};
  125. // the collada spec allows the animation of data in various ways.
  126. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  127. switch ( transform ) {
  128. case 'matrix':
  129. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  130. time = inputSource.array[ i ];
  131. stride = i * outputSource.stride;
  132. if ( data[ time ] === undefined ) data[ time ] = {};
  133. if ( channel.arraySyntax === true ) {
  134. const value = outputSource.array[ stride ];
  135. const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  136. data[ time ][ index ] = value;
  137. } else {
  138. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  139. data[ time ][ j ] = outputSource.array[ stride + j ];
  140. }
  141. }
  142. }
  143. break;
  144. case 'translate':
  145. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  146. break;
  147. case 'rotate':
  148. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  149. break;
  150. case 'scale':
  151. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  152. break;
  153. }
  154. const keyframes = this.prepareAnimationData( data, defaultMatrix );
  155. const animation = {
  156. name: object3D.uuid,
  157. keyframes: keyframes
  158. };
  159. return animation;
  160. }
  161. prepareAnimationData( data, defaultMatrix ) {
  162. const keyframes = [];
  163. // transfer data into a sortable array
  164. for ( const time in data ) {
  165. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  166. }
  167. // ensure keyframes are sorted by time
  168. keyframes.sort( ascending );
  169. // now we clean up all animation data, so we can use them for keyframe tracks
  170. for ( let i = 0; i < 16; i ++ ) {
  171. this.transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  172. }
  173. return keyframes;
  174. // array sort function
  175. function ascending( a, b ) {
  176. return a.time - b.time;
  177. }
  178. }
  179. createKeyframeTracks( animation, tracks ) {
  180. const keyframes = animation.keyframes;
  181. const name = animation.name;
  182. const times = [];
  183. const positionData = [];
  184. const quaternionData = [];
  185. const scaleData = [];
  186. const position = this.position;
  187. const quaternion = this.quaternion;
  188. const scale = this.scale;
  189. const matrix = this.matrix;
  190. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  191. const keyframe = keyframes[ i ];
  192. const time = keyframe.time;
  193. const value = keyframe.value;
  194. matrix.fromArray( value ).transpose();
  195. matrix.decompose( position, quaternion, scale );
  196. times.push( time );
  197. positionData.push( position.x, position.y, position.z );
  198. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  199. scaleData.push( scale.x, scale.y, scale.z );
  200. }
  201. if ( positionData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.position', times, positionData ) );
  202. if ( quaternionData.length > 0 ) tracks.push( new QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  203. if ( scaleData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  204. return tracks;
  205. }
  206. transformAnimationData( keyframes, property, defaultValue ) {
  207. let keyframe;
  208. let empty = true;
  209. let i, l;
  210. // check, if values of a property are missing in our keyframes
  211. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  212. keyframe = keyframes[ i ];
  213. if ( keyframe.value[ property ] === undefined ) {
  214. keyframe.value[ property ] = null; // mark as missing
  215. } else {
  216. empty = false;
  217. }
  218. }
  219. if ( empty === true ) {
  220. // no values at all, so we set a default value
  221. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  222. keyframe = keyframes[ i ];
  223. keyframe.value[ property ] = defaultValue;
  224. }
  225. } else {
  226. // filling gaps
  227. this.createMissingKeyframes( keyframes, property );
  228. }
  229. }
  230. createMissingKeyframes( keyframes, property ) {
  231. let prev, next;
  232. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  233. const keyframe = keyframes[ i ];
  234. if ( keyframe.value[ property ] === null ) {
  235. prev = this.getPrev( keyframes, i, property );
  236. next = this.getNext( keyframes, i, property );
  237. if ( prev === null ) {
  238. keyframe.value[ property ] = next.value[ property ];
  239. continue;
  240. }
  241. if ( next === null ) {
  242. keyframe.value[ property ] = prev.value[ property ];
  243. continue;
  244. }
  245. this.interpolate( keyframe, prev, next, property );
  246. }
  247. }
  248. }
  249. getPrev( keyframes, i, property ) {
  250. while ( i >= 0 ) {
  251. const keyframe = keyframes[ i ];
  252. if ( keyframe.value[ property ] !== null ) return keyframe;
  253. i --;
  254. }
  255. return null;
  256. }
  257. getNext( keyframes, i, property ) {
  258. while ( i < keyframes.length ) {
  259. const keyframe = keyframes[ i ];
  260. if ( keyframe.value[ property ] !== null ) return keyframe;
  261. i ++;
  262. }
  263. return null;
  264. }
  265. interpolate( key, prev, next, property ) {
  266. if ( ( next.time - prev.time ) === 0 ) {
  267. key.value[ property ] = prev.value[ property ];
  268. return;
  269. }
  270. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  271. }
  272. // animation clips
  273. buildAnimationClip( data ) {
  274. const tracks = [];
  275. const name = data.name;
  276. const duration = ( data.end - data.start ) || - 1;
  277. const animations = data.animations;
  278. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  279. const animationTracks = this.getAnimation( animations[ i ] );
  280. for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  281. tracks.push( animationTracks[ j ] );
  282. }
  283. }
  284. return new AnimationClip( name, duration, tracks );
  285. }
  286. getAnimationClip( id ) {
  287. return this.getBuild( this.library.clips[ id ], this.buildAnimationClip.bind( this ) );
  288. }
  289. // controller
  290. buildController( data ) {
  291. const build = {
  292. id: data.id
  293. };
  294. const geometry = this.library.geometries[ build.id ];
  295. if ( data.skin !== undefined ) {
  296. build.skin = this.buildSkin( data.skin );
  297. // we enhance the 'sources' property of the corresponding geometry with our skin data
  298. geometry.sources.skinIndices = build.skin.indices;
  299. geometry.sources.skinWeights = build.skin.weights;
  300. }
  301. return build;
  302. }
  303. buildSkin( data ) {
  304. const BONE_LIMIT = 4;
  305. const build = {
  306. joints: [], // this must be an array to preserve the joint order
  307. indices: {
  308. array: [],
  309. stride: BONE_LIMIT
  310. },
  311. weights: {
  312. array: [],
  313. stride: BONE_LIMIT
  314. }
  315. };
  316. const sources = data.sources;
  317. const vertexWeights = data.vertexWeights;
  318. const vcount = vertexWeights.vcount;
  319. const v = vertexWeights.v;
  320. const jointOffset = vertexWeights.inputs.JOINT.offset;
  321. const weightOffset = vertexWeights.inputs.WEIGHT.offset;
  322. const jointSource = data.sources[ data.joints.inputs.JOINT ];
  323. const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  324. const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  325. let stride = 0;
  326. let i, j, l;
  327. // process skin data for each vertex
  328. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  329. const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  330. const vertexSkinData = [];
  331. for ( j = 0; j < jointCount; j ++ ) {
  332. const skinIndex = v[ stride + jointOffset ];
  333. const weightId = v[ stride + weightOffset ];
  334. const skinWeight = weights[ weightId ];
  335. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  336. stride += 2;
  337. }
  338. // we sort the joints in descending order based on the weights.
  339. // this ensures, we only proceed the most important joints of the vertex
  340. vertexSkinData.sort( descending );
  341. // now we provide for each vertex a set of four index and weight values.
  342. // the order of the skin data matches the order of vertices
  343. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  344. const d = vertexSkinData[ j ];
  345. if ( d !== undefined ) {
  346. build.indices.array.push( d.index );
  347. build.weights.array.push( d.weight );
  348. } else {
  349. build.indices.array.push( 0 );
  350. build.weights.array.push( 0 );
  351. }
  352. }
  353. }
  354. // setup bind matrix
  355. if ( data.bindShapeMatrix ) {
  356. build.bindMatrix = new Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  357. } else {
  358. build.bindMatrix = new Matrix4().identity();
  359. }
  360. // process bones and inverse bind matrix data
  361. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  362. const name = jointSource.array[ i ];
  363. const boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  364. build.joints.push( { name: name, boneInverse: boneInverse } );
  365. }
  366. return build;
  367. // array sort function
  368. function descending( a, b ) {
  369. return b.weight - a.weight;
  370. }
  371. }
  372. getController( id ) {
  373. return this.getBuild( this.library.controllers[ id ], this.buildController.bind( this ) );
  374. }
  375. // image
  376. buildImage( data ) {
  377. if ( data.build !== undefined ) return data.build;
  378. return data.init_from;
  379. }
  380. getImage( id ) {
  381. const data = this.library.images[ id ];
  382. if ( data !== undefined ) {
  383. return this.getBuild( data, this.buildImage.bind( this ) );
  384. }
  385. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  386. return null;
  387. }
  388. // effect
  389. buildEffect( data ) {
  390. return data;
  391. }
  392. getEffect( id ) {
  393. return this.getBuild( this.library.effects[ id ], this.buildEffect.bind( this ) );
  394. }
  395. // material
  396. getTextureLoader( image ) {
  397. let loader;
  398. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  399. extension = extension.toLowerCase();
  400. switch ( extension ) {
  401. case 'tga':
  402. loader = this.tgaLoader;
  403. break;
  404. default:
  405. loader = this.textureLoader;
  406. }
  407. return loader;
  408. }
  409. buildMaterial( data ) {
  410. const effect = this.getEffect( data.url );
  411. const technique = effect.profile.technique;
  412. let material;
  413. switch ( technique.type ) {
  414. case 'phong':
  415. case 'blinn':
  416. material = new MeshPhongMaterial();
  417. break;
  418. case 'lambert':
  419. material = new MeshLambertMaterial();
  420. break;
  421. default:
  422. material = new MeshBasicMaterial();
  423. break;
  424. }
  425. material.name = data.name || '';
  426. const self = this;
  427. function getTexture( textureObject, colorSpace = null ) {
  428. const sampler = effect.profile.samplers[ textureObject.id ];
  429. let image = null;
  430. // get image
  431. if ( sampler !== undefined ) {
  432. const surface = effect.profile.surfaces[ sampler.source ];
  433. image = self.getImage( surface.init_from );
  434. } else {
  435. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  436. image = self.getImage( textureObject.id );
  437. }
  438. // create texture if image is available
  439. if ( image !== null ) {
  440. const loader = self.getTextureLoader( image );
  441. if ( loader !== undefined ) {
  442. const texture = loader.load( image );
  443. const extra = textureObject.extra;
  444. if ( extra !== undefined && extra.technique !== undefined && self.isEmpty( extra.technique ) === false ) {
  445. const technique = extra.technique;
  446. texture.wrapS = technique.wrapU ? RepeatWrapping : ClampToEdgeWrapping;
  447. texture.wrapT = technique.wrapV ? RepeatWrapping : ClampToEdgeWrapping;
  448. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  449. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  450. } else {
  451. texture.wrapS = RepeatWrapping;
  452. texture.wrapT = RepeatWrapping;
  453. }
  454. if ( colorSpace !== null ) {
  455. texture.colorSpace = colorSpace;
  456. }
  457. return texture;
  458. } else {
  459. console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
  460. return null;
  461. }
  462. } else {
  463. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  464. return null;
  465. }
  466. }
  467. const parameters = technique.parameters;
  468. for ( const key in parameters ) {
  469. const parameter = parameters[ key ];
  470. switch ( key ) {
  471. case 'diffuse':
  472. if ( parameter.color ) material.color.fromArray( parameter.color );
  473. if ( parameter.texture ) material.map = getTexture( parameter.texture, SRGBColorSpace );
  474. break;
  475. case 'specular':
  476. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  477. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  478. break;
  479. case 'bump':
  480. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  481. break;
  482. case 'ambient':
  483. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture, SRGBColorSpace );
  484. break;
  485. case 'shininess':
  486. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  487. break;
  488. case 'emission':
  489. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  490. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture, SRGBColorSpace );
  491. break;
  492. }
  493. }
  494. ColorManagement.colorSpaceToWorking( material.color, SRGBColorSpace );
  495. if ( material.specular ) ColorManagement.colorSpaceToWorking( material.specular, SRGBColorSpace );
  496. if ( material.emissive ) ColorManagement.colorSpaceToWorking( material.emissive, SRGBColorSpace );
  497. //
  498. let transparent = parameters[ 'transparent' ];
  499. let transparency = parameters[ 'transparency' ];
  500. // <transparency> does not exist but <transparent>
  501. if ( transparency === undefined && transparent ) {
  502. transparency = {
  503. float: 1
  504. };
  505. }
  506. // <transparent> does not exist but <transparency>
  507. if ( transparent === undefined && transparency ) {
  508. transparent = {
  509. opaque: 'A_ONE',
  510. data: {
  511. color: [ 1, 1, 1, 1 ]
  512. } };
  513. }
  514. if ( transparent && transparency ) {
  515. // handle case if a texture exists but no color
  516. if ( transparent.data.texture ) {
  517. // we do not set an alpha map (see #13792)
  518. material.transparent = true;
  519. } else {
  520. const color = transparent.data.color;
  521. switch ( transparent.opaque ) {
  522. case 'A_ONE':
  523. material.opacity = color[ 3 ] * transparency.float;
  524. break;
  525. case 'RGB_ZERO':
  526. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  527. break;
  528. case 'A_ZERO':
  529. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  530. break;
  531. case 'RGB_ONE':
  532. material.opacity = color[ 0 ] * transparency.float;
  533. break;
  534. default:
  535. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  536. }
  537. if ( material.opacity < 1 ) material.transparent = true;
  538. }
  539. }
  540. //
  541. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  542. const techniques = technique.extra.technique;
  543. for ( const k in techniques ) {
  544. const v = techniques[ k ];
  545. switch ( k ) {
  546. case 'double_sided':
  547. material.side = ( v === 1 ? DoubleSide : FrontSide );
  548. break;
  549. case 'bump':
  550. material.normalMap = getTexture( v.texture );
  551. material.normalScale = new Vector2( 1, 1 );
  552. break;
  553. }
  554. }
  555. }
  556. return material;
  557. }
  558. getMaterial( id ) {
  559. return this.getBuild( this.library.materials[ id ], this.buildMaterial.bind( this ) );
  560. }
  561. // camera
  562. buildCamera( data ) {
  563. let camera;
  564. switch ( data.optics.technique ) {
  565. case 'perspective':
  566. camera = new PerspectiveCamera(
  567. data.optics.parameters.yfov,
  568. data.optics.parameters.aspect_ratio,
  569. data.optics.parameters.znear,
  570. data.optics.parameters.zfar
  571. );
  572. break;
  573. case 'orthographic':
  574. let ymag = data.optics.parameters.ymag;
  575. let xmag = data.optics.parameters.xmag;
  576. const aspectRatio = data.optics.parameters.aspect_ratio;
  577. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  578. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  579. xmag *= 0.5;
  580. ymag *= 0.5;
  581. camera = new OrthographicCamera(
  582. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  583. data.optics.parameters.znear,
  584. data.optics.parameters.zfar
  585. );
  586. break;
  587. default:
  588. camera = new PerspectiveCamera();
  589. break;
  590. }
  591. camera.name = data.name || '';
  592. return camera;
  593. }
  594. getCamera( id ) {
  595. const data = this.library.cameras[ id ];
  596. if ( data !== undefined ) {
  597. return this.getBuild( data, this.buildCamera.bind( this ) );
  598. }
  599. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  600. return null;
  601. }
  602. // light
  603. buildLight( data ) {
  604. let light;
  605. switch ( data.technique ) {
  606. case 'directional':
  607. light = new DirectionalLight();
  608. break;
  609. case 'point':
  610. light = new PointLight();
  611. break;
  612. case 'spot':
  613. light = new SpotLight();
  614. break;
  615. case 'ambient':
  616. light = new AmbientLight();
  617. break;
  618. }
  619. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  620. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  621. return light;
  622. }
  623. getLight( id ) {
  624. const data = this.library.lights[ id ];
  625. if ( data !== undefined ) {
  626. return this.getBuild( data, this.buildLight.bind( this ) );
  627. }
  628. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  629. return null;
  630. }
  631. // geometry
  632. groupPrimitives( primitives ) {
  633. const build = {};
  634. for ( let i = 0; i < primitives.length; i ++ ) {
  635. const primitive = primitives[ i ];
  636. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  637. build[ primitive.type ].push( primitive );
  638. }
  639. return build;
  640. }
  641. checkUVCoordinates( primitives ) {
  642. let count = 0;
  643. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  644. const primitive = primitives[ i ];
  645. if ( primitive.hasUV === true ) {
  646. count ++;
  647. }
  648. }
  649. if ( count > 0 && count < primitives.length ) {
  650. primitives.uvsNeedsFix = true;
  651. }
  652. }
  653. buildGeometry( data ) {
  654. const build = {};
  655. const sources = data.sources;
  656. const vertices = data.vertices;
  657. const primitives = data.primitives;
  658. if ( primitives.length === 0 ) return {};
  659. // our goal is to create one buffer geometry for a single type of primitives
  660. // first, we group all primitives by their type
  661. const groupedPrimitives = this.groupPrimitives( primitives );
  662. for ( const type in groupedPrimitives ) {
  663. const primitiveType = groupedPrimitives[ type ];
  664. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  665. this.checkUVCoordinates( primitiveType );
  666. // third, create a buffer geometry for each type of primitives
  667. build[ type ] = this.buildGeometryType( primitiveType, sources, vertices );
  668. }
  669. return build;
  670. }
  671. buildGeometryType( primitives, sources, vertices ) {
  672. const build = {};
  673. const position = { array: [], stride: 0 };
  674. const normal = { array: [], stride: 0 };
  675. const uv = { array: [], stride: 0 };
  676. const uv1 = { array: [], stride: 0 };
  677. const color = { array: [], stride: 0 };
  678. const skinIndex = { array: [], stride: 4 };
  679. const skinWeight = { array: [], stride: 4 };
  680. const geometry = new BufferGeometry();
  681. const materialKeys = [];
  682. let start = 0;
  683. for ( let p = 0; p < primitives.length; p ++ ) {
  684. const primitive = primitives[ p ];
  685. const inputs = primitive.inputs;
  686. // groups
  687. let count = 0;
  688. switch ( primitive.type ) {
  689. case 'lines':
  690. case 'linestrips':
  691. count = primitive.count * 2;
  692. break;
  693. case 'triangles':
  694. count = primitive.count * 3;
  695. break;
  696. case 'polylist':
  697. for ( let g = 0; g < primitive.count; g ++ ) {
  698. const vc = primitive.vcount[ g ];
  699. switch ( vc ) {
  700. case 3:
  701. count += 3; // single triangle
  702. break;
  703. case 4:
  704. count += 6; // quad, subdivided into two triangles
  705. break;
  706. default:
  707. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  708. break;
  709. }
  710. }
  711. break;
  712. default:
  713. console.warn( 'THREE.ColladaLoader: Unknown primitive type:', primitive.type );
  714. }
  715. geometry.addGroup( start, count, p );
  716. start += count;
  717. // material
  718. if ( primitive.material ) {
  719. materialKeys.push( primitive.material );
  720. }
  721. // geometry data
  722. for ( const name in inputs ) {
  723. const input = inputs[ name ];
  724. switch ( name ) {
  725. case 'VERTEX':
  726. for ( const key in vertices ) {
  727. const id = vertices[ key ];
  728. switch ( key ) {
  729. case 'POSITION':
  730. const prevLength = position.array.length;
  731. this.buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  732. position.stride = sources[ id ].stride;
  733. if ( sources.skinWeights && sources.skinIndices ) {
  734. this.buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  735. this.buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  736. }
  737. // see #3803
  738. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  739. const count = ( position.array.length - prevLength ) / position.stride;
  740. for ( let i = 0; i < count; i ++ ) {
  741. // fill missing uv coordinates
  742. uv.array.push( 0, 0 );
  743. }
  744. }
  745. break;
  746. case 'NORMAL':
  747. this.buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  748. normal.stride = sources[ id ].stride;
  749. break;
  750. case 'COLOR':
  751. this.buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  752. color.stride = sources[ id ].stride;
  753. break;
  754. case 'TEXCOORD':
  755. this.buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  756. uv.stride = sources[ id ].stride;
  757. break;
  758. case 'TEXCOORD1':
  759. this.buildGeometryData( primitive, sources[ id ], input.offset, uv1.array );
  760. uv.stride = sources[ id ].stride;
  761. break;
  762. default:
  763. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  764. }
  765. }
  766. break;
  767. case 'NORMAL':
  768. this.buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  769. normal.stride = sources[ input.id ].stride;
  770. break;
  771. case 'COLOR':
  772. this.buildGeometryData( primitive, sources[ input.id ], input.offset, color.array, true );
  773. color.stride = sources[ input.id ].stride;
  774. break;
  775. case 'TEXCOORD':
  776. this.buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  777. uv.stride = sources[ input.id ].stride;
  778. break;
  779. case 'TEXCOORD1':
  780. this.buildGeometryData( primitive, sources[ input.id ], input.offset, uv1.array );
  781. uv1.stride = sources[ input.id ].stride;
  782. break;
  783. }
  784. }
  785. }
  786. // build geometry
  787. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position.array, position.stride ) );
  788. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal.array, normal.stride ) );
  789. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color.array, color.stride ) );
  790. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( uv.array, uv.stride ) );
  791. if ( uv1.array.length > 0 ) geometry.setAttribute( 'uv1', new Float32BufferAttribute( uv1.array, uv1.stride ) );
  792. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  793. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  794. build.data = geometry;
  795. build.type = primitives[ 0 ].type;
  796. build.materialKeys = materialKeys;
  797. return build;
  798. }
  799. buildGeometryData( primitive, source, offset, array, isColor = false ) {
  800. const indices = primitive.p;
  801. const stride = primitive.stride;
  802. const vcount = primitive.vcount;
  803. const tempColor = this.tempColor;
  804. function pushVector( i ) {
  805. let index = indices[ i + offset ] * sourceStride;
  806. const length = index + sourceStride;
  807. for ( ; index < length; index ++ ) {
  808. array.push( sourceArray[ index ] );
  809. }
  810. if ( isColor ) {
  811. // convert the vertex colors from srgb to linear if present
  812. const startIndex = array.length - sourceStride - 1;
  813. tempColor.setRGB(
  814. array[ startIndex + 0 ],
  815. array[ startIndex + 1 ],
  816. array[ startIndex + 2 ],
  817. SRGBColorSpace
  818. );
  819. array[ startIndex + 0 ] = tempColor.r;
  820. array[ startIndex + 1 ] = tempColor.g;
  821. array[ startIndex + 2 ] = tempColor.b;
  822. }
  823. }
  824. const sourceArray = source.array;
  825. const sourceStride = source.stride;
  826. if ( primitive.vcount !== undefined ) {
  827. let index = 0;
  828. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  829. const count = vcount[ i ];
  830. if ( count === 4 ) {
  831. const a = index + stride * 0;
  832. const b = index + stride * 1;
  833. const c = index + stride * 2;
  834. const d = index + stride * 3;
  835. pushVector( a ); pushVector( b ); pushVector( d );
  836. pushVector( b ); pushVector( c ); pushVector( d );
  837. } else if ( count === 3 ) {
  838. const a = index + stride * 0;
  839. const b = index + stride * 1;
  840. const c = index + stride * 2;
  841. pushVector( a ); pushVector( b ); pushVector( c );
  842. } else if ( count > 4 ) {
  843. for ( let k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  844. const a = index + stride * 0;
  845. const b = index + stride * k;
  846. const c = index + stride * ( k + 1 );
  847. pushVector( a ); pushVector( b ); pushVector( c );
  848. }
  849. }
  850. index += stride * count;
  851. }
  852. } else {
  853. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  854. pushVector( i );
  855. }
  856. }
  857. }
  858. getGeometry( id ) {
  859. return this.getBuild( this.library.geometries[ id ], this.buildGeometry.bind( this ) );
  860. }
  861. // kinematics
  862. buildKinematicsModel( data ) {
  863. if ( data.build !== undefined ) return data.build;
  864. return data;
  865. }
  866. getKinematicsModel( id ) {
  867. return this.getBuild( this.library.kinematicsModels[ id ], this.buildKinematicsModel.bind( this ) );
  868. }
  869. buildKinematicsScene( data ) {
  870. if ( data.build !== undefined ) return data.build;
  871. return data;
  872. }
  873. getKinematicsScene( id ) {
  874. return this.getBuild( this.library.kinematicsScenes[ id ], this.buildKinematicsScene.bind( this ) );
  875. }
  876. setupKinematics() {
  877. const kinematicsModelId = Object.keys( this.library.kinematicsModels )[ 0 ];
  878. const kinematicsSceneId = Object.keys( this.library.kinematicsScenes )[ 0 ];
  879. const visualSceneId = Object.keys( this.library.visualScenes )[ 0 ];
  880. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  881. const kinematicsModel = this.getKinematicsModel( kinematicsModelId );
  882. const kinematicsScene = this.getKinematicsScene( kinematicsSceneId );
  883. const visualScene = this.getVisualScene( visualSceneId );
  884. const bindJointAxis = kinematicsScene.bindJointAxis;
  885. const jointMap = {};
  886. const collada = this.collada;
  887. const self = this;
  888. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  889. const axis = bindJointAxis[ i ];
  890. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  891. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  892. if ( targetElement ) {
  893. // get the parent of the transform element
  894. const parentVisualElement = targetElement.parentElement;
  895. // connect the joint of the kinematics model with the element in the visual scene
  896. connect( axis.jointIndex, parentVisualElement );
  897. }
  898. }
  899. function connect( jointIndex, visualElement ) {
  900. const visualElementName = visualElement.getAttribute( 'name' );
  901. const joint = kinematicsModel.joints[ jointIndex ];
  902. const transforms = self.buildTransformList( visualElement );
  903. visualScene.traverse( function ( object ) {
  904. if ( object.name === visualElementName ) {
  905. jointMap[ jointIndex ] = {
  906. object: object,
  907. transforms: transforms,
  908. joint: joint,
  909. position: joint.zeroPosition
  910. };
  911. }
  912. } );
  913. }
  914. const m0 = new Matrix4();
  915. const matrix = this.matrix;
  916. this.kinematics = {
  917. joints: kinematicsModel && kinematicsModel.joints,
  918. getJointValue: function ( jointIndex ) {
  919. const jointData = jointMap[ jointIndex ];
  920. if ( jointData ) {
  921. return jointData.position;
  922. } else {
  923. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  924. }
  925. },
  926. setJointValue: function ( jointIndex, value ) {
  927. const jointData = jointMap[ jointIndex ];
  928. if ( jointData ) {
  929. const joint = jointData.joint;
  930. if ( value > joint.limits.max || value < joint.limits.min ) {
  931. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  932. } else if ( joint.static ) {
  933. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  934. } else {
  935. const object = jointData.object;
  936. const axis = joint.axis;
  937. const transforms = jointData.transforms;
  938. matrix.identity();
  939. // each update, we have to apply all transforms in the correct order
  940. for ( let i = 0; i < transforms.length; i ++ ) {
  941. const transform = transforms[ i ];
  942. // if there is a connection of the transform node with a joint, apply the joint value
  943. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  944. switch ( joint.type ) {
  945. case 'revolute':
  946. matrix.multiply( m0.makeRotationAxis( axis, MathUtils.degToRad( value ) ) );
  947. break;
  948. case 'prismatic':
  949. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  950. break;
  951. default:
  952. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  953. break;
  954. }
  955. } else {
  956. switch ( transform.type ) {
  957. case 'matrix':
  958. matrix.multiply( transform.obj );
  959. break;
  960. case 'translate':
  961. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  962. break;
  963. case 'scale':
  964. matrix.scale( transform.obj );
  965. break;
  966. case 'rotate':
  967. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  968. break;
  969. }
  970. }
  971. }
  972. object.matrix.copy( matrix );
  973. object.matrix.decompose( object.position, object.quaternion, object.scale );
  974. jointMap[ jointIndex ].position = value;
  975. }
  976. } else {
  977. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' does not exist.' );
  978. }
  979. }
  980. };
  981. }
  982. buildTransformList( node ) {
  983. const transforms = [];
  984. const xml = this.collada.querySelector( '[id="' + node.id + '"]' );
  985. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  986. const child = xml.childNodes[ i ];
  987. if ( child.nodeType !== 1 ) continue;
  988. let array, vector;
  989. switch ( child.nodeName ) {
  990. case 'matrix':
  991. array = parseFloats( child.textContent );
  992. const matrix = new Matrix4().fromArray( array ).transpose();
  993. transforms.push( {
  994. sid: child.getAttribute( 'sid' ),
  995. type: child.nodeName,
  996. obj: matrix
  997. } );
  998. break;
  999. case 'translate':
  1000. case 'scale':
  1001. array = parseFloats( child.textContent );
  1002. vector = new Vector3().fromArray( array );
  1003. transforms.push( {
  1004. sid: child.getAttribute( 'sid' ),
  1005. type: child.nodeName,
  1006. obj: vector
  1007. } );
  1008. break;
  1009. case 'rotate':
  1010. array = parseFloats( child.textContent );
  1011. vector = new Vector3().fromArray( array );
  1012. const angle = MathUtils.degToRad( array[ 3 ] );
  1013. transforms.push( {
  1014. sid: child.getAttribute( 'sid' ),
  1015. type: child.nodeName,
  1016. obj: vector,
  1017. angle: angle
  1018. } );
  1019. break;
  1020. }
  1021. }
  1022. return transforms;
  1023. }
  1024. // nodes
  1025. buildSkeleton( skeletons, joints ) {
  1026. const boneData = [];
  1027. const sortedBoneData = [];
  1028. let i, j, data;
  1029. // a skeleton can have multiple root bones. collada expresses this
  1030. // situation with multiple "skeleton" tags per controller instance
  1031. for ( i = 0; i < skeletons.length; i ++ ) {
  1032. const skeleton = skeletons[ i ];
  1033. let root;
  1034. if ( this.hasNode( skeleton ) ) {
  1035. root = this.getNode( skeleton );
  1036. this.buildBoneHierarchy( root, joints, boneData );
  1037. } else if ( this.hasVisualScene( skeleton ) ) {
  1038. // handle case where the skeleton refers to the visual scene (#13335)
  1039. const visualScene = this.library.visualScenes[ skeleton ];
  1040. const children = visualScene.children;
  1041. for ( let j = 0; j < children.length; j ++ ) {
  1042. const child = children[ j ];
  1043. if ( child.type === 'JOINT' ) {
  1044. const root = this.getNode( child.id );
  1045. this.buildBoneHierarchy( root, joints, boneData );
  1046. }
  1047. }
  1048. } else {
  1049. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  1050. }
  1051. }
  1052. // sort bone data (the order is defined in the corresponding controller)
  1053. for ( i = 0; i < joints.length; i ++ ) {
  1054. for ( j = 0; j < boneData.length; j ++ ) {
  1055. data = boneData[ j ];
  1056. if ( data.bone.name === joints[ i ].name ) {
  1057. sortedBoneData[ i ] = data;
  1058. data.processed = true;
  1059. break;
  1060. }
  1061. }
  1062. }
  1063. // add unprocessed bone data at the end of the list
  1064. for ( i = 0; i < boneData.length; i ++ ) {
  1065. data = boneData[ i ];
  1066. if ( data.processed === false ) {
  1067. sortedBoneData.push( data );
  1068. data.processed = true;
  1069. }
  1070. }
  1071. // setup arrays for skeleton creation
  1072. const bones = [];
  1073. const boneInverses = [];
  1074. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  1075. data = sortedBoneData[ i ];
  1076. bones.push( data.bone );
  1077. boneInverses.push( data.boneInverse );
  1078. }
  1079. return new Skeleton( bones, boneInverses );
  1080. }
  1081. buildBoneHierarchy( root, joints, boneData ) {
  1082. // setup bone data from visual scene
  1083. root.traverse( function ( object ) {
  1084. if ( object.isBone === true ) {
  1085. let boneInverse;
  1086. // retrieve the boneInverse from the controller data
  1087. for ( let i = 0; i < joints.length; i ++ ) {
  1088. const joint = joints[ i ];
  1089. if ( joint.name === object.name ) {
  1090. boneInverse = joint.boneInverse;
  1091. break;
  1092. }
  1093. }
  1094. if ( boneInverse === undefined ) {
  1095. // Unfortunately, there can be joints in the visual scene that are not part of the
  1096. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  1097. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  1098. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  1099. // ensure a correct animation of the model.
  1100. boneInverse = new Matrix4();
  1101. }
  1102. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  1103. }
  1104. } );
  1105. }
  1106. buildNode( data ) {
  1107. const objects = [];
  1108. const matrix = data.matrix;
  1109. const nodes = data.nodes;
  1110. const type = data.type;
  1111. const instanceCameras = data.instanceCameras;
  1112. const instanceControllers = data.instanceControllers;
  1113. const instanceLights = data.instanceLights;
  1114. const instanceGeometries = data.instanceGeometries;
  1115. const instanceNodes = data.instanceNodes;
  1116. // nodes
  1117. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  1118. objects.push( this.getNode( nodes[ i ] ) );
  1119. }
  1120. // instance cameras
  1121. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  1122. const instanceCamera = this.getCamera( instanceCameras[ i ] );
  1123. if ( instanceCamera !== null ) {
  1124. objects.push( instanceCamera.clone() );
  1125. }
  1126. }
  1127. // instance controllers
  1128. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  1129. const instance = instanceControllers[ i ];
  1130. const controller = this.getController( instance.id );
  1131. const geometries = this.getGeometry( controller.id );
  1132. const newObjects = this.buildObjects( geometries, instance.materials );
  1133. const skeletons = instance.skeletons;
  1134. const joints = controller.skin.joints;
  1135. const skeleton = this.buildSkeleton( skeletons, joints );
  1136. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  1137. const object = newObjects[ j ];
  1138. if ( object.isSkinnedMesh ) {
  1139. object.bind( skeleton, controller.skin.bindMatrix );
  1140. object.normalizeSkinWeights();
  1141. }
  1142. objects.push( object );
  1143. }
  1144. }
  1145. // instance lights
  1146. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  1147. const instanceLight = this.getLight( instanceLights[ i ] );
  1148. if ( instanceLight !== null ) {
  1149. objects.push( instanceLight.clone() );
  1150. }
  1151. }
  1152. // instance geometries
  1153. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  1154. const instance = instanceGeometries[ i ];
  1155. // a single geometry instance in collada can lead to multiple object3Ds.
  1156. // this is the case when primitives are combined like triangles and lines
  1157. const geometries = this.getGeometry( instance.id );
  1158. const newObjects = this.buildObjects( geometries, instance.materials );
  1159. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  1160. objects.push( newObjects[ j ] );
  1161. }
  1162. }
  1163. // instance nodes
  1164. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  1165. objects.push( this.getNode( instanceNodes[ i ] ).clone() );
  1166. }
  1167. let object;
  1168. if ( nodes.length === 0 && objects.length === 1 ) {
  1169. object = objects[ 0 ];
  1170. } else {
  1171. object = ( type === 'JOINT' ) ? new Bone() : new Group();
  1172. for ( let i = 0; i < objects.length; i ++ ) {
  1173. object.add( objects[ i ] );
  1174. }
  1175. }
  1176. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  1177. object.matrix.copy( matrix );
  1178. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1179. return object;
  1180. }
  1181. resolveMaterialBinding( keys, instanceMaterials ) {
  1182. const materials = [];
  1183. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  1184. const id = instanceMaterials[ keys[ i ] ];
  1185. if ( id === undefined ) {
  1186. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  1187. materials.push( this.fallbackMaterial );
  1188. } else {
  1189. materials.push( this.getMaterial( id ) );
  1190. }
  1191. }
  1192. return materials;
  1193. }
  1194. get fallbackMaterial() {
  1195. if ( this._fallbackMaterial === undefined ) {
  1196. this._fallbackMaterial = new MeshBasicMaterial( {
  1197. name: Loader.DEFAULT_MATERIAL_NAME,
  1198. color: 0xff00ff
  1199. } );
  1200. }
  1201. return this._fallbackMaterial;
  1202. }
  1203. buildObjects( geometries, instanceMaterials ) {
  1204. const objects = [];
  1205. for ( const type in geometries ) {
  1206. const geometry = geometries[ type ];
  1207. const materials = this.resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  1208. // handle case if no materials are defined
  1209. if ( materials.length === 0 ) {
  1210. if ( type === 'lines' || type === 'linestrips' ) {
  1211. materials.push( new LineBasicMaterial() );
  1212. } else {
  1213. materials.push( new MeshPhongMaterial() );
  1214. }
  1215. }
  1216. // Collada allows to use phong and lambert materials with lines. Replacing these cases with LineBasicMaterial.
  1217. if ( type === 'lines' || type === 'linestrips' ) {
  1218. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1219. const material = materials[ i ];
  1220. if ( material.isMeshPhongMaterial === true || material.isMeshLambertMaterial === true ) {
  1221. const lineMaterial = new LineBasicMaterial();
  1222. // copy compatible properties
  1223. lineMaterial.color.copy( material.color );
  1224. lineMaterial.opacity = material.opacity;
  1225. lineMaterial.transparent = material.transparent;
  1226. // replace material
  1227. materials[ i ] = lineMaterial;
  1228. }
  1229. }
  1230. }
  1231. // regard skinning
  1232. const skinning = ( geometry.data.attributes.skinIndex !== undefined );
  1233. // choose between a single or multi materials (material array)
  1234. const material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  1235. // now create a specific 3D object
  1236. let object;
  1237. switch ( type ) {
  1238. case 'lines':
  1239. object = new LineSegments( geometry.data, material );
  1240. break;
  1241. case 'linestrips':
  1242. object = new Line( geometry.data, material );
  1243. break;
  1244. case 'triangles':
  1245. case 'polylist':
  1246. if ( skinning ) {
  1247. object = new SkinnedMesh( geometry.data, material );
  1248. } else {
  1249. object = new Mesh( geometry.data, material );
  1250. }
  1251. break;
  1252. }
  1253. objects.push( object );
  1254. }
  1255. return objects;
  1256. }
  1257. hasNode( id ) {
  1258. return this.library.nodes[ id ] !== undefined;
  1259. }
  1260. getNode( id ) {
  1261. return this.getBuild( this.library.nodes[ id ], this.buildNode.bind( this ) );
  1262. }
  1263. // visual scenes
  1264. buildVisualScene( data ) {
  1265. const group = new Group();
  1266. group.name = data.name;
  1267. const children = data.children;
  1268. for ( let i = 0; i < children.length; i ++ ) {
  1269. const child = children[ i ];
  1270. group.add( this.getNode( child.id ) );
  1271. }
  1272. return group;
  1273. }
  1274. hasVisualScene( id ) {
  1275. return this.library.visualScenes[ id ] !== undefined;
  1276. }
  1277. getVisualScene( id ) {
  1278. return this.getBuild( this.library.visualScenes[ id ], this.buildVisualScene.bind( this ) );
  1279. }
  1280. // scenes
  1281. parseScene( xml ) {
  1282. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  1283. return this.getVisualScene( this.parseId( instance.getAttribute( 'url' ) ) );
  1284. }
  1285. parseId( text ) {
  1286. return text.substring( 1 );
  1287. }
  1288. setupAnimations() {
  1289. const clips = this.library.clips;
  1290. if ( this.isEmpty( clips ) === true ) {
  1291. if ( this.isEmpty( this.library.animations ) === false ) {
  1292. // if there are animations but no clips, we create a default clip for playback
  1293. const tracks = [];
  1294. for ( const id in this.library.animations ) {
  1295. const animationTracks = this.getAnimation( id );
  1296. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  1297. tracks.push( animationTracks[ i ] );
  1298. }
  1299. }
  1300. this.animations.push( new AnimationClip( 'default', - 1, tracks ) );
  1301. }
  1302. } else {
  1303. for ( const id in clips ) {
  1304. this.animations.push( this.getAnimationClip( id ) );
  1305. }
  1306. }
  1307. }
  1308. }
  1309. export { ColladaComposer };
粤ICP备19079148号