GLTFExporter.js 62 KB

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