GLTFExporter.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  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` is not scaled by `material.emissiveIntensity` for now to accommodate glTF spec. see #21849.
  733. const emissive = material.emissive.toArray();
  734. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  735. materialDef.emissiveFactor = emissive;
  736. } // emissiveTexture
  737. if ( material.emissiveMap ) {
  738. const emissiveMapDef = {
  739. index: this.processTexture( material.emissiveMap )
  740. };
  741. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  742. materialDef.emissiveTexture = emissiveMapDef;
  743. }
  744. } // normalTexture
  745. if ( material.normalMap ) {
  746. const normalMapDef = {
  747. index: this.processTexture( material.normalMap )
  748. };
  749. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  750. if ( material.normalScale.x !== material.normalScale.y ) {
  751. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  752. }
  753. normalMapDef.scale = material.normalScale.x;
  754. }
  755. this.applyTextureTransform( normalMapDef, material.normalMap );
  756. materialDef.normalTexture = normalMapDef;
  757. } // occlusionTexture
  758. if ( material.aoMap ) {
  759. const occlusionMapDef = {
  760. index: this.processTexture( material.aoMap ),
  761. texCoord: 1
  762. };
  763. if ( material.aoMapIntensity !== 1.0 ) {
  764. occlusionMapDef.strength = material.aoMapIntensity;
  765. }
  766. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  767. materialDef.occlusionTexture = occlusionMapDef;
  768. } // alphaMode
  769. if ( material.transparent ) {
  770. materialDef.alphaMode = 'BLEND';
  771. } else {
  772. if ( material.alphaTest > 0.0 ) {
  773. materialDef.alphaMode = 'MASK';
  774. materialDef.alphaCutoff = material.alphaTest;
  775. }
  776. } // doubleSided
  777. if ( material.side === THREE.DoubleSide ) materialDef.doubleSided = true;
  778. if ( material.name !== '' ) materialDef.name = material.name;
  779. this.serializeUserData( material, materialDef );
  780. this._invokeAll( function ( ext ) {
  781. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  782. } );
  783. const index = json.materials.push( materialDef ) - 1;
  784. cache.materials.set( material, index );
  785. return index;
  786. }
  787. /**
  788. * Process mesh
  789. * @param {THREE.Mesh} mesh Mesh to process
  790. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  791. */
  792. processMesh( mesh ) {
  793. const cache = this.cache;
  794. const json = this.json;
  795. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  796. if ( Array.isArray( mesh.material ) ) {
  797. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  798. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  799. }
  800. } else {
  801. meshCacheKeyParts.push( mesh.material.uuid );
  802. }
  803. const meshCacheKey = meshCacheKeyParts.join( ':' );
  804. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  805. const geometry = mesh.geometry;
  806. let mode; // Use the correct mode
  807. if ( mesh.isLineSegments ) {
  808. mode = WEBGL_CONSTANTS.LINES;
  809. } else if ( mesh.isLineLoop ) {
  810. mode = WEBGL_CONSTANTS.LINE_LOOP;
  811. } else if ( mesh.isLine ) {
  812. mode = WEBGL_CONSTANTS.LINE_STRIP;
  813. } else if ( mesh.isPoints ) {
  814. mode = WEBGL_CONSTANTS.POINTS;
  815. } else {
  816. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  817. }
  818. if ( geometry.isBufferGeometry !== true ) {
  819. throw new Error( 'THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.' );
  820. }
  821. const meshDef = {};
  822. const attributes = {};
  823. const primitives = [];
  824. const targets = []; // Conversion between attributes names in threejs and gltf spec
  825. const nameConversion = {
  826. uv: 'TEXCOORD_0',
  827. uv2: 'TEXCOORD_1',
  828. color: 'COLOR_0',
  829. skinWeight: 'WEIGHTS_0',
  830. skinIndex: 'JOINTS_0'
  831. };
  832. const originalNormal = geometry.getAttribute( 'normal' );
  833. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  834. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  835. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  836. } // @QUESTION Detect if .vertexColors = true?
  837. // For every attribute create an accessor
  838. let modifiedAttribute = null;
  839. for ( let attributeName in geometry.attributes ) {
  840. // Ignore morph target attributes, which are exported later.
  841. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  842. const attribute = geometry.attributes[ attributeName ];
  843. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase(); // Prefix all geometry attributes except the ones specifically
  844. // listed in the spec; non-spec attributes are considered custom.
  845. const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  846. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  847. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  848. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  849. continue;
  850. } // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  851. modifiedAttribute = null;
  852. const array = attribute.array;
  853. if ( attributeName === 'JOINTS_0' && ! ( array instanceof Uint16Array ) && ! ( array instanceof Uint8Array ) ) {
  854. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  855. modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  856. }
  857. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  858. if ( accessor !== null ) {
  859. attributes[ attributeName ] = accessor;
  860. cache.attributes.set( this.getUID( attribute ), accessor );
  861. }
  862. }
  863. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal ); // Skip if no exportable attributes found
  864. if ( Object.keys( attributes ).length === 0 ) return null; // Morph targets
  865. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  866. const weights = [];
  867. const targetNames = [];
  868. const reverseDictionary = {};
  869. if ( mesh.morphTargetDictionary !== undefined ) {
  870. for ( const key in mesh.morphTargetDictionary ) {
  871. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  872. }
  873. }
  874. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  875. const target = {};
  876. let warned = false;
  877. for ( const attributeName in geometry.morphAttributes ) {
  878. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  879. // Three.js doesn't support TANGENT yet.
  880. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  881. if ( ! warned ) {
  882. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  883. warned = true;
  884. }
  885. continue;
  886. }
  887. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  888. const gltfAttributeName = attributeName.toUpperCase(); // Three.js morph attribute has absolute values while the one of glTF has relative values.
  889. //
  890. // glTF 2.0 Specification:
  891. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  892. const baseAttribute = geometry.attributes[ attributeName ];
  893. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  894. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute ) );
  895. continue;
  896. } // Clones attribute not to override
  897. const relativeAttribute = attribute.clone();
  898. if ( ! geometry.morphTargetsRelative ) {
  899. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  900. relativeAttribute.setXYZ( j, attribute.getX( j ) - baseAttribute.getX( j ), attribute.getY( j ) - baseAttribute.getY( j ), attribute.getZ( j ) - baseAttribute.getZ( j ) );
  901. }
  902. }
  903. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  904. cache.attributes.set( this.getUID( baseAttribute ), target[ gltfAttributeName ] );
  905. }
  906. targets.push( target );
  907. weights.push( mesh.morphTargetInfluences[ i ] );
  908. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  909. }
  910. meshDef.weights = weights;
  911. if ( targetNames.length > 0 ) {
  912. meshDef.extras = {};
  913. meshDef.extras.targetNames = targetNames;
  914. }
  915. }
  916. const isMultiMaterial = Array.isArray( mesh.material );
  917. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  918. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  919. const groups = isMultiMaterial ? geometry.groups : [ {
  920. materialIndex: 0,
  921. start: undefined,
  922. count: undefined
  923. } ];
  924. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  925. const primitive = {
  926. mode: mode,
  927. attributes: attributes
  928. };
  929. this.serializeUserData( geometry, primitive );
  930. if ( targets.length > 0 ) primitive.targets = targets;
  931. if ( geometry.index !== null ) {
  932. let cacheKey = this.getUID( geometry.index );
  933. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  934. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  935. }
  936. if ( cache.attributes.has( cacheKey ) ) {
  937. primitive.indices = cache.attributes.get( cacheKey );
  938. } else {
  939. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  940. cache.attributes.set( cacheKey, primitive.indices );
  941. }
  942. if ( primitive.indices === null ) delete primitive.indices;
  943. }
  944. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  945. if ( material !== null ) primitive.material = material;
  946. primitives.push( primitive );
  947. }
  948. meshDef.primitives = primitives;
  949. if ( ! json.meshes ) json.meshes = [];
  950. this._invokeAll( function ( ext ) {
  951. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  952. } );
  953. const index = json.meshes.push( meshDef ) - 1;
  954. cache.meshes.set( meshCacheKey, index );
  955. return index;
  956. }
  957. /**
  958. * Process camera
  959. * @param {THREE.Camera} camera Camera to process
  960. * @return {Integer} Index of the processed mesh in the "camera" array
  961. */
  962. processCamera( camera ) {
  963. const json = this.json;
  964. if ( ! json.cameras ) json.cameras = [];
  965. const isOrtho = camera.isOrthographicCamera;
  966. const cameraDef = {
  967. type: isOrtho ? 'orthographic' : 'perspective'
  968. };
  969. if ( isOrtho ) {
  970. cameraDef.orthographic = {
  971. xmag: camera.right * 2,
  972. ymag: camera.top * 2,
  973. zfar: camera.far <= 0 ? 0.001 : camera.far,
  974. znear: camera.near < 0 ? 0 : camera.near
  975. };
  976. } else {
  977. cameraDef.perspective = {
  978. aspectRatio: camera.aspect,
  979. yfov: THREE.MathUtils.degToRad( camera.fov ),
  980. zfar: camera.far <= 0 ? 0.001 : camera.far,
  981. znear: camera.near < 0 ? 0 : camera.near
  982. };
  983. } // Question: Is saving "type" as name intentional?
  984. if ( camera.name !== '' ) cameraDef.name = camera.type;
  985. return json.cameras.push( cameraDef ) - 1;
  986. }
  987. /**
  988. * Creates glTF animation entry from AnimationClip object.
  989. *
  990. * Status:
  991. * - Only properties listed in PATH_PROPERTIES may be animated.
  992. *
  993. * @param {THREE.AnimationClip} clip
  994. * @param {THREE.Object3D} root
  995. * @return {number|null}
  996. */
  997. processAnimation( clip, root ) {
  998. const json = this.json;
  999. const nodeMap = this.nodeMap;
  1000. if ( ! json.animations ) json.animations = [];
  1001. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1002. const tracks = clip.tracks;
  1003. const channels = [];
  1004. const samplers = [];
  1005. for ( let i = 0; i < tracks.length; ++ i ) {
  1006. const track = tracks[ i ];
  1007. const trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  1008. let trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  1009. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1010. if ( trackBinding.objectName === 'bones' ) {
  1011. if ( trackNode.isSkinnedMesh === true ) {
  1012. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1013. } else {
  1014. trackNode = undefined;
  1015. }
  1016. }
  1017. if ( ! trackNode || ! trackProperty ) {
  1018. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1019. return null;
  1020. }
  1021. const inputItemSize = 1;
  1022. let outputItemSize = track.values.length / track.times.length;
  1023. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1024. outputItemSize /= trackNode.morphTargetInfluences.length;
  1025. }
  1026. let interpolation; // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1027. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1028. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1029. // valid value from .getInterpolation().
  1030. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1031. interpolation = 'CUBICSPLINE'; // itemSize of CUBICSPLINE keyframe is 9
  1032. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1033. // but needs to be stored as VEC3 so dividing by 3 here.
  1034. outputItemSize /= 3;
  1035. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  1036. interpolation = 'STEP';
  1037. } else {
  1038. interpolation = 'LINEAR';
  1039. }
  1040. samplers.push( {
  1041. input: this.processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  1042. output: this.processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  1043. interpolation: interpolation
  1044. } );
  1045. channels.push( {
  1046. sampler: samplers.length - 1,
  1047. target: {
  1048. node: nodeMap.get( trackNode ),
  1049. path: trackProperty
  1050. }
  1051. } );
  1052. }
  1053. json.animations.push( {
  1054. name: clip.name || 'clip_' + json.animations.length,
  1055. samplers: samplers,
  1056. channels: channels
  1057. } );
  1058. return json.animations.length - 1;
  1059. }
  1060. /**
  1061. * @param {THREE.Object3D} object
  1062. * @return {number|null}
  1063. */
  1064. processSkin( object ) {
  1065. const json = this.json;
  1066. const nodeMap = this.nodeMap;
  1067. const node = json.nodes[ nodeMap.get( object ) ];
  1068. const skeleton = object.skeleton;
  1069. if ( skeleton === undefined ) return null;
  1070. const rootJoint = object.skeleton.bones[ 0 ];
  1071. if ( rootJoint === undefined ) return null;
  1072. const joints = [];
  1073. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1074. const temporaryBoneInverse = new THREE.Matrix4();
  1075. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1076. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1077. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1078. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1079. }
  1080. if ( json.skins === undefined ) json.skins = [];
  1081. json.skins.push( {
  1082. inverseBindMatrices: this.processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  1083. joints: joints,
  1084. skeleton: nodeMap.get( rootJoint )
  1085. } );
  1086. const skinIndex = node.skin = json.skins.length - 1;
  1087. return skinIndex;
  1088. }
  1089. /**
  1090. * Process Object3D node
  1091. * @param {THREE.Object3D} node Object3D to processNode
  1092. * @return {Integer} Index of the node in the nodes list
  1093. */
  1094. processNode( object ) {
  1095. const json = this.json;
  1096. const options = this.options;
  1097. const nodeMap = this.nodeMap;
  1098. if ( ! json.nodes ) json.nodes = [];
  1099. const nodeDef = {};
  1100. if ( options.trs ) {
  1101. const rotation = object.quaternion.toArray();
  1102. const position = object.position.toArray();
  1103. const scale = object.scale.toArray();
  1104. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1105. nodeDef.rotation = rotation;
  1106. }
  1107. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1108. nodeDef.translation = position;
  1109. }
  1110. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1111. nodeDef.scale = scale;
  1112. }
  1113. } else {
  1114. if ( object.matrixAutoUpdate ) {
  1115. object.updateMatrix();
  1116. }
  1117. if ( isIdentityMatrix( object.matrix ) === false ) {
  1118. nodeDef.matrix = object.matrix.elements;
  1119. }
  1120. } // We don't export empty strings name because it represents no-name in Three.js.
  1121. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1122. this.serializeUserData( object, nodeDef );
  1123. if ( object.isMesh || object.isLine || object.isPoints ) {
  1124. const meshIndex = this.processMesh( object );
  1125. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1126. } else if ( object.isCamera ) {
  1127. nodeDef.camera = this.processCamera( object );
  1128. }
  1129. if ( object.isSkinnedMesh ) this.skins.push( object );
  1130. if ( object.children.length > 0 ) {
  1131. const children = [];
  1132. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1133. const child = object.children[ i ];
  1134. if ( child.visible || options.onlyVisible === false ) {
  1135. const nodeIndex = this.processNode( child );
  1136. if ( nodeIndex !== null ) children.push( nodeIndex );
  1137. }
  1138. }
  1139. if ( children.length > 0 ) nodeDef.children = children;
  1140. }
  1141. this._invokeAll( function ( ext ) {
  1142. ext.writeNode && ext.writeNode( object, nodeDef );
  1143. } );
  1144. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1145. nodeMap.set( object, nodeIndex );
  1146. return nodeIndex;
  1147. }
  1148. /**
  1149. * Process THREE.Scene
  1150. * @param {Scene} node THREE.Scene to process
  1151. */
  1152. processScene( scene ) {
  1153. const json = this.json;
  1154. const options = this.options;
  1155. if ( ! json.scenes ) {
  1156. json.scenes = [];
  1157. json.scene = 0;
  1158. }
  1159. const sceneDef = {};
  1160. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1161. json.scenes.push( sceneDef );
  1162. const nodes = [];
  1163. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1164. const child = scene.children[ i ];
  1165. if ( child.visible || options.onlyVisible === false ) {
  1166. const nodeIndex = this.processNode( child );
  1167. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1168. }
  1169. }
  1170. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1171. this.serializeUserData( scene, sceneDef );
  1172. }
  1173. /**
  1174. * Creates a THREE.Scene to hold a list of objects and parse it
  1175. * @param {Array} objects List of objects to process
  1176. */
  1177. processObjects( objects ) {
  1178. const scene = new THREE.Scene();
  1179. scene.name = 'AuxScene';
  1180. for ( let i = 0; i < objects.length; i ++ ) {
  1181. // We push directly to children instead of calling `add` to prevent
  1182. // modify the .parent and break its original scene and hierarchy
  1183. scene.children.push( objects[ i ] );
  1184. }
  1185. this.processScene( scene );
  1186. }
  1187. /**
  1188. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1189. */
  1190. processInput( input ) {
  1191. const options = this.options;
  1192. input = input instanceof Array ? input : [ input ];
  1193. this._invokeAll( function ( ext ) {
  1194. ext.beforeParse && ext.beforeParse( input );
  1195. } );
  1196. const objectsWithoutScene = [];
  1197. for ( let i = 0; i < input.length; i ++ ) {
  1198. if ( input[ i ] instanceof THREE.Scene ) {
  1199. this.processScene( input[ i ] );
  1200. } else {
  1201. objectsWithoutScene.push( input[ i ] );
  1202. }
  1203. }
  1204. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1205. for ( let i = 0; i < this.skins.length; ++ i ) {
  1206. this.processSkin( this.skins[ i ] );
  1207. }
  1208. for ( let i = 0; i < options.animations.length; ++ i ) {
  1209. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1210. }
  1211. this._invokeAll( function ( ext ) {
  1212. ext.afterParse && ext.afterParse( input );
  1213. } );
  1214. }
  1215. _invokeAll( func ) {
  1216. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1217. func( this.plugins[ i ] );
  1218. }
  1219. }
  1220. }
  1221. /**
  1222. * Punctual Lights Extension
  1223. *
  1224. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1225. */
  1226. class GLTFLightExtension {
  1227. constructor( writer ) {
  1228. this.writer = writer;
  1229. this.name = 'KHR_lights_punctual';
  1230. }
  1231. writeNode( light, nodeDef ) {
  1232. if ( ! light.isLight ) return;
  1233. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1234. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1235. return;
  1236. }
  1237. const writer = this.writer;
  1238. const json = writer.json;
  1239. const extensionsUsed = writer.extensionsUsed;
  1240. const lightDef = {};
  1241. if ( light.name ) lightDef.name = light.name;
  1242. lightDef.color = light.color.toArray();
  1243. lightDef.intensity = light.intensity;
  1244. if ( light.isDirectionalLight ) {
  1245. lightDef.type = 'directional';
  1246. } else if ( light.isPointLight ) {
  1247. lightDef.type = 'point';
  1248. if ( light.distance > 0 ) lightDef.range = light.distance;
  1249. } else if ( light.isSpotLight ) {
  1250. lightDef.type = 'spot';
  1251. if ( light.distance > 0 ) lightDef.range = light.distance;
  1252. lightDef.spot = {};
  1253. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1254. lightDef.spot.outerConeAngle = light.angle;
  1255. }
  1256. if ( light.decay !== undefined && light.decay !== 2 ) {
  1257. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + 'and expects light.decay=2.' );
  1258. }
  1259. if ( light.target && ( light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== - 1 ) ) {
  1260. 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.' );
  1261. }
  1262. if ( ! extensionsUsed[ this.name ] ) {
  1263. json.extensions = json.extensions || {};
  1264. json.extensions[ this.name ] = {
  1265. lights: []
  1266. };
  1267. extensionsUsed[ this.name ] = true;
  1268. }
  1269. const lights = json.extensions[ this.name ].lights;
  1270. lights.push( lightDef );
  1271. nodeDef.extensions = nodeDef.extensions || {};
  1272. nodeDef.extensions[ this.name ] = {
  1273. light: lights.length - 1
  1274. };
  1275. }
  1276. }
  1277. /**
  1278. * Unlit Materials Extension
  1279. *
  1280. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1281. */
  1282. class GLTFMaterialsUnlitExtension {
  1283. constructor( writer ) {
  1284. this.writer = writer;
  1285. this.name = 'KHR_materials_unlit';
  1286. }
  1287. writeMaterial( material, materialDef ) {
  1288. if ( ! material.isMeshBasicMaterial ) return;
  1289. const writer = this.writer;
  1290. const extensionsUsed = writer.extensionsUsed;
  1291. materialDef.extensions = materialDef.extensions || {};
  1292. materialDef.extensions[ this.name ] = {};
  1293. extensionsUsed[ this.name ] = true;
  1294. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1295. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1296. }
  1297. }
  1298. /**
  1299. * Specular-Glossiness Extension
  1300. *
  1301. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  1302. */
  1303. class GLTFMaterialsPBRSpecularGlossiness {
  1304. constructor( writer ) {
  1305. this.writer = writer;
  1306. this.name = 'KHR_materials_pbrSpecularGlossiness';
  1307. }
  1308. writeMaterial( material, materialDef ) {
  1309. if ( ! material.isGLTFSpecularGlossinessMaterial ) return;
  1310. const writer = this.writer;
  1311. const extensionsUsed = writer.extensionsUsed;
  1312. const extensionDef = {};
  1313. if ( materialDef.pbrMetallicRoughness.baseColorFactor ) {
  1314. extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor;
  1315. }
  1316. const specularFactor = [ 1, 1, 1 ];
  1317. material.specular.toArray( specularFactor, 0 );
  1318. extensionDef.specularFactor = specularFactor;
  1319. extensionDef.glossinessFactor = material.glossiness;
  1320. if ( materialDef.pbrMetallicRoughness.baseColorTexture ) {
  1321. extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture;
  1322. }
  1323. if ( material.specularMap ) {
  1324. const specularMapDef = {
  1325. index: writer.processTexture( material.specularMap )
  1326. };
  1327. writer.applyTextureTransform( specularMapDef, material.specularMap );
  1328. extensionDef.specularGlossinessTexture = specularMapDef;
  1329. }
  1330. materialDef.extensions = materialDef.extensions || {};
  1331. materialDef.extensions[ this.name ] = extensionDef;
  1332. extensionsUsed[ this.name ] = true;
  1333. }
  1334. }
  1335. /**
  1336. * Static utility functions
  1337. */
  1338. GLTFExporter.Utils = {
  1339. insertKeyframe: function ( track, time ) {
  1340. const tolerance = 0.001; // 1ms
  1341. const valueSize = track.getValueSize();
  1342. const times = new track.TimeBufferType( track.times.length + 1 );
  1343. const values = new track.ValueBufferType( track.values.length + valueSize );
  1344. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1345. let index;
  1346. if ( track.times.length === 0 ) {
  1347. times[ 0 ] = time;
  1348. for ( let i = 0; i < valueSize; i ++ ) {
  1349. values[ i ] = 0;
  1350. }
  1351. index = 0;
  1352. } else if ( time < track.times[ 0 ] ) {
  1353. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1354. times[ 0 ] = time;
  1355. times.set( track.times, 1 );
  1356. values.set( interpolant.evaluate( time ), 0 );
  1357. values.set( track.values, valueSize );
  1358. index = 0;
  1359. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1360. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1361. return track.times.length - 1;
  1362. }
  1363. times[ times.length - 1 ] = time;
  1364. times.set( track.times, 0 );
  1365. values.set( track.values, 0 );
  1366. values.set( interpolant.evaluate( time ), track.values.length );
  1367. index = times.length - 1;
  1368. } else {
  1369. for ( let i = 0; i < track.times.length; i ++ ) {
  1370. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1371. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1372. times.set( track.times.slice( 0, i + 1 ), 0 );
  1373. times[ i + 1 ] = time;
  1374. times.set( track.times.slice( i + 1 ), i + 2 );
  1375. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1376. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1377. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1378. index = i + 1;
  1379. break;
  1380. }
  1381. }
  1382. }
  1383. track.times = times;
  1384. track.values = values;
  1385. return index;
  1386. },
  1387. mergeMorphTargetTracks: function ( clip, root ) {
  1388. const tracks = [];
  1389. const mergedTracks = {};
  1390. const sourceTracks = clip.tracks;
  1391. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  1392. let sourceTrack = sourceTracks[ i ];
  1393. const sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
  1394. const sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1395. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1396. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1397. tracks.push( sourceTrack );
  1398. continue;
  1399. }
  1400. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1401. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1402. // This should never happen, because glTF morph target animations
  1403. // affect all targets already.
  1404. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1405. }
  1406. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1407. sourceTrack = sourceTrack.clone();
  1408. sourceTrack.setInterpolation( THREE.InterpolateLinear );
  1409. }
  1410. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  1411. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1412. if ( targetIndex === undefined ) {
  1413. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1414. }
  1415. let mergedTrack; // If this is the first time we've seen this object, create a new
  1416. // track to store merged keyframe data for each morph target.
  1417. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1418. mergedTrack = sourceTrack.clone();
  1419. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1420. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1421. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1422. } // We need to take into consideration the intended target node
  1423. // of our original un-merged morphTarget animation.
  1424. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  1425. mergedTrack.values = values;
  1426. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1427. tracks.push( mergedTrack );
  1428. continue;
  1429. }
  1430. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1431. mergedTrack = mergedTracks[ sourceTrackNode.uuid ]; // For every existing keyframe of the merged track, write a (possibly
  1432. // interpolated) value from the source track.
  1433. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1434. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1435. } // For every existing keyframe of the source track, write a (possibly
  1436. // new) keyframe to the merged track. Values from the previous loop may
  1437. // be written again, but keyframes are de-duplicated.
  1438. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  1439. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1440. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1441. }
  1442. }
  1443. clip.tracks = tracks;
  1444. return clip;
  1445. }
  1446. };
  1447. THREE.GLTFExporter = GLTFExporter;
  1448. } )();