GLTFExporter.js 16.9 KB
Newer Older
F
Fernando Serrano 已提交
1 2 3 4
/**
 * @author fernandojsg / http://fernandojsg.com
 */

F
Fernando Serrano 已提交
5 6 7
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
F
Fernando Serrano 已提交
8 9 10
THREE.GLTFExporter = function ( renderer ) {
	this.renderer = renderer;
};
F
Fernando Serrano 已提交
11 12 13 14

THREE.GLTFExporter.prototype = {

	constructor: THREE.GLTFExporter,
F
Fernando Serrano 已提交
15

F
Fernando Serrano 已提交
16 17 18 19 20 21 22
	/**
	 * Parse scenes and generate GLTF output
	 * @param  {THREE.Scene or [THREE.Scenes]} input   THREE.Scene or Array of THREE.Scenes
	 * @param  {[type]} onDone  Callback on completed
	 * @param  {[type]} options options
	 *                          trs: Exports position, rotation and scale instead of matrix
	 */
F
Fernando Serrano 已提交
23 24
	parse: function ( input, onDone, options ) {

F
Fernando Serrano 已提交
25
		options = options || {};
F
Fernando Serrano 已提交
26

27 28
		var glUtils = new THREE.WebGLUtils( this.renderer.context, this.renderer.extensions );
		var gl = this.renderer.context;
F
Fernando Serrano 已提交
29

F
Fernando Serrano 已提交
30
		var outputJSON = {
F
Fernando Serrano 已提交
31 32 33 34
			asset: {
				version: "2.0",
				generator: "THREE.JS GLTFExporter" // @QUESTION Does it support spaces?
		 	}
F
Fernando Serrano 已提交
35 36 37 38
    };

		var byteOffset = 0;
		var dataViews = [];
F
Fernando Serrano 已提交
39

F
Fernando Serrano 已提交
40 41 42
		/**
		 * Compare two arrays
		 */
43
		function equalArray ( array1, array2 ) {
F
Fernando Serrano 已提交
44 45 46 47 48
			return ( array1.length === array2.length ) && array1.every( function( element, index ) {
    		return element === array2[ index ];
			});
		}

F
Fernando Serrano 已提交
49 50 51 52 53 54 55 56 57 58 59 60
		/**
		 * Get the min and he max vectors from the given attribute
		 * @param  {THREE.WebGLAttribute} attribute Attribute to find the min/max
		 * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
		 */
		function getMinMax ( attribute ) {
			var output = {
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
			};

			for ( var i = 0; i < attribute.count; i++ ) {
F
Fernando Serrano 已提交
61 62
				for ( var a = 0; a < attribute.itemSize; a++ ) {
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
63 64 65 66 67 68 69
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );
				}
			}

			return output;
		}
F
Fernando Serrano 已提交
70

F
Fernando Serrano 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84
		/**
		 * Add extension to the extensions array
		 * @param {String} extensionName Extension name
		 */
		function addExtension ( extensionName ) {
			if ( !outputJSON.extensionsUsed ) {
				outputJSON.extensionsUsed = [];
			}

			if ( outputJSON.extensionsUsed.indexOf( extensionName ) !== -1 ) {
				outputJSON.extensionsUsed.push( extensionName );
			}
		}

F
Fernando Serrano 已提交
85
		/**
F
Fernando Serrano 已提交
86 87 88 89
		 * Process a buffer to append to the default one.
		 * @param  {THREE.BufferAttribute} attribute     Attribute to store
		 * @param  {Integer} componentType Component type (Unsigned short, unsigned int or float)
		 * @return {Integer}               Index of the buffer created (Currently always 0)
F
Fernando Serrano 已提交
90 91
		 */
		function processBuffer ( attribute, componentType ) {
F
Fernando Serrano 已提交
92
			if ( !outputJSON.buffers ) {
F
Fernando Serrano 已提交
93 94 95 96 97 98 99 100
				outputJSON.buffers = [
					{
						byteLength: 0,
						uri: ''
					}
				];
			}

F
Fernando Serrano 已提交
101
			// Create a new dataview and dump the attribute's array into it
F
Fernando Serrano 已提交
102 103 104
			var dataView = new DataView( new ArrayBuffer( attribute.array.byteLength ) );

			var offset = 0;
105
			var offsetInc = componentType === gl.UNSIGNED_SHORT ? 2 : 4;
F
Fernando Serrano 已提交
106 107 108

			for ( var i = 0; i < attribute.count; i++ ) {
				for (var a = 0; a < attribute.itemSize; a++ ) {
F
Fernando Serrano 已提交
109
					var value = attribute.array[ i * attribute.itemSize + a ];
110
					if ( componentType === gl.FLOAT ) {
F
Fernando Serrano 已提交
111
						dataView.setFloat32( offset, value, true );
112
					} else if ( componentType === gl.UNSIGNED_INT ) {
F
Fernando Serrano 已提交
113
						dataView.setUint8( offset, value, true );
114
					} else if ( componentType === gl.UNSIGNED_SHORT ) {
F
Fernando Serrano 已提交
115
						dataView.setUint16( offset, value, true );
F
Fernando Serrano 已提交
116 117 118 119 120
					}
					offset += offsetInc;
				}
			}

F
Fernando Serrano 已提交
121
			// We just use one buffer
F
Fernando Serrano 已提交
122
			dataViews.push( dataView );
F
Fernando Serrano 已提交
123 124 125 126 127

			return 0;
		}

		/**
F
Fernando Serrano 已提交
128
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
129 130 131 132
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		function processBufferView ( data, componentType ) {
133
			var isVertexAttributes = componentType === gl.FLOAT;
F
Fernando Serrano 已提交
134
			if ( !outputJSON.bufferViews ) {
F
Fernando Serrano 已提交
135 136 137 138 139 140 141
				outputJSON.bufferViews = [];
			}

			var gltfBufferView = {
				buffer: processBuffer( data, componentType ),
				byteOffset: byteOffset,
				byteLength: data.array.byteLength,
142 143
				byteStride: data.itemSize * ( componentType === gl.UNSIGNED_SHORT ? 2 : 4 ),
				target: isVertexAttributes ? gl.ARRAY_BUFFER : gl.ELEMENT_ARRAY_BUFFER
F
Fernando Serrano 已提交
144 145 146 147
			};

			byteOffset += data.array.byteLength;

F
Fernando Serrano 已提交
148
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
149 150

			// @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
F
Fernando Serrano 已提交
151 152 153 154 155 156 157 158
			var output = {
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
			};
			return output;
		}

		/**
F
Fernando Serrano 已提交
159 160 161
		 * Process attribute to generate an accessor
		 * @param  {THREE.WebGLAttribute} attribute Attribute to process
		 * @return {Integer}           Index of the processed accessor on the "accessors" array
F
Fernando Serrano 已提交
162 163
		 */
		function processAccessor ( attribute ) {
F
Fernando Serrano 已提交
164
			if ( !outputJSON.accessors ) {
F
Fernando Serrano 已提交
165 166 167 168
				outputJSON.accessors = [];
			}

			var types = [
F
Fernando Serrano 已提交
169 170 171 172
				'SCALAR',
				'VEC2',
				'VEC3',
				'VEC4'
F
Fernando Serrano 已提交
173 174
			];

175 176
			var componentType;

F
Fernando Serrano 已提交
177
			// Detect the component type of the attribute array (float, uint or ushort)
178 179 180 181 182 183 184 185 186
			if ( attribute.array.constructor === Float32Array ) {
				componentType = gl.FLOAT;
			} else if ( attribute.array.constructor === Uint32Array ) {
				componentType = gl.UNSIGNED_INT;
			} else if ( attribute.array.constructor === Uint16Array ) {
				componentType = gl.UNSIGNED_SHORT;
			} else {
				throw new Error( 'THREE.GLTF2Exporter: Unsupported bufferAttribute component type.' );
			}
F
Fernando Serrano 已提交
187 188 189

			var minMax = getMinMax( attribute );
			var bufferView = processBufferView( attribute, componentType );
F
Fernando Serrano 已提交
190

F
Fernando Serrano 已提交
191 192 193 194 195 196 197
			var gltfAccessor = {
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
				count: attribute.count,
				max: minMax.max,
				min: minMax.min,
F
Fernando Serrano 已提交
198
				type: types[ attribute.itemSize - 1 ]
F
Fernando Serrano 已提交
199 200 201 202 203 204 205 206
			};

			outputJSON.accessors.push( gltfAccessor );

			return outputJSON.accessors.length - 1;
		}

		/**
F
Fernando Serrano 已提交
207 208 209 210 211
		 * Process image
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "images" array
		 */
		function processImage ( map ) {
F
Fernando Serrano 已提交
212
			if ( !outputJSON.images ) {
F
Fernando Serrano 已提交
213 214 215 216 217
				outputJSON.images = [];
			}

			var gltfImage = {};

F
Fernando Serrano 已提交
218
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
				// @TODO { bufferView, mimeType }
			} else {
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
			}

			outputJSON.images.push( gltfImage );

			return outputJSON.images.length - 1;
		}

		/**
		 * Process sampler
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "samplers" array
		 */
		function processSampler ( map ) {
F
Fernando Serrano 已提交
236
			if ( !outputJSON.samplers ) {
F
Fernando Serrano 已提交
237 238 239 240
				outputJSON.samplers = [];
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
241 242 243 244
				magFilter: glUtils.convert( map.magFilter ),
				minFilter: glUtils.convert( map.minFilter ),
				wrapS: glUtils.convert( map.wrapS ),
				wrapT: glUtils.convert( map.wrapT )
F
Fernando Serrano 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
			};

			outputJSON.samplers.push( gltfSampler );

			return outputJSON.samplers.length - 1;
		}

		/**
		 * Process texture
		 * @param  {Texture} map Map to process
		 * @return {Integer}     Index of the processed texture in the "textures" array
		 */
		function processTexture ( map ) {
			if (!outputJSON.textures) {
				outputJSON.textures = [];
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
263 264
				sampler: processSampler( map ),
				source: processImage( map )
F
Fernando Serrano 已提交
265 266 267 268 269 270 271 272 273 274 275
			};

			outputJSON.textures.push( gltfTexture );

			return outputJSON.textures.length - 1;
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
276 277
		 */
		function processMaterial ( material ) {
F
Fernando Serrano 已提交
278
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
279 280
				outputJSON.materials = [];
			}
F
Fernando Serrano 已提交
281

282 283 284 285
			if ( !( material instanceof THREE.MeshStandardMaterial ) ) {

				console.warn( 'Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );

F
Fernando Serrano 已提交
286 287 288
			}

			// @QUESTION Should we avoid including any attribute that has the default value?
289 290 291 292 293
			var gltfMaterial = {};

			if ( material instanceof THREE.MeshStandardMaterial ) {

				gltfMaterial.pbrMetallicRoughness = {
F
Fernando Serrano 已提交
294
					baseColorFactor: material.color.toArray().concat( [ material.opacity ] ),
F
Fernando Serrano 已提交
295 296
					metallicFactor: material.metalness,
					roughnessFactor: material.roughness
297 298 299 300
				};

			}

301
			if ( material instanceof THREE.MeshBasicMaterial
F
Fernando Serrano 已提交
302 303
				|| material instanceof THREE.LineBasicMaterial
				|| material instanceof THREE.PointsMaterial ) {
304 305 306 307 308 309 310

				// emissiveFactor
				var color = material.color.toArray();
				if ( !equalArray( color, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = color;

F
Fernando Serrano 已提交
311 312
				}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
				// emissiveTexture
				if ( material.map ) {

					gltfMaterial.emissiveTexture = {

						index: processTexture( material.map ),
						texCoord: 0 // @FIXME

					};

				}

			} else {

				// emissiveFactor
				var emissive = material.emissive.toArray();
				if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
333
				}
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

				// pbrMetallicRoughness.baseColorTexture
				if ( material.map ) {

					gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
						index: processTexture( material.map ),
						texCoord: 0 // @FIXME
					};

				}

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

						index: processTexture( material.emissiveMap ),
						texCoord: 0 // @FIXME

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

				gltfMaterial.normalTexture = {
					index: processTexture( material.normalMap ),
					texCoord: 0 // @FIXME
				};

F
Fernando Serrano 已提交
367 368
			}

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
			// occlusionTexture
			if ( material.aoMap ) {

				gltfMaterial.occlusionTexture = {
					index: processTexture( material.aoMap ),
					texCoord: 0 // @FIXME
				};

			}

			// alphaMode
			if ( material.transparent ) {

				gltfMaterial.alphaMode = 'BLEND'; // @FIXME We should detect MASK or BLEND

			}

			// doubleSided
F
Fernando Serrano 已提交
387
			if ( material.side === THREE.DoubleSide ) {
388

F
Fernando Serrano 已提交
389
				gltfMaterial.doubleSided = true;
390

F
Fernando Serrano 已提交
391 392
			}

393 394
			if ( material.name !== undefined ) {

F
Fernando Serrano 已提交
395
				gltfMaterial.name = material.name;
396

F
Fernando Serrano 已提交
397 398
			}

F
Fernando Serrano 已提交
399
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
400 401

			return outputJSON.materials.length - 1;
402

F
Fernando Serrano 已提交
403 404 405
		}

		/**
F
Fernando Serrano 已提交
406 407 408
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
409 410 411
		 */
		function processMesh( mesh ) {
			if ( !outputJSON.meshes ) {
412
					outputJSON.meshes = [];
F
Fernando Serrano 已提交
413 414 415
			}

			var geometry = mesh.geometry;
F
Fernando Serrano 已提交
416

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
			// Use the correct mode
			if ( mesh instanceof THREE.LineSegments ) {

				mode = gl.LINES;

			} else if ( mesh instanceof THREE.LineLoop ) {

				mode = gl.LINE_LOOP;

			} else if ( mesh instanceof THREE.Line ) {

				mode = gl.LINE_STRIP;

			} else if ( mesh instanceof THREE.Points ) {

				mode = gl.POINTS;

			} else {

436 437 438 439 440 441 442 443
				if ( !( geometry instanceof THREE.BufferGeometry) ) {

					var geometryTemp = new THREE.BufferGeometry();
					geometryTemp.fromGeometry( geometry );
					geometry = geometryTemp;

				}

444 445
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
446
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
447
					mode = gl.TRIANGLE_FAN;
448 449 450

				} else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {

F
Fernando Serrano 已提交
451
					mode = mesh.material.wireframe ? gl.LINE_STRIP : gl.TRIANGLE_STRIP;
452 453 454

				} else {

F
Fernando Serrano 已提交
455
					mode = mesh.material.wireframe ? gl.LINES : gl.TRIANGLES;
456 457 458 459

				}

			}
