GLTFExporter.js 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. ( function () {
  2. class GLTFExporter {
  3. constructor() {
  4. this.pluginCallbacks = [];
  5. this.register( function ( writer ) {
  6. return new GLTFLightExtension( writer );
  7. } );
  8. this.register( function ( writer ) {
  9. return new GLTFMaterialsUnlitExtension( writer );
  10. } );
  11. this.register( function ( writer ) {
  12. return new GLTFMaterialsPBRSpecularGlossiness( writer );
  13. } );
  14. }
  15. register( callback ) {
  16. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  17. this.pluginCallbacks.push( callback );
  18. }
  19. return this;
  20. }
  21. unregister( callback ) {
  22. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  23. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  24. }
  25. return this;
  26. }
  27. /**
  28. * Parse scenes and generate GLTF output
  29. * @param {Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  30. * @param {Function} onDone Callback on completed
  31. * @param {Object} options options
  32. */
  33. parse( input, onDone, options ) {
  34. const writer = new GLTFWriter();
  35. const plugins = [];
  36. for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
  37. plugins.push( this.pluginCallbacks[ i ]( writer ) );
  38. }
  39. writer.setPlugins( plugins );
  40. writer.write( input, onDone, options );
  41. }
  42. } //------------------------------------------------------------------------------
  43. // Constants
  44. //------------------------------------------------------------------------------
  45. const WEBGL_CONSTANTS = {
  46. POINTS: 0x0000,
  47. LINES: 0x0001,
  48. LINE_LOOP: 0x0002,
  49. LINE_STRIP: 0x0003,
  50. TRIANGLES: 0x0004,
  51. TRIANGLE_STRIP: 0x0005,
  52. TRIANGLE_FAN: 0x0006,
  53. UNSIGNED_BYTE: 0x1401,
  54. UNSIGNED_SHORT: 0x1403,
  55. FLOAT: 0x1406,
  56. UNSIGNED_INT: 0x1405,
  57. ARRAY_BUFFER: 0x8892,
  58. ELEMENT_ARRAY_BUFFER: 0x8893,
  59. NEAREST: 0x2600,
  60. LINEAR: 0x2601,
  61. NEAREST_MIPMAP_NEAREST: 0x2700,
  62. LINEAR_MIPMAP_NEAREST: 0x2701,
  63. NEAREST_MIPMAP_LINEAR: 0x2702,
  64. LINEAR_MIPMAP_LINEAR: 0x2703,
  65. CLAMP_TO_EDGE: 33071,
  66. MIRRORED_REPEAT: 33648,
  67. REPEAT: 10497
  68. };
  69. const THREE_TO_WEBGL = {};
  70. THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  71. THREE_TO_WEBGL[ THREE.NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  72. THREE_TO_WEBGL[ THREE.NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  73. THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  74. THREE_TO_WEBGL[ THREE.LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  75. THREE_TO_WEBGL[ THREE.LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  76. THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  77. THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  78. THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  79. const PATH_PROPERTIES = {
  80. scale: 'scale',
  81. position: 'translation',
  82. quaternion: 'rotation',
  83. morphTargetInfluences: 'weights'
  84. }; // GLB constants
  85. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  86. const GLB_HEADER_BYTES = 12;
  87. const GLB_HEADER_MAGIC = 0x46546C67;
  88. const GLB_VERSION = 2;
  89. const GLB_CHUNK_PREFIX_BYTES = 8;
  90. const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  91. const GLB_CHUNK_TYPE_BIN = 0x004E4942; //------------------------------------------------------------------------------
  92. // Utility functions
  93. //------------------------------------------------------------------------------
  94. /**
  95. * Compare two arrays
  96. * @param {Array} array1 Array 1 to compare
  97. * @param {Array} array2 Array 2 to compare
  98. * @return {Boolean} Returns true if both arrays are equal
  99. */
  100. function equalArray( array1, array2 ) {
  101. return array1.length === array2.length && array1.every( function ( element, index ) {
  102. return element === array2[ index ];
  103. } );
  104. }
  105. /**
  106. * Converts a string to an ArrayBuffer.
  107. * @param {string} text
  108. * @return {ArrayBuffer}
  109. */
  110. function stringToArrayBuffer( text ) {
  111. if ( window.TextEncoder !== undefined ) {
  112. return new TextEncoder().encode( text ).buffer;
  113. }
  114. const array = new Uint8Array( new ArrayBuffer( text.length ) );
  115. for ( let i = 0, il = text.length; i < il; i ++ ) {
  116. const value = text.charCodeAt( i ); // Replacing multi-byte character with space(0x20).
  117. array[ i ] = value > 0xFF ? 0x20 : value;
  118. }
  119. return array.buffer;
  120. }
  121. /**
  122. * Is identity matrix
  123. *
  124. * @param {Matrix4} matrix
  125. * @returns {Boolean} Returns true, if parameter is identity matrix
  126. */
  127. function isIdentityMatrix( matrix ) {
  128. return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
  129. }
  130. /**
  131. * Get the min and max vectors from the given attribute
  132. * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  133. * @param {Integer} start
  134. * @param {Integer} count
  135. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  136. */
  137. function getMinMax( attribute, start, count ) {
  138. const output = {
  139. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  140. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  141. };
  142. for ( let i = start; i < start + count; i ++ ) {
  143. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  144. let value;
  145. if ( attribute.itemSize > 4 ) {
  146. // no support for interleaved data for itemSize > 4
  147. value = attribute.array[ i * attribute.itemSize + a ];
  148. } else {
  149. if ( a === 0 ) value = attribute.getX( i ); else if ( a === 1 ) value = attribute.getY( i ); else if ( a === 2 ) value = attribute.getZ( i ); else if ( a === 3 ) value = attribute.getW( i );
  150. }
  151. output.min[ a ] = Math.min( output.min[ a ], value );
  152. output.max[ a ] = Math.max( output.max[ a ], value );
  153. }
  154. }
  155. return output;
  156. }
  157. /**
  158. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  159. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  160. *
  161. * @param {Integer} bufferSize The size the original buffer.
  162. * @returns {Integer} new buffer size with required padding.
  163. *
  164. */
  165. function getPaddedBufferSize( bufferSize ) {
  166. return Math.ceil( bufferSize / 4 ) * 4;
  167. }
  168. /**
  169. * Returns a buffer aligned to 4-byte boundary.
  170. *
  171. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  172. * @param {Integer} paddingByte (Optional)
  173. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  174. */
  175. function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
  176. const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  177. if ( paddedLength !== arrayBuffer.byteLength ) {
  178. const array = new Uint8Array( paddedLength );
  179. array.set( new Uint8Array( arrayBuffer ) );
  180. if ( paddingByte !== 0 ) {
  181. for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  182. array[ i ] = paddingByte;
  183. }
  184. }
  185. return array.buffer;
  186. }
  187. return arrayBuffer;
  188. }
  189. let cachedCanvas = null;
  190. /**
  191. * Writer
  192. */
  193. class GLTFWriter {
  194. constructor() {
  195. this.plugins = [];
  196. this.options = {};
  197. this.pending = [];
  198. this.buffers = [];
  199. this.byteOffset = 0;
  200. this.buffers = [];
  201. this.nodeMap = new Map();
  202. this.skins = [];
  203. this.extensionsUsed = {};
  204. this.uids = new Map();
  205. this.uid = 0;
  206. this.json = {
  207. asset: {
  208. version: '2.0',
  209. generator: 'THREE.GLTFExporter'
  210. }
  211. };
  212. this.cache = {
  213. meshes: new Map(),
  214. attributes: new Map(),
  215. attributesNormalized: new Map(),
  216. materials: new Map(),
  217. textures: new Map(),
  218. images: new Map()
  219. };
  220. }
  221. setPlugins( plugins ) {
  222. this.plugins = plugins;
  223. }
  224. /**
  225. * Parse scenes and generate GLTF output
  226. * @param {Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  227. * @param {Function} onDone Callback on completed
  228. * @param {Object} options options
  229. */
  230. write( input, onDone, options ) {
  231. this.options = Object.assign( {}, {
  232. // default options
  233. binary: false,
  234. trs: false,
  235. onlyVisible: true,
  236. truncateDrawRange: true,
  237. embedImages: true,
  238. maxTextureSize: Infinity,
  239. animations: [],
  240. includeCustomExtensions: false
  241. }, options );
  242. if ( this.options.animations.length > 0 ) {
  243. // Only TRS properties, and not matrices, may be targeted by animation.
  244. this.options.trs = true;
  245. }
  246. this.processInput( input );
  247. const writer = this;
  248. Promise.all( this.pending ).then( function () {
  249. const buffers = writer.buffers;
  250. const json = writer.json;
  251. const options = writer.options;
  252. const extensionsUsed = writer.extensionsUsed; // Merge buffers.
  253. const blob = new Blob( buffers, {
  254. type: 'application/octet-stream'
  255. } ); // Declare extensions.
  256. const extensionsUsedList = Object.keys( extensionsUsed );
  257. if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList; // Update bytelength of the single buffer.
  258. if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
  259. if ( options.binary === true ) {
  260. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  261. const reader = new window.FileReader();
  262. reader.readAsArrayBuffer( blob );
  263. reader.onloadend = function () {
  264. // Binary chunk.
  265. const binaryChunk = getPaddedArrayBuffer( reader.result );
  266. const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  267. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  268. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true ); // JSON chunk.
  269. const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
  270. const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  271. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  272. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true ); // GLB header.
  273. const header = new ArrayBuffer( GLB_HEADER_BYTES );
  274. const headerView = new DataView( header );
  275. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  276. headerView.setUint32( 4, GLB_VERSION, true );
  277. const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  278. headerView.setUint32( 8, totalByteLength, true );
  279. const glbBlob = new Blob( [ header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk ], {
  280. type: 'application/octet-stream'
  281. } );
  282. const glbReader = new window.FileReader();
  283. glbReader.readAsArrayBuffer( glbBlob );
  284. glbReader.onloadend = function () {
  285. onDone( glbReader.result );
  286. };
  287. };
  288. } else {
  289. if ( json.buffers && json.buffers.length > 0 ) {
  290. const reader = new window.FileReader();
  291. reader.readAsDataURL( blob );
  292. reader.onloadend = function () {
  293. const base64data = reader.result;
  294. json.buffers[ 0 ].uri = base64data;
  295. onDone( json );
  296. };
  297. } else {
  298. onDone( json );
  299. }
  300. }
  301. } );
  302. }
  303. /**
  304. * Serializes a userData.
  305. *
  306. * @param {THREE.Object3D|THREE.Material} object
  307. * @param {Object} objectDef
  308. */
  309. serializeUserData( object, objectDef ) {
  310. if ( Object.keys( object.userData ).length === 0 ) return;
  311. const options = this.options;
  312. const extensionsUsed = this.extensionsUsed;
  313. try {
  314. const json = JSON.parse( JSON.stringify( object.userData ) );
  315. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  316. if ( objectDef.extensions === undefined ) objectDef.extensions = {};
  317. for ( const extensionName in json.gltfExtensions ) {
  318. objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  319. extensionsUsed[ extensionName ] = true;
  320. }
  321. delete json.gltfExtensions;
  322. }
  323. if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
  324. } catch ( error ) {
  325. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' + 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  326. }
  327. }
  328. /**
  329. * Assign and return a temporal unique id for an object
  330. * especially which doesn't have .uuid
  331. * @param {Object} object
  332. * @return {Integer}
  333. */
  334. getUID( object ) {
  335. if ( ! this.uids.has( object ) ) this.uids.set( object, this.uid ++ );
  336. return this.uids.get( object );
  337. }
  338. /**
  339. * Checks if normal attribute values are normalized.
  340. *
  341. * @param {BufferAttribute} normal
  342. * @returns {Boolean}
  343. */
  344. isNormalizedNormalAttribute( normal ) {
  345. const cache = this.cache;
  346. if ( cache.attributesNormalized.has( normal ) ) return false;
  347. const v = new THREE.Vector3();
  348. for ( let i = 0, il = normal.count; i < il; i ++ ) {
  349. // 0.0005 is from glTF-validator
  350. if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
  351. }
  352. return true;
  353. }
  354. /**
  355. * Creates normalized normal buffer attribute.
  356. *
  357. * @param {BufferAttribute} normal
  358. * @returns {BufferAttribute}
  359. *
  360. */
  361. createNormalizedNormalAttribute( normal ) {
  362. const cache = this.cache;
  363. if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
  364. const attribute = normal.clone();
  365. const v = new THREE.Vector3();
  366. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  367. v.fromBufferAttribute( attribute, i );
  368. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  369. // if values can't be normalized set (1, 0, 0)
  370. v.setX( 1.0 );
  371. } else {
  372. v.normalize();
  373. }
  374. attribute.setXYZ( i, v.x, v.y, v.z );
  375. }
  376. cache.attributesNormalized.set( normal, attribute );
  377. return attribute;
  378. }
  379. /**
  380. * Applies a texture transform, if present, to the map definition. Requires
  381. * the KHR_texture_transform extension.
  382. *
  383. * @param {Object} mapDef
  384. * @param {THREE.Texture} texture
  385. */
  386. applyTextureTransform( mapDef, texture ) {
  387. let didTransform = false;
  388. const transformDef = {};
  389. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  390. transformDef.offset = texture.offset.toArray();
  391. didTransform = true;
  392. }
  393. if ( texture.rotation !== 0 ) {
  394. transformDef.rotation = texture.rotation;
  395. didTransform = true;
  396. }
  397. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  398. transformDef.scale = texture.repeat.toArray();
  399. didTransform = true;
  400. }
  401. if ( didTransform ) {
  402. mapDef.extensions = mapDef.extensions || {};
  403. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  404. this.extensionsUsed[ 'KHR_texture_transform' ] = true;
  405. }
  406. }
  407. /**
  408. * Process a buffer to append to the default one.
  409. * @param {ArrayBuffer} buffer
  410. * @return {Integer}
  411. */
  412. processBuffer( buffer ) {
  413. const json = this.json;
  414. const buffers = this.buffers;
  415. if ( ! json.buffers ) json.buffers = [ {
  416. byteLength: 0
  417. } ]; // All buffers are merged before export.
  418. buffers.push( buffer );
  419. return 0;
  420. }
  421. /**
  422. * Process and generate a BufferView
  423. * @param {BufferAttribute} attribute
  424. * @param {number} componentType
  425. * @param {number} start
  426. * @param {number} count
  427. * @param {number} target (Optional) Target usage of the BufferView
  428. * @return {Object}
  429. */
  430. processBufferView( attribute, componentType, start, count, target ) {
  431. const json = this.json;
  432. if ( ! json.bufferViews ) json.bufferViews = []; // Create a new dataview and dump the attribute's array into it
  433. let componentSize;
  434. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  435. componentSize = 1;
  436. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  437. componentSize = 2;
  438. } else {
  439. componentSize = 4;
  440. }
  441. const byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  442. const dataView = new DataView( new ArrayBuffer( byteLength ) );
  443. let offset = 0;
  444. for ( let i = start; i < start + count; i ++ ) {
  445. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  446. let value;
  447. if ( attribute.itemSize > 4 ) {
  448. // no support for interleaved data for itemSize > 4
  449. value = attribute.array[ i * attribute.itemSize + a ];
  450. } else {
  451. if ( a === 0 ) value = attribute.getX( i ); else if ( a === 1 ) value = attribute.getY( i ); else if ( a === 2 ) value = attribute.getZ( i ); else if ( a === 3 ) value = attribute.getW( i );
  452. }
  453. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  454. dataView.setFloat32( offset, value, true );
  455. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  456. dataView.setUint32( offset, value, true );
  457. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  458. dataView.setUint16( offset, value, true );
  459. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  460. dataView.setUint8( offset, value );
  461. }
  462. offset += componentSize;
  463. }
  464. }
  465. const bufferViewDef = {
  466. buffer: this.processBuffer( dataView.buffer ),
  467. byteOffset: this.byteOffset,
  468. byteLength: byteLength
  469. };
  470. if ( target !== undefined ) bufferViewDef.target = target;
  471. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  472. // Only define byteStride for vertex attributes.
  473. bufferViewDef.byteStride = attribute.itemSize * componentSize;
  474. }
  475. this.byteOffset += byteLength;
  476. json.bufferViews.push( bufferViewDef ); // @TODO Merge bufferViews where possible.
  477. const output = {
  478. id: json.bufferViews.length - 1,
  479. byteLength: 0
  480. };
  481. return output;
  482. }
  483. /**
  484. * Process and generate a BufferView from an image Blob.
  485. * @param {Blob} blob
  486. * @return {Promise<Integer>}
  487. */
  488. processBufferViewImage( blob ) {
  489. const writer = this;
  490. const json = writer.json;
  491. if ( ! json.bufferViews ) json.bufferViews = [];
  492. return new Promise( function ( resolve ) {
  493. const reader = new window.FileReader();
  494. reader.readAsArrayBuffer( blob );
  495. reader.onloadend = function () {
  496. const buffer = getPaddedArrayBuffer( reader.result );
  497. const bufferViewDef = {
  498. buffer: writer.processBuffer( buffer ),
  499. byteOffset: writer.byteOffset,
  500. byteLength: buffer.byteLength
  501. };
  502. writer.byteOffset += buffer.byteLength;
  503. resolve( json.bufferViews.push( bufferViewDef ) - 1 );
  504. };
  505. } );
  506. }
  507. /**
  508. * Process attribute to generate an accessor
  509. * @param {BufferAttribute} attribute Attribute to process
  510. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  511. * @param {Integer} start (Optional)
  512. * @param {Integer} count (Optional)
  513. * @return {Integer|null} Index of the processed accessor on the "accessors" array
  514. */
  515. processAccessor( attribute, geometry, start, count ) {
  516. const options = this.options;
  517. const json = this.json;
  518. const types = {
  519. 1: 'SCALAR',
  520. 2: 'VEC2',
  521. 3: 'VEC3',
  522. 4: 'VEC4',
  523. 16: 'MAT4'
  524. };
  525. let componentType; // Detect the component type of the attribute array (float, uint or ushort)
  526. if ( attribute.array.constructor === Float32Array ) {
  527. componentType = WEBGL_CONSTANTS.FLOAT;
  528. } else if ( attribute.array.constructor === Uint32Array ) {
  529. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  530. } else if ( attribute.array.constructor === Uint16Array ) {
  531. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  532. } else if ( attribute.array.constructor === Uint8Array ) {
  533. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  534. } else {
  535. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  536. }
  537. if ( start === undefined ) start = 0;
  538. if ( count === undefined ) count = attribute.count; // @TODO Indexed buffer geometry with drawRange not supported yet
  539. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  540. const end = start + count;
  541. const end2 = geometry.drawRange.count === Infinity ? attribute.count : geometry.drawRange.start + geometry.drawRange.count;
  542. start = Math.max( start, geometry.drawRange.start );
  543. count = Math.min( end, end2 ) - start;
  544. if ( count < 0 ) count = 0;
  545. } // Skip creating an accessor if the attribute doesn't have data to export
  546. if ( count === 0 ) return null;
  547. const minMax = getMinMax( attribute, start, count );
  548. let bufferViewTarget; // If geometry isn't provided, don't infer the target usage of the bufferView. For
  549. // animation samplers, target must not be set.
  550. if ( geometry !== undefined ) {
  551. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  552. }
  553. const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
  554. const accessorDef = {
  555. bufferView: bufferView.id,
  556. byteOffset: bufferView.byteOffset,
  557. componentType: componentType,
  558. count: count,
  559. max: minMax.max,
  560. min: minMax.min,
  561. type: types[ attribute.itemSize ]
  562. };
  563. if ( attribute.normalized === true ) accessorDef.normalized = true;
  564. if ( ! json.accessors ) json.accessors = [];
  565. return json.accessors.push( accessorDef ) - 1;
  566. }
  567. /**
  568. * Process image
  569. * @param {Image} image to process
  570. * @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
  571. * @param {Boolean} flipY before writing out the image
  572. * @return {Integer} Index of the processed texture in the "images" array
  573. */
  574. processImage( image, format, flipY ) {
  575. const writer = this;
  576. const cache = writer.cache;
  577. const json = writer.json;
  578. const options = writer.options;
  579. const pending = writer.pending;
  580. if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
  581. const cachedImages = cache.images.get( image );
  582. const mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  583. const key = mimeType + ':flipY/' + flipY.toString();
  584. if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
  585. if ( ! json.images ) json.images = [];
  586. const imageDef = {
  587. mimeType: mimeType
  588. };
  589. if ( options.embedImages ) {
  590. const canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  591. canvas.width = Math.min( image.width, options.maxTextureSize );
  592. canvas.height = Math.min( image.height, options.maxTextureSize );
  593. const ctx = canvas.getContext( '2d' );
  594. if ( flipY === true ) {
  595. ctx.translate( 0, canvas.height );
  596. ctx.scale( 1, - 1 );
  597. }
  598. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) {
  599. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  600. } else {
  601. if ( format !== THREE.RGBAFormat && format !== THREE.RGBFormat ) {
  602. console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
  603. }
  604. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  605. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  606. }
  607. const data = new Uint8ClampedArray( image.height * image.width * 4 );
  608. if ( format === THREE.RGBAFormat ) {
  609. for ( let i = 0; i < data.length; i += 4 ) {
  610. data[ i + 0 ] = image.data[ i + 0 ];
  611. data[ i + 1 ] = image.data[ i + 1 ];
  612. data[ i + 2 ] = image.data[ i + 2 ];
  613. data[ i + 3 ] = image.data[ i + 3 ];
  614. }
  615. } else {
  616. for ( let i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
  617. data[ i + 0 ] = image.data[ j + 0 ];
  618. data[ i + 1 ] = image.data[ j + 1 ];
  619. data[ i + 2 ] = image.data[ j + 2 ];
  620. data[ i + 3 ] = 255;
  621. }
  622. }
  623. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  624. }
  625. if ( options.binary === true ) {
  626. pending.push( new Promise( function ( resolve ) {
  627. canvas.toBlob( function ( blob ) {
  628. writer.processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  629. imageDef.bufferView = bufferViewIndex;
  630. resolve();
  631. } );
  632. }, mimeType );
  633. } ) );
  634. } else {
  635. imageDef.uri = canvas.toDataURL( mimeType );
  636. }
  637. } else {
  638. imageDef.uri = image.src;
  639. }
  640. const index = json.images.push( imageDef ) - 1;
  641. cachedImages[ key ] = index;
  642. return index;
  643. }
  644. /**
  645. * Process sampler
  646. * @param {Texture} map Texture to process
  647. * @return {Integer} Index of the processed texture in the "samplers" array
  648. */
  649. processSampler( map ) {
  650. const json = this.json;
  651. if ( ! json.samplers ) json.samplers = [];
  652. const samplerDef = {
  653. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  654. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  655. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  656. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  657. };
  658. return json.samplers.push( samplerDef ) - 1;
  659. }
  660. /**
  661. * Process texture
  662. * @param {Texture} map Map to process
  663. * @return {Integer} Index of the processed texture in the "textures" array
  664. */
  665. processTexture( map ) {
  666. const cache = this.cache;
  667. const json = this.json;
  668. if ( cache.textures.has( map ) ) return cache.textures.get( map );
  669. if ( ! json.textures ) json.textures = [];
  670. const textureDef = {
  671. sampler: this.processSampler( map ),
  672. source: this.processImage( map.image, map.format, map.flipY )
  673. };
  674. if ( map.name ) textureDef.name = map.name;
  675. this._invokeAll( function ( ext ) {
  676. ext.writeTexture && ext.writeTexture( map, textureDef );
  677. } );
  678. const index = json.textures.push( textureDef ) - 1;
  679. cache.textures.set( map, index );
  680. return index;
  681. }
  682. /**
  683. * Process material
  684. * @param {THREE.Material} material Material to process
  685. * @return {Integer|null} Index of the processed material in the "materials" array
  686. */
  687. processMaterial( material ) {
  688. const cache = this.cache;
  689. const json = this.json;
  690. if ( cache.materials.has( material ) ) return cache.materials.get( material );
  691. if ( material.isShaderMaterial ) {
  692. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  693. return null;
  694. }
  695. if ( ! json.materials ) json.materials = []; // @QUESTION Should we avoid including any attribute that has the default value?
  696. const materialDef = {
  697. pbrMetallicRoughness: {}
  698. };
  699. if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
  700. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  701. } // pbrMetallicRoughness.baseColorFactor
  702. const color = material.color.toArray().concat( [ material.opacity ] );
  703. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  704. materialDef.pbrMetallicRoughness.baseColorFactor = color;
  705. }
  706. if ( material.isMeshStandardMaterial ) {
  707. materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
  708. materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
  709. } else {
  710. materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
  711. materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
  712. } // pbrMetallicRoughness.metallicRoughnessTexture
  713. if ( material.metalnessMap || material.roughnessMap ) {
  714. if ( material.metalnessMap === material.roughnessMap ) {
  715. const metalRoughMapDef = {
  716. index: this.processTexture( material.metalnessMap )
  717. };
  718. this.applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  719. materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  720. } else {
  721. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  722. }
  723. } // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
  724. if ( material.map ) {
  725. const baseColorMapDef = {
  726. index: this.processTexture( material.map )
  727. };
  728. this.applyTextureTransform( baseColorMapDef, material.map );
  729. materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  730. }
  731. if ( material.emissive ) {
  732. // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000.
  733. const emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity );
  734. const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
  735. if ( maxEmissiveComponent > 1 ) {
  736. emissive.multiplyScalar( 1 / maxEmissiveComponent );
  737. console.warn( 'THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited' );
  738. }
  739. if ( maxEmissiveComponent > 0 ) {
  740. materialDef.emissiveFactor = emissive.toArray();
  741. } // emissiveTexture
  742. if ( material.emissiveMap ) {
  743. const emissiveMapDef = {
  744. index: this.processTexture( material.emissiveMap )
  745. };
  746. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  747. materialDef.emissiveTexture = emissiveMapDef;
  748. }
  749. } // normalTexture
  750. if ( material.normalMap ) {
  751. const normalMapDef = {
  752. index: this.processTexture( material.normalMap )
  753. };
  754. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  755. if ( material.normalScale.x !== material.normalScale.y ) {
  756. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  757. }
  758. normalMapDef.scale = material.normalScale.x;
  759. }
  760. this.applyTextureTransform( normalMapDef, material.normalMap );
  761. materialDef.normalTexture = normalMapDef;
  762. } // occlusionTexture
  763. if ( material.aoMap ) {
  764. const occlusionMapDef = {
  765. index: this.processTexture( material.aoMap ),
  766. texCoord: 1
  767. };
  768. if ( material.aoMapIntensity !== 1.0 ) {
  769. occlusionMapDef.strength = material.aoMapIntensity;
  770. }
  771. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  772. materialDef.occlusionTexture = occlusionMapDef;
  773. } // alphaMode
  774. if ( material.transparent ) {
  775. materialDef.alphaMode = 'BLEND';
  776. } else {
  777. if ( material.alphaTest > 0.0 ) {
  778. materialDef.alphaMode = 'MASK';
  779. materialDef.alphaCutoff = material.alphaTest;
  780. }
  781. } // doubleSided
  782. if ( material.side === THREE.DoubleSide ) materialDef.doubleSided = true;
  783. if ( material.name !== '' ) materialDef.name = material.name;
  784. this.serializeUserData( material, materialDef );
  785. this._invokeAll( function ( ext ) {
  786. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  787. } );
  788. const index = json.materials.push( materialDef ) - 1;
  789. cache.materials.set( material, index );
  790. return index;
  791. }
  792. /**
  793. * Process mesh
  794. * @param {THREE.Mesh} mesh Mesh to process
  795. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  796. */
  797. processMesh( mesh ) {
  798. const cache = this.cache;
  799. const json = this.json;
  800. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  801. if ( Array.isArray( mesh.material ) ) {
  802. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  803. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  804. }
  805. } else {
  806. meshCacheKeyParts.push( mesh.material.uuid );
  807. }
  808. const meshCacheKey = meshCacheKeyParts.join( ':' );
  809. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  810. const geometry = mesh.geometry;
  811. let mode; // Use the correct mode
  812. if ( mesh.isLineSegments ) {
  813. mode = WEBGL_CONSTANTS.LINES;
  814. } else if ( mesh.isLineLoop ) {
  815. mode = WEBGL_CONSTANTS.LINE_LOOP;
  816. } else if ( mesh.isLine ) {
  817. mode = WEBGL_CONSTANTS.LINE_STRIP;
  818. } else if ( mesh.isPoints ) {
  819. mode = WEBGL_CONSTANTS.POINTS;
  820. } else {
  821. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  822. }
  823. if ( geometry.isBufferGeometry !== true ) {
  824. throw new Error( 'THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.' );
  825. }
  826. const meshDef = {};
  827. const attributes = {};
  828. const primitives = [];
  829. const targets = []; // Conversion between attributes names in threejs and gltf spec
  830. const nameConversion = {
  831. uv: 'TEXCOORD_0',
  832. uv2: 'TEXCOORD_1',
  833. color: 'COLOR_0',
  834. skinWeight: 'WEIGHTS_0',
  835. skinIndex: 'JOINTS_0'
  836. };
  837. const originalNormal = geometry.getAttribute( 'normal' );
  838. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  839. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  840. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  841. } // @QUESTION Detect if .vertexColors = true?
  842. // For every attribute create an accessor
  843. let modifiedAttribute = null;
  844. for ( let attributeName in geometry.attributes ) {
  845. // Ignore morph target attributes, which are exported later.
  846. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  847. const attribute = geometry.attributes[ attributeName ];
  848. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase(); // Prefix all geometry attributes except the ones specifically
  849. // listed in the spec; non-spec attributes are considered custom.
  850. const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  851. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  852. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  853. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  854. continue;
  855. } // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  856. modifiedAttribute = null;
  857. const array = attribute.array;
  858. if ( attributeName === 'JOINTS_0' && ! ( array instanceof Uint16Array ) && ! ( array instanceof Uint8Array ) ) {
  859. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  860. modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  861. }
  862. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  863. if ( accessor !== null ) {
  864. attributes[ attributeName ] = accessor;
  865. cache.attributes.set( this.getUID( attribute ), accessor );
  866. }
  867. }
  868. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal ); // Skip if no exportable attributes found
  869. if ( Object.keys( attributes ).length === 0 ) return null; // Morph targets
  870. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  871. const weights = [];
  872. const targetNames = [];
  873. const reverseDictionary = {};
  874. if ( mesh.morphTargetDictionary !== undefined ) {
  875. for ( const key in mesh.morphTargetDictionary ) {
  876. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  877. }
  878. }
  879. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  880. const target = {};
  881. let warned = false;
  882. for ( const attributeName in geometry.morphAttributes ) {
  883. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  884. // Three.js doesn't support TANGENT yet.
  885. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  886. if ( ! warned ) {
  887. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  888. warned = true;
  889. }
  890. continue;
  891. }
  892. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  893. const gltfAttributeName = attributeName.toUpperCase(); // Three.js morph attribute has absolute values while the one of glTF has relative values.
  894. //
  895. // glTF 2.0 Specification:
  896. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  897. const baseAttribute = geometry.attributes[ attributeName ];
  898. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  899. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute ) );
  900. continue;
  901. } // Clones attribute not to override
  902. const relativeAttribute = attribute.clone();
  903. if ( ! geometry.morphTargetsRelative ) {
  904. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  905. relativeAttribute.setXYZ( j, attribute.getX( j ) - baseAttribute.getX( j ), attribute.getY( j ) - baseAttribute.getY( j ), attribute.getZ( j ) - baseAttribute.getZ( j ) );
  906. }
  907. }
  908. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  909. cache.attributes.set( this.getUID( baseAttribute ), target[ gltfAttributeName ] );
  910. }
  911. targets.push( target );
  912. weights.push( mesh.morphTargetInfluences[ i ] );
  913. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  914. }
  915. meshDef.weights = weights;
  916. if ( targetNames.length > 0 ) {
  917. meshDef.extras = {};
  918. meshDef.extras.targetNames = targetNames;
  919. }
  920. }
  921. const isMultiMaterial = Array.isArray( mesh.material );
  922. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  923. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  924. const groups = isMultiMaterial ? geometry.groups : [ {
  925. materialIndex: 0,
  926. start: undefined,
  927. count: undefined
  928. } ];
  929. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  930. const primitive = {
  931. mode: mode,
  932. attributes: attributes
  933. };
  934. this.serializeUserData( geometry, primitive );
  935. if ( targets.length > 0 ) primitive.targets = targets;
  936. if ( geometry.index !== null ) {
  937. let cacheKey = this.getUID( geometry.index );
  938. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  939. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  940. }
  941. if ( cache.attributes.has( cacheKey ) ) {
  942. primitive.indices = cache.attributes.get( cacheKey );
  943. } else {
  944. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  945. cache.attributes.set( cacheKey, primitive.indices );
  946. }
  947. if ( primitive.indices === null ) delete primitive.indices;
  948. }
  949. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  950. if ( material !== null ) primitive.material = material;
  951. primitives.push( primitive );
  952. }
  953. meshDef.primitives = primitives;
  954. if ( ! json.meshes ) json.meshes = [];
  955. this._invokeAll( function ( ext ) {
  956. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  957. } );
  958. const index = json.meshes.push( meshDef ) - 1;
  959. cache.meshes.set( meshCacheKey, index );
  960. return index;
  961. }
  962. /**
  963. * Process camera
  964. * @param {THREE.Camera} camera Camera to process
  965. * @return {Integer} Index of the processed mesh in the "camera" array
  966. */
  967. processCamera( camera ) {
  968. const json = this.json;
  969. if ( ! json.cameras ) json.cameras = [];
  970. const isOrtho = camera.isOrthographicCamera;
  971. const cameraDef = {
  972. type: isOrtho ? 'orthographic' : 'perspective'
  973. };
  974. if ( isOrtho ) {
  975. cameraDef.orthographic = {
  976. xmag: camera.right * 2,
  977. ymag: camera.top * 2,
  978. zfar: camera.far <= 0 ? 0.001 : camera.far,
  979. znear: camera.near < 0 ? 0 : camera.near
  980. };
  981. } else {
  982. cameraDef.perspective = {
  983. aspectRatio: camera.aspect,
  984. yfov: THREE.MathUtils.degToRad( camera.fov ),
  985. zfar: camera.far <= 0 ? 0.001 : camera.far,
  986. znear: camera.near < 0 ? 0 : camera.near
  987. };
  988. } // Question: Is saving "type" as name intentional?
  989. if ( camera.name !== '' ) cameraDef.name = camera.type;
  990. return json.cameras.push( cameraDef ) - 1;
  991. }
  992. /**
  993. * Creates glTF animation entry from AnimationClip object.
  994. *
  995. * Status:
  996. * - Only properties listed in PATH_PROPERTIES may be animated.
  997. *
  998. * @param {THREE.AnimationClip} clip
  999. * @param {THREE.Object3D} root
  1000. * @return {number|null}
  1001. */
  1002. processAnimation( clip, root ) {
  1003. const json = this.json;
  1004. const nodeMap = this.nodeMap;
  1005. if ( ! json.animations ) json.animations = [];
  1006. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1007. const tracks = clip.tracks;
  1008. const channels = [];
  1009. const samplers = [];
  1010. for ( let i = 0; i < tracks.length; ++ i ) {
  1011. const track = tracks[ i ];
  1012. const trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  1013. let trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  1014. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1015. if ( trackBinding.objectName === 'bones' ) {
  1016. if ( trackNode.isSkinnedMesh === true ) {
  1017. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1018. } else {
  1019. trackNode = undefined;
  1020. }
  1021. }
  1022. if ( ! trackNode || ! trackProperty ) {
  1023. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1024. return null;
  1025. }
  1026. const inputItemSize = 1;
  1027. let outputItemSize = track.values.length / track.times.length;
  1028. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1029. outputItemSize /= trackNode.morphTargetInfluences.length;
  1030. }
  1031. let interpolation; // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1032. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1033. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1034. // valid value from .getInterpolation().
  1035. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1036. interpolation = 'CUBICSPLINE'; // itemSize of CUBICSPLINE keyframe is 9
  1037. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1038. // but needs to be stored as VEC3 so dividing by 3 here.
  1039. outputItemSize /= 3;
  1040. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  1041. interpolation = 'STEP';
  1042. } else {
  1043. interpolation = 'LINEAR';
  1044. }
  1045. samplers.push( {
  1046. input: this.processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  1047. output: this.processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  1048. interpolation: interpolation
  1049. } );
  1050. channels.push( {
  1051. sampler: samplers.length - 1,
  1052. target: {
  1053. node: nodeMap.get( trackNode ),
  1054. path: trackProperty
  1055. }
  1056. } );
  1057. }
  1058. json.animations.push( {
  1059. name: clip.name || 'clip_' + json.animations.length,
  1060. samplers: samplers,
  1061. channels: channels
  1062. } );
  1063. return json.animations.length - 1;
  1064. }
  1065. /**
  1066. * @param {THREE.Object3D} object
  1067. * @return {number|null}
  1068. */
  1069. processSkin( object ) {
  1070. const json = this.json;
  1071. const nodeMap = this.nodeMap;
  1072. const node = json.nodes[ nodeMap.get( object ) ];
  1073. const skeleton = object.skeleton;
  1074. if ( skeleton === undefined ) return null;
  1075. const rootJoint = object.skeleton.bones[ 0 ];
  1076. if ( rootJoint === undefined ) return null;
  1077. const joints = [];
  1078. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1079. const temporaryBoneInverse = new THREE.Matrix4();
  1080. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1081. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1082. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1083. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1084. }
  1085. if ( json.skins === undefined ) json.skins = [];
  1086. json.skins.push( {
  1087. inverseBindMatrices: this.processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  1088. joints: joints,
  1089. skeleton: nodeMap.get( rootJoint )
  1090. } );
  1091. const skinIndex = node.skin = json.skins.length - 1;
  1092. return skinIndex;
  1093. }
  1094. /**
  1095. * Process Object3D node
  1096. * @param {THREE.Object3D} node Object3D to processNode
  1097. * @return {Integer} Index of the node in the nodes list
  1098. */
  1099. processNode( object ) {
  1100. const json = this.json;
  1101. const options = this.options;
  1102. const nodeMap = this.nodeMap;
  1103. if ( ! json.nodes ) json.nodes = [];
  1104. const nodeDef = {};
  1105. if ( options.trs ) {
  1106. const rotation = object.quaternion.toArray();
  1107. const position = object.position.toArray();
  1108. const scale = object.scale.toArray();
  1109. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1110. nodeDef.rotation = rotation;
  1111. }
  1112. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1113. nodeDef.translation = position;
  1114. }
  1115. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1116. nodeDef.scale = scale;
  1117. }
  1118. } else {
  1119. if ( object.matrixAutoUpdate ) {
  1120. object.updateMatrix();
  1121. }
  1122. if ( isIdentityMatrix( object.matrix ) === false ) {
  1123. nodeDef.matrix = object.matrix.elements;
  1124. }
  1125. } // We don't export empty strings name because it represents no-name in Three.js.
  1126. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1127. this.serializeUserData( object, nodeDef );
  1128. if ( object.isMesh || object.isLine || object.isPoints ) {
  1129. const meshIndex = this.processMesh( object );
  1130. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1131. } else if ( object.isCamera ) {
  1132. nodeDef.camera = this.processCamera( object );
  1133. }
  1134. if ( object.isSkinnedMesh ) this.skins.push( object );
  1135. if ( object.children.length > 0 ) {
  1136. const children = [];
  1137. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1138. const child = object.children[ i ];
  1139. if ( child.visible || options.onlyVisible === false ) {
  1140. const nodeIndex = this.processNode( child );
  1141. if ( nodeIndex !== null ) children.push( nodeIndex );
  1142. }
  1143. }
  1144. if ( children.length > 0 ) nodeDef.children = children;
  1145. }
  1146. this._invokeAll( function ( ext ) {
  1147. ext.writeNode && ext.writeNode( object, nodeDef );
  1148. } );
  1149. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1150. nodeMap.set( object, nodeIndex );
  1151. return nodeIndex;
  1152. }
  1153. /**
  1154. * Process THREE.Scene
  1155. * @param {Scene} node THREE.Scene to process
  1156. */
  1157. processScene( scene ) {
  1158. const json = this.json;
  1159. const options = this.options;
  1160. if ( ! json.scenes ) {
  1161. json.scenes = [];
  1162. json.scene = 0;
  1163. }
  1164. const sceneDef = {};
  1165. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1166. json.scenes.push( sceneDef );
  1167. const nodes = [];
  1168. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1169. const child = scene.children[ i ];
  1170. if ( child.visible || options.onlyVisible === false ) {
  1171. const nodeIndex = this.processNode( child );
  1172. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1173. }
  1174. }
  1175. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1176. this.serializeUserData( scene, sceneDef );
  1177. }
  1178. /**
  1179. * Creates a THREE.Scene to hold a list of objects and parse it
  1180. * @param {Array} objects List of objects to process
  1181. */
  1182. processObjects( objects ) {
  1183. const scene = new THREE.Scene();
  1184. scene.name = 'AuxScene';
  1185. for ( let i = 0; i < objects.length; i ++ ) {
  1186. // We push directly to children instead of calling `add` to prevent
  1187. // modify the .parent and break its original scene and hierarchy
  1188. scene.children.push( objects[ i ] );
  1189. }
  1190. this.processScene( scene );
  1191. }
  1192. /**
  1193. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1194. */
  1195. processInput( input ) {
  1196. const options = this.options;
  1197. input = input instanceof Array ? input : [ input ];
  1198. this._invokeAll( function ( ext ) {
  1199. ext.beforeParse && ext.beforeParse( input );
  1200. } );
  1201. const objectsWithoutScene = [];
  1202. for ( let i = 0; i < input.length; i ++ ) {
  1203. if ( input[ i ] instanceof THREE.Scene ) {
  1204. this.processScene( input[ i ] );
  1205. } else {
  1206. objectsWithoutScene.push( input[ i ] );
  1207. }
  1208. }
  1209. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1210. for ( let i = 0; i < this.skins.length; ++ i ) {
  1211. this.processSkin( this.skins[ i ] );
  1212. }
  1213. for ( let i = 0; i < options.animations.length; ++ i ) {
  1214. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1215. }
  1216. this._invokeAll( function ( ext ) {
  1217. ext.afterParse && ext.afterParse( input );
  1218. } );
  1219. }
  1220. _invokeAll( func ) {
  1221. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1222. func( this.plugins[ i ] );
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Punctual Lights Extension
  1228. *
  1229. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1230. */
  1231. class GLTFLightExtension {
  1232. constructor( writer ) {
  1233. this.writer = writer;
  1234. this.name = 'KHR_lights_punctual';
  1235. }
  1236. writeNode( light, nodeDef ) {
  1237. if ( ! light.isLight ) return;
  1238. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1239. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1240. return;
  1241. }
  1242. const writer = this.writer;
  1243. const json = writer.json;
  1244. const extensionsUsed = writer.extensionsUsed;
  1245. const lightDef = {};
  1246. if ( light.name ) lightDef.name = light.name;
  1247. lightDef.color = light.color.toArray();
  1248. lightDef.intensity = light.intensity;
  1249. if ( light.isDirectionalLight ) {
  1250. lightDef.type = 'directional';
  1251. } else if ( light.isPointLight ) {
  1252. lightDef.type = 'point';
  1253. if ( light.distance > 0 ) lightDef.range = light.distance;
  1254. } else if ( light.isSpotLight ) {
  1255. lightDef.type = 'spot';
  1256. if ( light.distance > 0 ) lightDef.range = light.distance;
  1257. lightDef.spot = {};
  1258. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1259. lightDef.spot.outerConeAngle = light.angle;
  1260. }
  1261. if ( light.decay !== undefined && light.decay !== 2 ) {
  1262. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + 'and expects light.decay=2.' );
  1263. }
  1264. if ( light.target && ( light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== - 1 ) ) {
  1265. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, ' + 'make light.target a child of the light with position 0,0,-1.' );
  1266. }
  1267. if ( ! extensionsUsed[ this.name ] ) {
  1268. json.extensions = json.extensions || {};
  1269. json.extensions[ this.name ] = {
  1270. lights: []
  1271. };
  1272. extensionsUsed[ this.name ] = true;
  1273. }
  1274. const lights = json.extensions[ this.name ].lights;
  1275. lights.push( lightDef );
  1276. nodeDef.extensions = nodeDef.extensions || {};
  1277. nodeDef.extensions[ this.name ] = {
  1278. light: lights.length - 1
  1279. };
  1280. }
  1281. }
  1282. /**
  1283. * Unlit Materials Extension
  1284. *
  1285. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1286. */
  1287. class GLTFMaterialsUnlitExtension {
  1288. constructor( writer ) {
  1289. this.writer = writer;
  1290. this.name = 'KHR_materials_unlit';
  1291. }
  1292. writeMaterial( material, materialDef ) {
  1293. if ( ! material.isMeshBasicMaterial ) return;
  1294. const writer = this.writer;
  1295. const extensionsUsed = writer.extensionsUsed;
  1296. materialDef.extensions = materialDef.extensions || {};
  1297. materialDef.extensions[ this.name ] = {};
  1298. extensionsUsed[ this.name ] = true;
  1299. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1300. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1301. }
  1302. }
  1303. /**
  1304. * Specular-Glossiness Extension
  1305. *
  1306. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  1307. */
  1308. class GLTFMaterialsPBRSpecularGlossiness {
  1309. constructor( writer ) {
  1310. this.writer = writer;
  1311. this.name = 'KHR_materials_pbrSpecularGlossiness';
  1312. }
  1313. writeMaterial( material, materialDef ) {
  1314. if ( ! material.isGLTFSpecularGlossinessMaterial ) return;
  1315. const writer = this.writer;
  1316. const extensionsUsed = writer.extensionsUsed;
  1317. const extensionDef = {};
  1318. if ( materialDef.pbrMetallicRoughness.baseColorFactor ) {
  1319. extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor;
  1320. }
  1321. const specularFactor = [ 1, 1, 1 ];
  1322. material.specular.toArray( specularFactor, 0 );
  1323. extensionDef.specularFactor = specularFactor;
  1324. extensionDef.glossinessFactor = material.glossiness;
  1325. if ( materialDef.pbrMetallicRoughness.baseColorTexture ) {
  1326. extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture;
  1327. }
  1328. if ( material.specularMap ) {
  1329. const specularMapDef = {
  1330. index: writer.processTexture( material.specularMap )
  1331. };
  1332. writer.applyTextureTransform( specularMapDef, material.specularMap );
  1333. extensionDef.specularGlossinessTexture = specularMapDef;
  1334. }
  1335. materialDef.extensions = materialDef.extensions || {};
  1336. materialDef.extensions[ this.name ] = extensionDef;
  1337. extensionsUsed[ this.name ] = true;
  1338. }
  1339. }
  1340. /**
  1341. * Static utility functions
  1342. */
  1343. GLTFExporter.Utils = {
  1344. insertKeyframe: function ( track, time ) {
  1345. const tolerance = 0.001; // 1ms
  1346. const valueSize = track.getValueSize();
  1347. const times = new track.TimeBufferType( track.times.length + 1 );
  1348. const values = new track.ValueBufferType( track.values.length + valueSize );
  1349. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1350. let index;
  1351. if ( track.times.length === 0 ) {
  1352. times[ 0 ] = time;
  1353. for ( let i = 0; i < valueSize; i ++ ) {
  1354. values[ i ] = 0;
  1355. }
  1356. index = 0;
  1357. } else if ( time < track.times[ 0 ] ) {
  1358. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1359. times[ 0 ] = time;
  1360. times.set( track.times, 1 );
  1361. values.set( interpolant.evaluate( time ), 0 );
  1362. values.set( track.values, valueSize );
  1363. index = 0;
  1364. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1365. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1366. return track.times.length - 1;
  1367. }
  1368. times[ times.length - 1 ] = time;
  1369. times.set( track.times, 0 );
  1370. values.set( track.values, 0 );
  1371. values.set( interpolant.evaluate( time ), track.values.length );
  1372. index = times.length - 1;
  1373. } else {
  1374. for ( let i = 0; i < track.times.length; i ++ ) {
  1375. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1376. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1377. times.set( track.times.slice( 0, i + 1 ), 0 );
  1378. times[ i + 1 ] = time;
  1379. times.set( track.times.slice( i + 1 ), i + 2 );
  1380. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1381. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1382. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1383. index = i + 1;
  1384. break;
  1385. }
  1386. }
  1387. }
  1388. track.times = times;
  1389. track.values = values;
  1390. return index;
  1391. },
  1392. mergeMorphTargetTracks: function ( clip, root ) {
  1393. const tracks = [];
  1394. const mergedTracks = {};
  1395. const sourceTracks = clip.tracks;
  1396. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  1397. let sourceTrack = sourceTracks[ i ];
  1398. const sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
  1399. const sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1400. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1401. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1402. tracks.push( sourceTrack );
  1403. continue;
  1404. }
  1405. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1406. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1407. // This should never happen, because glTF morph target animations
  1408. // affect all targets already.
  1409. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1410. }
  1411. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1412. sourceTrack = sourceTrack.clone();
  1413. sourceTrack.setInterpolation( THREE.InterpolateLinear );
  1414. }
  1415. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  1416. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1417. if ( targetIndex === undefined ) {
  1418. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1419. }
  1420. let mergedTrack; // If this is the first time we've seen this object, create a new
  1421. // track to store merged keyframe data for each morph target.
  1422. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1423. mergedTrack = sourceTrack.clone();
  1424. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1425. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1426. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1427. } // We need to take into consideration the intended target node
  1428. // of our original un-merged morphTarget animation.
  1429. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  1430. mergedTrack.values = values;
  1431. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1432. tracks.push( mergedTrack );
  1433. continue;
  1434. }
  1435. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1436. mergedTrack = mergedTracks[ sourceTrackNode.uuid ]; // For every existing keyframe of the merged track, write a (possibly
  1437. // interpolated) value from the source track.
  1438. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1439. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1440. } // For every existing keyframe of the source track, write a (possibly
  1441. // new) keyframe to the merged track. Values from the previous loop may
  1442. // be written again, but keyframes are de-duplicated.
  1443. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  1444. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1445. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1446. }
  1447. }
  1448. clip.tracks = tracks;
  1449. return clip;
  1450. }
  1451. };
  1452. THREE.GLTFExporter = GLTFExporter;
  1453. } )();