GLTFExporter.js 41 KB

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