GLTFExporter.js 73 KB

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