GLTFExporter.js 63 KB

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