GLTFExporter.js 34 KB

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