GLTFExporter.js 58 KB

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