GLTFExporter.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. var PATH_PROPERTIES = {
  38. scale: 'scale',
  39. position: 'translation',
  40. quaternion: 'rotation',
  41. morphTargetInfluences: 'weights'
  42. };
  43. //------------------------------------------------------------------------------
  44. // GLTF Exporter
  45. //------------------------------------------------------------------------------
  46. THREE.GLTFExporter = function () {};
  47. THREE.GLTFExporter.prototype = {
  48. constructor: THREE.GLTFExporter,
  49. /**
  50. * Parse scenes and generate GLTF output
  51. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  52. * @param {Function} onDone Callback on completed
  53. * @param {Object} options options
  54. */
  55. parse: function ( input, onDone, options ) {
  56. var DEFAULT_OPTIONS = {
  57. trs: false,
  58. onlyVisible: true,
  59. truncateDrawRange: true,
  60. embedImages: true,
  61. animations: []
  62. };
  63. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  64. if ( options.animations.length > 0 ) {
  65. // Only TRS properties, and not matrices, may be targeted by animation.
  66. options.trs = true;
  67. }
  68. var outputJSON = {
  69. asset: {
  70. version: "2.0",
  71. generator: "THREE.GLTFExporter"
  72. }
  73. };
  74. var byteOffset = 0;
  75. var dataViews = [];
  76. var nodeMap = {};
  77. var skins = [];
  78. var cachedData = {
  79. images: {},
  80. materials: {}
  81. };
  82. var cachedCanvas;
  83. /**
  84. * Compare two arrays
  85. */
  86. /**
  87. * Compare two arrays
  88. * @param {Array} array1 Array 1 to compare
  89. * @param {Array} array2 Array 2 to compare
  90. * @return {Boolean} Returns true if both arrays are equal
  91. */
  92. function equalArray( array1, array2 ) {
  93. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  94. return element === array2[ index ];
  95. } );
  96. }
  97. /**
  98. * Converts a string to an ArrayBuffer.
  99. * @param {string} text
  100. * @return {ArrayBuffer}
  101. */
  102. function stringToArrayBuffer( text ) {
  103. if ( window.TextEncoder !== undefined ) {
  104. return new TextEncoder().encode( text ).buffer;
  105. }
  106. var buffer = new ArrayBuffer( text.length );
  107. var bufferView = new Uint8Array( buffer );
  108. for ( var i = 0; i < text.length; ++ i ) {
  109. bufferView[ i ] = text.charCodeAt( i );
  110. }
  111. return buffer;
  112. }
  113. /**
  114. * Get the min and max vectors from the given attribute
  115. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max
  116. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  117. */
  118. function getMinMax( attribute ) {
  119. var output = {
  120. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  121. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  122. };
  123. for ( var i = 0; i < attribute.count; i ++ ) {
  124. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  125. var value = attribute.array[ i * attribute.itemSize + a ];
  126. output.min[ a ] = Math.min( output.min[ a ], value );
  127. output.max[ a ] = Math.max( output.max[ a ], value );
  128. }
  129. }
  130. return output;
  131. }
  132. /**
  133. * Process a buffer to append to the default one.
  134. * @param {THREE.BufferAttribute} attribute Attribute to store
  135. * @param {Integer} componentType Component type (Unsigned short, unsigned int or float)
  136. * @return {Integer} Index of the buffer created (Currently always 0)
  137. */
  138. function processBuffer( attribute, componentType, start, count ) {
  139. if ( ! outputJSON.buffers ) {
  140. outputJSON.buffers = [
  141. {
  142. byteLength: 0,
  143. uri: ''
  144. }
  145. ];
  146. }
  147. var offset = 0;
  148. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  149. // Create a new dataview and dump the attribute's array into it
  150. var byteLength = count * attribute.itemSize * componentSize;
  151. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  152. for ( var i = start; i < start + count; i ++ ) {
  153. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  154. var value = attribute.array[ i * attribute.itemSize + a ];
  155. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  156. dataView.setFloat32( offset, value, true );
  157. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  158. dataView.setUint8( offset, value, true );
  159. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  160. dataView.setUint16( offset, value, true );
  161. }
  162. offset += componentSize;
  163. }
  164. }
  165. // We just use one buffer
  166. dataViews.push( dataView );
  167. // Always using just one buffer
  168. return 0;
  169. }
  170. /**
  171. * Process and generate a BufferView
  172. * @param {THREE.BufferAttribute} data
  173. * @param {number} componentType
  174. * @param {number} start
  175. * @param {number} count
  176. * @param {number} target (Optional) Target usage of the BufferView
  177. * @return {Object}
  178. */
  179. function processBufferView( data, componentType, start, count, target ) {
  180. if ( ! outputJSON.bufferViews ) {
  181. outputJSON.bufferViews = [];
  182. }
  183. var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
  184. // Create a new dataview and dump the attribute's array into it
  185. var byteLength = count * data.itemSize * componentSize;
  186. var gltfBufferView = {
  187. buffer: processBuffer( data, componentType, start, count ),
  188. byteOffset: byteOffset,
  189. byteLength: byteLength
  190. };
  191. if ( target !== undefined ) gltfBufferView.target = target;
  192. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  193. // Only define byteStride for vertex attributes.
  194. gltfBufferView.byteStride = data.itemSize * componentSize;
  195. }
  196. byteOffset += byteLength;
  197. outputJSON.bufferViews.push( gltfBufferView );
  198. // @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
  199. var output = {
  200. id: outputJSON.bufferViews.length - 1,
  201. byteLength: 0
  202. };
  203. return output;
  204. }
  205. /**
  206. * Process attribute to generate an accessor
  207. * @param {THREE.BufferAttribute} attribute Attribute to process
  208. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  209. * @return {Integer} Index of the processed accessor on the "accessors" array
  210. */
  211. function processAccessor( attribute, geometry ) {
  212. if ( ! outputJSON.accessors ) {
  213. outputJSON.accessors = [];
  214. }
  215. var types = {
  216. 1: 'SCALAR',
  217. 2: 'VEC2',
  218. 3: 'VEC3',
  219. 4: 'VEC4',
  220. 16: 'MAT4'
  221. };
  222. var componentType;
  223. // Detect the component type of the attribute array (float, uint or ushort)
  224. if ( attribute.array.constructor === Float32Array ) {
  225. componentType = WEBGL_CONSTANTS.FLOAT;
  226. } else if ( attribute.array.constructor === Uint32Array ) {
  227. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  228. } else if ( attribute.array.constructor === Uint16Array ) {
  229. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  230. } else {
  231. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  232. }
  233. var minMax = getMinMax( attribute );
  234. var start = 0;
  235. var count = attribute.count;
  236. // @TODO Indexed buffer geometry with drawRange not supported yet
  237. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  238. start = geometry.drawRange.start;
  239. count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
  240. }
  241. var bufferViewTarget;
  242. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  243. // animation samplers, target must not be set.
  244. if ( geometry !== undefined ) {
  245. var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
  246. bufferViewTarget = isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER;
  247. }
  248. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  249. var gltfAccessor = {
  250. bufferView: bufferView.id,
  251. byteOffset: bufferView.byteOffset,
  252. componentType: componentType,
  253. count: count,
  254. max: minMax.max,
  255. min: minMax.min,
  256. type: types[ attribute.itemSize ]
  257. };
  258. outputJSON.accessors.push( gltfAccessor );
  259. return outputJSON.accessors.length - 1;
  260. }
  261. /**
  262. * Process image
  263. * @param {Texture} map Texture to process
  264. * @return {Integer} Index of the processed texture in the "images" array
  265. */
  266. function processImage( map ) {
  267. if ( cachedData.images[ map.uuid ] !== undefined ) {
  268. return cachedData.images[ map.uuid ];
  269. }
  270. if ( ! outputJSON.images ) {
  271. outputJSON.images = [];
  272. }
  273. var mimeType = map.format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  274. var gltfImage = {mimeType: mimeType};
  275. if ( options.embedImages ) {
  276. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  277. canvas.width = map.image.width;
  278. canvas.height = map.image.height;
  279. var ctx = canvas.getContext( '2d' );
  280. if ( map.flipY === true ) {
  281. ctx.translate( 0, map.image.height );
  282. ctx.scale( 1, -1 );
  283. }
  284. ctx.drawImage( map.image, 0, 0 );
  285. // @TODO Embed in { bufferView } if options.binary set.
  286. gltfImage.uri = canvas.toDataURL( mimeType );
  287. } else {
  288. gltfImage.uri = map.image.src;
  289. }
  290. outputJSON.images.push( gltfImage );
  291. var index = outputJSON.images.length - 1;
  292. cachedData.images[ map.uuid ] = index;
  293. return index;
  294. }
  295. /**
  296. * Process sampler
  297. * @param {Texture} map Texture to process
  298. * @return {Integer} Index of the processed texture in the "samplers" array
  299. */
  300. function processSampler( map ) {
  301. if ( ! outputJSON.samplers ) {
  302. outputJSON.samplers = [];
  303. }
  304. var gltfSampler = {
  305. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  306. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  307. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  308. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  309. };
  310. outputJSON.samplers.push( gltfSampler );
  311. return outputJSON.samplers.length - 1;
  312. }
  313. /**
  314. * Process texture
  315. * @param {Texture} map Map to process
  316. * @return {Integer} Index of the processed texture in the "textures" array
  317. */
  318. function processTexture( map ) {
  319. if ( ! outputJSON.textures ) {
  320. outputJSON.textures = [];
  321. }
  322. var gltfTexture = {
  323. sampler: processSampler( map ),
  324. source: processImage( map )
  325. };
  326. outputJSON.textures.push( gltfTexture );
  327. return outputJSON.textures.length - 1;
  328. }
  329. /**
  330. * Process material
  331. * @param {THREE.Material} material Material to process
  332. * @return {Integer} Index of the processed material in the "materials" array
  333. */
  334. function processMaterial( material ) {
  335. if ( cachedData.materials[ material.uuid ] !== undefined ) {
  336. return cachedData.materials[ material.uuid ];
  337. }
  338. if ( ! outputJSON.materials ) {
  339. outputJSON.materials = [];
  340. }
  341. if ( material instanceof THREE.ShaderMaterial ) {
  342. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  343. return null;
  344. }
  345. if ( ! ( material instanceof THREE.MeshStandardMaterial ) ) {
  346. console.warn( 'GLTFExporter: Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
  347. }
  348. // @QUESTION Should we avoid including any attribute that has the default value?
  349. var gltfMaterial = {
  350. pbrMetallicRoughness: {}
  351. };
  352. // pbrMetallicRoughness.baseColorFactor
  353. var color = material.color.toArray().concat( [ material.opacity ] );
  354. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  355. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  356. }
  357. if ( material instanceof THREE.MeshStandardMaterial ) {
  358. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  359. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  360. } else {
  361. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  362. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  363. }
  364. // pbrMetallicRoughness.baseColorTexture
  365. if ( material.map ) {
  366. gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
  367. index: processTexture( material.map )
  368. };
  369. }
  370. if ( material instanceof THREE.MeshBasicMaterial ||
  371. material instanceof THREE.LineBasicMaterial ||
  372. material instanceof THREE.PointsMaterial ) {
  373. } else {
  374. // emissiveFactor
  375. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  376. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  377. gltfMaterial.emissiveFactor = emissive;
  378. }
  379. // emissiveTexture
  380. if ( material.emissiveMap ) {
  381. gltfMaterial.emissiveTexture = {
  382. index: processTexture( material.emissiveMap )
  383. };
  384. }
  385. }
  386. // normalTexture
  387. if ( material.normalMap ) {
  388. gltfMaterial.normalTexture = {
  389. index: processTexture( material.normalMap )
  390. };
  391. if ( material.normalScale.x !== - 1 ) {
  392. if ( material.normalScale.x !== material.normalScale.y ) {
  393. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  394. }
  395. gltfMaterial.normalTexture.scale = material.normalScale.x;
  396. }
  397. }
  398. // occlusionTexture
  399. if ( material.aoMap ) {
  400. gltfMaterial.occlusionTexture = {
  401. index: processTexture( material.aoMap )
  402. };
  403. if ( material.aoMapIntensity !== 1.0 ) {
  404. gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;
  405. }
  406. }
  407. // alphaMode
  408. if ( material.transparent || material.alphaTest > 0.0 ) {
  409. gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
  410. // Write alphaCutoff if it's non-zero and different from the default (0.5).
  411. if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
  412. gltfMaterial.alphaCutoff = material.alphaTest;
  413. }
  414. }
  415. // doubleSided
  416. if ( material.side === THREE.DoubleSide ) {
  417. gltfMaterial.doubleSided = true;
  418. }
  419. if ( material.name ) {
  420. gltfMaterial.name = material.name;
  421. }
  422. outputJSON.materials.push( gltfMaterial );
  423. var index = outputJSON.materials.length - 1;
  424. cachedData.materials[ material.uuid ] = index;
  425. return index;
  426. }
  427. /**
  428. * Process mesh
  429. * @param {THREE.Mesh} mesh Mesh to process
  430. * @return {Integer} Index of the processed mesh in the "meshes" array
  431. */
  432. function processMesh( mesh ) {
  433. if ( ! outputJSON.meshes ) {
  434. outputJSON.meshes = [];
  435. }
  436. var geometry = mesh.geometry;
  437. var mode;
  438. // Use the correct mode
  439. if ( mesh instanceof THREE.LineSegments ) {
  440. mode = WEBGL_CONSTANTS.LINES;
  441. } else if ( mesh instanceof THREE.LineLoop ) {
  442. mode = WEBGL_CONSTANTS.LINE_LOOP;
  443. } else if ( mesh instanceof THREE.Line ) {
  444. mode = WEBGL_CONSTANTS.LINE_STRIP;
  445. } else if ( mesh instanceof THREE.Points ) {
  446. mode = WEBGL_CONSTANTS.POINTS;
  447. } else {
  448. if ( ! geometry.isBufferGeometry ) {
  449. var geometryTemp = new THREE.BufferGeometry();
  450. geometryTemp.fromGeometry( geometry );
  451. geometry = geometryTemp;
  452. }
  453. if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {
  454. console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
  455. mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
  456. } else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {
  457. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
  458. } else {
  459. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  460. }
  461. }
  462. var gltfMesh = {
  463. primitives: [
  464. {
  465. mode: mode,
  466. attributes: {},
  467. }
  468. ]
  469. };
  470. var material = processMaterial( mesh.material );
  471. if ( material !== null ) {
  472. gltfMesh.primitives[ 0 ].material = material;
  473. }
  474. if ( geometry.index ) {
  475. gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
  476. }
  477. // We've just one primitive per mesh
  478. var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
  479. // Conversion between attributes names in threejs and gltf spec
  480. var nameConversion = {
  481. uv: 'TEXCOORD_0',
  482. uv2: 'TEXCOORD_1',
  483. color: 'COLOR_0',
  484. skinWeight: 'WEIGHTS_0',
  485. skinIndex: 'JOINTS_0'
  486. };
  487. // @QUESTION Detect if .vertexColors = THREE.VertexColors?
  488. // For every attribute create an accessor
  489. for ( var attributeName in geometry.attributes ) {
  490. var attribute = geometry.attributes[ attributeName ];
  491. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  492. if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
  493. gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
  494. }
  495. }
  496. // Morph targets
  497. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  498. gltfMesh.primitives[ 0 ].targets = [];
  499. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  500. var target = {};
  501. for ( var attributeName in geometry.morphAttributes ) {
  502. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  503. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  504. target[ attributeName ] = processAccessor( attribute, geometry );
  505. }
  506. gltfMesh.primitives[ 0 ].targets.push( target );
  507. }
  508. }
  509. outputJSON.meshes.push( gltfMesh );
  510. return outputJSON.meshes.length - 1;
  511. }
  512. /**
  513. * Process camera
  514. * @param {THREE.Camera} camera Camera to process
  515. * @return {Integer} Index of the processed mesh in the "camera" array
  516. */
  517. function processCamera( camera ) {
  518. if ( ! outputJSON.cameras ) {
  519. outputJSON.cameras = [];
  520. }
  521. var isOrtho = camera instanceof THREE.OrthographicCamera;
  522. var gltfCamera = {
  523. type: isOrtho ? 'orthographic' : 'perspective'
  524. };
  525. if ( isOrtho ) {
  526. gltfCamera.orthographic = {
  527. xmag: camera.right * 2,
  528. ymag: camera.top * 2,
  529. zfar: camera.far,
  530. znear: camera.near
  531. };
  532. } else {
  533. gltfCamera.perspective = {
  534. aspectRatio: camera.aspect,
  535. yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
  536. zfar: camera.far,
  537. znear: camera.near
  538. };
  539. }
  540. if ( camera.name ) {
  541. gltfCamera.name = camera.type;
  542. }
  543. outputJSON.cameras.push( gltfCamera );
  544. return outputJSON.cameras.length - 1;
  545. }
  546. /**
  547. * Creates glTF animation entry from AnimationClip object.
  548. *
  549. * Status:
  550. * - Only properties listed in PATH_PROPERTIES may be animated.
  551. * - Only LINEAR and STEP interpolation currently supported.
  552. *
  553. * @param {THREE.AnimationClip} clip
  554. * @param {THREE.Object3D} root
  555. * @return {number}
  556. */
  557. function processAnimation ( clip, root ) {
  558. if ( ! outputJSON.animations ) {
  559. outputJSON.animations = [];
  560. }
  561. var channels = [];
  562. var samplers = [];
  563. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  564. var track = clip.tracks[ i ];
  565. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  566. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  567. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  568. if ( trackBinding.objectName === 'bones' ) {
  569. if ( trackNode.isSkinnedMesh === true ) {
  570. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  571. } else {
  572. trackNode = undefined;
  573. }
  574. }
  575. if ( ! trackNode || ! trackProperty ) {
  576. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  577. return null;
  578. }
  579. var inputItemSize = 1;
  580. var outputItemSize = track.values.length / track.times.length;
  581. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  582. outputItemSize /= trackNode.morphTargetInfluences.length;
  583. }
  584. samplers.push( {
  585. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  586. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  587. interpolation: track.interpolation === THREE.InterpolateDiscrete ? 'STEP' : 'LINEAR'
  588. } );
  589. channels.push( {
  590. sampler: samplers.length - 1,
  591. target: {
  592. node: nodeMap[ trackNode.uuid ],
  593. path: trackProperty
  594. }
  595. } );
  596. }
  597. outputJSON.animations.push( {
  598. name: clip.name || 'clip_' + outputJSON.animations.length,
  599. samplers: samplers,
  600. channels: channels
  601. } );
  602. return outputJSON.animations.length - 1;
  603. }
  604. function processSkin( object ) {
  605. var node = outputJSON.nodes[ nodeMap[ object.uuid ] ];
  606. var skeleton = object.skeleton;
  607. var rootJoint = object.skeleton.bones[ 0 ];
  608. if ( rootJoint === undefined ) return null;
  609. var joints = [];
  610. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  611. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  612. joints.push( nodeMap[ skeleton.bones[ i ].uuid ] );
  613. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  614. }
  615. if ( outputJSON.skins === undefined ) {
  616. outputJSON.skins = [];
  617. }
  618. outputJSON.skins.push( {
  619. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  620. joints: joints,
  621. skeleton: nodeMap[ rootJoint.uuid ]
  622. } );
  623. var skinIndex = node.skin = outputJSON.skins.length - 1;
  624. return skinIndex;
  625. }
  626. /**
  627. * Process Object3D node
  628. * @param {THREE.Object3D} node Object3D to processNode
  629. * @return {Integer} Index of the node in the nodes list
  630. */
  631. function processNode( object ) {
  632. if ( object instanceof THREE.Light ) {
  633. console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
  634. return null;
  635. }
  636. if ( ! outputJSON.nodes ) {
  637. outputJSON.nodes = [];
  638. }
  639. var gltfNode = {};
  640. if ( options.trs ) {
  641. var rotation = object.quaternion.toArray();
  642. var position = object.position.toArray();
  643. var scale = object.scale.toArray();
  644. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  645. gltfNode.rotation = rotation;
  646. }
  647. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  648. gltfNode.translation = position;
  649. }
  650. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  651. gltfNode.scale = scale;
  652. }
  653. } else {
  654. object.updateMatrix();
  655. if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
  656. gltfNode.matrix = object.matrix.elements;
  657. }
  658. }
  659. if ( object.name ) {
  660. gltfNode.name = object.name;
  661. }
  662. if ( object.userData && Object.keys( object.userData ).length > 0 ) {
  663. try {
  664. gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );
  665. } catch ( e ) {
  666. throw new Error( 'THREE.GLTFExporter: userData can\'t be serialized' );
  667. }
  668. }
  669. if ( object instanceof THREE.Mesh ||
  670. object instanceof THREE.Line ||
  671. object instanceof THREE.Points ) {
  672. gltfNode.mesh = processMesh( object );
  673. } else if ( object instanceof THREE.Camera ) {
  674. gltfNode.camera = processCamera( object );
  675. }
  676. if ( object instanceof THREE.SkinnedMesh ) {
  677. skins.push( object );
  678. }
  679. if ( object.children.length > 0 ) {
  680. var children = [];
  681. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  682. var child = object.children[ i ];
  683. if ( child.visible || options.onlyVisible === false ) {
  684. var node = processNode( child );
  685. if ( node !== null ) {
  686. children.push( node );
  687. }
  688. }
  689. }
  690. if ( children.length > 0 ) {
  691. gltfNode.children = children;
  692. }
  693. }
  694. outputJSON.nodes.push( gltfNode );
  695. var nodeIndex = nodeMap[ object.uuid ] = outputJSON.nodes.length - 1;
  696. return nodeIndex;
  697. }
  698. /**
  699. * Process Scene
  700. * @param {THREE.Scene} node Scene to process
  701. */
  702. function processScene( scene ) {
  703. if ( ! outputJSON.scenes ) {
  704. outputJSON.scenes = [];
  705. outputJSON.scene = 0;
  706. }
  707. var gltfScene = {
  708. nodes: []
  709. };
  710. if ( scene.name ) {
  711. gltfScene.name = scene.name;
  712. }
  713. outputJSON.scenes.push( gltfScene );
  714. var nodes = [];
  715. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  716. var child = scene.children[ i ];
  717. if ( child.visible || options.onlyVisible === false ) {
  718. var node = processNode( child );
  719. if ( node !== null ) {
  720. nodes.push( node );
  721. }
  722. }
  723. }
  724. if ( nodes.length > 0 ) {
  725. gltfScene.nodes = nodes;
  726. }
  727. }
  728. /**
  729. * Creates a THREE.Scene to hold a list of objects and parse it
  730. * @param {Array} objects List of objects to process
  731. */
  732. function processObjects( objects ) {
  733. var scene = new THREE.Scene();
  734. scene.name = 'AuxScene';
  735. for ( var i = 0; i < objects.length; i ++ ) {
  736. // We push directly to children instead of calling `add` to prevent
  737. // modify the .parent and break its original scene and hierarchy
  738. scene.children.push( objects[ i ] );
  739. }
  740. processScene( scene );
  741. }
  742. function processInput( input ) {
  743. input = input instanceof Array ? input : [ input ];
  744. var objectsWithoutScene = [];
  745. for ( var i = 0; i < input.length; i ++ ) {
  746. if ( input[ i ] instanceof THREE.Scene ) {
  747. processScene( input[ i ] );
  748. } else {
  749. objectsWithoutScene.push( input[ i ] );
  750. }
  751. }
  752. if ( objectsWithoutScene.length > 0 ) {
  753. processObjects( objectsWithoutScene );
  754. }
  755. for ( var i = 0; i < skins.length; ++ i ) {
  756. processSkin( skins[ i ] );
  757. }
  758. for ( var i = 0; i < options.animations.length; ++ i ) {
  759. processAnimation( options.animations[ i ], input[ 0 ] );
  760. }
  761. }
  762. processInput( input );
  763. // Generate buffer
  764. // Create a new blob with all the dataviews from the buffers
  765. var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
  766. // Update the bytlength of the only main buffer and update the uri with the base64 representation of it
  767. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  768. outputJSON.buffers[ 0 ].byteLength = blob.size;
  769. var reader = new window.FileReader();
  770. if ( options.binary === true ) {
  771. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  772. var GLB_HEADER_BYTES = 12;
  773. var GLB_HEADER_MAGIC = 0x46546C67;
  774. var GLB_VERSION = 2;
  775. var GLB_CHUNK_PREFIX_BYTES = 8;
  776. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  777. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  778. reader.readAsArrayBuffer( blob );
  779. reader.onloadend = function () {
  780. // Binary chunk.
  781. var binaryChunk = reader.result;
  782. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  783. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  784. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  785. // JSON chunk.
  786. delete outputJSON.buffers[ 0 ].uri; // Omitted URI indicates use of binary chunk.
  787. var jsonChunk = stringToArrayBuffer( JSON.stringify( outputJSON ) );
  788. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  789. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  790. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  791. // GLB header.
  792. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  793. var headerView = new DataView( header );
  794. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  795. headerView.setUint32( 4, GLB_VERSION, true );
  796. var totalByteLength = GLB_HEADER_BYTES
  797. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  798. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  799. headerView.setUint32( 8, totalByteLength, true );
  800. var glbBlob = new Blob( [
  801. header,
  802. jsonChunkPrefix,
  803. jsonChunk,
  804. binaryChunkPrefix,
  805. binaryChunk
  806. ], { type: 'application/octet-stream' } );
  807. var glbReader = new window.FileReader();
  808. glbReader.readAsArrayBuffer( glbBlob );
  809. glbReader.onloadend = function () {
  810. onDone( glbReader.result );
  811. };
  812. };
  813. } else {
  814. reader.readAsDataURL( blob );
  815. reader.onloadend = function () {
  816. var base64data = reader.result;
  817. outputJSON.buffers[ 0 ].uri = base64data;
  818. onDone( outputJSON );
  819. };
  820. }
  821. } else {
  822. onDone( outputJSON );
  823. }
  824. }
  825. };