GLTFExporter.js 70 KB

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