GLTFExporter.js 56 KB

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