GLTFExporter.js 77 KB

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