GLTFExporter.js 62 KB

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