GLTFExporter.js 62 KB

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