ColladaComposer.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  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. InterpolateBezier,
  15. InterpolateDiscrete,
  16. Line,
  17. LineBasicMaterial,
  18. LineSegments,
  19. Loader,
  20. MathUtils,
  21. Matrix4,
  22. Mesh,
  23. MeshBasicMaterial,
  24. MeshLambertMaterial,
  25. MeshPhongMaterial,
  26. OrthographicCamera,
  27. PerspectiveCamera,
  28. PointLight,
  29. Quaternion,
  30. QuaternionKeyframeTrack,
  31. RepeatWrapping,
  32. Skeleton,
  33. SkinnedMesh,
  34. SpotLight,
  35. Triangle,
  36. Vector2,
  37. Vector3,
  38. VectorKeyframeTrack,
  39. SRGBColorSpace,
  40. ShapeUtils
  41. } from 'three';
  42. import { getElementsByTagName, parseFloats } from './ColladaParser.js';
  43. /**
  44. * ColladaComposer converts parsed library data into Three.js objects.
  45. */
  46. class ColladaComposer {
  47. constructor( library, collada, textureLoader, tgaLoader ) {
  48. this.library = library;
  49. this.collada = collada;
  50. this.textureLoader = textureLoader;
  51. this.tgaLoader = tgaLoader;
  52. this.tempColor = new Color();
  53. this.animations = [];
  54. this.kinematics = {};
  55. // Reusable objects for animation
  56. this.position = new Vector3();
  57. this.scale = new Vector3();
  58. this.quaternion = new Quaternion();
  59. this.matrix = new Matrix4();
  60. // Storage for deferred pivot animation data
  61. // Nodes with pivot transforms need all their animation channels collected
  62. // before building tracks, as channels may be split across animation elements
  63. this.deferredPivotAnimations = {};
  64. // Storage for transform node hierarchy
  65. // Maps nodeId -> transformSid -> Object3D for animation targeting
  66. this.transformNodes = {};
  67. }
  68. compose() {
  69. const library = this.library;
  70. this.buildLibrary( library.animations, this.buildAnimation.bind( this ) );
  71. this.buildLibrary( library.clips, this.buildAnimationClip.bind( this ) );
  72. this.buildLibrary( library.controllers, this.buildController.bind( this ) );
  73. this.buildLibrary( library.images, this.buildImage.bind( this ) );
  74. this.buildLibrary( library.effects, this.buildEffect.bind( this ) );
  75. this.buildLibrary( library.materials, this.buildMaterial.bind( this ) );
  76. this.buildLibrary( library.cameras, this.buildCamera.bind( this ) );
  77. this.buildLibrary( library.lights, this.buildLight.bind( this ) );
  78. this.buildLibrary( library.geometries, this.buildGeometry.bind( this ) );
  79. this.buildLibrary( library.visualScenes, this.buildVisualScene.bind( this ) );
  80. this.setupAnimations();
  81. this.setupKinematics();
  82. const scene = this.parseScene( getElementsByTagName( this.collada, 'scene' )[ 0 ] );
  83. scene.animations = this.animations;
  84. return {
  85. scene: scene,
  86. animations: this.animations,
  87. kinematics: this.kinematics
  88. };
  89. }
  90. buildLibrary( data, builder ) {
  91. for ( const name in data ) {
  92. const object = data[ name ];
  93. object.build = builder( data[ name ] );
  94. }
  95. }
  96. getBuild( data, builder ) {
  97. if ( data.build !== undefined ) return data.build;
  98. data.build = builder( data );
  99. return data.build;
  100. }
  101. isEmpty( object ) {
  102. return Object.keys( object ).length === 0;
  103. }
  104. buildAnimation( data ) {
  105. const tracks = [];
  106. const channels = data.channels;
  107. const samplers = data.samplers;
  108. const sources = data.sources;
  109. const aggregated = this.aggregateAnimationChannels( channels, samplers, sources );
  110. for ( const nodeId in aggregated ) {
  111. const nodeData = this.library.nodes[ nodeId ];
  112. if ( ! nodeData ) continue;
  113. const nodeChannels = aggregated[ nodeId ];
  114. if ( this.hasPivotTransforms( nodeData ) ) {
  115. // Defer - nodes haven't been built yet
  116. this.collectDeferredPivotAnimation( nodeId, nodeChannels );
  117. } else {
  118. const object3D = this.getNode( nodeId );
  119. let rotationTrackBuilt = false;
  120. for ( const sid in nodeChannels ) {
  121. const transformType = nodeData.transforms[ sid ];
  122. const transformInfo = nodeData.transformData[ sid ];
  123. const channelData = nodeChannels[ sid ];
  124. switch ( transformType ) {
  125. case 'matrix':
  126. this.buildMatrixTracks( object3D, channelData, nodeData, tracks );
  127. break;
  128. case 'translate':
  129. this.buildTranslateTrack( object3D, channelData, transformInfo, tracks );
  130. break;
  131. case 'rotate':
  132. if ( ! rotationTrackBuilt ) {
  133. this.buildRotateTrack( object3D, sid, channelData, transformInfo, nodeData, tracks );
  134. rotationTrackBuilt = true;
  135. }
  136. break;
  137. case 'scale':
  138. this.buildScaleTrack( object3D, channelData, transformInfo, tracks );
  139. break;
  140. }
  141. }
  142. }
  143. }
  144. return tracks;
  145. }
  146. collectDeferredPivotAnimation( nodeId, nodeChannels ) {
  147. if ( ! this.deferredPivotAnimations[ nodeId ] ) {
  148. this.deferredPivotAnimations[ nodeId ] = {};
  149. }
  150. const deferred = this.deferredPivotAnimations[ nodeId ];
  151. for ( const sid in nodeChannels ) {
  152. if ( ! deferred[ sid ] ) {
  153. deferred[ sid ] = {};
  154. }
  155. for ( const member in nodeChannels[ sid ] ) {
  156. deferred[ sid ][ member ] = nodeChannels[ sid ][ member ];
  157. }
  158. }
  159. }
  160. hasPivotTransforms( nodeData ) {
  161. const pivotSids = [
  162. 'rotatePivot', 'rotatePivotInverse', 'rotatePivotTranslation',
  163. 'scalePivot', 'scalePivotInverse', 'scalePivotTranslation'
  164. ];
  165. for ( const sid of pivotSids ) {
  166. if ( nodeData.transforms[ sid ] !== undefined ) {
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. getAnimation( id ) {
  173. return this.getBuild( this.library.animations[ id ], this.buildAnimation.bind( this ) );
  174. }
  175. aggregateAnimationChannels( channels, samplers, sources ) {
  176. const aggregated = {};
  177. for ( const target in channels ) {
  178. if ( ! channels.hasOwnProperty( target ) ) continue;
  179. const channel = channels[ target ];
  180. const sampler = samplers[ channel.sampler ];
  181. const inputId = sampler.inputs.INPUT;
  182. const outputId = sampler.inputs.OUTPUT;
  183. const inputSource = sources[ inputId ];
  184. const outputSource = sources[ outputId ];
  185. const interpolationId = sampler.inputs.INTERPOLATION;
  186. const inTangentId = sampler.inputs.IN_TANGENT;
  187. const outTangentId = sampler.inputs.OUT_TANGENT;
  188. const interpolationSource = interpolationId ? sources[ interpolationId ] : null;
  189. const inTangentSource = inTangentId ? sources[ inTangentId ] : null;
  190. const outTangentSource = outTangentId ? sources[ outTangentId ] : null;
  191. const nodeId = channel.id;
  192. const sid = channel.sid;
  193. const member = channel.member || 'default';
  194. if ( ! aggregated[ nodeId ] ) aggregated[ nodeId ] = {};
  195. if ( ! aggregated[ nodeId ][ sid ] ) aggregated[ nodeId ][ sid ] = {};
  196. aggregated[ nodeId ][ sid ][ member ] = {
  197. times: inputSource.array,
  198. values: outputSource.array,
  199. stride: outputSource.stride,
  200. arraySyntax: channel.arraySyntax,
  201. indices: channel.indices,
  202. interpolation: interpolationSource ? interpolationSource.array : null,
  203. inTangent: inTangentSource ? inTangentSource.array : null,
  204. outTangent: outTangentSource ? outTangentSource.array : null,
  205. inTangentStride: inTangentSource ? inTangentSource.stride : 0,
  206. outTangentStride: outTangentSource ? outTangentSource.stride : 0
  207. };
  208. }
  209. return aggregated;
  210. }
  211. buildMatrixTracks( object3D, channelData, nodeData, tracks ) {
  212. const defaultMatrix = nodeData.matrix.clone().transpose();
  213. const data = {};
  214. for ( const member in channelData ) {
  215. const component = channelData[ member ];
  216. const times = component.times;
  217. const values = component.values;
  218. const stride = component.stride;
  219. for ( let i = 0, il = times.length; i < il; i ++ ) {
  220. const time = times[ i ];
  221. const valueOffset = i * stride;
  222. if ( data[ time ] === undefined ) data[ time ] = {};
  223. if ( component.arraySyntax === true ) {
  224. const value = values[ valueOffset ];
  225. const index = component.indices[ 0 ] + 4 * component.indices[ 1 ];
  226. data[ time ][ index ] = value;
  227. } else {
  228. for ( let j = 0; j < stride; j ++ ) {
  229. data[ time ][ j ] = values[ valueOffset + j ];
  230. }
  231. }
  232. }
  233. }
  234. const keyframes = this.prepareAnimationData( data, defaultMatrix );
  235. const animation = { name: object3D.uuid, keyframes: keyframes };
  236. this.createKeyframeTracks( animation, tracks );
  237. }
  238. buildTranslateTrack( object3D, channelData, transformInfo, tracks ) {
  239. if ( channelData.default && channelData.default.stride === 3 ) {
  240. const data = channelData.default;
  241. const times = Array.from( data.times );
  242. const values = Array.from( data.values );
  243. const track = new VectorKeyframeTrack(
  244. object3D.uuid + '.position',
  245. times,
  246. values
  247. );
  248. const interpolationInfo = this.getInterpolationInfo( channelData );
  249. this.applyInterpolation( track, interpolationInfo, channelData );
  250. tracks.push( track );
  251. return;
  252. }
  253. const times = this.getTimesForAllAxes( channelData );
  254. if ( times.length === 0 ) return;
  255. const values = [];
  256. const interpolationInfo = this.getInterpolationInfo( channelData );
  257. for ( let i = 0; i < times.length; i ++ ) {
  258. const time = times[ i ];
  259. const x = this.getValueAtTime( channelData.X, time, transformInfo.x );
  260. const y = this.getValueAtTime( channelData.Y, time, transformInfo.y );
  261. const z = this.getValueAtTime( channelData.Z, time, transformInfo.z );
  262. values.push( x, y, z );
  263. }
  264. const track = new VectorKeyframeTrack(
  265. object3D.uuid + '.position',
  266. times,
  267. values
  268. );
  269. this.applyInterpolation( track, interpolationInfo );
  270. tracks.push( track );
  271. }
  272. buildRotateTrack( object3D, sid, channelData, transformInfo, nodeData, tracks ) {
  273. const angleData = channelData.ANGLE || channelData.default;
  274. if ( ! angleData ) return;
  275. const times = Array.from( angleData.times );
  276. if ( times.length === 0 ) return;
  277. // Collect all rotations to compose them in order
  278. const rotations = [];
  279. for ( const transformSid of nodeData.transformOrder ) {
  280. const transformType = nodeData.transforms[ transformSid ];
  281. if ( transformType === 'rotate' ) {
  282. const info = nodeData.transformData[ transformSid ];
  283. rotations.push( {
  284. sid: transformSid,
  285. axis: new Vector3( info.axis[ 0 ], info.axis[ 1 ], info.axis[ 2 ] ),
  286. defaultAngle: info.angle
  287. } );
  288. }
  289. }
  290. const quaternion = new Quaternion();
  291. const prevQuaternion = new Quaternion();
  292. const tempQuat = new Quaternion();
  293. const values = [];
  294. const interpolationInfo = this.getInterpolationInfo( channelData );
  295. for ( let i = 0; i < times.length; i ++ ) {
  296. const time = times[ i ];
  297. quaternion.identity();
  298. for ( const rotation of rotations ) {
  299. let angleDegrees;
  300. if ( rotation.sid === sid ) {
  301. angleDegrees = this.getValueAtTime( angleData, time, rotation.defaultAngle );
  302. } else {
  303. angleDegrees = rotation.defaultAngle;
  304. }
  305. const angleRadians = MathUtils.degToRad( angleDegrees );
  306. tempQuat.setFromAxisAngle( rotation.axis, angleRadians );
  307. quaternion.multiply( tempQuat );
  308. }
  309. // Ensure quaternion continuity
  310. if ( i > 0 && prevQuaternion.dot( quaternion ) < 0 ) {
  311. quaternion.x = - quaternion.x;
  312. quaternion.y = - quaternion.y;
  313. quaternion.z = - quaternion.z;
  314. quaternion.w = - quaternion.w;
  315. }
  316. prevQuaternion.copy( quaternion );
  317. values.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  318. }
  319. const track = new QuaternionKeyframeTrack(
  320. object3D.uuid + '.quaternion',
  321. times,
  322. values
  323. );
  324. this.applyInterpolation( track, interpolationInfo );
  325. tracks.push( track );
  326. }
  327. buildScaleTrack( object3D, channelData, transformInfo, tracks ) {
  328. if ( channelData.default && channelData.default.stride === 3 ) {
  329. const data = channelData.default;
  330. const times = Array.from( data.times );
  331. const values = Array.from( data.values );
  332. const track = new VectorKeyframeTrack(
  333. object3D.uuid + '.scale',
  334. times,
  335. values
  336. );
  337. const interpolationInfo = this.getInterpolationInfo( channelData );
  338. this.applyInterpolation( track, interpolationInfo, channelData );
  339. tracks.push( track );
  340. return;
  341. }
  342. const times = this.getTimesForAllAxes( channelData );
  343. if ( times.length === 0 ) return;
  344. const values = [];
  345. const interpolationInfo = this.getInterpolationInfo( channelData );
  346. for ( let i = 0; i < times.length; i ++ ) {
  347. const time = times[ i ];
  348. const x = this.getValueAtTime( channelData.X, time, transformInfo.x );
  349. const y = this.getValueAtTime( channelData.Y, time, transformInfo.y );
  350. const z = this.getValueAtTime( channelData.Z, time, transformInfo.z );
  351. values.push( x, y, z );
  352. }
  353. const track = new VectorKeyframeTrack(
  354. object3D.uuid + '.scale',
  355. times,
  356. values
  357. );
  358. this.applyInterpolation( track, interpolationInfo );
  359. tracks.push( track );
  360. }
  361. getTimesForAllAxes( channelData ) {
  362. let times = [];
  363. if ( channelData.X ) times = times.concat( Array.from( channelData.X.times ) );
  364. if ( channelData.Y ) times = times.concat( Array.from( channelData.Y.times ) );
  365. if ( channelData.Z ) times = times.concat( Array.from( channelData.Z.times ) );
  366. if ( channelData.ANGLE ) times = times.concat( Array.from( channelData.ANGLE.times ) );
  367. if ( channelData.default ) times = times.concat( Array.from( channelData.default.times ) );
  368. times = [ ...new Set( times ) ].sort( ( a, b ) => a - b );
  369. return times;
  370. }
  371. getValueAtTime( componentData, time, defaultValue ) {
  372. if ( ! componentData ) return defaultValue;
  373. const times = componentData.times;
  374. const values = componentData.values;
  375. const interpolation = componentData.interpolation;
  376. for ( let i = 0; i < times.length; i ++ ) {
  377. if ( times[ i ] === time ) {
  378. return values[ i ];
  379. }
  380. if ( times[ i ] > time ) {
  381. if ( i === 0 ) {
  382. return values[ 0 ];
  383. }
  384. const i0 = i - 1;
  385. const i1 = i;
  386. const t0 = times[ i0 ];
  387. const t1 = times[ i1 ];
  388. const v0 = values[ i0 ];
  389. const v1 = values[ i1 ];
  390. const interp = interpolation ? interpolation[ i0 ] : 'LINEAR';
  391. if ( interp === 'STEP' ) {
  392. return v0;
  393. } else if ( interp === 'BEZIER' && componentData.inTangent && componentData.outTangent ) {
  394. return this.evaluateBezierComponent( componentData, i0, i1, t0, t1, time );
  395. } else {
  396. const t = ( time - t0 ) / ( t1 - t0 );
  397. return v0 + t * ( v1 - v0 );
  398. }
  399. }
  400. }
  401. return values[ values.length - 1 ];
  402. }
  403. evaluateBezierComponent( componentData, i0, i1, t0, t1, time ) {
  404. const values = componentData.values;
  405. const inTangent = componentData.inTangent;
  406. const outTangent = componentData.outTangent;
  407. const tangentStride = componentData.inTangentStride || 1;
  408. const v0 = values[ i0 ];
  409. const v1 = values[ i1 ];
  410. let c0x, c0y, c1x, c1y;
  411. if ( tangentStride === 2 ) {
  412. c0x = outTangent[ i0 * 2 ];
  413. c0y = outTangent[ i0 * 2 + 1 ];
  414. c1x = inTangent[ i1 * 2 ];
  415. c1y = inTangent[ i1 * 2 + 1 ];
  416. } else {
  417. c0x = t0 + ( t1 - t0 ) / 3;
  418. c0y = outTangent[ i0 ];
  419. c1x = t1 - ( t1 - t0 ) / 3;
  420. c1y = inTangent[ i1 ];
  421. }
  422. // Newton-Raphson to solve Bx(s) = time
  423. let s = ( time - t0 ) / ( t1 - t0 );
  424. for ( let iter = 0; iter < 8; iter ++ ) {
  425. const s2 = s * s;
  426. const s3 = s2 * s;
  427. const oneMinusS = 1 - s;
  428. const oneMinusS2 = oneMinusS * oneMinusS;
  429. const oneMinusS3 = oneMinusS2 * oneMinusS;
  430. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  431. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  432. if ( Math.abs( dbx ) < 1e-10 ) break;
  433. const error = bx - time;
  434. if ( Math.abs( error ) < 1e-10 ) break;
  435. s = s - error / dbx;
  436. s = Math.max( 0, Math.min( 1, s ) );
  437. }
  438. const s2 = s * s;
  439. const s3 = s2 * s;
  440. const oneMinusS = 1 - s;
  441. const oneMinusS2 = oneMinusS * oneMinusS;
  442. const oneMinusS3 = oneMinusS2 * oneMinusS;
  443. return oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  444. }
  445. getInterpolationInfo( channelData ) {
  446. const components = [ 'X', 'Y', 'Z', 'ANGLE', 'default' ];
  447. let interpolationType = null;
  448. let isUniform = true;
  449. for ( const comp of components ) {
  450. const data = channelData[ comp ];
  451. if ( ! data || ! data.interpolation ) continue;
  452. const interpArray = data.interpolation;
  453. for ( let i = 0; i < interpArray.length; i ++ ) {
  454. const interp = interpArray[ i ];
  455. if ( interpolationType === null ) {
  456. interpolationType = interp;
  457. } else if ( interp !== interpolationType ) {
  458. isUniform = false;
  459. }
  460. }
  461. }
  462. return {
  463. type: interpolationType || 'LINEAR',
  464. uniform: isUniform
  465. };
  466. }
  467. applyInterpolation( track, interpolationInfo, channelData = null ) {
  468. if ( interpolationInfo.type === 'STEP' && interpolationInfo.uniform ) {
  469. track.setInterpolation( InterpolateDiscrete );
  470. } else if ( interpolationInfo.type === 'BEZIER' && interpolationInfo.uniform && channelData ) {
  471. const data = channelData.default;
  472. if ( data && data.inTangent && data.outTangent ) {
  473. track.setInterpolation( InterpolateBezier );
  474. track.settings = {
  475. inTangents: new Float32Array( data.inTangent ),
  476. outTangents: new Float32Array( data.outTangent )
  477. };
  478. }
  479. }
  480. }
  481. prepareAnimationData( data, defaultMatrix ) {
  482. const keyframes = [];
  483. for ( const time in data ) {
  484. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  485. }
  486. keyframes.sort( ( a, b ) => a.time - b.time );
  487. for ( let i = 0; i < 16; i ++ ) {
  488. this.transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  489. }
  490. return keyframes;
  491. }
  492. createKeyframeTracks( animation, tracks ) {
  493. const keyframes = animation.keyframes;
  494. const name = animation.name;
  495. const times = [];
  496. const positionData = [];
  497. const quaternionData = [];
  498. const scaleData = [];
  499. const position = this.position;
  500. const quaternion = this.quaternion;
  501. const scale = this.scale;
  502. const matrix = this.matrix;
  503. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  504. const keyframe = keyframes[ i ];
  505. const time = keyframe.time;
  506. const value = keyframe.value;
  507. matrix.fromArray( value ).transpose();
  508. matrix.decompose( position, quaternion, scale );
  509. times.push( time );
  510. positionData.push( position.x, position.y, position.z );
  511. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  512. scaleData.push( scale.x, scale.y, scale.z );
  513. }
  514. if ( positionData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.position', times, positionData ) );
  515. if ( quaternionData.length > 0 ) tracks.push( new QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  516. if ( scaleData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  517. return tracks;
  518. }
  519. transformAnimationData( keyframes, property, defaultValue ) {
  520. let keyframe;
  521. let empty = true;
  522. let i, l;
  523. // check, if values of a property are missing in our keyframes
  524. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  525. keyframe = keyframes[ i ];
  526. if ( keyframe.value[ property ] === undefined ) {
  527. keyframe.value[ property ] = null; // mark as missing
  528. } else {
  529. empty = false;
  530. }
  531. }
  532. if ( empty === true ) {
  533. // no values at all, so we set a default value
  534. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  535. keyframe = keyframes[ i ];
  536. keyframe.value[ property ] = defaultValue;
  537. }
  538. } else {
  539. // filling gaps
  540. this.createMissingKeyframes( keyframes, property );
  541. }
  542. }
  543. createMissingKeyframes( keyframes, property ) {
  544. let prev, next;
  545. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  546. const keyframe = keyframes[ i ];
  547. if ( keyframe.value[ property ] === null ) {
  548. prev = this.getPrev( keyframes, i, property );
  549. next = this.getNext( keyframes, i, property );
  550. if ( prev === null ) {
  551. keyframe.value[ property ] = next.value[ property ];
  552. continue;
  553. }
  554. if ( next === null ) {
  555. keyframe.value[ property ] = prev.value[ property ];
  556. continue;
  557. }
  558. this.interpolate( keyframe, prev, next, property );
  559. }
  560. }
  561. }
  562. getPrev( keyframes, i, property ) {
  563. while ( i >= 0 ) {
  564. const keyframe = keyframes[ i ];
  565. if ( keyframe.value[ property ] !== null ) return keyframe;
  566. i --;
  567. }
  568. return null;
  569. }
  570. getNext( keyframes, i, property ) {
  571. while ( i < keyframes.length ) {
  572. const keyframe = keyframes[ i ];
  573. if ( keyframe.value[ property ] !== null ) return keyframe;
  574. i ++;
  575. }
  576. return null;
  577. }
  578. interpolate( key, prev, next, property ) {
  579. if ( ( next.time - prev.time ) === 0 ) {
  580. key.value[ property ] = prev.value[ property ];
  581. return;
  582. }
  583. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  584. }
  585. buildAnimationClip( data ) {
  586. const tracks = [];
  587. const name = data.name;
  588. const duration = ( data.end - data.start ) || - 1;
  589. const animations = data.animations;
  590. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  591. const animationTracks = this.getAnimation( animations[ i ] );
  592. for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  593. tracks.push( animationTracks[ j ] );
  594. }
  595. }
  596. return new AnimationClip( name, duration, tracks );
  597. }
  598. getAnimationClip( id ) {
  599. return this.getBuild( this.library.clips[ id ], this.buildAnimationClip.bind( this ) );
  600. }
  601. buildController( data ) {
  602. const build = {
  603. id: data.id
  604. };
  605. const geometry = this.library.geometries[ build.id ];
  606. if ( data.skin !== undefined ) {
  607. build.skin = this.buildSkin( data.skin );
  608. // we enhance the 'sources' property of the corresponding geometry with our skin data
  609. geometry.sources.skinIndices = build.skin.indices;
  610. geometry.sources.skinWeights = build.skin.weights;
  611. }
  612. return build;
  613. }
  614. buildSkin( data ) {
  615. const BONE_LIMIT = 4;
  616. const build = {
  617. joints: [], // this must be an array to preserve the joint order
  618. indices: {
  619. array: [],
  620. stride: BONE_LIMIT
  621. },
  622. weights: {
  623. array: [],
  624. stride: BONE_LIMIT
  625. }
  626. };
  627. const sources = data.sources;
  628. const vertexWeights = data.vertexWeights;
  629. const vcount = vertexWeights.vcount;
  630. const v = vertexWeights.v;
  631. const jointOffset = vertexWeights.inputs.JOINT.offset;
  632. const weightOffset = vertexWeights.inputs.WEIGHT.offset;
  633. const jointSource = data.sources[ data.joints.inputs.JOINT ];
  634. const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  635. const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  636. let stride = 0;
  637. let i, j, l;
  638. // process skin data for each vertex
  639. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  640. const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  641. const vertexSkinData = [];
  642. for ( j = 0; j < jointCount; j ++ ) {
  643. const skinIndex = v[ stride + jointOffset ];
  644. const weightId = v[ stride + weightOffset ];
  645. const skinWeight = weights[ weightId ];
  646. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  647. stride += 2;
  648. }
  649. // we sort the joints in descending order based on the weights.
  650. // this ensures, we only proceed the most important joints of the vertex
  651. vertexSkinData.sort( descending );
  652. // now we provide for each vertex a set of four index and weight values.
  653. // the order of the skin data matches the order of vertices
  654. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  655. const d = vertexSkinData[ j ];
  656. if ( d !== undefined ) {
  657. build.indices.array.push( d.index );
  658. build.weights.array.push( d.weight );
  659. } else {
  660. build.indices.array.push( 0 );
  661. build.weights.array.push( 0 );
  662. }
  663. }
  664. }
  665. // setup bind matrix
  666. if ( data.bindShapeMatrix ) {
  667. build.bindMatrix = new Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  668. } else {
  669. build.bindMatrix = new Matrix4().identity();
  670. }
  671. // process bones and inverse bind matrix data
  672. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  673. const name = jointSource.array[ i ];
  674. const boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  675. build.joints.push( { name: name, boneInverse: boneInverse } );
  676. }
  677. return build;
  678. // array sort function
  679. function descending( a, b ) {
  680. return b.weight - a.weight;
  681. }
  682. }
  683. getController( id ) {
  684. return this.getBuild( this.library.controllers[ id ], this.buildController.bind( this ) );
  685. }
  686. buildImage( data ) {
  687. if ( data.build !== undefined ) return data.build;
  688. return data.init_from;
  689. }
  690. getImage( id ) {
  691. const data = this.library.images[ id ];
  692. if ( data !== undefined ) {
  693. return this.getBuild( data, this.buildImage.bind( this ) );
  694. }
  695. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  696. return null;
  697. }
  698. buildEffect( data ) {
  699. return data;
  700. }
  701. getEffect( id ) {
  702. return this.getBuild( this.library.effects[ id ], this.buildEffect.bind( this ) );
  703. }
  704. getTextureLoader( image ) {
  705. let loader;
  706. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  707. extension = extension.toLowerCase();
  708. switch ( extension ) {
  709. case 'tga':
  710. loader = this.tgaLoader;
  711. break;
  712. default:
  713. loader = this.textureLoader;
  714. }
  715. return loader;
  716. }
  717. buildMaterial( data ) {
  718. const effect = this.getEffect( data.url );
  719. const technique = effect.profile.technique;
  720. let material;
  721. switch ( technique.type ) {
  722. case 'phong':
  723. case 'blinn':
  724. material = new MeshPhongMaterial();
  725. break;
  726. case 'lambert':
  727. material = new MeshLambertMaterial();
  728. break;
  729. default:
  730. material = new MeshBasicMaterial();
  731. break;
  732. }
  733. material.name = data.name || '';
  734. const self = this;
  735. function getTexture( textureObject, colorSpace = null ) {
  736. const sampler = effect.profile.samplers[ textureObject.id ];
  737. let image = null;
  738. // get image
  739. if ( sampler !== undefined ) {
  740. const surface = effect.profile.surfaces[ sampler.source ];
  741. image = self.getImage( surface.init_from );
  742. } else {
  743. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  744. image = self.getImage( textureObject.id );
  745. }
  746. // create texture if image is available
  747. if ( image !== null ) {
  748. const loader = self.getTextureLoader( image );
  749. if ( loader !== undefined ) {
  750. const texture = loader.load( image );
  751. const extra = textureObject.extra;
  752. if ( extra !== undefined && extra.technique !== undefined && self.isEmpty( extra.technique ) === false ) {
  753. const technique = extra.technique;
  754. texture.wrapS = technique.wrapU ? RepeatWrapping : ClampToEdgeWrapping;
  755. texture.wrapT = technique.wrapV ? RepeatWrapping : ClampToEdgeWrapping;
  756. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  757. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  758. } else {
  759. texture.wrapS = RepeatWrapping;
  760. texture.wrapT = RepeatWrapping;
  761. }
  762. if ( colorSpace !== null ) {
  763. texture.colorSpace = colorSpace;
  764. }
  765. return texture;
  766. } else {
  767. console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
  768. return null;
  769. }
  770. } else {
  771. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  772. return null;
  773. }
  774. }
  775. const parameters = technique.parameters;
  776. for ( const key in parameters ) {
  777. const parameter = parameters[ key ];
  778. switch ( key ) {
  779. case 'diffuse':
  780. if ( parameter.color ) material.color.fromArray( parameter.color );
  781. if ( parameter.texture ) material.map = getTexture( parameter.texture, SRGBColorSpace );
  782. break;
  783. case 'specular':
  784. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  785. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  786. break;
  787. case 'bump':
  788. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  789. break;
  790. case 'ambient':
  791. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture, SRGBColorSpace );
  792. break;
  793. case 'shininess':
  794. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  795. break;
  796. case 'emission':
  797. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  798. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture, SRGBColorSpace );
  799. break;
  800. }
  801. }
  802. ColorManagement.colorSpaceToWorking( material.color, SRGBColorSpace );
  803. if ( material.specular ) ColorManagement.colorSpaceToWorking( material.specular, SRGBColorSpace );
  804. if ( material.emissive ) ColorManagement.colorSpaceToWorking( material.emissive, SRGBColorSpace );
  805. //
  806. let transparent = parameters[ 'transparent' ];
  807. let transparency = parameters[ 'transparency' ];
  808. // <transparency> does not exist but <transparent>
  809. if ( transparency === undefined && transparent ) {
  810. transparency = {
  811. float: 1
  812. };
  813. }
  814. // <transparent> does not exist but <transparency>
  815. if ( transparent === undefined && transparency ) {
  816. transparent = {
  817. opaque: 'A_ONE',
  818. data: {
  819. color: [ 1, 1, 1, 1 ]
  820. } };
  821. }
  822. if ( transparent && transparency ) {
  823. // handle case if a texture exists but no color
  824. if ( transparent.data.texture ) {
  825. // we do not set an alpha map (see #13792)
  826. material.transparent = true;
  827. } else {
  828. const color = transparent.data.color;
  829. switch ( transparent.opaque ) {
  830. case 'A_ONE':
  831. material.opacity = color[ 3 ] * transparency.float;
  832. break;
  833. case 'RGB_ZERO':
  834. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  835. break;
  836. case 'A_ZERO':
  837. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  838. break;
  839. case 'RGB_ONE':
  840. material.opacity = color[ 0 ] * transparency.float;
  841. break;
  842. default:
  843. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  844. }
  845. if ( material.opacity < 1 ) material.transparent = true;
  846. }
  847. }
  848. //
  849. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  850. const techniques = technique.extra.technique;
  851. for ( const k in techniques ) {
  852. const v = techniques[ k ];
  853. switch ( k ) {
  854. case 'double_sided':
  855. material.side = ( v === 1 ? DoubleSide : FrontSide );
  856. break;
  857. case 'bump':
  858. material.normalMap = getTexture( v.texture );
  859. material.normalScale = new Vector2( 1, 1 );
  860. break;
  861. }
  862. }
  863. }
  864. return material;
  865. }
  866. getMaterial( id ) {
  867. return this.getBuild( this.library.materials[ id ], this.buildMaterial.bind( this ) );
  868. }
  869. buildCamera( data ) {
  870. let camera;
  871. switch ( data.optics.technique ) {
  872. case 'perspective':
  873. camera = new PerspectiveCamera(
  874. data.optics.parameters.yfov,
  875. data.optics.parameters.aspect_ratio,
  876. data.optics.parameters.znear,
  877. data.optics.parameters.zfar
  878. );
  879. break;
  880. case 'orthographic':
  881. let ymag = data.optics.parameters.ymag;
  882. let xmag = data.optics.parameters.xmag;
  883. const aspectRatio = data.optics.parameters.aspect_ratio;
  884. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  885. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  886. xmag *= 0.5;
  887. ymag *= 0.5;
  888. camera = new OrthographicCamera(
  889. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  890. data.optics.parameters.znear,
  891. data.optics.parameters.zfar
  892. );
  893. break;
  894. default:
  895. camera = new PerspectiveCamera();
  896. break;
  897. }
  898. camera.name = data.name || '';
  899. return camera;
  900. }
  901. getCamera( id ) {
  902. const data = this.library.cameras[ id ];
  903. if ( data !== undefined ) {
  904. return this.getBuild( data, this.buildCamera.bind( this ) );
  905. }
  906. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  907. return null;
  908. }
  909. buildLight( data ) {
  910. let light;
  911. switch ( data.technique ) {
  912. case 'directional':
  913. light = new DirectionalLight();
  914. break;
  915. case 'point':
  916. light = new PointLight();
  917. break;
  918. case 'spot':
  919. light = new SpotLight();
  920. break;
  921. case 'ambient':
  922. light = new AmbientLight();
  923. break;
  924. }
  925. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  926. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  927. if ( data.parameters.falloffAngle ) light.angle = MathUtils.degToRad( data.parameters.falloffAngle );
  928. return light;
  929. }
  930. getLight( id ) {
  931. const data = this.library.lights[ id ];
  932. if ( data !== undefined ) {
  933. return this.getBuild( data, this.buildLight.bind( this ) );
  934. }
  935. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  936. return null;
  937. }
  938. groupPrimitives( primitives ) {
  939. const build = {};
  940. for ( let i = 0; i < primitives.length; i ++ ) {
  941. const primitive = primitives[ i ];
  942. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  943. build[ primitive.type ].push( primitive );
  944. }
  945. return build;
  946. }
  947. checkUVCoordinates( primitives ) {
  948. let count = 0;
  949. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  950. const primitive = primitives[ i ];
  951. if ( primitive.hasUV === true ) {
  952. count ++;
  953. }
  954. }
  955. if ( count > 0 && count < primitives.length ) {
  956. primitives.uvsNeedsFix = true;
  957. }
  958. }
  959. buildGeometry( data ) {
  960. const build = {};
  961. const sources = data.sources;
  962. const vertices = data.vertices;
  963. const primitives = data.primitives;
  964. if ( primitives.length === 0 ) return {};
  965. // our goal is to create one buffer geometry for a single type of primitives
  966. // first, we group all primitives by their type
  967. const groupedPrimitives = this.groupPrimitives( primitives );
  968. for ( const type in groupedPrimitives ) {
  969. const primitiveType = groupedPrimitives[ type ];
  970. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  971. this.checkUVCoordinates( primitiveType );
  972. // third, create a buffer geometry for each type of primitives
  973. build[ type ] = this.buildGeometryType( primitiveType, sources, vertices );
  974. }
  975. return build;
  976. }
  977. buildGeometryType( primitives, sources, vertices ) {
  978. const build = {};
  979. const position = { array: [], stride: 0 };
  980. const normal = { array: [], stride: 0 };
  981. const uv = { array: [], stride: 0 };
  982. const uv1 = { array: [], stride: 0 };
  983. const color = { array: [], stride: 0 };
  984. const skinIndex = { array: [], stride: 4 };
  985. const skinWeight = { array: [], stride: 4 };
  986. const geometry = new BufferGeometry();
  987. const materialKeys = [];
  988. let start = 0;
  989. for ( let p = 0; p < primitives.length; p ++ ) {
  990. const primitive = primitives[ p ];
  991. const inputs = primitive.inputs;
  992. // groups
  993. let count = 0;
  994. switch ( primitive.type ) {
  995. case 'lines':
  996. case 'linestrips':
  997. count = primitive.count * 2;
  998. break;
  999. case 'triangles':
  1000. count = primitive.count * 3;
  1001. break;
  1002. case 'polygons':
  1003. case 'polylist':
  1004. for ( let g = 0; g < primitive.count; g ++ ) {
  1005. const vc = primitive.vcount[ g ];
  1006. switch ( vc ) {
  1007. case 3:
  1008. count += 3; // single triangle
  1009. break;
  1010. case 4:
  1011. count += 6; // quad, subdivided into two triangles
  1012. break;
  1013. default:
  1014. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1015. break;
  1016. }
  1017. }
  1018. break;
  1019. default:
  1020. console.warn( 'THREE.ColladaLoader: Unknown primitive type:', primitive.type );
  1021. }
  1022. geometry.addGroup( start, count, p );
  1023. start += count;
  1024. // material
  1025. if ( primitive.material ) {
  1026. materialKeys.push( primitive.material );
  1027. }
  1028. // geometry data
  1029. for ( const name in inputs ) {
  1030. const input = inputs[ name ];
  1031. switch ( name ) {
  1032. case 'VERTEX':
  1033. for ( const key in vertices ) {
  1034. const id = vertices[ key ];
  1035. switch ( key ) {
  1036. case 'POSITION':
  1037. const prevLength = position.array.length;
  1038. this.buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1039. position.stride = sources[ id ].stride;
  1040. if ( sources.skinWeights && sources.skinIndices ) {
  1041. this.buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1042. this.buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1043. }
  1044. // see #3803
  1045. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1046. const count = ( position.array.length - prevLength ) / position.stride;
  1047. for ( let i = 0; i < count; i ++ ) {
  1048. // fill missing uv coordinates
  1049. uv.array.push( 0, 0 );
  1050. }
  1051. }
  1052. break;
  1053. case 'NORMAL':
  1054. this.buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1055. normal.stride = sources[ id ].stride;
  1056. break;
  1057. case 'COLOR':
  1058. this.buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1059. color.stride = sources[ id ].stride;
  1060. break;
  1061. case 'TEXCOORD':
  1062. this.buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1063. uv.stride = sources[ id ].stride;
  1064. break;
  1065. case 'TEXCOORD1':
  1066. this.buildGeometryData( primitive, sources[ id ], input.offset, uv1.array );
  1067. uv.stride = sources[ id ].stride;
  1068. break;
  1069. default:
  1070. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1071. }
  1072. }
  1073. break;
  1074. case 'NORMAL':
  1075. this.buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1076. normal.stride = sources[ input.id ].stride;
  1077. break;
  1078. case 'COLOR':
  1079. this.buildGeometryData( primitive, sources[ input.id ], input.offset, color.array, true );
  1080. color.stride = sources[ input.id ].stride;
  1081. break;
  1082. case 'TEXCOORD':
  1083. this.buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1084. uv.stride = sources[ input.id ].stride;
  1085. break;
  1086. case 'TEXCOORD1':
  1087. this.buildGeometryData( primitive, sources[ input.id ], input.offset, uv1.array );
  1088. uv1.stride = sources[ input.id ].stride;
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. // build geometry
  1094. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position.array, position.stride ) );
  1095. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal.array, normal.stride ) );
  1096. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color.array, color.stride ) );
  1097. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( uv.array, uv.stride ) );
  1098. if ( uv1.array.length > 0 ) geometry.setAttribute( 'uv1', new Float32BufferAttribute( uv1.array, uv1.stride ) );
  1099. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1100. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1101. build.data = geometry;
  1102. build.type = primitives[ 0 ].type;
  1103. build.materialKeys = materialKeys;
  1104. return build;
  1105. }
  1106. buildGeometryData( primitive, source, offset, array, isColor = false ) {
  1107. const indices = primitive.p;
  1108. const stride = primitive.stride;
  1109. const vcount = primitive.vcount;
  1110. const tempColor = this.tempColor;
  1111. function pushVector( i ) {
  1112. let index = indices[ i + offset ] * sourceStride;
  1113. const length = index + sourceStride;
  1114. for ( ; index < length; index ++ ) {
  1115. array.push( sourceArray[ index ] );
  1116. }
  1117. if ( isColor ) {
  1118. // convert the vertex colors from srgb to linear if present
  1119. const startIndex = array.length - sourceStride - 1;
  1120. tempColor.setRGB(
  1121. array[ startIndex + 0 ],
  1122. array[ startIndex + 1 ],
  1123. array[ startIndex + 2 ],
  1124. SRGBColorSpace
  1125. );
  1126. array[ startIndex + 0 ] = tempColor.r;
  1127. array[ startIndex + 1 ] = tempColor.g;
  1128. array[ startIndex + 2 ] = tempColor.b;
  1129. }
  1130. }
  1131. const sourceArray = source.array;
  1132. const sourceStride = source.stride;
  1133. if ( primitive.vcount !== undefined ) {
  1134. let index = 0;
  1135. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1136. const count = vcount[ i ];
  1137. if ( count === 4 ) {
  1138. const a = index + stride * 0;
  1139. const b = index + stride * 1;
  1140. const c = index + stride * 2;
  1141. const d = index + stride * 3;
  1142. pushVector( a ); pushVector( b ); pushVector( d );
  1143. pushVector( b ); pushVector( c ); pushVector( d );
  1144. } else if ( count === 3 ) {
  1145. const a = index + stride * 0;
  1146. const b = index + stride * 1;
  1147. const c = index + stride * 2;
  1148. pushVector( a ); pushVector( b ); pushVector( c );
  1149. } else if ( count > 4 ) {
  1150. const vertices = [];
  1151. // prepare vertices which represent the polygon's contour
  1152. for ( let k = 0; k < count; k ++ ) {
  1153. const a = index + stride * k;
  1154. const positionIndex = indices[ a ] * sourceStride;
  1155. const x = sourceArray[ positionIndex ];
  1156. const y = sourceArray[ positionIndex + 1 ];
  1157. const z = sourceArray[ positionIndex + 2 ];
  1158. vertices.push( new Vector3( x, y, z ) );
  1159. }
  1160. // determine surface normal
  1161. const normal = new Vector3();
  1162. const _triangle = new Triangle();
  1163. _triangle.a = vertices[ 0 ];
  1164. _triangle.b = vertices[ 1 ];
  1165. _triangle.c = vertices[ 2 ];
  1166. _triangle.getNormal( normal );
  1167. // project to 2D and triangulate
  1168. const vertices2D = [];
  1169. if ( Math.abs( normal.x ) > Math.abs( normal.y ) && Math.abs( normal.x ) > Math.abs( normal.z ) ) {
  1170. for ( let k = 0; k < count; k ++ ) {
  1171. vertices2D.push( new Vector2( vertices[ k ].y, vertices[ k ].z ) );
  1172. }
  1173. } else if ( Math.abs( normal.y ) > Math.abs( normal.z ) ) {
  1174. for ( let k = 0; k < count; k ++ ) {
  1175. vertices2D.push( new Vector2( vertices[ k ].x, vertices[ k ].z ) );
  1176. }
  1177. } else {
  1178. for ( let k = 0; k < count; k ++ ) {
  1179. vertices2D.push( new Vector2( vertices[ k ].x, vertices[ k ].y ) );
  1180. }
  1181. }
  1182. const isClockWise = ShapeUtils.isClockWise( vertices2D );
  1183. if ( isClockWise === true ) {
  1184. vertices2D.reverse();
  1185. }
  1186. const faces = ShapeUtils.triangulateShape( vertices2D, [] );
  1187. // build indices
  1188. for ( let k = 0; k < faces.length; k ++ ) {
  1189. const face = faces[ k ];
  1190. let i0, i1, i2;
  1191. if ( isClockWise === false ) {
  1192. i0 = face[ 0 ];
  1193. i1 = face[ 1 ];
  1194. i2 = face[ 2 ];
  1195. } else {
  1196. i0 = count - 1 - face[ 0 ];
  1197. i1 = count - 1 - face[ 2 ];
  1198. i2 = count - 1 - face[ 1 ];
  1199. }
  1200. const a = index + stride * i0;
  1201. const b = index + stride * i1;
  1202. const c = index + stride * i2;
  1203. pushVector( a );
  1204. pushVector( b );
  1205. pushVector( c );
  1206. }
  1207. }
  1208. index += stride * count;
  1209. }
  1210. } else {
  1211. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1212. pushVector( i );
  1213. }
  1214. }
  1215. }
  1216. getGeometry( id ) {
  1217. return this.getBuild( this.library.geometries[ id ], this.buildGeometry.bind( this ) );
  1218. }
  1219. buildKinematicsModel( data ) {
  1220. if ( data.build !== undefined ) return data.build;
  1221. return data;
  1222. }
  1223. getKinematicsModel( id ) {
  1224. return this.getBuild( this.library.kinematicsModels[ id ], this.buildKinematicsModel.bind( this ) );
  1225. }
  1226. buildKinematicsScene( data ) {
  1227. if ( data.build !== undefined ) return data.build;
  1228. return data;
  1229. }
  1230. getKinematicsScene( id ) {
  1231. return this.getBuild( this.library.kinematicsScenes[ id ], this.buildKinematicsScene.bind( this ) );
  1232. }
  1233. setupKinematics() {
  1234. const kinematicsModelId = Object.keys( this.library.kinematicsModels )[ 0 ];
  1235. const kinematicsSceneId = Object.keys( this.library.kinematicsScenes )[ 0 ];
  1236. const visualSceneId = Object.keys( this.library.visualScenes )[ 0 ];
  1237. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1238. const kinematicsModel = this.getKinematicsModel( kinematicsModelId );
  1239. const kinematicsScene = this.getKinematicsScene( kinematicsSceneId );
  1240. const visualScene = this.getVisualScene( visualSceneId );
  1241. const bindJointAxis = kinematicsScene.bindJointAxis;
  1242. const jointMap = {};
  1243. const collada = this.collada;
  1244. const self = this;
  1245. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1246. const axis = bindJointAxis[ i ];
  1247. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1248. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1249. if ( targetElement ) {
  1250. // get the parent of the transform element
  1251. const parentVisualElement = targetElement.parentElement;
  1252. // connect the joint of the kinematics model with the element in the visual scene
  1253. connect( axis.jointIndex, parentVisualElement );
  1254. }
  1255. }
  1256. function connect( jointIndex, visualElement ) {
  1257. const visualElementName = visualElement.getAttribute( 'name' );
  1258. const joint = kinematicsModel.joints[ jointIndex ];
  1259. const transforms = self.buildTransformList( visualElement );
  1260. visualScene.traverse( function ( object ) {
  1261. if ( object.name === visualElementName ) {
  1262. jointMap[ jointIndex ] = {
  1263. object: object,
  1264. transforms: transforms,
  1265. joint: joint,
  1266. position: joint.zeroPosition
  1267. };
  1268. }
  1269. } );
  1270. }
  1271. const m0 = new Matrix4();
  1272. const matrix = this.matrix;
  1273. this.kinematics = {
  1274. joints: kinematicsModel && kinematicsModel.joints,
  1275. getJointValue: function ( jointIndex ) {
  1276. const jointData = jointMap[ jointIndex ];
  1277. if ( jointData ) {
  1278. return jointData.position;
  1279. } else {
  1280. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1281. }
  1282. },
  1283. setJointValue: function ( jointIndex, value ) {
  1284. const jointData = jointMap[ jointIndex ];
  1285. if ( jointData ) {
  1286. const joint = jointData.joint;
  1287. if ( value > joint.limits.max || value < joint.limits.min ) {
  1288. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1289. } else if ( joint.static ) {
  1290. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1291. } else {
  1292. const object = jointData.object;
  1293. const axis = joint.axis;
  1294. const transforms = jointData.transforms;
  1295. matrix.identity();
  1296. // each update, we have to apply all transforms in the correct order
  1297. for ( let i = 0; i < transforms.length; i ++ ) {
  1298. const transform = transforms[ i ];
  1299. // if there is a connection of the transform node with a joint, apply the joint value
  1300. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1301. switch ( joint.type ) {
  1302. case 'revolute':
  1303. matrix.multiply( m0.makeRotationAxis( axis, MathUtils.degToRad( value ) ) );
  1304. break;
  1305. case 'prismatic':
  1306. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1307. break;
  1308. default:
  1309. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1310. break;
  1311. }
  1312. } else {
  1313. switch ( transform.type ) {
  1314. case 'matrix':
  1315. matrix.multiply( transform.obj );
  1316. break;
  1317. case 'translate':
  1318. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1319. break;
  1320. case 'scale':
  1321. matrix.scale( transform.obj );
  1322. break;
  1323. case 'rotate':
  1324. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1325. break;
  1326. }
  1327. }
  1328. }
  1329. object.matrix.copy( matrix );
  1330. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1331. jointMap[ jointIndex ].position = value;
  1332. }
  1333. } else {
  1334. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' does not exist.' );
  1335. }
  1336. }
  1337. };
  1338. }
  1339. buildTransformList( node ) {
  1340. const transforms = [];
  1341. const xml = this.collada.querySelector( '[id="' + node.id + '"]' );
  1342. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1343. const child = xml.childNodes[ i ];
  1344. if ( child.nodeType !== 1 ) continue;
  1345. let array, vector;
  1346. switch ( child.nodeName ) {
  1347. case 'matrix':
  1348. array = parseFloats( child.textContent );
  1349. const matrix = new Matrix4().fromArray( array ).transpose();
  1350. transforms.push( {
  1351. sid: child.getAttribute( 'sid' ),
  1352. type: child.nodeName,
  1353. obj: matrix
  1354. } );
  1355. break;
  1356. case 'translate':
  1357. case 'scale':
  1358. array = parseFloats( child.textContent );
  1359. vector = new Vector3().fromArray( array );
  1360. transforms.push( {
  1361. sid: child.getAttribute( 'sid' ),
  1362. type: child.nodeName,
  1363. obj: vector
  1364. } );
  1365. break;
  1366. case 'rotate':
  1367. array = parseFloats( child.textContent );
  1368. vector = new Vector3().fromArray( array );
  1369. const angle = MathUtils.degToRad( array[ 3 ] );
  1370. transforms.push( {
  1371. sid: child.getAttribute( 'sid' ),
  1372. type: child.nodeName,
  1373. obj: vector,
  1374. angle: angle
  1375. } );
  1376. break;
  1377. }
  1378. }
  1379. return transforms;
  1380. }
  1381. buildSkeleton( skeletons, joints ) {
  1382. const boneData = [];
  1383. const sortedBoneData = [];
  1384. let i, j, data;
  1385. // a skeleton can have multiple root bones. collada expresses this
  1386. // situation with multiple "skeleton" tags per controller instance
  1387. for ( i = 0; i < skeletons.length; i ++ ) {
  1388. const skeleton = skeletons[ i ];
  1389. let root;
  1390. if ( this.hasNode( skeleton ) ) {
  1391. root = this.getNode( skeleton );
  1392. this.buildBoneHierarchy( root, joints, boneData );
  1393. } else if ( this.hasVisualScene( skeleton ) ) {
  1394. // handle case where the skeleton refers to the visual scene (#13335)
  1395. const visualScene = this.library.visualScenes[ skeleton ];
  1396. const children = visualScene.children;
  1397. for ( let j = 0; j < children.length; j ++ ) {
  1398. const child = children[ j ];
  1399. if ( child.type === 'JOINT' ) {
  1400. const root = this.getNode( child.id );
  1401. this.buildBoneHierarchy( root, joints, boneData );
  1402. }
  1403. }
  1404. } else {
  1405. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  1406. }
  1407. }
  1408. // sort bone data (the order is defined in the corresponding controller)
  1409. for ( i = 0; i < joints.length; i ++ ) {
  1410. for ( j = 0; j < boneData.length; j ++ ) {
  1411. data = boneData[ j ];
  1412. if ( data.bone.name === joints[ i ].name ) {
  1413. sortedBoneData[ i ] = data;
  1414. data.processed = true;
  1415. break;
  1416. }
  1417. }
  1418. }
  1419. // add unprocessed bone data at the end of the list
  1420. for ( i = 0; i < boneData.length; i ++ ) {
  1421. data = boneData[ i ];
  1422. if ( data.processed === false ) {
  1423. sortedBoneData.push( data );
  1424. data.processed = true;
  1425. }
  1426. }
  1427. // setup arrays for skeleton creation
  1428. const bones = [];
  1429. const boneInverses = [];
  1430. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  1431. data = sortedBoneData[ i ];
  1432. bones.push( data.bone );
  1433. boneInverses.push( data.boneInverse );
  1434. }
  1435. return new Skeleton( bones, boneInverses );
  1436. }
  1437. buildBoneHierarchy( root, joints, boneData ) {
  1438. // setup bone data from visual scene
  1439. root.traverse( function ( object ) {
  1440. if ( object.isBone === true ) {
  1441. let boneInverse;
  1442. // retrieve the boneInverse from the controller data
  1443. for ( let i = 0; i < joints.length; i ++ ) {
  1444. const joint = joints[ i ];
  1445. if ( joint.name === object.name ) {
  1446. boneInverse = joint.boneInverse;
  1447. break;
  1448. }
  1449. }
  1450. if ( boneInverse === undefined ) {
  1451. // Unfortunately, there can be joints in the visual scene that are not part of the
  1452. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  1453. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  1454. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  1455. // ensure a correct animation of the model.
  1456. boneInverse = new Matrix4();
  1457. }
  1458. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  1459. }
  1460. } );
  1461. }
  1462. buildNode( data ) {
  1463. const objects = [];
  1464. const matrix = data.matrix;
  1465. const nodes = data.nodes;
  1466. const type = data.type;
  1467. const instanceCameras = data.instanceCameras;
  1468. const instanceControllers = data.instanceControllers;
  1469. const instanceLights = data.instanceLights;
  1470. const instanceGeometries = data.instanceGeometries;
  1471. const instanceNodes = data.instanceNodes;
  1472. // nodes
  1473. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  1474. objects.push( this.getNode( nodes[ i ] ) );
  1475. }
  1476. // instance cameras
  1477. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  1478. const instanceCamera = this.getCamera( instanceCameras[ i ] );
  1479. if ( instanceCamera !== null ) {
  1480. objects.push( instanceCamera.clone() );
  1481. }
  1482. }
  1483. // instance controllers
  1484. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  1485. const instance = instanceControllers[ i ];
  1486. const controller = this.getController( instance.id );
  1487. const geometries = this.getGeometry( controller.id );
  1488. const newObjects = this.buildObjects( geometries, instance.materials );
  1489. const skeletons = instance.skeletons;
  1490. const joints = controller.skin.joints;
  1491. const skeleton = this.buildSkeleton( skeletons, joints );
  1492. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  1493. const object = newObjects[ j ];
  1494. if ( object.isSkinnedMesh ) {
  1495. object.bind( skeleton, controller.skin.bindMatrix );
  1496. object.normalizeSkinWeights();
  1497. }
  1498. objects.push( object );
  1499. }
  1500. }
  1501. // instance lights
  1502. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  1503. const instanceLight = this.getLight( instanceLights[ i ] );
  1504. if ( instanceLight !== null ) {
  1505. objects.push( instanceLight.clone() );
  1506. }
  1507. }
  1508. // instance geometries
  1509. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  1510. const instance = instanceGeometries[ i ];
  1511. // a single geometry instance in collada can lead to multiple object3Ds.
  1512. // this is the case when primitives are combined like triangles and lines
  1513. const geometries = this.getGeometry( instance.id );
  1514. const newObjects = this.buildObjects( geometries, instance.materials );
  1515. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  1516. objects.push( newObjects[ j ] );
  1517. }
  1518. }
  1519. // instance nodes
  1520. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  1521. objects.push( this.getNode( instanceNodes[ i ] ).clone() );
  1522. }
  1523. let object;
  1524. if ( nodes.length === 0 && objects.length === 1 ) {
  1525. object = objects[ 0 ];
  1526. } else {
  1527. object = ( type === 'JOINT' ) ? new Bone() : new Group();
  1528. for ( let i = 0; i < objects.length; i ++ ) {
  1529. object.add( objects[ i ] );
  1530. }
  1531. }
  1532. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  1533. if ( type !== 'JOINT' && this.hasPivotTransforms( data ) ) {
  1534. return this.wrapWithTransformHierarchy( object, data );
  1535. }
  1536. object.matrix.copy( matrix );
  1537. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1538. return object;
  1539. }
  1540. wrapWithTransformHierarchy( contentObject, nodeData ) {
  1541. const nodeId = nodeData.id;
  1542. this.transformNodes[ nodeId ] = {};
  1543. const transformOrder = nodeData.transformOrder;
  1544. const transformData = nodeData.transformData;
  1545. const rootNode = new Group();
  1546. rootNode.name = nodeData.name;
  1547. let currentParent = rootNode;
  1548. for ( let i = 0; i < transformOrder.length; i ++ ) {
  1549. const sid = transformOrder[ i ];
  1550. const info = transformData[ sid ];
  1551. const transformNode = new Group();
  1552. transformNode.name = nodeData.name + '_' + sid;
  1553. switch ( info.type ) {
  1554. case 'translate':
  1555. transformNode.position.set( info.x, info.y, info.z );
  1556. break;
  1557. case 'rotate': {
  1558. const axis = new Vector3( info.axis[ 0 ], info.axis[ 1 ], info.axis[ 2 ] );
  1559. const angle = MathUtils.degToRad( info.angle );
  1560. transformNode.quaternion.setFromAxisAngle( axis, angle );
  1561. transformNode.userData.rotationAxis = axis;
  1562. break;
  1563. }
  1564. case 'scale':
  1565. transformNode.scale.set( info.x, info.y, info.z );
  1566. break;
  1567. case 'matrix': {
  1568. const matrix = new Matrix4().fromArray( info.array ).transpose();
  1569. matrix.decompose( transformNode.position, transformNode.quaternion, transformNode.scale );
  1570. break;
  1571. }
  1572. }
  1573. this.transformNodes[ nodeId ][ sid ] = transformNode;
  1574. currentParent.add( transformNode );
  1575. currentParent = transformNode;
  1576. }
  1577. currentParent.add( contentObject );
  1578. return rootNode;
  1579. }
  1580. resolveMaterialBinding( keys, instanceMaterials ) {
  1581. const materials = [];
  1582. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  1583. const id = instanceMaterials[ keys[ i ] ];
  1584. if ( id === undefined ) {
  1585. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  1586. materials.push( this.fallbackMaterial );
  1587. } else {
  1588. materials.push( this.getMaterial( id ) );
  1589. }
  1590. }
  1591. return materials;
  1592. }
  1593. get fallbackMaterial() {
  1594. if ( this._fallbackMaterial === undefined ) {
  1595. this._fallbackMaterial = new MeshBasicMaterial( {
  1596. name: Loader.DEFAULT_MATERIAL_NAME,
  1597. color: 0xff00ff
  1598. } );
  1599. }
  1600. return this._fallbackMaterial;
  1601. }
  1602. buildObjects( geometries, instanceMaterials ) {
  1603. const objects = [];
  1604. for ( const type in geometries ) {
  1605. const geometry = geometries[ type ];
  1606. const materials = this.resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  1607. // handle case if no materials are defined
  1608. if ( materials.length === 0 ) {
  1609. if ( type === 'lines' || type === 'linestrips' ) {
  1610. materials.push( new LineBasicMaterial() );
  1611. } else {
  1612. materials.push( new MeshPhongMaterial() );
  1613. }
  1614. }
  1615. // Collada allows to use phong and lambert materials with lines. Replacing these cases with LineBasicMaterial.
  1616. if ( type === 'lines' || type === 'linestrips' ) {
  1617. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1618. const material = materials[ i ];
  1619. if ( material.isMeshPhongMaterial === true || material.isMeshLambertMaterial === true ) {
  1620. const lineMaterial = new LineBasicMaterial();
  1621. // copy compatible properties
  1622. lineMaterial.color.copy( material.color );
  1623. lineMaterial.opacity = material.opacity;
  1624. lineMaterial.transparent = material.transparent;
  1625. // replace material
  1626. materials[ i ] = lineMaterial;
  1627. }
  1628. }
  1629. }
  1630. // regard skinning
  1631. const skinning = ( geometry.data.attributes.skinIndex !== undefined );
  1632. // choose between a single or multi materials (material array)
  1633. const material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  1634. // now create a specific 3D object
  1635. let object;
  1636. switch ( type ) {
  1637. case 'lines':
  1638. object = new LineSegments( geometry.data, material );
  1639. break;
  1640. case 'linestrips':
  1641. object = new Line( geometry.data, material );
  1642. break;
  1643. case 'triangles':
  1644. case 'polygons':
  1645. case 'polylist':
  1646. if ( skinning ) {
  1647. object = new SkinnedMesh( geometry.data, material );
  1648. } else {
  1649. object = new Mesh( geometry.data, material );
  1650. }
  1651. break;
  1652. }
  1653. objects.push( object );
  1654. }
  1655. return objects;
  1656. }
  1657. hasNode( id ) {
  1658. return this.library.nodes[ id ] !== undefined;
  1659. }
  1660. getNode( id ) {
  1661. return this.getBuild( this.library.nodes[ id ], this.buildNode.bind( this ) );
  1662. }
  1663. buildVisualScene( data ) {
  1664. const group = new Group();
  1665. group.name = data.name;
  1666. const children = data.children;
  1667. for ( let i = 0; i < children.length; i ++ ) {
  1668. const child = children[ i ];
  1669. group.add( this.getNode( child.id ) );
  1670. }
  1671. return group;
  1672. }
  1673. hasVisualScene( id ) {
  1674. return this.library.visualScenes[ id ] !== undefined;
  1675. }
  1676. getVisualScene( id ) {
  1677. return this.getBuild( this.library.visualScenes[ id ], this.buildVisualScene.bind( this ) );
  1678. }
  1679. parseScene( xml ) {
  1680. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  1681. return this.getVisualScene( this.parseId( instance.getAttribute( 'url' ) ) );
  1682. }
  1683. parseId( text ) {
  1684. return text.substring( 1 );
  1685. }
  1686. setupAnimations() {
  1687. const clips = this.library.clips;
  1688. if ( this.isEmpty( clips ) === true ) {
  1689. if ( this.isEmpty( this.library.animations ) === false ) {
  1690. // if there are animations but no clips, we create a default clip for playback
  1691. const tracks = [];
  1692. for ( const id in this.library.animations ) {
  1693. const animationTracks = this.getAnimation( id );
  1694. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  1695. tracks.push( animationTracks[ i ] );
  1696. }
  1697. }
  1698. this.buildDeferredPivotAnimationTracks( tracks );
  1699. this.animations.push( new AnimationClip( 'default', - 1, tracks ) );
  1700. }
  1701. } else {
  1702. for ( const id in clips ) {
  1703. this.animations.push( this.getAnimationClip( id ) );
  1704. }
  1705. }
  1706. }
  1707. buildDeferredPivotAnimationTracks( tracks ) {
  1708. for ( const nodeId in this.deferredPivotAnimations ) {
  1709. const nodeData = this.library.nodes[ nodeId ];
  1710. if ( ! nodeData ) continue;
  1711. const mergedChannels = this.deferredPivotAnimations[ nodeId ];
  1712. this.buildTransformHierarchyTracks( nodeId, mergedChannels, nodeData, tracks );
  1713. }
  1714. }
  1715. buildTransformHierarchyTracks( nodeId, nodeChannels, nodeData, tracks ) {
  1716. const transformNodes = this.transformNodes[ nodeId ];
  1717. if ( ! transformNodes ) {
  1718. console.warn( 'THREE.ColladaLoader: Transform hierarchy not found for node:', nodeId );
  1719. return;
  1720. }
  1721. for ( const sid in nodeChannels ) {
  1722. const transformNode = transformNodes[ sid ];
  1723. if ( ! transformNode ) continue;
  1724. const transformType = nodeData.transforms[ sid ];
  1725. const transformInfo = nodeData.transformData[ sid ];
  1726. const channelData = nodeChannels[ sid ];
  1727. switch ( transformType ) {
  1728. case 'translate':
  1729. this.buildHierarchyTranslateTrack( transformNode, channelData, transformInfo, tracks );
  1730. break;
  1731. case 'rotate':
  1732. this.buildHierarchyRotateTrack( transformNode, channelData, transformInfo, tracks );
  1733. break;
  1734. case 'scale':
  1735. this.buildHierarchyScaleTrack( transformNode, channelData, transformInfo, tracks );
  1736. break;
  1737. }
  1738. }
  1739. }
  1740. buildHierarchyTranslateTrack( transformNode, channelData, transformInfo, tracks ) {
  1741. if ( channelData.default && channelData.default.stride === 3 ) {
  1742. const data = channelData.default;
  1743. const track = new VectorKeyframeTrack(
  1744. transformNode.uuid + '.position',
  1745. Array.from( data.times ),
  1746. Array.from( data.values )
  1747. );
  1748. const interpolationInfo = this.getInterpolationInfo( channelData );
  1749. this.applyInterpolation( track, interpolationInfo, channelData );
  1750. tracks.push( track );
  1751. return;
  1752. }
  1753. const times = this.getTimesForAllAxes( channelData );
  1754. if ( times.length === 0 ) return;
  1755. const values = [];
  1756. const interpolationInfo = this.getInterpolationInfo( channelData );
  1757. for ( let i = 0; i < times.length; i ++ ) {
  1758. const time = times[ i ];
  1759. const x = this.getValueAtTime( channelData.X, time, transformInfo.x );
  1760. const y = this.getValueAtTime( channelData.Y, time, transformInfo.y );
  1761. const z = this.getValueAtTime( channelData.Z, time, transformInfo.z );
  1762. values.push( x, y, z );
  1763. }
  1764. const track = new VectorKeyframeTrack(
  1765. transformNode.uuid + '.position',
  1766. times,
  1767. values
  1768. );
  1769. this.applyInterpolation( track, interpolationInfo );
  1770. tracks.push( track );
  1771. }
  1772. buildHierarchyRotateTrack( transformNode, channelData, transformInfo, tracks ) {
  1773. const angleData = channelData.ANGLE || channelData.default;
  1774. if ( ! angleData ) return;
  1775. const times = Array.from( angleData.times );
  1776. if ( times.length === 0 ) return;
  1777. const axis = transformNode.userData.rotationAxis ||
  1778. new Vector3( transformInfo.axis[ 0 ], transformInfo.axis[ 1 ], transformInfo.axis[ 2 ] );
  1779. const quaternion = new Quaternion();
  1780. const prevQuaternion = new Quaternion();
  1781. const values = [];
  1782. const interpolationInfo = this.getInterpolationInfo( channelData );
  1783. for ( let i = 0; i < times.length; i ++ ) {
  1784. const time = times[ i ];
  1785. const angleDegrees = this.getValueAtTime( angleData, time, transformInfo.angle );
  1786. const angleRadians = MathUtils.degToRad( angleDegrees );
  1787. quaternion.setFromAxisAngle( axis, angleRadians );
  1788. // Ensure quaternion continuity
  1789. if ( i > 0 && prevQuaternion.dot( quaternion ) < 0 ) {
  1790. quaternion.x = - quaternion.x;
  1791. quaternion.y = - quaternion.y;
  1792. quaternion.z = - quaternion.z;
  1793. quaternion.w = - quaternion.w;
  1794. }
  1795. prevQuaternion.copy( quaternion );
  1796. values.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  1797. }
  1798. const track = new QuaternionKeyframeTrack(
  1799. transformNode.uuid + '.quaternion',
  1800. times,
  1801. values
  1802. );
  1803. this.applyInterpolation( track, interpolationInfo );
  1804. tracks.push( track );
  1805. }
  1806. buildHierarchyScaleTrack( transformNode, channelData, transformInfo, tracks ) {
  1807. if ( channelData.default && channelData.default.stride === 3 ) {
  1808. const data = channelData.default;
  1809. const track = new VectorKeyframeTrack(
  1810. transformNode.uuid + '.scale',
  1811. Array.from( data.times ),
  1812. Array.from( data.values )
  1813. );
  1814. const interpolationInfo = this.getInterpolationInfo( channelData );
  1815. this.applyInterpolation( track, interpolationInfo, channelData );
  1816. tracks.push( track );
  1817. return;
  1818. }
  1819. const times = this.getTimesForAllAxes( channelData );
  1820. if ( times.length === 0 ) return;
  1821. const values = [];
  1822. const interpolationInfo = this.getInterpolationInfo( channelData );
  1823. for ( let i = 0; i < times.length; i ++ ) {
  1824. const time = times[ i ];
  1825. const x = this.getValueAtTime( channelData.X, time, transformInfo.x );
  1826. const y = this.getValueAtTime( channelData.Y, time, transformInfo.y );
  1827. const z = this.getValueAtTime( channelData.Z, time, transformInfo.z );
  1828. values.push( x, y, z );
  1829. }
  1830. const track = new VectorKeyframeTrack(
  1831. transformNode.uuid + '.scale',
  1832. times,
  1833. values
  1834. );
  1835. this.applyInterpolation( track, interpolationInfo );
  1836. tracks.push( track );
  1837. }
  1838. }
  1839. export { ColladaComposer };
粤ICP备19079148号