F
Fernando Serrano 已提交
460 461 462 463 464 465

			var gltfMesh = {
				primitives: [
					{
						mode: mode,
						attributes: {},
466
						material: processMaterial( mesh.material )
F
Fernando Serrano 已提交
467 468 469 470
					}
				]
			};

471 472 473 474 475 476
			if ( geometry.index ) {

				gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index );

			}

F
Fernando Serrano 已提交
477 478
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
479 480
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
481 482
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
483 484
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
485 486 487
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
488 489
			};

490
			// @QUESTION Detect if .vertexColors = THREE.VertexColors?
F
Fernando Serrano 已提交
491
			// For every attribute create an accessor
F
Fernando Serrano 已提交
492
			for ( attributeName in geometry.attributes ) {
F
Fernando Serrano 已提交
493
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
494 495
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase()
				gltfAttributes[ attributeName ] = processAccessor( attribute );
F
Fernando Serrano 已提交
496 497 498 499 500 501 502
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
		/**
		 * Process camera
		 * @param  {THREE.Camera} camera Camera to process
		 * @return {Integer}      Index of the processed mesh in the "camera" array
		 */
		function processCamera( camera ) {
			if ( !outputJSON.cameras ) {
				outputJSON.cameras = [];
			}

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
				type: isOrtho ? 'orthographic' : 'perspective'
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

					xmag: camera.right * 2,
					ymag: camera.top * 2,
					zfar: camera.far,
					znear: camera.near

				}

			} else {

				gltfCamera.perspective = {

					aspectRatio: camera.aspect,
					yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
					zfar: camera.far,
					znear: camera.near

				};

			}

