GLTFExporter.js 88 KB

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