GLTFExporter.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698
  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 ? metalnessMap.image : null;
  495. const roughness = roughnessMap ? roughnessMap.image : null;
  496. const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 );
  497. const height = Math.max( metalness ? metalness.height : 0, roughness ? 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. if ( image !== null ) {
  701. const writer = this;
  702. const cache = writer.cache;
  703. const json = writer.json;
  704. const options = writer.options;
  705. const pending = writer.pending;
  706. if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
  707. const cachedImages = cache.images.get( image );
  708. const key = mimeType + ':flipY/' + flipY.toString();
  709. if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
  710. if ( ! json.images ) json.images = [];
  711. const imageDef = { mimeType: mimeType };
  712. const canvas = getCanvas();
  713. canvas.width = Math.min( image.width, options.maxTextureSize );
  714. canvas.height = Math.min( image.height, options.maxTextureSize );
  715. const ctx = canvas.getContext( '2d' );
  716. if ( flipY === true ) {
  717. ctx.translate( 0, canvas.height );
  718. ctx.scale( 1, - 1 );
  719. }
  720. if ( image.data !== undefined ) { // THREE.DataTexture
  721. if ( format !== RGBAFormat ) {
  722. console.error( 'GLTFExporter: Only RGBAFormat is supported.' );
  723. }
  724. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  725. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  726. }
  727. const data = new Uint8ClampedArray( image.height * image.width * 4 );
  728. for ( let i = 0; i < data.length; i += 4 ) {
  729. data[ i + 0 ] = image.data[ i + 0 ];
  730. data[ i + 1 ] = image.data[ i + 1 ];
  731. data[ i + 2 ] = image.data[ i + 2 ];
  732. data[ i + 3 ] = image.data[ i + 3 ];
  733. }
  734. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  735. } else {
  736. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  737. }
  738. if ( options.binary === true ) {
  739. pending.push(
  740. getToBlobPromise( canvas, mimeType )
  741. .then( blob => writer.processBufferViewImage( blob ) )
  742. .then( bufferViewIndex => {
  743. imageDef.bufferView = bufferViewIndex;
  744. } )
  745. );
  746. } else {
  747. if ( canvas.toDataURL !== undefined ) {
  748. imageDef.uri = canvas.toDataURL( mimeType );
  749. } else {
  750. pending.push(
  751. getToBlobPromise( canvas, mimeType )
  752. .then( blob => new FileReader().readAsDataURL( blob ) )
  753. .then( dataURL => {
  754. imageDef.uri = dataURL;
  755. } )
  756. );
  757. }
  758. }
  759. const index = json.images.push( imageDef ) - 1;
  760. cachedImages[ key ] = index;
  761. return index;
  762. } else {
  763. throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
  764. }
  765. }
  766. /**
  767. * Process sampler
  768. * @param {Texture} map Texture to process
  769. * @return {Integer} Index of the processed texture in the "samplers" array
  770. */
  771. processSampler( map ) {
  772. const json = this.json;
  773. if ( ! json.samplers ) json.samplers = [];
  774. const samplerDef = {
  775. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  776. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  777. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  778. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  779. };
  780. return json.samplers.push( samplerDef ) - 1;
  781. }
  782. /**
  783. * Process texture
  784. * @param {Texture} map Map to process
  785. * @return {Integer} Index of the processed texture in the "textures" array
  786. */
  787. processTexture( map ) {
  788. const cache = this.cache;
  789. const json = this.json;
  790. if ( cache.textures.has( map ) ) return cache.textures.get( map );
  791. if ( ! json.textures ) json.textures = [];
  792. let mimeType = map.userData.mimeType;
  793. if ( mimeType === 'image/webp' ) mimeType = 'image/png';
  794. const textureDef = {
  795. sampler: this.processSampler( map ),
  796. source: this.processImage( map.image, map.format, map.flipY, mimeType )
  797. };
  798. if ( map.name ) textureDef.name = map.name;
  799. this._invokeAll( function ( ext ) {
  800. ext.writeTexture && ext.writeTexture( map, textureDef );
  801. } );
  802. const index = json.textures.push( textureDef ) - 1;
  803. cache.textures.set( map, index );
  804. return index;
  805. }
  806. /**
  807. * Process material
  808. * @param {THREE.Material} material Material to process
  809. * @return {Integer|null} Index of the processed material in the "materials" array
  810. */
  811. processMaterial( material ) {
  812. const cache = this.cache;
  813. const json = this.json;
  814. if ( cache.materials.has( material ) ) return cache.materials.get( material );
  815. if ( material.isShaderMaterial ) {
  816. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  817. return null;
  818. }
  819. if ( ! json.materials ) json.materials = [];
  820. // @QUESTION Should we avoid including any attribute that has the default value?
  821. const materialDef = { pbrMetallicRoughness: {} };
  822. if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
  823. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  824. }
  825. // pbrMetallicRoughness.baseColorFactor
  826. const color = material.color.toArray().concat( [ material.opacity ] );
  827. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  828. materialDef.pbrMetallicRoughness.baseColorFactor = color;
  829. }
  830. if ( material.isMeshStandardMaterial ) {
  831. materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
  832. materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
  833. } else {
  834. materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
  835. materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
  836. }
  837. // pbrMetallicRoughness.metallicRoughnessTexture
  838. if ( material.metalnessMap || material.roughnessMap ) {
  839. const metalRoughTexture = this.buildMetalRoughTexture( material.metalnessMap, material.roughnessMap );
  840. const metalRoughMapDef = { index: this.processTexture( metalRoughTexture ) };
  841. this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
  842. materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  843. }
  844. // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
  845. if ( material.map ) {
  846. const baseColorMapDef = { index: this.processTexture( material.map ) };
  847. this.applyTextureTransform( baseColorMapDef, material.map );
  848. materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  849. }
  850. if ( material.emissive ) {
  851. // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000.
  852. const emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity );
  853. const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
  854. if ( maxEmissiveComponent > 1 ) {
  855. emissive.multiplyScalar( 1 / maxEmissiveComponent );
  856. console.warn( 'THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited' );
  857. }
  858. if ( maxEmissiveComponent > 0 ) {
  859. materialDef.emissiveFactor = emissive.toArray();
  860. }
  861. // emissiveTexture
  862. if ( material.emissiveMap ) {
  863. const emissiveMapDef = { index: this.processTexture( material.emissiveMap ) };
  864. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  865. materialDef.emissiveTexture = emissiveMapDef;
  866. }
  867. }
  868. // normalTexture
  869. if ( material.normalMap ) {
  870. const normalMapDef = { index: this.processTexture( material.normalMap ) };
  871. if ( material.normalScale && material.normalScale.x !== 1 ) {
  872. // glTF normal scale is univariate. Ignore `y`, which may be flipped.
  873. // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  874. normalMapDef.scale = material.normalScale.x;
  875. }
  876. this.applyTextureTransform( normalMapDef, material.normalMap );
  877. materialDef.normalTexture = normalMapDef;
  878. }
  879. // occlusionTexture
  880. if ( material.aoMap ) {
  881. const occlusionMapDef = {
  882. index: this.processTexture( material.aoMap ),
  883. texCoord: 1
  884. };
  885. if ( material.aoMapIntensity !== 1.0 ) {
  886. occlusionMapDef.strength = material.aoMapIntensity;
  887. }
  888. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  889. materialDef.occlusionTexture = occlusionMapDef;
  890. }
  891. // alphaMode
  892. if ( material.transparent ) {
  893. materialDef.alphaMode = 'BLEND';
  894. } else {
  895. if ( material.alphaTest > 0.0 ) {
  896. materialDef.alphaMode = 'MASK';
  897. materialDef.alphaCutoff = material.alphaTest;
  898. }
  899. }
  900. // doubleSided
  901. if ( material.side === DoubleSide ) materialDef.doubleSided = true;
  902. if ( material.name !== '' ) materialDef.name = material.name;
  903. this.serializeUserData( material, materialDef );
  904. this._invokeAll( function ( ext ) {
  905. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  906. } );
  907. const index = json.materials.push( materialDef ) - 1;
  908. cache.materials.set( material, index );
  909. return index;
  910. }
  911. /**
  912. * Process mesh
  913. * @param {THREE.Mesh} mesh Mesh to process
  914. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  915. */
  916. processMesh( mesh ) {
  917. const cache = this.cache;
  918. const json = this.json;
  919. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  920. if ( Array.isArray( mesh.material ) ) {
  921. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  922. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  923. }
  924. } else {
  925. meshCacheKeyParts.push( mesh.material.uuid );
  926. }
  927. const meshCacheKey = meshCacheKeyParts.join( ':' );
  928. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  929. const geometry = mesh.geometry;
  930. let mode;
  931. // Use the correct mode
  932. if ( mesh.isLineSegments ) {
  933. mode = WEBGL_CONSTANTS.LINES;
  934. } else if ( mesh.isLineLoop ) {
  935. mode = WEBGL_CONSTANTS.LINE_LOOP;
  936. } else if ( mesh.isLine ) {
  937. mode = WEBGL_CONSTANTS.LINE_STRIP;
  938. } else if ( mesh.isPoints ) {
  939. mode = WEBGL_CONSTANTS.POINTS;
  940. } else {
  941. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  942. }
  943. const meshDef = {};
  944. const attributes = {};
  945. const primitives = [];
  946. const targets = [];
  947. // Conversion between attributes names in threejs and gltf spec
  948. const nameConversion = {
  949. uv: 'TEXCOORD_0',
  950. uv2: 'TEXCOORD_1',
  951. color: 'COLOR_0',
  952. skinWeight: 'WEIGHTS_0',
  953. skinIndex: 'JOINTS_0'
  954. };
  955. const originalNormal = geometry.getAttribute( 'normal' );
  956. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  957. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  958. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  959. }
  960. // @QUESTION Detect if .vertexColors = true?
  961. // For every attribute create an accessor
  962. let modifiedAttribute = null;
  963. for ( let attributeName in geometry.attributes ) {
  964. // Ignore morph target attributes, which are exported later.
  965. if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
  966. const attribute = geometry.attributes[ attributeName ];
  967. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  968. // Prefix all geometry attributes except the ones specifically
  969. // listed in the spec; non-spec attributes are considered custom.
  970. const validVertexAttributes =
  971. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  972. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  973. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  974. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  975. continue;
  976. }
  977. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  978. modifiedAttribute = null;
  979. const array = attribute.array;
  980. if ( attributeName === 'JOINTS_0' &&
  981. ! ( array instanceof Uint16Array ) &&
  982. ! ( array instanceof Uint8Array ) ) {
  983. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  984. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  985. }
  986. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  987. if ( accessor !== null ) {
  988. attributes[ attributeName ] = accessor;
  989. cache.attributes.set( this.getUID( attribute ), accessor );
  990. }
  991. }
  992. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  993. // Skip if no exportable attributes found
  994. if ( Object.keys( attributes ).length === 0 ) return null;
  995. // Morph targets
  996. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  997. const weights = [];
  998. const targetNames = [];
  999. const reverseDictionary = {};
  1000. if ( mesh.morphTargetDictionary !== undefined ) {
  1001. for ( const key in mesh.morphTargetDictionary ) {
  1002. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  1003. }
  1004. }
  1005. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  1006. const target = {};
  1007. let warned = false;
  1008. for ( const attributeName in geometry.morphAttributes ) {
  1009. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  1010. // Three.js doesn't support TANGENT yet.
  1011. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  1012. if ( ! warned ) {
  1013. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  1014. warned = true;
  1015. }
  1016. continue;
  1017. }
  1018. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  1019. const gltfAttributeName = attributeName.toUpperCase();
  1020. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  1021. //
  1022. // glTF 2.0 Specification:
  1023. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  1024. const baseAttribute = geometry.attributes[ attributeName ];
  1025. if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
  1026. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
  1027. continue;
  1028. }
  1029. // Clones attribute not to override
  1030. const relativeAttribute = attribute.clone();
  1031. if ( ! geometry.morphTargetsRelative ) {
  1032. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  1033. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  1034. if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
  1035. if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
  1036. if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
  1037. if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
  1038. }
  1039. }
  1040. }
  1041. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  1042. cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
  1043. }
  1044. targets.push( target );
  1045. weights.push( mesh.morphTargetInfluences[ i ] );
  1046. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  1047. }
  1048. meshDef.weights = weights;
  1049. if ( targetNames.length > 0 ) {
  1050. meshDef.extras = {};
  1051. meshDef.extras.targetNames = targetNames;
  1052. }
  1053. }
  1054. const isMultiMaterial = Array.isArray( mesh.material );
  1055. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  1056. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  1057. const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  1058. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  1059. const primitive = {
  1060. mode: mode,
  1061. attributes: attributes,
  1062. };
  1063. this.serializeUserData( geometry, primitive );
  1064. if ( targets.length > 0 ) primitive.targets = targets;
  1065. if ( geometry.index !== null ) {
  1066. let cacheKey = this.getUID( geometry.index );
  1067. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  1068. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  1069. }
  1070. if ( cache.attributes.has( cacheKey ) ) {
  1071. primitive.indices = cache.attributes.get( cacheKey );
  1072. } else {
  1073. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  1074. cache.attributes.set( cacheKey, primitive.indices );
  1075. }
  1076. if ( primitive.indices === null ) delete primitive.indices;
  1077. }
  1078. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  1079. if ( material !== null ) primitive.material = material;
  1080. primitives.push( primitive );
  1081. }
  1082. meshDef.primitives = primitives;
  1083. if ( ! json.meshes ) json.meshes = [];
  1084. this._invokeAll( function ( ext ) {
  1085. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  1086. } );
  1087. const index = json.meshes.push( meshDef ) - 1;
  1088. cache.meshes.set( meshCacheKey, index );
  1089. return index;
  1090. }
  1091. /**
  1092. * Process camera
  1093. * @param {THREE.Camera} camera Camera to process
  1094. * @return {Integer} Index of the processed mesh in the "camera" array
  1095. */
  1096. processCamera( camera ) {
  1097. const json = this.json;
  1098. if ( ! json.cameras ) json.cameras = [];
  1099. const isOrtho = camera.isOrthographicCamera;
  1100. const cameraDef = {
  1101. type: isOrtho ? 'orthographic' : 'perspective'
  1102. };
  1103. if ( isOrtho ) {
  1104. cameraDef.orthographic = {
  1105. xmag: camera.right * 2,
  1106. ymag: camera.top * 2,
  1107. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1108. znear: camera.near < 0 ? 0 : camera.near
  1109. };
  1110. } else {
  1111. cameraDef.perspective = {
  1112. aspectRatio: camera.aspect,
  1113. yfov: MathUtils.degToRad( camera.fov ),
  1114. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1115. znear: camera.near < 0 ? 0 : camera.near
  1116. };
  1117. }
  1118. // Question: Is saving "type" as name intentional?
  1119. if ( camera.name !== '' ) cameraDef.name = camera.type;
  1120. return json.cameras.push( cameraDef ) - 1;
  1121. }
  1122. /**
  1123. * Creates glTF animation entry from AnimationClip object.
  1124. *
  1125. * Status:
  1126. * - Only properties listed in PATH_PROPERTIES may be animated.
  1127. *
  1128. * @param {THREE.AnimationClip} clip
  1129. * @param {THREE.Object3D} root
  1130. * @return {number|null}
  1131. */
  1132. processAnimation( clip, root ) {
  1133. const json = this.json;
  1134. const nodeMap = this.nodeMap;
  1135. if ( ! json.animations ) json.animations = [];
  1136. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1137. const tracks = clip.tracks;
  1138. const channels = [];
  1139. const samplers = [];
  1140. for ( let i = 0; i < tracks.length; ++ i ) {
  1141. const track = tracks[ i ];
  1142. const trackBinding = PropertyBinding.parseTrackName( track.name );
  1143. let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  1144. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1145. if ( trackBinding.objectName === 'bones' ) {
  1146. if ( trackNode.isSkinnedMesh === true ) {
  1147. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1148. } else {
  1149. trackNode = undefined;
  1150. }
  1151. }
  1152. if ( ! trackNode || ! trackProperty ) {
  1153. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1154. return null;
  1155. }
  1156. const inputItemSize = 1;
  1157. let outputItemSize = track.values.length / track.times.length;
  1158. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1159. outputItemSize /= trackNode.morphTargetInfluences.length;
  1160. }
  1161. let interpolation;
  1162. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1163. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1164. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1165. // valid value from .getInterpolation().
  1166. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1167. interpolation = 'CUBICSPLINE';
  1168. // itemSize of CUBICSPLINE keyframe is 9
  1169. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1170. // but needs to be stored as VEC3 so dividing by 3 here.
  1171. outputItemSize /= 3;
  1172. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1173. interpolation = 'STEP';
  1174. } else {
  1175. interpolation = 'LINEAR';
  1176. }
  1177. samplers.push( {
  1178. input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1179. output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1180. interpolation: interpolation
  1181. } );
  1182. channels.push( {
  1183. sampler: samplers.length - 1,
  1184. target: {
  1185. node: nodeMap.get( trackNode ),
  1186. path: trackProperty
  1187. }
  1188. } );
  1189. }
  1190. json.animations.push( {
  1191. name: clip.name || 'clip_' + json.animations.length,
  1192. samplers: samplers,
  1193. channels: channels
  1194. } );
  1195. return json.animations.length - 1;
  1196. }
  1197. /**
  1198. * @param {THREE.Object3D} object
  1199. * @return {number|null}
  1200. */
  1201. processSkin( object ) {
  1202. const json = this.json;
  1203. const nodeMap = this.nodeMap;
  1204. const node = json.nodes[ nodeMap.get( object ) ];
  1205. const skeleton = object.skeleton;
  1206. if ( skeleton === undefined ) return null;
  1207. const rootJoint = object.skeleton.bones[ 0 ];
  1208. if ( rootJoint === undefined ) return null;
  1209. const joints = [];
  1210. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1211. const temporaryBoneInverse = new Matrix4();
  1212. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1213. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1214. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1215. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1216. }
  1217. if ( json.skins === undefined ) json.skins = [];
  1218. json.skins.push( {
  1219. inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1220. joints: joints,
  1221. skeleton: nodeMap.get( rootJoint )
  1222. } );
  1223. const skinIndex = node.skin = json.skins.length - 1;
  1224. return skinIndex;
  1225. }
  1226. /**
  1227. * Process Object3D node
  1228. * @param {THREE.Object3D} node Object3D to processNode
  1229. * @return {Integer} Index of the node in the nodes list
  1230. */
  1231. processNode( object ) {
  1232. const json = this.json;
  1233. const options = this.options;
  1234. const nodeMap = this.nodeMap;
  1235. if ( ! json.nodes ) json.nodes = [];
  1236. const nodeDef = {};
  1237. if ( options.trs ) {
  1238. const rotation = object.quaternion.toArray();
  1239. const position = object.position.toArray();
  1240. const scale = object.scale.toArray();
  1241. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1242. nodeDef.rotation = rotation;
  1243. }
  1244. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1245. nodeDef.translation = position;
  1246. }
  1247. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1248. nodeDef.scale = scale;
  1249. }
  1250. } else {
  1251. if ( object.matrixAutoUpdate ) {
  1252. object.updateMatrix();
  1253. }
  1254. if ( isIdentityMatrix( object.matrix ) === false ) {
  1255. nodeDef.matrix = object.matrix.elements;
  1256. }
  1257. }
  1258. // We don't export empty strings name because it represents no-name in Three.js.
  1259. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1260. this.serializeUserData( object, nodeDef );
  1261. if ( object.isMesh || object.isLine || object.isPoints ) {
  1262. const meshIndex = this.processMesh( object );
  1263. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1264. } else if ( object.isCamera ) {
  1265. nodeDef.camera = this.processCamera( object );
  1266. }
  1267. if ( object.isSkinnedMesh ) this.skins.push( object );
  1268. if ( object.children.length > 0 ) {
  1269. const children = [];
  1270. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1271. const child = object.children[ i ];
  1272. if ( child.visible || options.onlyVisible === false ) {
  1273. const nodeIndex = this.processNode( child );
  1274. if ( nodeIndex !== null ) children.push( nodeIndex );
  1275. }
  1276. }
  1277. if ( children.length > 0 ) nodeDef.children = children;
  1278. }
  1279. this._invokeAll( function ( ext ) {
  1280. ext.writeNode && ext.writeNode( object, nodeDef );
  1281. } );
  1282. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1283. nodeMap.set( object, nodeIndex );
  1284. return nodeIndex;
  1285. }
  1286. /**
  1287. * Process Scene
  1288. * @param {Scene} node Scene to process
  1289. */
  1290. processScene( scene ) {
  1291. const json = this.json;
  1292. const options = this.options;
  1293. if ( ! json.scenes ) {
  1294. json.scenes = [];
  1295. json.scene = 0;
  1296. }
  1297. const sceneDef = {};
  1298. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1299. json.scenes.push( sceneDef );
  1300. const nodes = [];
  1301. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1302. const child = scene.children[ i ];
  1303. if ( child.visible || options.onlyVisible === false ) {
  1304. const nodeIndex = this.processNode( child );
  1305. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1306. }
  1307. }
  1308. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1309. this.serializeUserData( scene, sceneDef );
  1310. }
  1311. /**
  1312. * Creates a Scene to hold a list of objects and parse it
  1313. * @param {Array} objects List of objects to process
  1314. */
  1315. processObjects( objects ) {
  1316. const scene = new Scene();
  1317. scene.name = 'AuxScene';
  1318. for ( let i = 0; i < objects.length; i ++ ) {
  1319. // We push directly to children instead of calling `add` to prevent
  1320. // modify the .parent and break its original scene and hierarchy
  1321. scene.children.push( objects[ i ] );
  1322. }
  1323. this.processScene( scene );
  1324. }
  1325. /**
  1326. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1327. */
  1328. processInput( input ) {
  1329. const options = this.options;
  1330. input = input instanceof Array ? input : [ input ];
  1331. this._invokeAll( function ( ext ) {
  1332. ext.beforeParse && ext.beforeParse( input );
  1333. } );
  1334. const objectsWithoutScene = [];
  1335. for ( let i = 0; i < input.length; i ++ ) {
  1336. if ( input[ i ] instanceof Scene ) {
  1337. this.processScene( input[ i ] );
  1338. } else {
  1339. objectsWithoutScene.push( input[ i ] );
  1340. }
  1341. }
  1342. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1343. for ( let i = 0; i < this.skins.length; ++ i ) {
  1344. this.processSkin( this.skins[ i ] );
  1345. }
  1346. for ( let i = 0; i < options.animations.length; ++ i ) {
  1347. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1348. }
  1349. this._invokeAll( function ( ext ) {
  1350. ext.afterParse && ext.afterParse( input );
  1351. } );
  1352. }
  1353. _invokeAll( func ) {
  1354. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1355. func( this.plugins[ i ] );
  1356. }
  1357. }
  1358. }
  1359. /**
  1360. * Punctual Lights Extension
  1361. *
  1362. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1363. */
  1364. class GLTFLightExtension {
  1365. constructor( writer ) {
  1366. this.writer = writer;
  1367. this.name = 'KHR_lights_punctual';
  1368. }
  1369. writeNode( light, nodeDef ) {
  1370. if ( ! light.isLight ) return;
  1371. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1372. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1373. return;
  1374. }
  1375. const writer = this.writer;
  1376. const json = writer.json;
  1377. const extensionsUsed = writer.extensionsUsed;
  1378. const lightDef = {};
  1379. if ( light.name ) lightDef.name = light.name;
  1380. lightDef.color = light.color.toArray();
  1381. lightDef.intensity = light.intensity;
  1382. if ( light.isDirectionalLight ) {
  1383. lightDef.type = 'directional';
  1384. } else if ( light.isPointLight ) {
  1385. lightDef.type = 'point';
  1386. if ( light.distance > 0 ) lightDef.range = light.distance;
  1387. } else if ( light.isSpotLight ) {
  1388. lightDef.type = 'spot';
  1389. if ( light.distance > 0 ) lightDef.range = light.distance;
  1390. lightDef.spot = {};
  1391. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1392. lightDef.spot.outerConeAngle = light.angle;
  1393. }
  1394. if ( light.decay !== undefined && light.decay !== 2 ) {
  1395. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1396. + 'and expects light.decay=2.' );
  1397. }
  1398. if ( light.target
  1399. && ( light.target.parent !== light
  1400. || light.target.position.x !== 0
  1401. || light.target.position.y !== 0
  1402. || light.target.position.z !== - 1 ) ) {
  1403. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1404. + 'make light.target a child of the light with position 0,0,-1.' );
  1405. }
  1406. if ( ! extensionsUsed[ this.name ] ) {
  1407. json.extensions = json.extensions || {};
  1408. json.extensions[ this.name ] = { lights: [] };
  1409. extensionsUsed[ this.name ] = true;
  1410. }
  1411. const lights = json.extensions[ this.name ].lights;
  1412. lights.push( lightDef );
  1413. nodeDef.extensions = nodeDef.extensions || {};
  1414. nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
  1415. }
  1416. }
  1417. /**
  1418. * Unlit Materials Extension
  1419. *
  1420. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1421. */
  1422. class GLTFMaterialsUnlitExtension {
  1423. constructor( writer ) {
  1424. this.writer = writer;
  1425. this.name = 'KHR_materials_unlit';
  1426. }
  1427. writeMaterial( material, materialDef ) {
  1428. if ( ! material.isMeshBasicMaterial ) return;
  1429. const writer = this.writer;
  1430. const extensionsUsed = writer.extensionsUsed;
  1431. materialDef.extensions = materialDef.extensions || {};
  1432. materialDef.extensions[ this.name ] = {};
  1433. extensionsUsed[ this.name ] = true;
  1434. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1435. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1436. }
  1437. }
  1438. /**
  1439. * Clearcoat Materials Extension
  1440. *
  1441. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  1442. */
  1443. class GLTFMaterialsClearcoatExtension {
  1444. constructor( writer ) {
  1445. this.writer = writer;
  1446. this.name = 'KHR_materials_clearcoat';
  1447. }
  1448. writeMaterial( material, materialDef ) {
  1449. if ( ! material.isMeshPhysicalMaterial ) return;
  1450. const writer = this.writer;
  1451. const extensionsUsed = writer.extensionsUsed;
  1452. const extensionDef = {};
  1453. extensionDef.clearcoatFactor = material.clearcoat;
  1454. if ( material.clearcoatMap ) {
  1455. const clearcoatMapDef = { index: writer.processTexture( material.clearcoatMap ) };
  1456. writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
  1457. extensionDef.clearcoatTexture = clearcoatMapDef;
  1458. }
  1459. extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
  1460. if ( material.clearcoatRoughnessMap ) {
  1461. const clearcoatRoughnessMapDef = { index: writer.processTexture( material.clearcoatRoughnessMap ) };
  1462. writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
  1463. extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
  1464. }
  1465. if ( material.clearcoatNormalMap ) {
  1466. const clearcoatNormalMapDef = { index: writer.processTexture( material.clearcoatNormalMap ) };
  1467. writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
  1468. extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
  1469. }
  1470. materialDef.extensions = materialDef.extensions || {};
  1471. materialDef.extensions[ this.name ] = extensionDef;
  1472. extensionsUsed[ this.name ] = true;
  1473. }
  1474. }
  1475. /**
  1476. * Iridescence Materials Extension
  1477. *
  1478. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  1479. */
  1480. class GLTFMaterialsIridescenceExtension {
  1481. constructor( writer ) {
  1482. this.writer = writer;
  1483. this.name = 'KHR_materials_iridescence';
  1484. }
  1485. writeMaterial( material, materialDef ) {
  1486. if ( ! material.isMeshPhysicalMaterial ) return;
  1487. const writer = this.writer;
  1488. const extensionsUsed = writer.extensionsUsed;
  1489. const extensionDef = {};
  1490. extensionDef.iridescenceFactor = material.iridescence;
  1491. if ( material.iridescenceMap ) {
  1492. const iridescenceMapDef = { index: writer.processTexture( material.iridescenceMap ) };
  1493. writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
  1494. extensionDef.iridescenceTexture = iridescenceMapDef;
  1495. }
  1496. extensionDef.iridescenceIor = material.iridescenceIOR;
  1497. extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
  1498. extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
  1499. if ( material.iridescenceThicknessMap ) {
  1500. const iridescenceThicknessMapDef = { index: writer.processTexture( material.iridescenceThicknessMap ) };
  1501. writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
  1502. extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
  1503. }
  1504. materialDef.extensions = materialDef.extensions || {};
  1505. materialDef.extensions[ this.name ] = extensionDef;
  1506. extensionsUsed[ this.name ] = true;
  1507. }
  1508. }
  1509. /**
  1510. * Transmission Materials Extension
  1511. *
  1512. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  1513. */
  1514. class GLTFMaterialsTransmissionExtension {
  1515. constructor( writer ) {
  1516. this.writer = writer;
  1517. this.name = 'KHR_materials_transmission';
  1518. }
  1519. writeMaterial( material, materialDef ) {
  1520. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1521. const writer = this.writer;
  1522. const extensionsUsed = writer.extensionsUsed;
  1523. const extensionDef = {};
  1524. extensionDef.transmissionFactor = material.transmission;
  1525. if ( material.transmissionMap ) {
  1526. const transmissionMapDef = { index: writer.processTexture( material.transmissionMap ) };
  1527. writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
  1528. extensionDef.transmissionTexture = transmissionMapDef;
  1529. }
  1530. materialDef.extensions = materialDef.extensions || {};
  1531. materialDef.extensions[ this.name ] = extensionDef;
  1532. extensionsUsed[ this.name ] = true;
  1533. }
  1534. }
  1535. /**
  1536. * Materials Volume Extension
  1537. *
  1538. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  1539. */
  1540. class GLTFMaterialsVolumeExtension {
  1541. constructor( writer ) {
  1542. this.writer = writer;
  1543. this.name = 'KHR_materials_volume';
  1544. }
  1545. writeMaterial( material, materialDef ) {
  1546. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1547. const writer = this.writer;
  1548. const extensionsUsed = writer.extensionsUsed;
  1549. const extensionDef = {};
  1550. extensionDef.thicknessFactor = material.thickness;
  1551. if ( material.thicknessMap ) {
  1552. const thicknessMapDef = { index: writer.processTexture( material.thicknessMap ) };
  1553. writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
  1554. extensionDef.thicknessTexture = thicknessMapDef;
  1555. }
  1556. extensionDef.attenuationDistance = material.attenuationDistance;
  1557. extensionDef.attenuationColor = material.attenuationColor.toArray();
  1558. materialDef.extensions = materialDef.extensions || {};
  1559. materialDef.extensions[ this.name ] = extensionDef;
  1560. extensionsUsed[ this.name ] = true;
  1561. }
  1562. }
  1563. /**
  1564. * Static utility functions
  1565. */
  1566. GLTFExporter.Utils = {
  1567. insertKeyframe: function ( track, time ) {
  1568. const tolerance = 0.001; // 1ms
  1569. const valueSize = track.getValueSize();
  1570. const times = new track.TimeBufferType( track.times.length + 1 );
  1571. const values = new track.ValueBufferType( track.values.length + valueSize );
  1572. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1573. let index;
  1574. if ( track.times.length === 0 ) {
  1575. times[ 0 ] = time;
  1576. for ( let i = 0; i < valueSize; i ++ ) {
  1577. values[ i ] = 0;
  1578. }
  1579. index = 0;
  1580. } else if ( time < track.times[ 0 ] ) {
  1581. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1582. times[ 0 ] = time;
  1583. times.set( track.times, 1 );
  1584. values.set( interpolant.evaluate( time ), 0 );
  1585. values.set( track.values, valueSize );
  1586. index = 0;
  1587. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1588. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1589. return track.times.length - 1;
  1590. }
  1591. times[ times.length - 1 ] = time;
  1592. times.set( track.times, 0 );
  1593. values.set( track.values, 0 );
  1594. values.set( interpolant.evaluate( time ), track.values.length );
  1595. index = times.length - 1;
  1596. } else {
  1597. for ( let i = 0; i < track.times.length; i ++ ) {
  1598. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1599. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1600. times.set( track.times.slice( 0, i + 1 ), 0 );
  1601. times[ i + 1 ] = time;
  1602. times.set( track.times.slice( i + 1 ), i + 2 );
  1603. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1604. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1605. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1606. index = i + 1;
  1607. break;
  1608. }
  1609. }
  1610. }
  1611. track.times = times;
  1612. track.values = values;
  1613. return index;
  1614. },
  1615. mergeMorphTargetTracks: function ( clip, root ) {
  1616. const tracks = [];
  1617. const mergedTracks = {};
  1618. const sourceTracks = clip.tracks;
  1619. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  1620. let sourceTrack = sourceTracks[ i ];
  1621. const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  1622. const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1623. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1624. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1625. tracks.push( sourceTrack );
  1626. continue;
  1627. }
  1628. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1629. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1630. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1631. // This should never happen, because glTF morph target animations
  1632. // affect all targets already.
  1633. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1634. }
  1635. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1636. sourceTrack = sourceTrack.clone();
  1637. sourceTrack.setInterpolation( InterpolateLinear );
  1638. }
  1639. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  1640. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1641. if ( targetIndex === undefined ) {
  1642. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1643. }
  1644. let mergedTrack;
  1645. // If this is the first time we've seen this object, create a new
  1646. // track to store merged keyframe data for each morph target.
  1647. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1648. mergedTrack = sourceTrack.clone();
  1649. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1650. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1651. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1652. }
  1653. // We need to take into consideration the intended target node
  1654. // of our original un-merged morphTarget animation.
  1655. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  1656. mergedTrack.values = values;
  1657. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1658. tracks.push( mergedTrack );
  1659. continue;
  1660. }
  1661. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1662. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1663. // For every existing keyframe of the merged track, write a (possibly
  1664. // interpolated) value from the source track.
  1665. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1666. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1667. }
  1668. // For every existing keyframe of the source track, write a (possibly
  1669. // new) keyframe to the merged track. Values from the previous loop may
  1670. // be written again, but keyframes are de-duplicated.
  1671. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  1672. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1673. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1674. }
  1675. }
  1676. clip.tracks = tracks;
  1677. return clip;
  1678. }
  1679. };
  1680. export { GLTFExporter };