543
			if ( camera.name !== undefined ) {
F
Fernando Serrano 已提交
544 545 546 547 548 549 550 551
				gltfCamera.name = camera.type;
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
552 553 554 555 556 557 558
		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
		function processNode ( object ) {

F
Fernando Serrano 已提交
559
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
560 561 562
				outputJSON.nodes = [];
			}

F
Fernando Serrano 已提交
563 564 565 566 567 568 569
			var gltfNode = {};

			if ( options.trs ) {
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

570
				if ( !equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
571 572 573
					gltfNode.rotation = rotation;
				}

574
				if ( !equalArray( position, [ 0, 0, 0 ] ) ) {
F
Fernando Serrano 已提交
575 576 577
					gltfNode.position = position;
				}

578
				if ( !equalArray( scale, [ 1, 1, 1 ] ) ) {
F
Fernando Serrano 已提交
579 580 581 582 583
					gltfNode.scale = scale;
				}

			} else {
				object.updateMatrix();
584
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
585 586
					gltfNode.matrix = object.matrix.elements;
				}
F
Fernando Serrano 已提交
587 588
			};

589
			if ( object.name !== undefined ) {
F
Fernando Serrano 已提交
590 591 592
				gltfNode.name = object.name;
			}

593 594 595 596 597 598 599 600 601 602 603 604 605 606
			if ( object.userData && Object.keys( object.userData ).length > 0 ) {

				try {

					gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );

				} catch (e) {

					throw new Error( 'GLTFExporter: userData can\'t be serialized' );

				}

			}

