GLTFExporter.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. */
  4. //------------------------------------------------------------------------------
  5. // Constants
  6. //------------------------------------------------------------------------------
  7. var WEBGL_CONSTANTS = {
  8. POINTS: 0x0000,
  9. LINES: 0x0001,
  10. LINE_LOOP: 0x0002,
  11. LINE_STRIP: 0x0003,
  12. TRIANGLES: 0x0004,
  13. TRIANGLE_STRIP: 0x0005,
  14. TRIANGLE_FAN: 0x0006,
  15. UNSIGNED_BYTE: 0x1401,
  16. UNSIGNED_SHORT: 0x1403,
  17. FLOAT: 0x1406,
  18. UNSIGNED_INT: 0x1405,
  19. ARRAY_BUFFER: 0x8892,
  20. ELEMENT_ARRAY_BUFFER: 0x8893,
  21. NEAREST: 0x2600,
  22. LINEAR: 0x2601,
  23. NEAREST_MIPMAP_NEAREST: 0x2700,
  24. LINEAR_MIPMAP_NEAREST: 0x2701,
  25. NEAREST_MIPMAP_LINEAR: 0x2702,
  26. LINEAR_MIPMAP_LINEAR: 0x2703
  27. };
  28. var THREE_TO_WEBGL = {
  29. // @TODO Replace with computed property name [THREE.*] when available on es6
  30. 1003: WEBGL_CONSTANTS.NEAREST,
  31. 1004: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
  32. 1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
  33. 1006: WEBGL_CONSTANTS.LINEAR,
  34. 1007: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
  35. 1008: WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR
  36. };
  37. var PATH_PROPERTIES = {
  38. scale: 'scale',
  39. position: 'translation',
  40. quaternion: 'rotation',
  41. morphTargetInfluences: 'weights'
  42. };
  43. //------------------------------------------------------------------------------
  44. // GLTF Exporter
  45. //------------------------------------------------------------------------------
  46. THREE.GLTFExporter = function () {};
  47. THREE.GLTFExporter.prototype = {
  48. constructor: THREE.GLTFExporter,
  49. /**
  50. * Parse scenes and generate GLTF output
  51. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  52. * @param {Function} onDone Callback on completed
  53. * @param {Object} options options
  54. */
  55. parse: function ( input, onDone, options ) {
  56. var DEFAULT_OPTIONS = {
  57. trs: false,
  58. onlyVisible: true,
  59. truncateDrawRange: true,
  60. embedImages: true,
  61. animations: [],
  62. forceIndices: false
  63. };
  64. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  65. if ( options.animations.length > 0 ) {
  66. // Only TRS properties, and not matrices, may be targeted by animation.
  67. options.trs = true;
  68. }
  69. var outputJSON = {
  70. asset: {
  71. version: "2.0",
  72. generator: "THREE.GLTFExporter"
  73. }
  74. };
  75. var byteOffset = 0;
  76. var dataViews = [];
  77. var nodeMap = {};
  78. var skins = [];
  79. var cachedData = {
  80. materials: {},
  81. textures: {}
  82. };
  83. var cachedCanvas;
  84. /**
  85. * Compare two arrays
  86. */
  87. /**
  88. * Compare two arrays
  89. * @param {Array} array1 Array 1 to compare
  90. * @param {Array} array2 Array 2 to compare
  91. * @return {Boolean} Returns true if both arrays are equal
  92. */
  93. function equalArray( array1, array2 ) {
  94. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  95. return element === array2[ index ];
  96. } );
  97. }
  98. /**
  99. * Converts a string to an ArrayBuffer.
  100. * @param {string} text
  101. * @return {ArrayBuffer}
  102. */
  103. function stringToArrayBuffer( text, padded ) {
  104. if ( padded ) {
  105. var pad = getPaddedBufferSize( text.length ) - text.length;
  106. for ( var i = 0; i < pad; i++ ) {
  107. text += ' ';
  108. }
  109. }
  110. if ( window.TextEncoder !== undefined ) {
  111. return new TextEncoder().encode( text ).buffer;
  112. }
  113. var buffer = new ArrayBuffer( text.length );
  114. var bufferView = new Uint8Array( buffer );
  115. for ( var i = 0; i < text.length; ++ i ) {
  116. bufferView[ i ] = text.charCodeAt( i );
  117. }
  118. return buffer;
  119. }
  120. /**
  121. * Get the min and max vectors from the given attribute
  122. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max
  123. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  124. */
  125. function getMinMax( attribute ) {
  126. var output = {
  127. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  128. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  129. };
  130. for ( var i = 0; i < attribute.count; i ++ ) {
  131. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  132. var value = attribute.array[ i * attribute.itemSize + a ];
  133. output.min[ a ] = Math.min( output.min[ a ], value );
  134. output.max[ a ] = Math.max( output.max[ a ], value );
  135. }
  136. }
  137. return output;
  138. }
  139. /**
  140. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  141. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  142. *
  143. * @param {Integer} bufferSize The size the original buffer.
  144. * @returns {Integer} new buffer size with required padding.
  145. *
  146. */
  147. function getPaddedBufferSize( bufferSize ) {
  148. return Math.ceil( bufferSize / 4 ) * 4;
  149. }
  150. /**
  151. * Returns a buffer aligned to 4-byte boundary.
  152. *
  153. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  154. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  155. */
  156. function getPaddedArrayBuffer( arrayBuffer ) {
  157. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  158. if (paddedLength !== arrayBuffer.byteLength ) {
  159. var paddedBuffer = new ArrayBuffer( paddedLength );
  160. new Uint8Array( paddedBuffer ).set(new Uint8Array(arrayBuffer));
  161. return paddedBuffer;
  162. }
  163. return arrayBuffer;
  164. }
  165. /**
  166. * Process a buffer to append to the default one.
  167. * @param {THREE.BufferAttribute} attribute Attribute to store
  168. * @param {Integer} componentType Component type (Unsigned short, unsigned int or float)
  169. * @return {Integer} Index of the buffer created (Currently always 0)
  170. */
  171. function processBuffer( attribute, componentType, start, count ) {
  172. if ( ! outputJSON.buffers ) {
  173. outputJSON.buffers = [
  174. {
  175. byteLength: 0,
  176. uri: ''
  177. }
  178. ];
  179. }
  180. var offset = 0;
  181. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  182. // Create a new dataview and dump the attribute's array into it
  183. var byteLength = count * attribute.itemSize * componentSize;
  184. // adjust required size of array buffer with padding
  185. // to satisfy gltf requirement that the length is divisible by 4
  186. byteLength = getPaddedBufferSize( byteLength );
  187. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  188. for ( var i = start; i < start + count; i ++ ) {
  189. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  190. var value = attribute.array[ i * attribute.itemSize + a ];
  191. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  192. dataView.setFloat32( offset, value, true );
  193. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  194. dataView.setUint32( offset, value, true );
  195. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  196. dataView.setUint16( offset, value, true );
  197. }
  198. offset += componentSize;
  199. }
  200. }
  201. // We just use one buffer
  202. dataViews.push( dataView );
  203. // Always using just one buffer
  204. return 0;
  205. }
  206. /**
  207. * Process and generate a BufferView
  208. * @param {THREE.BufferAttribute} data
  209. * @param {number} componentType
  210. * @param {number} start
  211. * @param {number} count
  212. * @param {number} target (Optional) Target usage of the BufferView
  213. * @return {Object}
  214. */
  215. function processBufferView( data, componentType, start, count, target ) {
  216. if ( ! outputJSON.bufferViews ) {
  217. outputJSON.bufferViews = [];
  218. }
  219. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  220. // Create a new dataview and dump the attribute's array into it
  221. var byteLength = count * data.itemSize * componentSize;
  222. var gltfBufferView = {
  223. buffer: processBuffer( data, componentType, start, count ),
  224. byteOffset: byteOffset,
  225. byteLength: byteLength
  226. };
  227. if ( target !== undefined ) gltfBufferView.target = target;
  228. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  229. // Only define byteStride for vertex attributes.
  230. gltfBufferView.byteStride = data.itemSize * componentSize;
  231. }
  232. byteOffset += byteLength;
  233. outputJSON.bufferViews.push( gltfBufferView );
  234. // @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
  235. var output = {
  236. id: outputJSON.bufferViews.length - 1,
  237. byteLength: 0
  238. };
  239. return output;
  240. }
  241. /**
  242. * Process attribute to generate an accessor
  243. * @param {THREE.BufferAttribute} attribute Attribute to process
  244. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  245. * @return {Integer} Index of the processed accessor on the "accessors" array
  246. */
  247. function processAccessor( attribute, geometry ) {
  248. if ( ! outputJSON.accessors ) {
  249. outputJSON.accessors = [];
  250. }
  251. var types = {
  252. 1: 'SCALAR',
  253. 2: 'VEC2',
  254. 3: 'VEC3',
  255. 4: 'VEC4',
  256. 16: 'MAT4'
  257. };
  258. var componentType;
  259. // Detect the component type of the attribute array (float, uint or ushort)
  260. if ( attribute.array.constructor === Float32Array ) {
  261. componentType = WEBGL_CONSTANTS.FLOAT;
  262. } else if ( attribute.array.constructor === Uint32Array ) {
  263. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  264. } else if ( attribute.array.constructor === Uint16Array ) {
  265. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  266. } else {
  267. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  268. }
  269. var minMax = getMinMax( attribute );
  270. var start = 0;
  271. var count = attribute.count;
  272. // @TODO Indexed buffer geometry with drawRange not supported yet
  273. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  274. start = geometry.drawRange.start;
  275. count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
  276. }
  277. var bufferViewTarget;
  278. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  279. // animation samplers, target must not be set.
  280. if ( geometry !== undefined ) {
  281. var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
  282. bufferViewTarget = isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER;
  283. }
  284. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  285. var gltfAccessor = {
  286. bufferView: bufferView.id,
  287. byteOffset: bufferView.byteOffset,
  288. componentType: componentType,
  289. count: count,
  290. max: minMax.max,
  291. min: minMax.min,
  292. type: types[ attribute.itemSize ]
  293. };
  294. outputJSON.accessors.push( gltfAccessor );
  295. return outputJSON.accessors.length - 1;
  296. }
  297. /**
  298. * Process image
  299. * @param {Texture} map Texture to process
  300. * @return {Integer} Index of the processed texture in the "images" array
  301. */
  302. function processImage( map ) {
  303. // @TODO Cache
  304. if ( ! outputJSON.images ) {
  305. outputJSON.images = [];
  306. }
  307. var mimeType = map.format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  308. var gltfImage = { mimeType: mimeType };
  309. if ( options.embedImages ) {
  310. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  311. canvas.width = map.image.width;
  312. canvas.height = map.image.height;
  313. var ctx = canvas.getContext( '2d' );
  314. if ( map.flipY === true ) {
  315. ctx.translate( 0, map.image.height );
  316. ctx.scale( 1, - 1 );
  317. }
  318. ctx.drawImage( map.image, 0, 0 );
  319. // @TODO Embed in { bufferView } if options.binary set.
  320. gltfImage.uri = canvas.toDataURL( mimeType );
  321. } else {
  322. gltfImage.uri = map.image.src;
  323. }
  324. outputJSON.images.push( gltfImage );
  325. return outputJSON.images.length - 1;
  326. }
  327. /**
  328. * Process sampler
  329. * @param {Texture} map Texture to process
  330. * @return {Integer} Index of the processed texture in the "samplers" array
  331. */
  332. function processSampler( map ) {
  333. if ( ! outputJSON.samplers ) {
  334. outputJSON.samplers = [];
  335. }
  336. var gltfSampler = {
  337. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  338. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  339. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  340. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  341. };
  342. outputJSON.samplers.push( gltfSampler );
  343. return outputJSON.samplers.length - 1;
  344. }
  345. /**
  346. * Process texture
  347. * @param {Texture} map Map to process
  348. * @return {Integer} Index of the processed texture in the "textures" array
  349. */
  350. function processTexture( map ) {
  351. if ( cachedData.textures[ map.uuid ] !== undefined ) {
  352. return cachedData.textures[ map.uuid ];
  353. }
  354. if ( ! outputJSON.textures ) {
  355. outputJSON.textures = [];
  356. }
  357. var gltfTexture = {
  358. sampler: processSampler( map ),
  359. source: processImage( map )
  360. };
  361. outputJSON.textures.push( gltfTexture );
  362. var index = outputJSON.textures.length - 1;
  363. cachedData.textures[ map.uuid ] = index;
  364. return index;
  365. }
  366. /**
  367. * Process material
  368. * @param {THREE.Material} material Material to process
  369. * @return {Integer} Index of the processed material in the "materials" array
  370. */
  371. function processMaterial( material ) {
  372. if ( cachedData.materials[ material.uuid ] !== undefined ) {
  373. return cachedData.materials[ material.uuid ];
  374. }
  375. if ( ! outputJSON.materials ) {
  376. outputJSON.materials = [];
  377. }
  378. if ( material instanceof THREE.ShaderMaterial ) {
  379. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  380. return null;
  381. }
  382. if ( ! ( material instanceof THREE.MeshStandardMaterial ) ) {
  383. console.warn( 'GLTFExporter: Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
  384. }
  385. // @QUESTION Should we avoid including any attribute that has the default value?
  386. var gltfMaterial = {
  387. pbrMetallicRoughness: {}
  388. };
  389. // pbrMetallicRoughness.baseColorFactor
  390. var color = material.color.toArray().concat( [ material.opacity ] );
  391. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  392. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  393. }
  394. if ( material instanceof THREE.MeshStandardMaterial ) {
  395. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  396. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  397. } else {
  398. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  399. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  400. }
  401. // pbrMetallicRoughness.metallicRoughnessTexture
  402. if ( material.metalnessMap || material.roughnessMap ) {
  403. if ( material.metalnessMap === material.roughnessMap ) {
  404. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = {
  405. index: processTexture( material.metalnessMap )
  406. };
  407. } else {
  408. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  409. }
  410. }
  411. // pbrMetallicRoughness.baseColorTexture
  412. if ( material.map ) {
  413. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  414. index: processTexture( material.map )
  415. };
  416. }
  417. if ( material instanceof THREE.MeshBasicMaterial ||
  418. material instanceof THREE.LineBasicMaterial ||
  419. material instanceof THREE.PointsMaterial ) {
  420. } else {
  421. // emissiveFactor
  422. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  423. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  424. gltfMaterial.emissiveFactor = emissive;
  425. }
  426. // emissiveTexture
  427. if ( material.emissiveMap ) {
  428. gltfMaterial.emissiveTexture = {
  429. index: processTexture( material.emissiveMap )
  430. };
  431. }
  432. }
  433. // normalTexture
  434. if ( material.normalMap ) {
  435. gltfMaterial.normalTexture = {
  436. index: processTexture( material.normalMap )
  437. };
  438. if ( material.normalScale.x !== - 1 ) {
  439. if ( material.normalScale.x !== material.normalScale.y ) {
  440. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  441. }
  442. gltfMaterial.normalTexture.scale = material.normalScale.x;
  443. }
  444. }
  445. // occlusionTexture
  446. if ( material.aoMap ) {
  447. gltfMaterial.occlusionTexture = {
  448. index: processTexture( material.aoMap )
  449. };
  450. if ( material.aoMapIntensity !== 1.0 ) {
  451. gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;
  452. }
  453. }
  454. // alphaMode
  455. if ( material.transparent || material.alphaTest > 0.0 ) {
  456. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  457. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  458. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  459. gltfMaterial.alphaCutoff = material.alphaTest;
  460. }
  461. }
  462. // doubleSided
  463. if ( material.side === THREE.DoubleSide ) {
  464. gltfMaterial.doubleSided = true;
  465. }
  466. if ( material.name ) {
  467. gltfMaterial.name = material.name;
  468. }
  469. outputJSON.materials.push( gltfMaterial );
  470. var index = outputJSON.materials.length - 1;
  471. cachedData.materials[ material.uuid ] = index;
  472. return index;
  473. }
  474. /**
  475. * Process mesh
  476. * @param {THREE.Mesh} mesh Mesh to process
  477. * @return {Integer} Index of the processed mesh in the "meshes" array
  478. */
  479. function processMesh( mesh ) {
  480. if ( ! outputJSON.meshes ) {
  481. outputJSON.meshes = [];
  482. }
  483. var geometry = mesh.geometry;
  484. var mode;
  485. // Use the correct mode
  486. if ( mesh instanceof THREE.LineSegments ) {
  487. mode = WEBGL_CONSTANTS.LINES;
  488. } else if ( mesh instanceof THREE.LineLoop ) {
  489. mode = WEBGL_CONSTANTS.LINE_LOOP;
  490. } else if ( mesh instanceof THREE.Line ) {
  491. mode = WEBGL_CONSTANTS.LINE_STRIP;
  492. } else if ( mesh instanceof THREE.Points ) {
  493. mode = WEBGL_CONSTANTS.POINTS;
  494. } else {
  495. if ( ! geometry.isBufferGeometry ) {
  496. var geometryTemp = new THREE.BufferGeometry();
  497. geometryTemp.fromGeometry( geometry );
  498. geometry = geometryTemp;
  499. }
  500. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  501. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  502. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  503. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  504. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  505. } else {
  506. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  507. }
  508. }
  509. var gltfMesh = {
  510. primitives: [
  511. {
  512. mode: mode,
  513. attributes: {},
  514. }
  515. ]
  516. };
  517. var material = processMaterial( mesh.material );
  518. if ( material !== null ) {
  519. gltfMesh.primitives[ 0 ].material = material;
  520. }
  521. if ( geometry.index ) {
  522. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
  523. } else if ( options.forceIndices ) {
  524. var numFaces = geometry.attributes.position.count;
  525. var indices = new Uint32Array( numFaces );
  526. for ( var i = 0; i < numFaces; i ++ ) {
  527. indices[ i ] = i;
  528. }
  529. gltfMesh.primitives[ 0 ].indices = processAccessor( new THREE.Uint32BufferAttribute( indices, 1 ), geometry );
  530. }
  531. // We've just one primitive per mesh
  532. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  533. // Conversion between attributes names in threejs and gltf spec
  534. var nameConversion = {
  535. uv: 'TEXCOORD_0',
  536. uv2: 'TEXCOORD_1',
  537. color: 'COLOR_0',
  538. skinWeight: 'WEIGHTS_0',
  539. skinIndex: 'JOINTS_0'
  540. };
  541. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  542. // For every attribute create an accessor
  543. for ( var attributeName in geometry.attributes ) {
  544. var attribute = geometry.attributes[ attributeName ];
  545. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  546. if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
  547. gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
  548. }
  549. }
  550. // Morph targets
  551. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  552. var weights = [];
  553. var targetNames = [];
  554. var reverseDictionary = {};
  555. if ( mesh.morphTargetDictionary !== undefined ) {
  556. for ( var key in mesh.morphTargetDictionary ) {
  557. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  558. }
  559. }
  560. gltfMesh.primitives[ 0 ].targets = [];
  561. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  562. var target = {};
  563. var warned = false;
  564. for ( var attributeName in geometry.morphAttributes ) {
  565. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  566. // Three.js doesn't support TANGENT yet.
  567. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  568. if ( ! warned ) {
  569. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  570. warned = true;
  571. }
  572. continue;
  573. }
  574. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  575. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  576. //
  577. // glTF 2.0 Specification:
  578. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  579. var baseAttribute = geometry.attributes[ attributeName ];
  580. // Clones attribute not to override
  581. var relativeAttribute = attribute.clone();
  582. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  583. relativeAttribute.setXYZ(
  584. j,
  585. attribute.getX( j ) - baseAttribute.getX( j ),
  586. attribute.getY( j ) - baseAttribute.getY( j ),
  587. attribute.getZ( j ) - baseAttribute.getZ( j )
  588. );
  589. }
  590. target[ attributeName.toUpperCase() ] = processAccessor( relativeAttribute, geometry );
  591. }
  592. gltfMesh.primitives[ 0 ].targets.push( target );
  593. weights.push( mesh.morphTargetInfluences[ i ] );
  594. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  595. }
  596. gltfMesh.weights = weights;
  597. if ( targetNames.length > 0 ) {
  598. gltfMesh.extras = {};
  599. gltfMesh.extras.targetNames = targetNames;
  600. }
  601. }
  602. outputJSON.meshes.push( gltfMesh );
  603. return outputJSON.meshes.length - 1;
  604. }
  605. /**
  606. * Process camera
  607. * @param {THREE.Camera} camera Camera to process
  608. * @return {Integer} Index of the processed mesh in the "camera" array
  609. */
  610. function processCamera( camera ) {
  611. if ( ! outputJSON.cameras ) {
  612. outputJSON.cameras = [];
  613. }
  614. var isOrtho = camera instanceof THREE.OrthographicCamera;
  615. var gltfCamera = {
  616. type: isOrtho ? 'orthographic' : 'perspective'
  617. };
  618. if ( isOrtho ) {
  619. gltfCamera.orthographic = {
  620. xmag: camera.right * 2,
  621. ymag: camera.top * 2,
  622. zfar: camera.far <= 0 ? 0.001 : camera.far,
  623. znear: camera.near < 0 ? 0 : camera.near
  624. };
  625. } else {
  626. gltfCamera.perspective = {
  627. aspectRatio: camera.aspect,
  628. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  629. zfar: camera.far <= 0 ? 0.001 : camera.far,
  630. znear: camera.near < 0 ? 0 : camera.near
  631. };
  632. }
  633. if ( camera.name ) {
  634. gltfCamera.name = camera.type;
  635. }
  636. outputJSON.cameras.push( gltfCamera );
  637. return outputJSON.cameras.length - 1;
  638. }
  639. /**
  640. * Creates glTF animation entry from AnimationClip object.
  641. *
  642. * Status:
  643. * - Only properties listed in PATH_PROPERTIES may be animated.
  644. *
  645. * @param {THREE.AnimationClip} clip
  646. * @param {THREE.Object3D} root
  647. * @return {number}
  648. */
  649. function processAnimation( clip, root ) {
  650. if ( ! outputJSON.animations ) {
  651. outputJSON.animations = [];
  652. }
  653. var channels = [];
  654. var samplers = [];
  655. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  656. var track = clip.tracks[ i ];
  657. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  658. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  659. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  660. if ( trackBinding.objectName === 'bones' ) {
  661. if ( trackNode.isSkinnedMesh === true ) {
  662. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  663. } else {
  664. trackNode = undefined;
  665. }
  666. }
  667. if ( ! trackNode || ! trackProperty ) {
  668. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  669. return null;
  670. }
  671. var inputItemSize = 1;
  672. var outputItemSize = track.values.length / track.times.length;
  673. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  674. outputItemSize /= trackNode.morphTargetInfluences.length;
  675. }
  676. var interpolation;
  677. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  678. // Detecting glTF cubic spline interpolant by checking factory method's special property
  679. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  680. // valid value from .getInterpolation().
  681. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  682. interpolation = 'CUBICSPLINE';
  683. // itemSize of CUBICSPLINE keyframe is 9
  684. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  685. // but needs to be stored as VEC3 so dividing by 3 here.
  686. outputItemSize /= 3;
  687. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  688. interpolation = 'STEP';
  689. } else {
  690. interpolation = 'LINEAR';
  691. }
  692. samplers.push( {
  693. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  694. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  695. interpolation: interpolation
  696. } );
  697. channels.push( {
  698. sampler: samplers.length - 1,
  699. target: {
  700. node: nodeMap[ trackNode.uuid ],
  701. path: trackProperty
  702. }
  703. } );
  704. }
  705. outputJSON.animations.push( {
  706. name: clip.name || 'clip_' + outputJSON.animations.length,
  707. samplers: samplers,
  708. channels: channels
  709. } );
  710. return outputJSON.animations.length - 1;
  711. }
  712. function processSkin( object ) {
  713. var node = outputJSON.nodes[ nodeMap[ object.uuid ] ];
  714. var skeleton = object.skeleton;
  715. var rootJoint = object.skeleton.bones[ 0 ];
  716. if ( rootJoint === undefined ) return null;
  717. var joints = [];
  718. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  719. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  720. joints.push( nodeMap[ skeleton.bones[ i ].uuid ] );
  721. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  722. }
  723. if ( outputJSON.skins === undefined ) {
  724. outputJSON.skins = [];
  725. }
  726. outputJSON.skins.push( {
  727. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  728. joints: joints,
  729. skeleton: nodeMap[ rootJoint.uuid ]
  730. } );
  731. var skinIndex = node.skin = outputJSON.skins.length - 1;
  732. return skinIndex;
  733. }
  734. /**
  735. * Process Object3D node
  736. * @param {THREE.Object3D} node Object3D to processNode
  737. * @return {Integer} Index of the node in the nodes list
  738. */
  739. function processNode( object ) {
  740. if ( object instanceof THREE.Light ) {
  741. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  742. return null;
  743. }
  744. if ( ! outputJSON.nodes ) {
  745. outputJSON.nodes = [];
  746. }
  747. var gltfNode = {};
  748. if ( options.trs ) {
  749. var rotation = object.quaternion.toArray();
  750. var position = object.position.toArray();
  751. var scale = object.scale.toArray();
  752. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  753. gltfNode.rotation = rotation;
  754. }
  755. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  756. gltfNode.translation = position;
  757. }
  758. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  759. gltfNode.scale = scale;
  760. }
  761. } else {
  762. object.updateMatrix();
  763. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  764. gltfNode.matrix = object.matrix.elements;
  765. }
  766. }
  767. // We don't export empty strings name because it represents no-name in Three.js.
  768. if ( object.name !== '' ) {
  769. gltfNode.name = String( object.name );
  770. }
  771. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  772. try {
  773. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  774. } catch ( e ) {
  775. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  776. }
  777. }
  778. if ( object instanceof THREE.Mesh ||
  779. object instanceof THREE.Line ||
  780. object instanceof THREE.Points ) {
  781. gltfNode.mesh = processMesh( object );
  782. } else if ( object instanceof THREE.Camera ) {
  783. gltfNode.camera = processCamera( object );
  784. }
  785. if ( object instanceof THREE.SkinnedMesh ) {
  786. skins.push( object );
  787. }
  788. if ( object.children.length > 0 ) {
  789. var children = [];
  790. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  791. var child = object.children[ i ];
  792. if ( child.visible || options.onlyVisible === false ) {
  793. var node = processNode( child );
  794. if ( node !== null ) {
  795. children.push( node );
  796. }
  797. }
  798. }
  799. if ( children.length > 0 ) {
  800. gltfNode.children = children;
  801. }
  802. }
  803. outputJSON.nodes.push( gltfNode );
  804. var nodeIndex = nodeMap[ object.uuid ] = outputJSON.nodes.length - 1;
  805. return nodeIndex;
  806. }
  807. /**
  808. * Process Scene
  809. * @param {THREE.Scene} node Scene to process
  810. */
  811. function processScene( scene ) {
  812. if ( ! outputJSON.scenes ) {
  813. outputJSON.scenes = [];
  814. outputJSON.scene = 0;
  815. }
  816. var gltfScene = {
  817. nodes: []
  818. };
  819. if ( scene.name ) {
  820. gltfScene.name = scene.name;
  821. }
  822. outputJSON.scenes.push( gltfScene );
  823. var nodes = [];
  824. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  825. var child = scene.children[ i ];
  826. if ( child.visible || options.onlyVisible === false ) {
  827. var node = processNode( child );
  828. if ( node !== null ) {
  829. nodes.push( node );
  830. }
  831. }
  832. }
  833. if ( nodes.length > 0 ) {
  834. gltfScene.nodes = nodes;
  835. }
  836. }
  837. /**
  838. * Creates a THREE.Scene to hold a list of objects and parse it
  839. * @param {Array} objects List of objects to process
  840. */
  841. function processObjects( objects ) {
  842. var scene = new THREE.Scene();
  843. scene.name = 'AuxScene';
  844. for ( var i = 0; i < objects.length; i ++ ) {
  845. // We push directly to children instead of calling `add` to prevent
  846. // modify the .parent and break its original scene and hierarchy
  847. scene.children.push( objects[ i ] );
  848. }
  849. processScene( scene );
  850. }
  851. function processInput( input ) {
  852. input = input instanceof Array ? input : [ input ];
  853. var objectsWithoutScene = [];
  854. for ( var i = 0; i < input.length; i ++ ) {
  855. if ( input[ i ] instanceof THREE.Scene ) {
  856. processScene( input[ i ] );
  857. } else {
  858. objectsWithoutScene.push( input[ i ] );
  859. }
  860. }
  861. if ( objectsWithoutScene.length > 0 ) {
  862. processObjects( objectsWithoutScene );
  863. }
  864. for ( var i = 0; i < skins.length; ++ i ) {
  865. processSkin( skins[ i ] );
  866. }
  867. for ( var i = 0; i < options.animations.length; ++ i ) {
  868. processAnimation( options.animations[ i ], input[ 0 ] );
  869. }
  870. }
  871. processInput( input );
  872. // Generate buffer
  873. // Create a new blob with all the dataviews from the buffers
  874. var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
  875. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  876. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  877. outputJSON.buffers[ 0 ].byteLength = blob.size;
  878. var reader = new window.FileReader();
  879. if ( options.binary === true ) {
  880. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  881. var GLB_HEADER_BYTES = 12;
  882. var GLB_HEADER_MAGIC = 0x46546C67;
  883. var GLB_VERSION = 2;
  884. var GLB_CHUNK_PREFIX_BYTES = 8;
  885. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  886. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  887. reader.readAsArrayBuffer( blob );
  888. reader.onloadend = function () {
  889. // Binary chunk.
  890. var binaryChunk = getPaddedArrayBuffer( reader.result );
  891. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  892. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  893. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  894. // JSON chunk.
  895. delete outputJSON.buffers[ 0 ].uri; // Omitted URI indicates use of binary chunk.
  896. var jsonChunk = stringToArrayBuffer( JSON.stringify( outputJSON ), true );
  897. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  898. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  899. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  900. // GLB header.
  901. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  902. var headerView = new DataView( header );
  903. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  904. headerView.setUint32( 4, GLB_VERSION, true );
  905. var totalByteLength = GLB_HEADER_BYTES
  906. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  907. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  908. headerView.setUint32( 8, totalByteLength, true );
  909. var glbBlob = new Blob( [
  910. header,
  911. jsonChunkPrefix,
  912. jsonChunk,
  913. binaryChunkPrefix,
  914. binaryChunk
  915. ], { type: 'application/octet-stream' } );
  916. var glbReader = new window.FileReader();
  917. glbReader.readAsArrayBuffer( glbBlob );
  918. glbReader.onloadend = function () {
  919. onDone( glbReader.result );
  920. };
  921. };
  922. } else {
  923. reader.readAsDataURL( blob );
  924. reader.onloadend = function () {
  925. var base64data = reader.result;
  926. outputJSON.buffers[ 0 ].uri = base64data;
  927. onDone( outputJSON );
  928. };
  929. }
  930. } else {
  931. onDone( outputJSON );
  932. }
  933. }
  934. };