GLTFExporter.js 56 KB

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