GLTFExporter.js 37 KB

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