GLTFExporter.js 65 KB

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