GLTFExporter.js 70 KB

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