GLTFExporter.js 40 KB

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