ColladaComposer.js 63 KB

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