GLTFExporter.js 55 KB

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