GLTFExporter.js 40 KB

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