GLTFExporter.js 62 KB

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