GLTFExporter.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. * @author Don McCurdy / https://www.donmccurdy.com
  4. * @author Takahiro / https://github.com/takahirox
  5. */
  6. //------------------------------------------------------------------------------
  7. // Constants
  8. //------------------------------------------------------------------------------
  9. var WEBGL_CONSTANTS = {
  10. POINTS: 0x0000,
  11. LINES: 0x0001,
  12. LINE_LOOP: 0x0002,
  13. LINE_STRIP: 0x0003,
  14. TRIANGLES: 0x0004,
  15. TRIANGLE_STRIP: 0x0005,
  16. TRIANGLE_FAN: 0x0006,
  17. UNSIGNED_BYTE: 0x1401,
  18. UNSIGNED_SHORT: 0x1403,
  19. FLOAT: 0x1406,
  20. UNSIGNED_INT: 0x1405,
  21. ARRAY_BUFFER: 0x8892,
  22. ELEMENT_ARRAY_BUFFER: 0x8893,
  23. NEAREST: 0x2600,
  24. LINEAR: 0x2601,
  25. NEAREST_MIPMAP_NEAREST: 0x2700,
  26. LINEAR_MIPMAP_NEAREST: 0x2701,
  27. NEAREST_MIPMAP_LINEAR: 0x2702,
  28. LINEAR_MIPMAP_LINEAR: 0x2703,
  29. CLAMP_TO_EDGE: 33071,
  30. MIRRORED_REPEAT: 33648,
  31. REPEAT: 10497
  32. };
  33. var THREE_TO_WEBGL = {};
  34. THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  35. THREE_TO_WEBGL[ NearestMipMapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  36. THREE_TO_WEBGL[ NearestMipMapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  37. THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  38. THREE_TO_WEBGL[ LinearMipMapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  39. THREE_TO_WEBGL[ LinearMipMapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  40. THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  41. THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  42. THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  43. var PATH_PROPERTIES = {
  44. scale: 'scale',
  45. position: 'translation',
  46. quaternion: 'rotation',
  47. morphTargetInfluences: 'weights'
  48. };
  49. //------------------------------------------------------------------------------
  50. // GLTF Exporter
  51. //------------------------------------------------------------------------------
  52. import {
  53. BufferAttribute,
  54. BufferGeometry,
  55. ClampToEdgeWrapping,
  56. DoubleSide,
  57. InterpolateDiscrete,
  58. LinearFilter,
  59. LinearMipMapLinearFilter,
  60. LinearMipMapNearestFilter,
  61. Math as _Math,
  62. MirroredRepeatWrapping,
  63. NearestFilter,
  64. NearestMipMapLinearFilter,
  65. NearestMipMapNearestFilter,
  66. PropertyBinding,
  67. RGBAFormat,
  68. RepeatWrapping,
  69. Scene,
  70. TriangleFanDrawMode,
  71. TriangleStripDrawMode,
  72. Vector3
  73. } from "../../../build/three.module.js";
  74. var GLTFExporter = function () {};
  75. GLTFExporter.prototype = {
  76. constructor: GLTFExporter,
  77. /**
  78. * Parse scenes and generate GLTF output
  79. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  80. * @param {Function} onDone Callback on completed
  81. * @param {Object} options options
  82. */
  83. parse: function ( input, onDone, options ) {
  84. var DEFAULT_OPTIONS = {
  85. binary: false,
  86. trs: false,
  87. onlyVisible: true,
  88. truncateDrawRange: true,
  89. embedImages: true,
  90. animations: [],
  91. forceIndices: false,
  92. forcePowerOfTwoTextures: false,
  93. includeCustomExtensions: false
  94. };
  95. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  96. if ( options.animations.length > 0 ) {
  97. // Only TRS properties, and not matrices, may be targeted by animation.
  98. options.trs = true;
  99. }
  100. var outputJSON = {
  101. asset: {
  102. version: "2.0",
  103. generator: "GLTFExporter"
  104. }
  105. };
  106. var byteOffset = 0;
  107. var buffers = [];
  108. var pending = [];
  109. var nodeMap = new Map();
  110. var skins = [];
  111. var extensionsUsed = {};
  112. var cachedData = {
  113. meshes: new Map(),
  114. attributes: new Map(),
  115. attributesNormalized: new Map(),
  116. materials: new Map(),
  117. textures: new Map(),
  118. images: new Map()
  119. };
  120. var cachedCanvas;
  121. /**
  122. * Compare two arrays
  123. */
  124. /**
  125. * Compare two arrays
  126. * @param {Array} array1 Array 1 to compare
  127. * @param {Array} array2 Array 2 to compare
  128. * @return {Boolean} Returns true if both arrays are equal
  129. */
  130. function equalArray( array1, array2 ) {
  131. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  132. return element === array2[ index ];
  133. } );
  134. }
  135. /**
  136. * Converts a string to an ArrayBuffer.
  137. * @param {string} text
  138. * @return {ArrayBuffer}
  139. */
  140. function stringToArrayBuffer( text ) {
  141. if ( window.TextEncoder !== undefined ) {
  142. return new TextEncoder().encode( text ).buffer;
  143. }
  144. var array = new Uint8Array( new ArrayBuffer( text.length ) );
  145. for ( var i = 0, il = text.length; i < il; i ++ ) {
  146. var value = text.charCodeAt( i );
  147. // Replacing multi-byte character with space(0x20).
  148. array[ i ] = value > 0xFF ? 0x20 : value;
  149. }
  150. return array.buffer;
  151. }
  152. /**
  153. * Get the min and max vectors from the given attribute
  154. * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  155. * @param {Integer} start
  156. * @param {Integer} count
  157. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  158. */
  159. function getMinMax( attribute, start, count ) {
  160. var output = {
  161. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  162. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  163. };
  164. for ( var i = start; i < start + count; i ++ ) {
  165. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  166. var value = attribute.array[ i * attribute.itemSize + a ];
  167. output.min[ a ] = Math.min( output.min[ a ], value );
  168. output.max[ a ] = Math.max( output.max[ a ], value );
  169. }
  170. }
  171. return output;
  172. }
  173. /**
  174. * Checks if image size is POT.
  175. *
  176. * @param {Image} image The image to be checked.
  177. * @returns {Boolean} Returns true if image size is POT.
  178. *
  179. */
  180. function isPowerOfTwo( image ) {
  181. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  182. }
  183. /**
  184. * Checks if normal attribute values are normalized.
  185. *
  186. * @param {BufferAttribute} normal
  187. * @returns {Boolean}
  188. *
  189. */
  190. function isNormalizedNormalAttribute( normal ) {
  191. if ( cachedData.attributesNormalized.has( normal ) ) {
  192. return false;
  193. }
  194. var v = new Vector3();
  195. for ( var i = 0, il = normal.count; i < il; i ++ ) {
  196. // 0.0005 is from glTF-validator
  197. if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
  198. }
  199. return true;
  200. }
  201. /**
  202. * Creates normalized normal buffer attribute.
  203. *
  204. * @param {BufferAttribute} normal
  205. * @returns {BufferAttribute}
  206. *
  207. */
  208. function createNormalizedNormalAttribute( normal ) {
  209. if ( cachedData.attributesNormalized.has( normal ) ) {
  210. return cachedData.attributesNormalized.get( normal );
  211. }
  212. var attribute = normal.clone();
  213. var v = new Vector3();
  214. for ( var i = 0, il = attribute.count; i < il; i ++ ) {
  215. v.fromArray( attribute.array, i * 3 );
  216. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  217. // if values can't be normalized set (1, 0, 0)
  218. v.setX( 1.0 );
  219. } else {
  220. v.normalize();
  221. }
  222. v.toArray( attribute.array, i * 3 );
  223. }
  224. cachedData.attributesNormalized.set( normal, attribute );
  225. return attribute;
  226. }
  227. /**
  228. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  229. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  230. *
  231. * @param {Integer} bufferSize The size the original buffer.
  232. * @returns {Integer} new buffer size with required padding.
  233. *
  234. */
  235. function getPaddedBufferSize( bufferSize ) {
  236. return Math.ceil( bufferSize / 4 ) * 4;
  237. }
  238. /**
  239. * Returns a buffer aligned to 4-byte boundary.
  240. *
  241. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  242. * @param {Integer} paddingByte (Optional)
  243. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  244. */
  245. function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
  246. paddingByte = paddingByte || 0;
  247. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  248. if ( paddedLength !== arrayBuffer.byteLength ) {
  249. var array = new Uint8Array( paddedLength );
  250. array.set( new Uint8Array( arrayBuffer ) );
  251. if ( paddingByte !== 0 ) {
  252. for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  253. array[ i ] = paddingByte;
  254. }
  255. }
  256. return array.buffer;
  257. }
  258. return arrayBuffer;
  259. }
  260. /**
  261. * Serializes a userData.
  262. *
  263. * @param {THREE.Object3D|THREE.Material} object
  264. * @param {Object} gltfProperty
  265. */
  266. function serializeUserData( object, gltfProperty ) {
  267. if ( Object.keys( object.userData ).length === 0 ) {
  268. return;
  269. }
  270. try {
  271. var json = JSON.parse( JSON.stringify( object.userData ) );
  272. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  273. if ( gltfProperty.extensions === undefined ) {
  274. gltfProperty.extensions = {};
  275. }
  276. for ( var extensionName in json.gltfExtensions ) {
  277. gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  278. extensionsUsed[ extensionName ] = true;
  279. }
  280. delete json.gltfExtensions;
  281. }
  282. if ( Object.keys( json ).length > 0 ) {
  283. gltfProperty.extras = json;
  284. }
  285. } catch ( error ) {
  286. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  287. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  288. }
  289. }
  290. /**
  291. * Applies a texture transform, if present, to the map definition. Requires
  292. * the KHR_texture_transform extension.
  293. */
  294. function applyTextureTransform( mapDef, texture ) {
  295. var didTransform = false;
  296. var transformDef = {};
  297. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  298. transformDef.offset = texture.offset.toArray();
  299. didTransform = true;
  300. }
  301. if ( texture.rotation !== 0 ) {
  302. transformDef.rotation = texture.rotation;
  303. didTransform = true;
  304. }
  305. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  306. transformDef.scale = texture.repeat.toArray();
  307. didTransform = true;
  308. }
  309. if ( didTransform ) {
  310. mapDef.extensions = mapDef.extensions || {};
  311. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  312. extensionsUsed[ 'KHR_texture_transform' ] = true;
  313. }
  314. }
  315. /**
  316. * Process a buffer to append to the default one.
  317. * @param {ArrayBuffer} buffer
  318. * @return {Integer}
  319. */
  320. function processBuffer( buffer ) {
  321. if ( ! outputJSON.buffers ) {
  322. outputJSON.buffers = [ { byteLength: 0 } ];
  323. }
  324. // All buffers are merged before export.
  325. buffers.push( buffer );
  326. return 0;
  327. }
  328. /**
  329. * Process and generate a BufferView
  330. * @param {BufferAttribute} attribute
  331. * @param {number} componentType
  332. * @param {number} start
  333. * @param {number} count
  334. * @param {number} target (Optional) Target usage of the BufferView
  335. * @return {Object}
  336. */
  337. function processBufferView( attribute, componentType, start, count, target ) {
  338. if ( ! outputJSON.bufferViews ) {
  339. outputJSON.bufferViews = [];
  340. }
  341. // Create a new dataview and dump the attribute's array into it
  342. var componentSize;
  343. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  344. componentSize = 1;
  345. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  346. componentSize = 2;
  347. } else {
  348. componentSize = 4;
  349. }
  350. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  351. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  352. var offset = 0;
  353. for ( var i = start; i < start + count; i ++ ) {
  354. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  355. // @TODO Fails on InterleavedBufferAttribute, and could probably be
  356. // optimized for normal BufferAttribute.
  357. var value = attribute.array[ i * attribute.itemSize + a ];
  358. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  359. dataView.setFloat32( offset, value, true );
  360. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  361. dataView.setUint32( offset, value, true );
  362. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  363. dataView.setUint16( offset, value, true );
  364. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  365. dataView.setUint8( offset, value );
  366. }
  367. offset += componentSize;
  368. }
  369. }
  370. var gltfBufferView = {
  371. buffer: processBuffer( dataView.buffer ),
  372. byteOffset: byteOffset,
  373. byteLength: byteLength
  374. };
  375. if ( target !== undefined ) gltfBufferView.target = target;
  376. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  377. // Only define byteStride for vertex attributes.
  378. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  379. }
  380. byteOffset += byteLength;
  381. outputJSON.bufferViews.push( gltfBufferView );
  382. // @TODO Merge bufferViews where possible.
  383. var output = {
  384. id: outputJSON.bufferViews.length - 1,
  385. byteLength: 0
  386. };
  387. return output;
  388. }
  389. /**
  390. * Process and generate a BufferView from an image Blob.
  391. * @param {Blob} blob
  392. * @return {Promise<Integer>}
  393. */
  394. function processBufferViewImage( blob ) {
  395. if ( ! outputJSON.bufferViews ) {
  396. outputJSON.bufferViews = [];
  397. }
  398. return new Promise( function ( resolve ) {
  399. var reader = new window.FileReader();
  400. reader.readAsArrayBuffer( blob );
  401. reader.onloadend = function () {
  402. var buffer = getPaddedArrayBuffer( reader.result );
  403. var bufferView = {
  404. buffer: processBuffer( buffer ),
  405. byteOffset: byteOffset,
  406. byteLength: buffer.byteLength
  407. };
  408. byteOffset += buffer.byteLength;
  409. outputJSON.bufferViews.push( bufferView );
  410. resolve( outputJSON.bufferViews.length - 1 );
  411. };
  412. } );
  413. }
  414. /**
  415. * Process attribute to generate an accessor
  416. * @param {BufferAttribute} attribute Attribute to process
  417. * @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  418. * @param {Integer} start (Optional)
  419. * @param {Integer} count (Optional)
  420. * @return {Integer} Index of the processed accessor on the "accessors" array
  421. */
  422. function processAccessor( attribute, geometry, start, count ) {
  423. var types = {
  424. 1: 'SCALAR',
  425. 2: 'VEC2',
  426. 3: 'VEC3',
  427. 4: 'VEC4',
  428. 16: 'MAT4'
  429. };
  430. var componentType;
  431. // Detect the component type of the attribute array (float, uint or ushort)
  432. if ( attribute.array.constructor === Float32Array ) {
  433. componentType = WEBGL_CONSTANTS.FLOAT;
  434. } else if ( attribute.array.constructor === Uint32Array ) {
  435. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  436. } else if ( attribute.array.constructor === Uint16Array ) {
  437. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  438. } else if ( attribute.array.constructor === Uint8Array ) {
  439. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  440. } else {
  441. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  442. }
  443. if ( start === undefined ) start = 0;
  444. if ( count === undefined ) count = attribute.count;
  445. // @TODO Indexed buffer geometry with drawRange not supported yet
  446. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  447. var end = start + count;
  448. var end2 = geometry.drawRange.count === Infinity
  449. ? attribute.count
  450. : geometry.drawRange.start + geometry.drawRange.count;
  451. start = Math.max( start, geometry.drawRange.start );
  452. count = Math.min( end, end2 ) - start;
  453. if ( count < 0 ) count = 0;
  454. }
  455. // Skip creating an accessor if the attribute doesn't have data to export
  456. if ( count === 0 ) {
  457. return null;
  458. }
  459. var minMax = getMinMax( attribute, start, count );
  460. var bufferViewTarget;
  461. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  462. // animation samplers, target must not be set.
  463. if ( geometry !== undefined ) {
  464. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  465. }
  466. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  467. var gltfAccessor = {
  468. bufferView: bufferView.id,
  469. byteOffset: bufferView.byteOffset,
  470. componentType: componentType,
  471. count: count,
  472. max: minMax.max,
  473. min: minMax.min,
  474. type: types[ attribute.itemSize ]
  475. };
  476. if ( ! outputJSON.accessors ) {
  477. outputJSON.accessors = [];
  478. }
  479. outputJSON.accessors.push( gltfAccessor );
  480. return outputJSON.accessors.length - 1;
  481. }
  482. /**
  483. * Process image
  484. * @param {Image} image to process
  485. * @param {Integer} format of the image (e.g. THREE.RGBFormat, RGBAFormat etc)
  486. * @param {Boolean} flipY before writing out the image
  487. * @return {Integer} Index of the processed texture in the "images" array
  488. */
  489. function processImage( image, format, flipY ) {
  490. if ( ! cachedData.images.has( image ) ) {
  491. cachedData.images.set( image, {} );
  492. }
  493. var cachedImages = cachedData.images.get( image );
  494. var mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg';
  495. var key = mimeType + ":flipY/" + flipY.toString();
  496. if ( cachedImages[ key ] !== undefined ) {
  497. return cachedImages[ key ];
  498. }
  499. if ( ! outputJSON.images ) {
  500. outputJSON.images = [];
  501. }
  502. var gltfImage = { mimeType: mimeType };
  503. if ( options.embedImages ) {
  504. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  505. canvas.width = image.width;
  506. canvas.height = image.height;
  507. if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( image ) ) {
  508. console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
  509. canvas.width = _Math.floorPowerOfTwo( canvas.width );
  510. canvas.height = _Math.floorPowerOfTwo( canvas.height );
  511. }
  512. var ctx = canvas.getContext( '2d' );
  513. if ( flipY === true ) {
  514. ctx.translate( 0, canvas.height );
  515. ctx.scale( 1, - 1 );
  516. }
  517. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  518. if ( options.binary === true ) {
  519. pending.push( new Promise( function ( resolve ) {
  520. canvas.toBlob( function ( blob ) {
  521. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  522. gltfImage.bufferView = bufferViewIndex;
  523. resolve();
  524. } );
  525. }, mimeType );
  526. } ) );
  527. } else {
  528. gltfImage.uri = canvas.toDataURL( mimeType );
  529. }
  530. } else {
  531. gltfImage.uri = image.src;
  532. }
  533. outputJSON.images.push( gltfImage );
  534. var index = outputJSON.images.length - 1;
  535. cachedImages[ key ] = index;
  536. return index;
  537. }
  538. /**
  539. * Process sampler
  540. * @param {Texture} map Texture to process
  541. * @return {Integer} Index of the processed texture in the "samplers" array
  542. */
  543. function processSampler( map ) {
  544. if ( ! outputJSON.samplers ) {
  545. outputJSON.samplers = [];
  546. }
  547. var gltfSampler = {
  548. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  549. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  550. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  551. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  552. };
  553. outputJSON.samplers.push( gltfSampler );
  554. return outputJSON.samplers.length - 1;
  555. }
  556. /**
  557. * Process texture
  558. * @param {Texture} map Map to process
  559. * @return {Integer} Index of the processed texture in the "textures" array
  560. */
  561. function processTexture( map ) {
  562. if ( cachedData.textures.has( map ) ) {
  563. return cachedData.textures.get( map );
  564. }
  565. if ( ! outputJSON.textures ) {
  566. outputJSON.textures = [];
  567. }
  568. var gltfTexture = {
  569. sampler: processSampler( map ),
  570. source: processImage( map.image, map.format, map.flipY )
  571. };
  572. outputJSON.textures.push( gltfTexture );
  573. var index = outputJSON.textures.length - 1;
  574. cachedData.textures.set( map, index );
  575. return index;
  576. }
  577. /**
  578. * Process material
  579. * @param {THREE.Material} material Material to process
  580. * @return {Integer} Index of the processed material in the "materials" array
  581. */
  582. function processMaterial( material ) {
  583. if ( cachedData.materials.has( material ) ) {
  584. return cachedData.materials.get( material );
  585. }
  586. if ( ! outputJSON.materials ) {
  587. outputJSON.materials = [];
  588. }
  589. if ( material.isShaderMaterial ) {
  590. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  591. return null;
  592. }
  593. // @QUESTION Should we avoid including any attribute that has the default value?
  594. var gltfMaterial = {
  595. pbrMetallicRoughness: {}
  596. };
  597. if ( material.isMeshBasicMaterial ) {
  598. gltfMaterial.extensions = { KHR_materials_unlit: {} };
  599. extensionsUsed[ 'KHR_materials_unlit' ] = true;
  600. } else if ( ! material.isMeshStandardMaterial ) {
  601. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  602. }
  603. // pbrMetallicRoughness.baseColorFactor
  604. var color = material.color.toArray().concat( [ material.opacity ] );
  605. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  606. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  607. }
  608. if ( material.isMeshStandardMaterial ) {
  609. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  610. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  611. } else if ( material.isMeshBasicMaterial ) {
  612. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
  613. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
  614. } else {
  615. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  616. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  617. }
  618. // pbrMetallicRoughness.metallicRoughnessTexture
  619. if ( material.metalnessMap || material.roughnessMap ) {
  620. if ( material.metalnessMap === material.roughnessMap ) {
  621. var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
  622. applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  623. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  624. } else {
  625. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  626. }
  627. }
  628. // pbrMetallicRoughness.baseColorTexture
  629. if ( material.map ) {
  630. var baseColorMapDef = { index: processTexture( material.map ) };
  631. applyTextureTransform( baseColorMapDef, material.map );
  632. gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  633. }
  634. if ( material.isMeshBasicMaterial ||
  635. material.isLineBasicMaterial ||
  636. material.isPointsMaterial ) {
  637. } else {
  638. // emissiveFactor
  639. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  640. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  641. gltfMaterial.emissiveFactor = emissive;
  642. }
  643. // emissiveTexture
  644. if ( material.emissiveMap ) {
  645. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  646. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  647. gltfMaterial.emissiveTexture = emissiveMapDef;
  648. }
  649. }
  650. // normalTexture
  651. if ( material.normalMap ) {
  652. var normalMapDef = { index: processTexture( material.normalMap ) };
  653. if ( material.normalScale.x !== - 1 ) {
  654. if ( material.normalScale.x !== material.normalScale.y ) {
  655. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  656. }
  657. normalMapDef.scale = material.normalScale.x;
  658. }
  659. applyTextureTransform( normalMapDef, material.normalMap );
  660. gltfMaterial.normalTexture = normalMapDef;
  661. }
  662. // occlusionTexture
  663. if ( material.aoMap ) {
  664. var occlusionMapDef = {
  665. index: processTexture( material.aoMap ),
  666. texCoord: 1
  667. };
  668. if ( material.aoMapIntensity !== 1.0 ) {
  669. occlusionMapDef.strength = material.aoMapIntensity;
  670. }
  671. applyTextureTransform( occlusionMapDef, material.aoMap );
  672. gltfMaterial.occlusionTexture = occlusionMapDef;
  673. }
  674. // alphaMode
  675. if ( material.transparent || material.alphaTest > 0.0 ) {
  676. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  677. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  678. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  679. gltfMaterial.alphaCutoff = material.alphaTest;
  680. }
  681. }
  682. // doubleSided
  683. if ( material.side === DoubleSide ) {
  684. gltfMaterial.doubleSided = true;
  685. }
  686. if ( material.name !== '' ) {
  687. gltfMaterial.name = material.name;
  688. }
  689. serializeUserData( material, gltfMaterial );
  690. outputJSON.materials.push( gltfMaterial );
  691. var index = outputJSON.materials.length - 1;
  692. cachedData.materials.set( material, index );
  693. return index;
  694. }
  695. /**
  696. * Process mesh
  697. * @param {THREE.Mesh} mesh Mesh to process
  698. * @return {Integer} Index of the processed mesh in the "meshes" array
  699. */
  700. function processMesh( mesh ) {
  701. var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid;
  702. if ( cachedData.meshes.has( cacheKey ) ) {
  703. return cachedData.meshes.get( cacheKey );
  704. }
  705. var geometry = mesh.geometry;
  706. var mode;
  707. // Use the correct mode
  708. if ( mesh.isLineSegments ) {
  709. mode = WEBGL_CONSTANTS.LINES;
  710. } else if ( mesh.isLineLoop ) {
  711. mode = WEBGL_CONSTANTS.LINE_LOOP;
  712. } else if ( mesh.isLine ) {
  713. mode = WEBGL_CONSTANTS.LINE_STRIP;
  714. } else if ( mesh.isPoints ) {
  715. mode = WEBGL_CONSTANTS.POINTS;
  716. } else {
  717. if ( ! geometry.isBufferGeometry ) {
  718. console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use BufferGeometry instead.' );
  719. var geometryTemp = new BufferGeometry();
  720. geometryTemp.fromGeometry( geometry );
  721. geometry = geometryTemp;
  722. }
  723. if ( mesh.drawMode === TriangleFanDrawMode ) {
  724. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  725. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  726. } else if ( mesh.drawMode === TriangleStripDrawMode ) {
  727. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  728. } else {
  729. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  730. }
  731. }
  732. var gltfMesh = {};
  733. var attributes = {};
  734. var primitives = [];
  735. var targets = [];
  736. // Conversion between attributes names in threejs and gltf spec
  737. var nameConversion = {
  738. uv: 'TEXCOORD_0',
  739. uv2: 'TEXCOORD_1',
  740. color: 'COLOR_0',
  741. skinWeight: 'WEIGHTS_0',
  742. skinIndex: 'JOINTS_0'
  743. };
  744. var originalNormal = geometry.getAttribute( 'normal' );
  745. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  746. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  747. geometry.addAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  748. }
  749. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  750. // For every attribute create an accessor
  751. var modifiedAttribute = null;
  752. for ( var attributeName in geometry.attributes ) {
  753. var attribute = geometry.attributes[ attributeName ];
  754. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  755. if ( cachedData.attributes.has( attribute ) ) {
  756. attributes[ attributeName ] = cachedData.attributes.get( attribute );
  757. continue;
  758. }
  759. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  760. modifiedAttribute = null;
  761. var array = attribute.array;
  762. if ( attributeName === 'JOINTS_0' &&
  763. ! ( array instanceof Uint16Array ) &&
  764. ! ( array instanceof Uint8Array ) ) {
  765. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  766. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  767. }
  768. if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
  769. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  770. if ( accessor !== null ) {
  771. attributes[ attributeName ] = accessor;
  772. cachedData.attributes.set( attribute, accessor );
  773. }
  774. }
  775. }
  776. if ( originalNormal !== undefined ) geometry.addAttribute( 'normal', originalNormal );
  777. // Skip if no exportable attributes found
  778. if ( Object.keys( attributes ).length === 0 ) {
  779. return null;
  780. }
  781. // Morph targets
  782. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  783. var weights = [];
  784. var targetNames = [];
  785. var reverseDictionary = {};
  786. if ( mesh.morphTargetDictionary !== undefined ) {
  787. for ( var key in mesh.morphTargetDictionary ) {
  788. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  789. }
  790. }
  791. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  792. var target = {};
  793. var warned = false;
  794. for ( var attributeName in geometry.morphAttributes ) {
  795. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  796. // Three.js doesn't support TANGENT yet.
  797. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  798. if ( ! warned ) {
  799. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  800. warned = true;
  801. }
  802. continue;
  803. }
  804. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  805. var gltfAttributeName = attributeName.toUpperCase();
  806. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  807. //
  808. // glTF 2.0 Specification:
  809. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  810. var baseAttribute = geometry.attributes[ attributeName ];
  811. if ( cachedData.attributes.has( attribute ) ) {
  812. target[ gltfAttributeName ] = cachedData.attributes.get( attribute );
  813. continue;
  814. }
  815. // Clones attribute not to override
  816. var relativeAttribute = attribute.clone();
  817. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  818. relativeAttribute.setXYZ(
  819. j,
  820. attribute.getX( j ) - baseAttribute.getX( j ),
  821. attribute.getY( j ) - baseAttribute.getY( j ),
  822. attribute.getZ( j ) - baseAttribute.getZ( j )
  823. );
  824. }
  825. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  826. cachedData.attributes.set( baseAttribute, target[ gltfAttributeName ] );
  827. }
  828. targets.push( target );
  829. weights.push( mesh.morphTargetInfluences[ i ] );
  830. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  831. }
  832. gltfMesh.weights = weights;
  833. if ( targetNames.length > 0 ) {
  834. gltfMesh.extras = {};
  835. gltfMesh.extras.targetNames = targetNames;
  836. }
  837. }
  838. var forceIndices = options.forceIndices;
  839. var isMultiMaterial = Array.isArray( mesh.material );
  840. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  841. if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
  842. // temporal workaround.
  843. console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
  844. forceIndices = true;
  845. }
  846. var didForceIndices = false;
  847. if ( geometry.index === null && forceIndices ) {
  848. var indices = [];
  849. for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  850. indices[ i ] = i;
  851. }
  852. geometry.setIndex( indices );
  853. didForceIndices = true;
  854. }
  855. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  856. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  857. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  858. var primitive = {
  859. mode: mode,
  860. attributes: attributes,
  861. };
  862. serializeUserData( geometry, primitive );
  863. if ( targets.length > 0 ) primitive.targets = targets;
  864. if ( geometry.index !== null ) {
  865. if ( cachedData.attributes.has( geometry.index ) ) {
  866. primitive.indices = cachedData.attributes.get( geometry.index );
  867. } else {
  868. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  869. cachedData.attributes.set( geometry.index, primitive.indices );
  870. }
  871. }
  872. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  873. if ( material !== null ) {
  874. primitive.material = material;
  875. }
  876. primitives.push( primitive );
  877. }
  878. if ( didForceIndices ) {
  879. geometry.setIndex( null );
  880. }
  881. gltfMesh.primitives = primitives;
  882. if ( ! outputJSON.meshes ) {
  883. outputJSON.meshes = [];
  884. }
  885. outputJSON.meshes.push( gltfMesh );
  886. var index = outputJSON.meshes.length - 1;
  887. cachedData.meshes.set( cacheKey, index );
  888. return index;
  889. }
  890. /**
  891. * Process camera
  892. * @param {THREE.Camera} camera Camera to process
  893. * @return {Integer} Index of the processed mesh in the "camera" array
  894. */
  895. function processCamera( camera ) {
  896. if ( ! outputJSON.cameras ) {
  897. outputJSON.cameras = [];
  898. }
  899. var isOrtho = camera.isOrthographicCamera;
  900. var gltfCamera = {
  901. type: isOrtho ? 'orthographic' : 'perspective'
  902. };
  903. if ( isOrtho ) {
  904. gltfCamera.orthographic = {
  905. xmag: camera.right * 2,
  906. ymag: camera.top * 2,
  907. zfar: camera.far <= 0 ? 0.001 : camera.far,
  908. znear: camera.near < 0 ? 0 : camera.near
  909. };
  910. } else {
  911. gltfCamera.perspective = {
  912. aspectRatio: camera.aspect,
  913. yfov: _Math.degToRad( camera.fov ),
  914. zfar: camera.far <= 0 ? 0.001 : camera.far,
  915. znear: camera.near < 0 ? 0 : camera.near
  916. };
  917. }
  918. if ( camera.name !== '' ) {
  919. gltfCamera.name = camera.type;
  920. }
  921. outputJSON.cameras.push( gltfCamera );
  922. return outputJSON.cameras.length - 1;
  923. }
  924. /**
  925. * Creates glTF animation entry from AnimationClip object.
  926. *
  927. * Status:
  928. * - Only properties listed in PATH_PROPERTIES may be animated.
  929. *
  930. * @param {THREE.AnimationClip} clip
  931. * @param {THREE.Object3D} root
  932. * @return {number}
  933. */
  934. function processAnimation( clip, root ) {
  935. if ( ! outputJSON.animations ) {
  936. outputJSON.animations = [];
  937. }
  938. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  939. var tracks = clip.tracks;
  940. var channels = [];
  941. var samplers = [];
  942. for ( var i = 0; i < tracks.length; ++ i ) {
  943. var track = tracks[ i ];
  944. var trackBinding = PropertyBinding.parseTrackName( track.name );
  945. var trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  946. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  947. if ( trackBinding.objectName === 'bones' ) {
  948. if ( trackNode.isSkinnedMesh === true ) {
  949. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  950. } else {
  951. trackNode = undefined;
  952. }
  953. }
  954. if ( ! trackNode || ! trackProperty ) {
  955. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  956. return null;
  957. }
  958. var inputItemSize = 1;
  959. var outputItemSize = track.values.length / track.times.length;
  960. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  961. outputItemSize /= trackNode.morphTargetInfluences.length;
  962. }
  963. var interpolation;
  964. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  965. // Detecting glTF cubic spline interpolant by checking factory method's special property
  966. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  967. // valid value from .getInterpolation().
  968. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  969. interpolation = 'CUBICSPLINE';
  970. // itemSize of CUBICSPLINE keyframe is 9
  971. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  972. // but needs to be stored as VEC3 so dividing by 3 here.
  973. outputItemSize /= 3;
  974. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  975. interpolation = 'STEP';
  976. } else {
  977. interpolation = 'LINEAR';
  978. }
  979. samplers.push( {
  980. input: processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  981. output: processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  982. interpolation: interpolation
  983. } );
  984. channels.push( {
  985. sampler: samplers.length - 1,
  986. target: {
  987. node: nodeMap.get( trackNode ),
  988. path: trackProperty
  989. }
  990. } );
  991. }
  992. outputJSON.animations.push( {
  993. name: clip.name || 'clip_' + outputJSON.animations.length,
  994. samplers: samplers,
  995. channels: channels
  996. } );
  997. return outputJSON.animations.length - 1;
  998. }
  999. function processSkin( object ) {
  1000. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  1001. var skeleton = object.skeleton;
  1002. var rootJoint = object.skeleton.bones[ 0 ];
  1003. if ( rootJoint === undefined ) return null;
  1004. var joints = [];
  1005. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1006. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  1007. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1008. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  1009. }
  1010. if ( outputJSON.skins === undefined ) {
  1011. outputJSON.skins = [];
  1012. }
  1013. outputJSON.skins.push( {
  1014. inverseBindMatrices: processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1015. joints: joints,
  1016. skeleton: nodeMap.get( rootJoint )
  1017. } );
  1018. var skinIndex = node.skin = outputJSON.skins.length - 1;
  1019. return skinIndex;
  1020. }
  1021. function processLight( light ) {
  1022. var lightDef = {};
  1023. if ( light.name ) lightDef.name = light.name;
  1024. lightDef.color = light.color.toArray();
  1025. lightDef.intensity = light.intensity;
  1026. if ( light.isDirectionalLight ) {
  1027. lightDef.type = 'directional';
  1028. } else if ( light.isPointLight ) {
  1029. lightDef.type = 'point';
  1030. if ( light.distance > 0 ) lightDef.range = light.distance;
  1031. } else if ( light.isSpotLight ) {
  1032. lightDef.type = 'spot';
  1033. if ( light.distance > 0 ) lightDef.range = light.distance;
  1034. lightDef.spot = {};
  1035. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1036. lightDef.spot.outerConeAngle = light.angle;
  1037. }
  1038. if ( light.decay !== undefined && light.decay !== 2 ) {
  1039. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1040. + 'and expects light.decay=2.' );
  1041. }
  1042. if ( light.target
  1043. && ( light.target.parent !== light
  1044. || light.target.position.x !== 0
  1045. || light.target.position.y !== 0
  1046. || light.target.position.z !== - 1 ) ) {
  1047. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1048. + 'make light.target a child of the light with position 0,0,-1.' );
  1049. }
  1050. var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
  1051. lights.push( lightDef );
  1052. return lights.length - 1;
  1053. }
  1054. /**
  1055. * Process Object3D node
  1056. * @param {THREE.Object3D} node Object3D to processNode
  1057. * @return {Integer} Index of the node in the nodes list
  1058. */
  1059. function processNode( object ) {
  1060. if ( ! outputJSON.nodes ) {
  1061. outputJSON.nodes = [];
  1062. }
  1063. var gltfNode = {};
  1064. if ( options.trs ) {
  1065. var rotation = object.quaternion.toArray();
  1066. var position = object.position.toArray();
  1067. var scale = object.scale.toArray();
  1068. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1069. gltfNode.rotation = rotation;
  1070. }
  1071. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1072. gltfNode.translation = position;
  1073. }
  1074. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1075. gltfNode.scale = scale;
  1076. }
  1077. } else {
  1078. object.updateMatrix();
  1079. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  1080. gltfNode.matrix = object.matrix.elements;
  1081. }
  1082. }
  1083. // We don't export empty strings name because it represents no-name in Three.js.
  1084. if ( object.name !== '' ) {
  1085. gltfNode.name = String( object.name );
  1086. }
  1087. serializeUserData( object, gltfNode );
  1088. if ( object.isMesh || object.isLine || object.isPoints ) {
  1089. var mesh = processMesh( object );
  1090. if ( mesh !== null ) {
  1091. gltfNode.mesh = mesh;
  1092. }
  1093. } else if ( object.isCamera ) {
  1094. gltfNode.camera = processCamera( object );
  1095. } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
  1096. if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
  1097. outputJSON.extensions = outputJSON.extensions || {};
  1098. outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
  1099. extensionsUsed[ 'KHR_lights_punctual' ] = true;
  1100. }
  1101. gltfNode.extensions = gltfNode.extensions || {};
  1102. gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
  1103. } else if ( object.isLight ) {
  1104. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.' );
  1105. return null;
  1106. }
  1107. if ( object.isSkinnedMesh ) {
  1108. skins.push( object );
  1109. }
  1110. if ( object.children.length > 0 ) {
  1111. var children = [];
  1112. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1113. var child = object.children[ i ];
  1114. if ( child.visible || options.onlyVisible === false ) {
  1115. var node = processNode( child );
  1116. if ( node !== null ) {
  1117. children.push( node );
  1118. }
  1119. }
  1120. }
  1121. if ( children.length > 0 ) {
  1122. gltfNode.children = children;
  1123. }
  1124. }
  1125. outputJSON.nodes.push( gltfNode );
  1126. var nodeIndex = outputJSON.nodes.length - 1;
  1127. nodeMap.set( object, nodeIndex );
  1128. return nodeIndex;
  1129. }
  1130. /**
  1131. * Process Scene
  1132. * @param {Scene} node Scene to process
  1133. */
  1134. function processScene( scene ) {
  1135. if ( ! outputJSON.scenes ) {
  1136. outputJSON.scenes = [];
  1137. outputJSON.scene = 0;
  1138. }
  1139. var gltfScene = {
  1140. nodes: []
  1141. };
  1142. if ( scene.name !== '' ) {
  1143. gltfScene.name = scene.name;
  1144. }
  1145. if ( scene.userData && Object.keys( scene.userData ).length > 0 ) {
  1146. gltfScene.extras = serializeUserData( scene );
  1147. }
  1148. outputJSON.scenes.push( gltfScene );
  1149. var nodes = [];
  1150. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1151. var child = scene.children[ i ];
  1152. if ( child.visible || options.onlyVisible === false ) {
  1153. var node = processNode( child );
  1154. if ( node !== null ) {
  1155. nodes.push( node );
  1156. }
  1157. }
  1158. }
  1159. if ( nodes.length > 0 ) {
  1160. gltfScene.nodes = nodes;
  1161. }
  1162. serializeUserData( scene, gltfScene );
  1163. }
  1164. /**
  1165. * Creates a Scene to hold a list of objects and parse it
  1166. * @param {Array} objects List of objects to process
  1167. */
  1168. function processObjects( objects ) {
  1169. var scene = new Scene();
  1170. scene.name = 'AuxScene';
  1171. for ( var i = 0; i < objects.length; i ++ ) {
  1172. // We push directly to children instead of calling `add` to prevent
  1173. // modify the .parent and break its original scene and hierarchy
  1174. scene.children.push( objects[ i ] );
  1175. }
  1176. processScene( scene );
  1177. }
  1178. function processInput( input ) {
  1179. input = input instanceof Array ? input : [ input ];
  1180. var objectsWithoutScene = [];
  1181. for ( var i = 0; i < input.length; i ++ ) {
  1182. if ( input[ i ] instanceof Scene ) {
  1183. processScene( input[ i ] );
  1184. } else {
  1185. objectsWithoutScene.push( input[ i ] );
  1186. }
  1187. }
  1188. if ( objectsWithoutScene.length > 0 ) {
  1189. processObjects( objectsWithoutScene );
  1190. }
  1191. for ( var i = 0; i < skins.length; ++ i ) {
  1192. processSkin( skins[ i ] );
  1193. }
  1194. for ( var i = 0; i < options.animations.length; ++ i ) {
  1195. processAnimation( options.animations[ i ], input[ 0 ] );
  1196. }
  1197. }
  1198. processInput( input );
  1199. Promise.all( pending ).then( function () {
  1200. // Merge buffers.
  1201. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1202. // Declare extensions.
  1203. var extensionsUsedList = Object.keys( extensionsUsed );
  1204. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1205. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1206. // Update bytelength of the single buffer.
  1207. outputJSON.buffers[ 0 ].byteLength = blob.size;
  1208. var reader = new window.FileReader();
  1209. if ( options.binary === true ) {
  1210. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1211. var GLB_HEADER_BYTES = 12;
  1212. var GLB_HEADER_MAGIC = 0x46546C67;
  1213. var GLB_VERSION = 2;
  1214. var GLB_CHUNK_PREFIX_BYTES = 8;
  1215. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1216. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1217. reader.readAsArrayBuffer( blob );
  1218. reader.onloadend = function () {
  1219. // Binary chunk.
  1220. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1221. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1222. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1223. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1224. // JSON chunk.
  1225. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1226. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1227. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1228. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1229. // GLB header.
  1230. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1231. var headerView = new DataView( header );
  1232. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1233. headerView.setUint32( 4, GLB_VERSION, true );
  1234. var totalByteLength = GLB_HEADER_BYTES
  1235. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1236. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1237. headerView.setUint32( 8, totalByteLength, true );
  1238. var glbBlob = new Blob( [
  1239. header,
  1240. jsonChunkPrefix,
  1241. jsonChunk,
  1242. binaryChunkPrefix,
  1243. binaryChunk
  1244. ], { type: 'application/octet-stream' } );
  1245. var glbReader = new window.FileReader();
  1246. glbReader.readAsArrayBuffer( glbBlob );
  1247. glbReader.onloadend = function () {
  1248. onDone( glbReader.result );
  1249. };
  1250. };
  1251. } else {
  1252. reader.readAsDataURL( blob );
  1253. reader.onloadend = function () {
  1254. var base64data = reader.result;
  1255. outputJSON.buffers[ 0 ].uri = base64data;
  1256. onDone( outputJSON );
  1257. };
  1258. }
  1259. } else {
  1260. onDone( outputJSON );
  1261. }
  1262. } );
  1263. }
  1264. };
  1265. GLTFExporter.Utils = {
  1266. insertKeyframe: function ( track, time ) {
  1267. var tolerance = 0.001; // 1ms
  1268. var valueSize = track.getValueSize();
  1269. var times = new track.TimeBufferType( track.times.length + 1 );
  1270. var values = new track.ValueBufferType( track.values.length + valueSize );
  1271. var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1272. var index;
  1273. if ( track.times.length === 0 ) {
  1274. times[ 0 ] = time;
  1275. for ( var i = 0; i < valueSize; i ++ ) {
  1276. values[ i ] = 0;
  1277. }
  1278. index = 0;
  1279. } else if ( time < track.times[ 0 ] ) {
  1280. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1281. times[ 0 ] = time;
  1282. times.set( track.times, 1 );
  1283. values.set( interpolant.evaluate( time ), 0 );
  1284. values.set( track.values, valueSize );
  1285. index = 0;
  1286. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1287. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1288. return track.times.length - 1;
  1289. }
  1290. times[ times.length - 1 ] = time;
  1291. times.set( track.times, 0 );
  1292. values.set( track.values, 0 );
  1293. values.set( interpolant.evaluate( time ), track.values.length );
  1294. index = times.length - 1;
  1295. } else {
  1296. for ( var i = 0; i < track.times.length; i ++ ) {
  1297. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1298. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1299. times.set( track.times.slice( 0, i + 1 ), 0 );
  1300. times[ i + 1 ] = time;
  1301. times.set( track.times.slice( i + 1 ), i + 2 );
  1302. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1303. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1304. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1305. index = i + 1;
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. track.times = times;
  1311. track.values = values;
  1312. return index;
  1313. },
  1314. mergeMorphTargetTracks: function ( clip, root ) {
  1315. var tracks = [];
  1316. var mergedTracks = {};
  1317. var sourceTracks = clip.tracks;
  1318. for ( var i = 0; i < sourceTracks.length; ++ i ) {
  1319. var sourceTrack = sourceTracks[ i ];
  1320. var sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  1321. var sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1322. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1323. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1324. tracks.push( sourceTrack );
  1325. continue;
  1326. }
  1327. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1328. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1329. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1330. // This should never happen, because glTF morph target animations
  1331. // affect all targets already.
  1332. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1333. }
  1334. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1335. sourceTrack = sourceTrack.clone();
  1336. sourceTrack.setInterpolation( InterpolateLinear );
  1337. }
  1338. var targetCount = sourceTrackNode.morphTargetInfluences.length;
  1339. var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1340. if ( targetIndex === undefined ) {
  1341. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1342. }
  1343. var mergedTrack;
  1344. // If this is the first time we've seen this object, create a new
  1345. // track to store merged keyframe data for each morph target.
  1346. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1347. mergedTrack = sourceTrack.clone();
  1348. var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1349. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1350. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1351. }
  1352. mergedTrack.name = '.morphTargetInfluences';
  1353. mergedTrack.values = values;
  1354. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1355. tracks.push( mergedTrack );
  1356. continue;
  1357. }
  1358. var mergedKeyframeIndex = 0;
  1359. var sourceKeyframeIndex = 0;
  1360. var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1361. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1362. // For every existing keyframe of the merged track, write a (possibly
  1363. // interpolated) value from the source track.
  1364. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1365. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1366. }
  1367. // For every existing keyframe of the source track, write a (possibly
  1368. // new) keyframe to the merged track. Values from the previous loop may
  1369. // be written again, but keyframes are de-duplicated.
  1370. for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
  1371. var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1372. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1373. }
  1374. }
  1375. clip.tracks = tracks;
  1376. return clip;
  1377. }
  1378. };
  1379. export { GLTFExporter };