GLTFExporter.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. /**
  2. * @author fernandojsg / http://fernandojsg.com
  3. */
  4. //------------------------------------------------------------------------------
  5. // Constants
  6. //------------------------------------------------------------------------------
  7. var WEBGL_CONSTANTS = {
  8. POINTS: 0x0000,
  9. LINES: 0x0001,
  10. LINE_LOOP: 0x0002,
  11. LINE_STRIP: 0x0003,
  12. TRIANGLES: 0x0004,
  13. TRIANGLE_STRIP: 0x0005,
  14. TRIANGLE_FAN: 0x0006,
  15. UNSIGNED_BYTE: 0x1401,
  16. UNSIGNED_SHORT: 0x1403,
  17. FLOAT: 0x1406,
  18. UNSIGNED_INT: 0x1405,
  19. ARRAY_BUFFER: 0x8892,
  20. ELEMENT_ARRAY_BUFFER: 0x8893,
  21. NEAREST: 0x2600,
  22. LINEAR: 0x2601,
  23. NEAREST_MIPMAP_NEAREST: 0x2700,
  24. LINEAR_MIPMAP_NEAREST: 0x2701,
  25. NEAREST_MIPMAP_LINEAR: 0x2702,
  26. LINEAR_MIPMAP_LINEAR: 0x2703
  27. };
  28. var THREE_TO_WEBGL = {
  29. // @TODO Replace with computed property name [THREE.*] when available on es6
  30. 1003: WEBGL_CONSTANTS.NEAREST,
  31. 1004: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
  32. 1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
  33. 1006: WEBGL_CONSTANTS.LINEAR,
  34. 1007: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
  35. 1008: WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR
  36. };
  37. //------------------------------------------------------------------------------
  38. // GLTF Exporter
  39. //------------------------------------------------------------------------------
  40. THREE.GLTFExporter = function () {};
  41. THREE.GLTFExporter.prototype = {
  42. constructor: THREE.GLTFExporter,
  43. /**
  44. * Parse scenes and generate GLTF output
  45. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  46. * @param {Function} onDone Callback on completed
  47. * @param {Object} options options
  48. * trs: Exports position, rotation and scale instead of matrix
  49. * binary: Exports `.glb` as ArrayBuffer, instead of `.gltf` as JSON
  50. */
  51. parse: function ( input, onDone, options ) {
  52. var DEFAULT_OPTIONS = {
  53. trs: false,
  54. onlyVisible: true,
  55. truncateDrawRange: true
  56. };
  57. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  58. var outputJSON = {
  59. asset: {
  60. version: "2.0",
  61. generator: "THREE.GLTFExporter"
  62. }
  63. };
  64. var byteOffset = 0;
  65. var dataViews = [];
  66. var cachedData = {
  67. images: {},
  68. materials: {}
  69. };
  70. /**
  71. * Compare two arrays
  72. */
  73. /**
  74. * Compare two arrays
  75. * @param {Array} array1 Array 1 to compare
  76. * @param {Array} array2 Array 2 to compare
  77. * @return {Boolean} Returns true if both arrays are equal
  78. */
  79. function equalArray( array1, array2 ) {
  80. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  81. return element === array2[ index ];
  82. } );
  83. }
  84. /**
  85. * Converts a string to an ArrayBuffer.
  86. * @param {string} text
  87. * @return {ArrayBuffer}
  88. */
  89. function stringToArrayBuffer( text ) {
  90. if ( window.TextEncoder !== undefined ) {
  91. return new TextEncoder().encode( text ).buffer;
  92. }
  93. var buffer = new ArrayBuffer( text.length * 2 ); // 2 bytes per character.
  94. var bufferView = new Uint16Array( buffer );
  95. for ( var i = 0; i < text.length; ++ i ) {
  96. bufferView[ i ] = text.charCodeAt( i );
  97. }
  98. return buffer;
  99. }
  100. /**
  101. * Get the min and he max vectors from the given attribute
  102. * @param {THREE.WebGLAttribute} attribute Attribute to find the min/max
  103. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  104. */
  105. function getMinMax( attribute ) {
  106. var output = {
  107. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  108. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  109. };
  110. for ( var i = 0; i < attribute.count; i ++ ) {
  111. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  112. var value = attribute.array[ i * attribute.itemSize + a ];
  113. output.min[ a ] = Math.min( output.min[ a ], value );
  114. output.max[ a ] = Math.max( output.max[ a ], value );
  115. }
  116. }
  117. return output;
  118. }
  119. /**
  120. * Process a buffer to append to the default one.
  121. * @param {THREE.BufferAttribute} attribute Attribute to store
  122. * @param {Integer} componentType Component type (Unsigned short, unsigned int or float)
  123. * @return {Integer} Index of the buffer created (Currently always 0)
  124. */
  125. function processBuffer( attribute, componentType, start, count ) {
  126. if ( ! outputJSON.buffers ) {
  127. outputJSON.buffers = [
  128. {
  129. byteLength: 0,
  130. uri: ''
  131. }
  132. ];
  133. }
  134. var offset = 0;
  135. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  136. // Create a new dataview and dump the attribute's array into it
  137. var byteLength = count * attribute.itemSize * componentSize;
  138. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  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. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  143. dataView.setFloat32( offset, value, true );
  144. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  145. dataView.setUint8( offset, value, true );
  146. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  147. dataView.setUint16( offset, value, true );
  148. }
  149. offset += componentSize;
  150. }
  151. }
  152. // We just use one buffer
  153. dataViews.push( dataView );
  154. // Always using just one buffer
  155. return 0;
  156. }
  157. /**
  158. * Process and generate a BufferView
  159. * @param {[type]} data [description]
  160. * @return {[type]} [description]
  161. */
  162. function processBufferView( data, componentType, start, count ) {
  163. var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
  164. if ( ! outputJSON.bufferViews ) {
  165. outputJSON.bufferViews = [];
  166. }
  167. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  168. // Create a new dataview and dump the attribute's array into it
  169. var byteLength = count * data.itemSize * componentSize;
  170. var gltfBufferView = {
  171. buffer: processBuffer( data, componentType, start, count ),
  172. byteOffset: byteOffset,
  173. byteLength: byteLength,
  174. byteStride: data.itemSize * componentSize,
  175. target: isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER
  176. };
  177. byteOffset += byteLength;
  178. outputJSON.bufferViews.push( gltfBufferView );
  179. // @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
  180. var output = {
  181. id: outputJSON.bufferViews.length - 1,
  182. byteLength: 0
  183. };
  184. return output;
  185. }
  186. /**
  187. * Process attribute to generate an accessor
  188. * @param {THREE.WebGLAttribute} attribute Attribute to process
  189. * @return {Integer} Index of the processed accessor on the "accessors" array
  190. */
  191. function processAccessor( attribute, geometry ) {
  192. if ( ! outputJSON.accessors ) {
  193. outputJSON.accessors = [];
  194. }
  195. var types = [
  196. 'SCALAR',
  197. 'VEC2',
  198. 'VEC3',
  199. 'VEC4'
  200. ];
  201. var componentType;
  202. // Detect the component type of the attribute array (float, uint or ushort)
  203. if ( attribute.array.constructor === Float32Array ) {
  204. componentType = WEBGL_CONSTANTS.FLOAT;
  205. } else if ( attribute.array.constructor === Uint32Array ) {
  206. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  207. } else if ( attribute.array.constructor === Uint16Array ) {
  208. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  209. } else {
  210. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  211. }
  212. var minMax = getMinMax( attribute );
  213. var start = 0;
  214. var count = attribute.count;
  215. // @TODO Indexed buffer geometry with drawRange not supported yet
  216. if ( options.truncateDrawRange && geometry.index === null ) {
  217. start = geometry.drawRange.start;
  218. count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
  219. }
  220. var bufferView = processBufferView( attribute, componentType, start, count );
  221. var gltfAccessor = {
  222. bufferView: bufferView.id,
  223. byteOffset: bufferView.byteOffset,
  224. componentType: componentType,
  225. count: count,
  226. max: minMax.max,
  227. min: minMax.min,
  228. type: types[ attribute.itemSize - 1 ]
  229. };
  230. outputJSON.accessors.push( gltfAccessor );
  231. return outputJSON.accessors.length - 1;
  232. }
  233. /**
  234. * Process image
  235. * @param {Texture} map Texture to process
  236. * @return {Integer} Index of the processed texture in the "images" array
  237. */
  238. function processImage( map ) {
  239. if ( cachedData.images[ map.uuid ] ) {
  240. return cachedData.images[ map.uuid ];
  241. }
  242. if ( ! outputJSON.images ) {
  243. outputJSON.images = [];
  244. }
  245. var gltfImage = {};
  246. if ( options.embedImages ) {
  247. // @TODO { bufferView, mimeType }
  248. } else {
  249. // @TODO base64 based on options
  250. gltfImage.uri = map.image.src;
  251. }
  252. outputJSON.images.push( gltfImage );
  253. var index = outputJSON.images.length - 1;
  254. cachedData.images[ map.uuid ] = index;
  255. return index;
  256. }
  257. /**
  258. * Process sampler
  259. * @param {Texture} map Texture to process
  260. * @return {Integer} Index of the processed texture in the "samplers" array
  261. */
  262. function processSampler( map ) {
  263. if ( ! outputJSON.samplers ) {
  264. outputJSON.samplers = [];
  265. }
  266. var gltfSampler = {
  267. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  268. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  269. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  270. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  271. };
  272. outputJSON.samplers.push( gltfSampler );
  273. return outputJSON.samplers.length - 1;
  274. }
  275. /**
  276. * Process texture
  277. * @param {Texture} map Map to process
  278. * @return {Integer} Index of the processed texture in the "textures" array
  279. */
  280. function processTexture( map ) {
  281. if ( ! outputJSON.textures ) {
  282. outputJSON.textures = [];
  283. }
  284. var gltfTexture = {
  285. sampler: processSampler( map ),
  286. source: processImage( map )
  287. };
  288. outputJSON.textures.push( gltfTexture );
  289. return outputJSON.textures.length - 1;
  290. }
  291. /**
  292. * Process material
  293. * @param {THREE.Material} material Material to process
  294. * @return {Integer} Index of the processed material in the "materials" array
  295. */
  296. function processMaterial( material ) {
  297. if ( cachedData.materials[ material.uuid ] ) {
  298. return cachedData.materials[ material.uuid ];
  299. }
  300. if ( ! outputJSON.materials ) {
  301. outputJSON.materials = [];
  302. }
  303. if ( material instanceof THREE.ShaderMaterial ) {
  304. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  305. return null;
  306. }
  307. if ( ! ( material instanceof THREE.MeshStandardMaterial ) ) {
  308. console.warn( 'GLTFExporter: Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
  309. }
  310. // @QUESTION Should we avoid including any attribute that has the default value?
  311. var gltfMaterial = {
  312. pbrMetallicRoughness: {}
  313. };
  314. // pbrMetallicRoughness.baseColorFactor
  315. var color = material.color.toArray().concat( [ material.opacity ] );
  316. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  317. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  318. }
  319. if ( material instanceof THREE.MeshStandardMaterial ) {
  320. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  321. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  322. } else {
  323. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  324. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  325. }
  326. // pbrMetallicRoughness.baseColorTexture
  327. if ( material.map ) {
  328. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  329. index: processTexture( material.map )
  330. };
  331. }
  332. if ( material instanceof THREE.MeshBasicMaterial ||
  333. material instanceof THREE.LineBasicMaterial ||
  334. material instanceof THREE.PointsMaterial ) {
  335. } else {
  336. // emissiveFactor
  337. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  338. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  339. gltfMaterial.emissiveFactor = emissive;
  340. }
  341. // emissiveTexture
  342. if ( material.emissiveMap ) {
  343. gltfMaterial.emissiveTexture = {
  344. index: processTexture( material.emissiveMap )
  345. };
  346. }
  347. }
  348. // normalTexture
  349. if ( material.normalMap ) {
  350. gltfMaterial.normalTexture = {
  351. index: processTexture( material.normalMap )
  352. };
  353. if ( material.normalScale.x !== - 1 ) {
  354. if ( material.normalScale.x !== material.normalScale.y ) {
  355. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  356. }
  357. gltfMaterial.normalTexture.scale = material.normalScale.x;
  358. }
  359. }
  360. // occlusionTexture
  361. if ( material.aoMap ) {
  362. gltfMaterial.occlusionTexture = {
  363. index: processTexture( material.aoMap )
  364. };
  365. if ( material.aoMapIntensity !== 1.0 ) {
  366. gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;
  367. }
  368. }
  369. // alphaMode
  370. if ( material.transparent ) {
  371. gltfMaterial.alphaMode = 'MASK'; // @FIXME We should detect MASK or BLEND
  372. if ( material.alphaTest !== 0.5 ) {
  373. gltfMaterial.alphaCutoff = material.alphaTest;
  374. }
  375. }
  376. // doubleSided
  377. if ( material.side === THREE.DoubleSide ) {
  378. gltfMaterial.doubleSided = true;
  379. }
  380. if ( material.name ) {
  381. gltfMaterial.name = material.name;
  382. }
  383. outputJSON.materials.push( gltfMaterial );
  384. var index = outputJSON.materials.length - 1;
  385. cachedData.materials[ material.uuid ] = index;
  386. return index;
  387. }
  388. /**
  389. * Process mesh
  390. * @param {THREE.Mesh} mesh Mesh to process
  391. * @return {Integer} Index of the processed mesh in the "meshes" array
  392. */
  393. function processMesh( mesh ) {
  394. if ( ! outputJSON.meshes ) {
  395. outputJSON.meshes = [];
  396. }
  397. var geometry = mesh.geometry;
  398. var mode;
  399. // Use the correct mode
  400. if ( mesh instanceof THREE.LineSegments ) {
  401. mode = WEBGL_CONSTANTS.LINES;
  402. } else if ( mesh instanceof THREE.LineLoop ) {
  403. mode = WEBGL_CONSTANTS.LINE_LOOP;
  404. } else if ( mesh instanceof THREE.Line ) {
  405. mode = WEBGL_CONSTANTS.LINE_STRIP;
  406. } else if ( mesh instanceof THREE.Points ) {
  407. mode = WEBGL_CONSTANTS.POINTS;
  408. } else {
  409. if ( ! geometry.isBufferGeometry ) {
  410. var geometryTemp = new THREE.BufferGeometry();
  411. geometryTemp.fromGeometry( geometry );
  412. geometry = geometryTemp;
  413. }
  414. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  415. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  416. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  417. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  418. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  419. } else {
  420. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  421. }
  422. }
  423. var gltfMesh = {
  424. primitives: [
  425. {
  426. mode: mode,
  427. attributes: {},
  428. }
  429. ]
  430. };
  431. var material = processMaterial( mesh.material );
  432. if ( material !== null ) {
  433. gltfMesh.primitives[ 0 ].material = material;
  434. }
  435. if ( geometry.index ) {
  436. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
  437. }
  438. // We've just one primitive per mesh
  439. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  440. // Conversion between attributes names in threejs and gltf spec
  441. var nameConversion = {
  442. uv: 'TEXCOORD_0',
  443. uv2: 'TEXCOORD_1',
  444. color: 'COLOR_0',
  445. skinWeight: 'WEIGHTS_0',
  446. skinIndex: 'JOINTS_0'
  447. };
  448. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  449. // For every attribute create an accessor
  450. for ( var attributeName in geometry.attributes ) {
  451. var attribute = geometry.attributes[ attributeName ];
  452. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  453. gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
  454. }
  455. outputJSON.meshes.push( gltfMesh );
  456. return outputJSON.meshes.length - 1;
  457. }
  458. /**
  459. * Process camera
  460. * @param {THREE.Camera} camera Camera to process
  461. * @return {Integer} Index of the processed mesh in the "camera" array
  462. */
  463. function processCamera( camera ) {
  464. if ( ! outputJSON.cameras ) {
  465. outputJSON.cameras = [];
  466. }
  467. var isOrtho = camera instanceof THREE.OrthographicCamera;
  468. var gltfCamera = {
  469. type: isOrtho ? 'orthographic' : 'perspective'
  470. };
  471. if ( isOrtho ) {
  472. gltfCamera.orthographic = {
  473. xmag: camera.right * 2,
  474. ymag: camera.top * 2,
  475. zfar: camera.far,
  476. znear: camera.near
  477. };
  478. } else {
  479. gltfCamera.perspective = {
  480. aspectRatio: camera.aspect,
  481. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  482. zfar: camera.far,
  483. znear: camera.near
  484. };
  485. }
  486. if ( camera.name ) {
  487. gltfCamera.name = camera.type;
  488. }
  489. outputJSON.cameras.push( gltfCamera );
  490. return outputJSON.cameras.length - 1;
  491. }
  492. /**
  493. * Process Object3D node
  494. * @param {THREE.Object3D} node Object3D to processNode
  495. * @return {Integer} Index of the node in the nodes list
  496. */
  497. function processNode( object ) {
  498. if ( object instanceof THREE.Light ) {
  499. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  500. return null;
  501. }
  502. if ( ! outputJSON.nodes ) {
  503. outputJSON.nodes = [];
  504. }
  505. var gltfNode = {};
  506. if ( options.trs ) {
  507. var rotation = object.quaternion.toArray();
  508. var position = object.position.toArray();
  509. var scale = object.scale.toArray();
  510. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  511. gltfNode.rotation = rotation;
  512. }
  513. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  514. gltfNode.position = position;
  515. }
  516. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  517. gltfNode.scale = scale;
  518. }
  519. } else {
  520. object.updateMatrix();
  521. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  522. gltfNode.matrix = object.matrix.elements;
  523. }
  524. }
  525. if ( object.name ) {
  526. gltfNode.name = object.name;
  527. }
  528. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  529. try {
  530. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  531. } catch ( e ) {
  532. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  533. }
  534. }
  535. if ( object instanceof THREE.Mesh ||
  536. object instanceof THREE.Line ||
  537. object instanceof THREE.Points ) {
  538. gltfNode.mesh = processMesh( object );
  539. } else if ( object instanceof THREE.Camera ) {
  540. gltfNode.camera = processCamera( object );
  541. }
  542. if ( object.children.length > 0 ) {
  543. var children = [];
  544. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  545. var child = object.children[ i ];
  546. if ( child.visible || options.onlyVisible === false ) {
  547. var node = processNode( child );
  548. if ( node !== null ) {
  549. children.push( node );
  550. }
  551. }
  552. }
  553. if ( children.length > 0 ) {
  554. gltfNode.children = children;
  555. }
  556. }
  557. outputJSON.nodes.push( gltfNode );
  558. return outputJSON.nodes.length - 1;
  559. }
  560. /**
  561. * Process Scene
  562. * @param {THREE.Scene} node Scene to process
  563. */
  564. function processScene( scene ) {
  565. if ( ! outputJSON.scenes ) {
  566. outputJSON.scenes = [];
  567. outputJSON.scene = 0;
  568. }
  569. var gltfScene = {
  570. nodes: []
  571. };
  572. if ( scene.name ) {
  573. gltfScene.name = scene.name;
  574. }
  575. outputJSON.scenes.push( gltfScene );
  576. var nodes = [];
  577. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  578. var child = scene.children[ i ];
  579. if ( child.visible || options.onlyVisible === false ) {
  580. var node = processNode( child );
  581. if ( node !== null ) {
  582. nodes.push( node );
  583. }
  584. }
  585. }
  586. if ( nodes.length > 0 ) {
  587. gltfScene.nodes = nodes;
  588. }
  589. }
  590. /**
  591. * Creates a THREE.Scene to hold a list of objects and parse it
  592. * @param {Array} objects List of objects to process
  593. */
  594. function processObjects( objects ) {
  595. var scene = new THREE.Scene();
  596. scene.name = 'AuxScene';
  597. for ( var i = 0; i < objects.length; i ++ ) {
  598. // We push directly to children instead of calling `add` to prevent
  599. // modify the .parent and break its original scene and hierarchy
  600. scene.children.push( objects[ i ] );
  601. }
  602. processScene( scene );
  603. }
  604. function processInput( input ) {
  605. input = input instanceof Array ? input : [ input ];
  606. var objectsWithoutScene = [];
  607. for ( var i = 0; i < input.length; i ++ ) {
  608. if ( input[ i ] instanceof THREE.Scene ) {
  609. processScene( input[ i ] );
  610. } else {
  611. objectsWithoutScene.push( input[ i ] );
  612. }
  613. }
  614. if ( objectsWithoutScene.length > 0 ) {
  615. processObjects( objectsWithoutScene );
  616. }
  617. }
  618. processInput( input );
  619. // Generate buffer
  620. // Create a new blob with all the dataviews from the buffers
  621. var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
  622. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  623. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  624. outputJSON.buffers[ 0 ].byteLength = blob.size;
  625. var reader = new window.FileReader();
  626. if ( options.binary === true ) {
  627. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  628. var GLB_HEADER_BYTES = 12;
  629. var GLB_HEADER_MAGIC = 0x46546C67;
  630. var GLB_VERSION = 2;
  631. var GLB_CHUNK_PREFIX_BYTES = 8;
  632. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  633. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  634. reader.readAsArrayBuffer( blob );
  635. reader.onloadend = function () {
  636. // Binary chunk.
  637. var binaryChunk = reader.result;
  638. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  639. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  640. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  641. // JSON chunk.
  642. delete outputJSON.buffers[ 0 ].uri; // Omitted URI indicates use of binary chunk.
  643. var jsonChunk = stringToArrayBuffer( JSON.stringify( outputJSON ) );
  644. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  645. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  646. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  647. // GLB header.
  648. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  649. var headerView = new DataView( header );
  650. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  651. headerView.setUint32( 4, GLB_VERSION, true );
  652. var totalByteLength = GLB_HEADER_BYTES
  653. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  654. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  655. headerView.setUint32( 8, totalByteLength, true );
  656. var glbBlob = new Blob( [
  657. header,
  658. jsonChunkPrefix,
  659. jsonChunk,
  660. binaryChunkPrefix,
  661. binaryChunk
  662. ], { type: 'application/octet-stream' } );
  663. var glbReader = new window.FileReader();
  664. glbReader.readAsArrayBuffer( glbBlob );
  665. glbReader.onloadend = function () {
  666. onDone( glbReader.result );
  667. };
  668. };
  669. } else {
  670. reader.readAsDataURL( blob );
  671. reader.onloadend = function () {
  672. var base64data = reader.result;
  673. outputJSON.buffers[ 0 ].uri = base64data;
  674. onDone( outputJSON );
  675. };
  676. }
  677. } else {
  678. onDone( outputJSON );
  679. }
  680. }
  681. };