F
Fernando Serrano 已提交
607
			if ( object instanceof THREE.Mesh
608
				|| object instanceof THREE.Line
F
Fernando Serrano 已提交
609
				|| object instanceof THREE.Points ) {
F
Fernando Serrano 已提交
610
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
611 612
			} else if ( object instanceof THREE.Camera ) {
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
613 614 615
			}

			if ( object.children.length > 0 ) {
F
Fernando Serrano 已提交
616
				gltfNode.children = [];
F
Fernando Serrano 已提交
617 618 619

				for ( var i = 0, l = object.children.length; i < l; i ++ ) {
					var child = object.children[ i ];
F
Fernando Serrano 已提交
620 621 622 623 624
					if ( child instanceof THREE.Mesh
						|| child instanceof THREE.Camera
						|| child instanceof THREE.Group
						|| child instanceof THREE.Line
						|| child instanceof THREE.Points) {
F
Fernando Serrano 已提交
625
						gltfNode.children.push( processNode( child ) );
F
Fernando Serrano 已提交
626 627 628 629 630 631 632 633 634 635
					}
				}
			}

			outputJSON.nodes.push( gltfNode );

			return outputJSON.nodes.length - 1;
		}

		/**
F
Fernando Serrano 已提交
636
		 * Process Scene
F
Fernando Serrano 已提交
637 638 639
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
640

641
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
642 643 644 645 646 647 648 649
				outputJSON.scenes = [];
				outputJSON.scene = 0;
			}

			var gltfScene = {
				nodes: []
			};

650
			if ( scene.name !== undefined ) {
F
Fernando Serrano 已提交
651 652 653
				gltfScene.name = scene.name;
			}

F
Fernando Serrano 已提交
654
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
655 656

			for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
657 658
				var child = scene.children[ i ];

F
Fernando Serrano 已提交
659
				// @TODO Right now we just process meshes and lights
F
Fernando Serrano 已提交
660 661 662 663 664
				if ( child instanceof THREE.Mesh
					|| child instanceof THREE.Camera
					|| child instanceof THREE.Group
					|| child instanceof THREE.Line
					|| child instanceof THREE.Points) {
F
Fernando Serrano 已提交
665 666
					gltfScene.nodes.push( processNode( child ) );
				}
F
Fernando Serrano 已提交
667 668 669
			}
		}

F
Fernando Serrano 已提交
670 671 672 673 674 675 676 677
		// Process the scene/s
		if ( input instanceof Array ) {
			for ( i = 0; i < input.length; i++ ) {
				processScene( input[ i ] );
			}
		} else {
			processScene( input );
		}
F
Fernando Serrano 已提交
678

F
Fernando Serrano 已提交
679
		// Generate buffer
F
Fernando Serrano 已提交
680 681 682 683
		// Create a new blob with all the dataviews from the buffers
		var blob = new Blob( dataViews, { type: 'application/octet-binary' } );

		// Update the bytlength of the only main buffer and update the uri with the base64 representation of it
684 685 686 687 688 689 690 691 692 693 694 695 696 697
		if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

			var reader = new window.FileReader();
			 reader.readAsDataURL( blob );
			 reader.onloadend = function() {
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
			 }
		} else {
			onDone ( outputJSON );
		}
F
Fernando Serrano 已提交
698 699
	}
};