GLTFExporter.js 55 KB

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