GLTFExporter.js 65 KB

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