GLTFExporter.js 36 KB

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