GLTFExporter.js 52.4 KB
Newer Older
F
Fernando Serrano 已提交
1 2
/**
 * @author fernandojsg / http://fernandojsg.com
3 4
 * @author Don McCurdy / https://www.donmccurdy.com
 * @author Takahiro / https://github.com/takahirox
F
Fernando Serrano 已提交
5 6
 */

M
Mugen87 已提交
7 8 9
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
10 11
var WEBGL_CONSTANTS = {
	POINTS: 0x0000,
F
Fernando Serrano 已提交
12 13 14 15 16 17
	LINES: 0x0001,
	LINE_LOOP: 0x0002,
	LINE_STRIP: 0x0003,
	TRIANGLES: 0x0004,
	TRIANGLE_STRIP: 0x0005,
	TRIANGLE_FAN: 0x0006,
18 19 20 21 22 23 24 25 26

	UNSIGNED_BYTE: 0x1401,
	UNSIGNED_SHORT: 0x1403,
	FLOAT: 0x1406,
	UNSIGNED_INT: 0x1405,
	ARRAY_BUFFER: 0x8892,
	ELEMENT_ARRAY_BUFFER: 0x8893,

	NEAREST: 0x2600,
F
Fernando Serrano 已提交
27 28 29 30
	LINEAR: 0x2601,
	NEAREST_MIPMAP_NEAREST: 0x2700,
	LINEAR_MIPMAP_NEAREST: 0x2701,
	NEAREST_MIPMAP_LINEAR: 0x2702,
31
	LINEAR_MIPMAP_LINEAR: 0x2703,
32

33 34 35
	CLAMP_TO_EDGE: 33071,
	MIRRORED_REPEAT: 33648,
	REPEAT: 10497
M
Mugen87 已提交
36
};
37

38 39 40
var THREE_TO_WEBGL = {};

THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
W
WestLangley 已提交
41 42
THREE_TO_WEBGL[ THREE.NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
43
THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
W
WestLangley 已提交
44 45
THREE_TO_WEBGL[ THREE.LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
46 47 48 49 50

THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;

51 52 53 54 55 56 57
var PATH_PROPERTIES = {
	scale: 'scale',
	position: 'translation',
	quaternion: 'rotation',
	morphTargetInfluences: 'weights'
};

F
Fernando Serrano 已提交
58 59 60
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
61
THREE.GLTFExporter = function () {};
F
Fernando Serrano 已提交
62 63 64 65

THREE.GLTFExporter.prototype = {

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

F
Fernando Serrano 已提交
67 68 69
	/**
	 * Parse scenes and generate GLTF output
	 * @param  {THREE.Scene or [THREE.Scenes]} input   THREE.Scene or Array of THREE.Scenes
F
Fernando Serrano 已提交
70 71
	 * @param  {Function} onDone  Callback on completed
	 * @param  {Object} options options
F
Fernando Serrano 已提交
72
	 */
F
Fernando Serrano 已提交
73 74
	parse: function ( input, onDone, options ) {

75
		var DEFAULT_OPTIONS = {
76
			binary: false,
77
			trs: false,
78
			onlyVisible: true,
79
			truncateDrawRange: true,
80
			embedImages: true,
81
			maxTextureSize: Infinity,
82
			animations: [],
83
			forceIndices: false,
84 85
			forcePowerOfTwoTextures: false,
			includeCustomExtensions: false
86 87 88 89
		};

		options = Object.assign( {}, DEFAULT_OPTIONS, options );

D
Don McCurdy 已提交
90 91 92 93 94 95 96
		if ( options.animations.length > 0 ) {

			// Only TRS properties, and not matrices, may be targeted by animation.
			options.trs = true;

		}

F
Fernando Serrano 已提交
97
		var outputJSON = {
F
Fernando Serrano 已提交
98

F
Fernando Serrano 已提交
99
			asset: {
F
Fernando Serrano 已提交
100

F
Fernando Serrano 已提交
101
				version: "2.0",
M
Mr.doob 已提交
102
				generator: "THREE.GLTFExporter"
F
Fernando Serrano 已提交
103

M
Mr.doob 已提交
104
			}
F
Fernando Serrano 已提交
105

M
Mr.doob 已提交
106
		};
F
Fernando Serrano 已提交
107 108

		var byteOffset = 0;
109 110
		var buffers = [];
		var pending = [];
T
Takahiro 已提交
111
		var nodeMap = new Map();
D
Don McCurdy 已提交
112
		var skins = [];
113
		var extensionsUsed = {};
114 115
		var cachedData = {

116
			meshes: new Map(),
117
			attributes: new Map(),
118
			attributesNormalized: new Map(),
119
			materials: new Map(),
120 121
			textures: new Map(),
			images: new Map()
122 123

		};
F
Fernando Serrano 已提交
124

125 126
		var cachedCanvas;

T
Takahiro 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
		var uids = new Map();
		var uid = 0;

		/**
		 * Assign and return a temporal unique id for an object
		 * especially which doesn't have .uuid
		 * @param  {Object} object
		 * @return {Integer}
		 */
		function getUID( object ) {

			if ( ! uids.has( object ) ) uids.set( object, uid ++ );

			return uids.get( object );

		}

F
Fernando Serrano 已提交
144 145 146 147 148 149
		/**
		 * Compare two arrays
		 * @param  {Array} array1 Array 1 to compare
		 * @param  {Array} array2 Array 2 to compare
		 * @return {Boolean}        Returns true if both arrays are equal
		 */
M
Mr.doob 已提交
150
		function equalArray( array1, array2 ) {
F
Fernando Serrano 已提交
151

M
Mugen87 已提交
152
			return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
F
Fernando Serrano 已提交
153

M
Mr.doob 已提交
154
				return element === array2[ index ];
F
Fernando Serrano 已提交
155

M
Mugen87 已提交
156
			} );
F
Fernando Serrano 已提交
157

F
Fernando Serrano 已提交
158 159
		}

160 161 162 163 164
		/**
		 * Converts a string to an ArrayBuffer.
		 * @param  {string} text
		 * @return {ArrayBuffer}
		 */
165
		function stringToArrayBuffer( text ) {
166 167 168 169 170 171 172

			if ( window.TextEncoder !== undefined ) {

				return new TextEncoder().encode( text ).buffer;

			}

173
			var array = new Uint8Array( new ArrayBuffer( text.length ) );
174

175
			for ( var i = 0, il = text.length; i < il; i ++ ) {
176

177
				var value = text.charCodeAt( i );
178

179
				// Replacing multi-byte character with space(0x20).
F
Fernando Serrano 已提交
180
				array[ i ] = value > 0xFF ? 0x20 : value;
181 182 183

			}

184
			return array.buffer;
185 186 187

		}

F
Fernando Serrano 已提交
188
		/**
189
		 * Get the min and max vectors from the given attribute
T
Takahiro 已提交
190 191 192
		 * @param  {THREE.BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
		 * @param  {Integer} start
		 * @param  {Integer} count
F
Fernando Serrano 已提交
193 194
		 * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
		 */
T
Takahiro 已提交
195
		function getMinMax( attribute, start, count ) {
F
Fernando Serrano 已提交
196

F
Fernando Serrano 已提交
197
			var output = {
F
Fernando Serrano 已提交
198

F
Fernando Serrano 已提交
199 200
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
F
Fernando Serrano 已提交
201

F
Fernando Serrano 已提交
202 203
			};

T
Takahiro 已提交
204
			for ( var i = start; i < start + count; i ++ ) {
F
Fernando Serrano 已提交
205

M
Mugen87 已提交
206
				for ( var a = 0; a < attribute.itemSize; a ++ ) {
F
Fernando Serrano 已提交
207

F
Fernando Serrano 已提交
208
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
209 210 211
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );

F
Fernando Serrano 已提交
212
				}
F
Fernando Serrano 已提交
213

F
Fernando Serrano 已提交
214 215
			}

F
Fernando Serrano 已提交
216
			return output;
M
Mugen87 已提交
217

F
Fernando Serrano 已提交
218 219
		}

220 221 222 223 224 225 226 227 228
		/**
		 * Checks if image size is POT.
		 *
		 * @param {Image} image The image to be checked.
		 * @returns {Boolean} Returns true if image size is POT.
		 *
		 */
		function isPowerOfTwo( image ) {

M
Mugen87 已提交
229
			return THREE.MathUtils.isPowerOfTwo( image.width ) && THREE.MathUtils.isPowerOfTwo( image.height );
230 231 232

		}

233 234 235 236 237 238 239 240 241
		/**
		 * Checks if normal attribute values are normalized.
		 *
		 * @param {THREE.BufferAttribute} normal
		 * @returns {Boolean}
		 *
		 */
		function isNormalizedNormalAttribute( normal ) {

242
			if ( cachedData.attributesNormalized.has( normal ) ) {
243 244 245 246 247

				return false;

			}

T
Takahiro 已提交
248
			var v = new THREE.Vector3();
249

T
Takahiro 已提交
250
			for ( var i = 0, il = normal.count; i < il; i ++ ) {
251 252

				// 0.0005 is from glTF-validator
T
Takahiro 已提交
253
				if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

			}

			return true;

		}

		/**
		 * Creates normalized normal buffer attribute.
		 *
		 * @param {THREE.BufferAttribute} normal
		 * @returns {THREE.BufferAttribute}
		 *
		 */
		function createNormalizedNormalAttribute( normal ) {

270
			if ( cachedData.attributesNormalized.has( normal ) ) {
271

272
				return cachedData.attributesNormalized.get( normal );
273 274 275 276 277 278 279

			}

			var attribute = normal.clone();

			var v = new THREE.Vector3();

T
Takahiro 已提交
280
			for ( var i = 0, il = attribute.count; i < il; i ++ ) {
281

T
Takahiro 已提交
282
				v.fromArray( attribute.array, i * 3 );
283 284 285 286 287 288 289 290 291 292 293 294

				if ( v.x === 0 && v.y === 0 && v.z === 0 ) {

					// if values can't be normalized set (1, 0, 0)
					v.setX( 1.0 );

				} else {

					v.normalize();

				}

T
Takahiro 已提交
295
				v.toArray( attribute.array, i * 3 );
296 297 298

			}

299
			cachedData.attributesNormalized.set( normal, attribute );
300 301 302 303 304

			return attribute;

		}

305 306 307 308 309 310 311 312 313 314
		/**
		 * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
		 * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
		 *
		 * @param {Integer} bufferSize The size the original buffer.
		 * @returns {Integer} new buffer size with required padding.
		 *
		 */
		function getPaddedBufferSize( bufferSize ) {

315
			return Math.ceil( bufferSize / 4 ) * 4;
316 317

		}
M
Mugen87 已提交
318

F
Fernando Serrano 已提交
319
		/**
320 321
		 * Returns a buffer aligned to 4-byte boundary.
		 *
F
Fernando Serrano 已提交
322
		 * @param {ArrayBuffer} arrayBuffer Buffer to pad
323
		 * @param {Integer} paddingByte (Optional)
F
Fernando Serrano 已提交
324 325
		 * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
		 */
326
		function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
327

328
			paddingByte = paddingByte || 0;
329

F
Fernando Serrano 已提交
330
			var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
331

332
			if ( paddedLength !== arrayBuffer.byteLength ) {
333

334 335
				var array = new Uint8Array( paddedLength );
				array.set( new Uint8Array( arrayBuffer ) );
336

337
				if ( paddingByte !== 0 ) {
338

T
Takahiro 已提交
339
					for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
340

341
						array[ i ] = paddingByte;
342 343 344 345

					}

				}
346

347
				return array.buffer;
F
Fernando Serrano 已提交
348 349 350 351 352 353 354

			}

			return arrayBuffer;

		}

355 356 357
		/**
		 * Serializes a userData.
		 *
358
		 * @param {THREE.Object3D|THREE.Material} object
R
Robert Long 已提交
359
		 * @param {Object} gltfProperty
360
		 */
R
Robert Long 已提交
361 362
		function serializeUserData( object, gltfProperty ) {

363
			if ( Object.keys( object.userData ).length === 0 ) {
R
Robert Long 已提交
364 365 366 367

				return;

			}
368 369 370

			try {

R
Robert Long 已提交
371 372
				var json = JSON.parse( JSON.stringify( object.userData ) );

373
				if ( options.includeCustomExtensions && json.gltfExtensions ) {
R
Robert Long 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387

					if ( gltfProperty.extensions === undefined ) {

						gltfProperty.extensions = {};

					}

					for ( var extensionName in json.gltfExtensions ) {

						gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
						extensionsUsed[ extensionName ] = true;

					}

388
					delete json.gltfExtensions;
R
Robert Long 已提交
389

390
				}
391

R
Robert Long 已提交
392 393 394 395 396
				if ( Object.keys( json ).length > 0 ) {

					gltfProperty.extras = json;

				}
397

398
			} catch ( error ) {
399

400 401
				console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
					'won\'t be serialized because of JSON.stringify error - ' + error.message );
402 403 404 405 406

			}

		}

407 408 409 410 411 412
		/**
		 * Applies a texture transform, if present, to the map definition. Requires
		 * the KHR_texture_transform extension.
		 */
		function applyTextureTransform( mapDef, texture ) {

M
Mugen87 已提交
413
			var didTransform = false;
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
			var transformDef = {};

			if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {

				transformDef.offset = texture.offset.toArray();
				didTransform = true;

			}

			if ( texture.rotation !== 0 ) {

				transformDef.rotation = texture.rotation;
				didTransform = true;

			}

			if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {

				transformDef.scale = texture.repeat.toArray();
D
Don McCurdy 已提交
433
				didTransform = true;
434 435 436 437 438 439 440 441 442 443 444 445 446

			}

			if ( didTransform ) {

				mapDef.extensions = mapDef.extensions || {};
				mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
				extensionsUsed[ 'KHR_texture_transform' ] = true;

			}

		}

F
Fernando Serrano 已提交
447
		/**
F
Fernando Serrano 已提交
448
		 * Process a buffer to append to the default one.
449 450
		 * @param  {ArrayBuffer} buffer
		 * @return {Integer}
F
Fernando Serrano 已提交
451
		 */
452
		function processBuffer( buffer ) {
F
Fernando Serrano 已提交
453

M
Mugen87 已提交
454
			if ( ! outputJSON.buffers ) {
F
Fernando Serrano 已提交
455

456
				outputJSON.buffers = [ { byteLength: 0 } ];
F
Fernando Serrano 已提交
457

458
			}
F
Fernando Serrano 已提交
459

460 461
			// All buffers are merged before export.
			buffers.push( buffer );
F
Fernando Serrano 已提交
462

463
			return 0;
F
Fernando Serrano 已提交
464

465
		}
F
Fernando Serrano 已提交
466

467 468 469 470 471 472 473 474 475 476
		/**
		 * Process and generate a BufferView
		 * @param  {THREE.BufferAttribute} attribute
		 * @param  {number} componentType
		 * @param  {number} start
		 * @param  {number} count
		 * @param  {number} target (Optional) Target usage of the BufferView
		 * @return {Object}
		 */
		function processBufferView( attribute, componentType, start, count, target ) {
F
Fernando Serrano 已提交
477

478
			if ( ! outputJSON.bufferViews ) {
479

480
				outputJSON.bufferViews = [];
M
Mugen87 已提交
481

482
			}
F
Fernando Serrano 已提交
483

484
			// Create a new dataview and dump the attribute's array into it
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

			var componentSize;

			if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {

				componentSize = 1;

			} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {

				componentSize = 2;

			} else {

				componentSize = 4;

			}

502
			var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
503
			var dataView = new DataView( new ArrayBuffer( byteLength ) );
504
			var offset = 0;
F
Fernando Serrano 已提交
505

M
Mugen87 已提交
506
			for ( var i = start; i < start + count; i ++ ) {
F
Fernando Serrano 已提交
507

M
Mugen87 已提交
508
				for ( var a = 0; a < attribute.itemSize; a ++ ) {
F
Fernando Serrano 已提交
509

510 511
					// @TODO Fails on InterleavedBufferAttribute, and could probably be
					// optimized for normal BufferAttribute.
F
Fernando Serrano 已提交
512
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
513

514
					if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
F
Fernando Serrano 已提交
515

F
Fernando Serrano 已提交
516
						dataView.setFloat32( offset, value, true );
F
Fernando Serrano 已提交
517

518
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
F
Fernando Serrano 已提交
519

S
selimbek 已提交
520
						dataView.setUint32( offset, value, true );
F
Fernando Serrano 已提交
521

522
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
F
Fernando Serrano 已提交
523

F
Fernando Serrano 已提交
524
						dataView.setUint16( offset, value, true );
F
Fernando Serrano 已提交
525

526 527 528 529
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {

						dataView.setUint8( offset, value );

F
Fernando Serrano 已提交
530
					}
F
Fernando Serrano 已提交
531

532
					offset += componentSize;
F
Fernando Serrano 已提交
533

F
Fernando Serrano 已提交
534
				}
F
Fernando Serrano 已提交
535

F
Fernando Serrano 已提交
536 537 538
			}

			var gltfBufferView = {
F
Fernando Serrano 已提交
539

540
				buffer: processBuffer( dataView.buffer ),
F
Fernando Serrano 已提交
541
				byteOffset: byteOffset,
542
				byteLength: byteLength
F
Fernando Serrano 已提交
543

F
Fernando Serrano 已提交
544 545
			};

546 547
			if ( target !== undefined ) gltfBufferView.target = target;

548 549 550
			if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {

				// Only define byteStride for vertex attributes.
551
				gltfBufferView.byteStride = attribute.itemSize * componentSize;
552 553 554

			}

555
			byteOffset += byteLength;
F
Fernando Serrano 已提交
556

F
Fernando Serrano 已提交
557
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
558

559
			// @TODO Merge bufferViews where possible.
F
Fernando Serrano 已提交
560
			var output = {
F
Fernando Serrano 已提交
561

F
Fernando Serrano 已提交
562 563
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
F
Fernando Serrano 已提交
564

F
Fernando Serrano 已提交
565
			};
F
Fernando Serrano 已提交
566

F
Fernando Serrano 已提交
567
			return output;
F
Fernando Serrano 已提交
568

F
Fernando Serrano 已提交
569 570
		}

571 572 573 574 575
		/**
		 * Process and generate a BufferView from an image Blob.
		 * @param {Blob} blob
		 * @return {Promise<Integer>}
		 */
D
Don McCurdy 已提交
576
		function processBufferViewImage( blob ) {
577 578 579 580 581 582 583

			if ( ! outputJSON.bufferViews ) {

				outputJSON.bufferViews = [];

			}

D
Don McCurdy 已提交
584
			return new Promise( function ( resolve ) {
585 586 587

				var reader = new window.FileReader();
				reader.readAsArrayBuffer( blob );
D
Don McCurdy 已提交
588
				reader.onloadend = function () {
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

					var buffer = getPaddedArrayBuffer( reader.result );

					var bufferView = {
						buffer: processBuffer( buffer ),
						byteOffset: byteOffset,
						byteLength: buffer.byteLength
					};

					byteOffset += buffer.byteLength;

					outputJSON.bufferViews.push( bufferView );

					resolve( outputJSON.bufferViews.length - 1 );

D
Don McCurdy 已提交
604
				};
605 606 607 608 609

			} );

		}

F
Fernando Serrano 已提交
610
		/**
F
Fernando Serrano 已提交
611
		 * Process attribute to generate an accessor
612 613
		 * @param  {THREE.BufferAttribute} attribute Attribute to process
		 * @param  {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
T
Takahiro 已提交
614 615
		 * @param  {Integer} start (Optional)
		 * @param  {Integer} count (Optional)
F
Fernando Serrano 已提交
616
		 * @return {Integer}           Index of the processed accessor on the "accessors" array
F
Fernando Serrano 已提交
617
		 */
T
Takahiro 已提交
618
		function processAccessor( attribute, geometry, start, count ) {
F
Fernando Serrano 已提交
619

D
Don McCurdy 已提交
620
			var types = {
F
Fernando Serrano 已提交
621

D
Don McCurdy 已提交
622 623 624 625 626
				1: 'SCALAR',
				2: 'VEC2',
				3: 'VEC3',
				4: 'VEC4',
				16: 'MAT4'
F
Fernando Serrano 已提交
627

D
Don McCurdy 已提交
628
			};
F
Fernando Serrano 已提交
629

630 631
			var componentType;

F
Fernando Serrano 已提交
632
			// Detect the component type of the attribute array (float, uint or ushort)
633
			if ( attribute.array.constructor === Float32Array ) {
F
Fernando Serrano 已提交
634

635
				componentType = WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
636

637
			} else if ( attribute.array.constructor === Uint32Array ) {
F
Fernando Serrano 已提交
638

639
				componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
F
Fernando Serrano 已提交
640

641
			} else if ( attribute.array.constructor === Uint16Array ) {
F
Fernando Serrano 已提交
642

643
				componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
F
Fernando Serrano 已提交
644

645 646 647 648
			} else if ( attribute.array.constructor === Uint8Array ) {

				componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;

649
			} else {
F
Fernando Serrano 已提交
650

651
				throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
F
Fernando Serrano 已提交
652

653
			}
F
Fernando Serrano 已提交
654

T
Takahiro 已提交
655 656
			if ( start === undefined ) start = 0;
			if ( count === undefined ) count = attribute.count;
657 658

			// @TODO Indexed buffer geometry with drawRange not supported yet
659
			if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
M
Mugen87 已提交
660

T
Takahiro 已提交
661 662
				var end = start + count;
				var end2 = geometry.drawRange.count === Infinity
M
Mugen87 已提交
663 664
					? attribute.count
					: geometry.drawRange.start + geometry.drawRange.count;
T
Takahiro 已提交
665 666 667 668 669

				start = Math.max( start, geometry.drawRange.start );
				count = Math.min( end, end2 ) - start;

				if ( count < 0 ) count = 0;
M
Mugen87 已提交
670

671 672
			}

673
			// Skip creating an accessor if the attribute doesn't have data to export
F
Fernando Serrano 已提交
674
			if ( count === 0 ) {
675

676
				return null;
677 678 679

			}

T
Takahiro 已提交
680 681
			var minMax = getMinMax( attribute, start, count );

682 683 684 685 686 687
			var bufferViewTarget;

			// If geometry isn't provided, don't infer the target usage of the bufferView. For
			// animation samplers, target must not be set.
			if ( geometry !== undefined ) {

T
Takahiro 已提交
688
				bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
689 690 691 692

			}

			var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
F
Fernando Serrano 已提交
693

F
Fernando Serrano 已提交
694
			var gltfAccessor = {
F
Fernando Serrano 已提交
695

F
Fernando Serrano 已提交
696 697 698
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
699
				count: count,
F
Fernando Serrano 已提交
700 701
				max: minMax.max,
				min: minMax.min,
D
Don McCurdy 已提交
702
				type: types[ attribute.itemSize ]
F
Fernando Serrano 已提交
703

F
Fernando Serrano 已提交
704 705
			};

706 707 708 709 710 711
			if ( ! outputJSON.accessors ) {

				outputJSON.accessors = [];

			}

F
Fernando Serrano 已提交
712 713 714
			outputJSON.accessors.push( gltfAccessor );

			return outputJSON.accessors.length - 1;
F
Fernando Serrano 已提交
715

F
Fernando Serrano 已提交
716 717 718
		}

		/**
F
Fernando Serrano 已提交
719
		 * Process image
720
		 * @param  {Image} image to process
721
		 * @param  {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
722
		 * @param  {Boolean} flipY before writing out the image
F
Fernando Serrano 已提交
723 724
		 * @return {Integer}     Index of the processed texture in the "images" array
		 */
725
		function processImage( image, format, flipY ) {
F
Fernando Serrano 已提交
726

727
			if ( ! cachedData.images.has( image ) ) {
728

729 730 731 732 733
				cachedData.images.set( image, {} );

			}

			var cachedImages = cachedData.images.get( image );
734 735
			var mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
			var key = mimeType + ":flipY/" + flipY.toString();
F
Fernando Serrano 已提交
736

737 738 739
			if ( cachedImages[ key ] !== undefined ) {

				return cachedImages[ key ];
740 741

			}
742

M
Mugen87 已提交
743
			if ( ! outputJSON.images ) {
F
Fernando Serrano 已提交
744

F
Fernando Serrano 已提交
745
				outputJSON.images = [];
F
Fernando Serrano 已提交
746

F
Fernando Serrano 已提交
747 748
			}

M
Mugen87 已提交
749
			var gltfImage = { mimeType: mimeType };
750

751
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
752

753
				var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
754

755 756
				canvas.width = Math.min( image.width, options.maxTextureSize );
				canvas.height = Math.min( image.height, options.maxTextureSize );
757

758
				if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( canvas ) ) {
759

760
					console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
761

M
Mugen87 已提交
762 763
					canvas.width = THREE.MathUtils.floorPowerOfTwo( canvas.width );
					canvas.height = THREE.MathUtils.floorPowerOfTwo( canvas.height );
764 765 766

				}

767
				var ctx = canvas.getContext( '2d' );
768

769
				if ( flipY === true ) {
770

771
					ctx.translate( 0, canvas.height );
M
Mugen87 已提交
772
					ctx.scale( 1, - 1 );
773 774 775

				}

776
				ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
777

778 779 780 781 782 783 784 785 786 787 788
				if ( options.binary === true ) {

					pending.push( new Promise( function ( resolve ) {

						canvas.toBlob( function ( blob ) {

							processBufferViewImage( blob ).then( function ( bufferViewIndex ) {

								gltfImage.bufferView = bufferViewIndex;

								resolve();
789

790 791 792 793 794 795 796 797 798 799 800
							} );

						}, mimeType );

					} ) );

				} else {

					gltfImage.uri = canvas.toDataURL( mimeType );

				}
F
Fernando Serrano 已提交
801

F
Fernando Serrano 已提交
802
			} else {
F
Fernando Serrano 已提交
803

804
				gltfImage.uri = image.src;
F
Fernando Serrano 已提交
805

F
Fernando Serrano 已提交
806 807 808 809
			}

			outputJSON.images.push( gltfImage );

810
			var index = outputJSON.images.length - 1;
811
			cachedImages[ key ] = index;
F
Fernando Serrano 已提交
812

813
			return index;
F
Fernando Serrano 已提交
814

F
Fernando Serrano 已提交
815 816 817 818 819 820 821
		}

		/**
		 * Process sampler
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "samplers" array
		 */
M
Mr.doob 已提交
822
		function processSampler( map ) {
F
Fernando Serrano 已提交
823

M
Mugen87 已提交
824
			if ( ! outputJSON.samplers ) {
F
Fernando Serrano 已提交
825

F
Fernando Serrano 已提交
826
				outputJSON.samplers = [];
F
Fernando Serrano 已提交
827

F
Fernando Serrano 已提交
828 829 830
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
831

832 833 834 835
				magFilter: THREE_TO_WEBGL[ map.magFilter ],
				minFilter: THREE_TO_WEBGL[ map.minFilter ],
				wrapS: THREE_TO_WEBGL[ map.wrapS ],
				wrapT: THREE_TO_WEBGL[ map.wrapT ]
F
Fernando Serrano 已提交
836

F
Fernando Serrano 已提交
837 838 839 840 841
			};

			outputJSON.samplers.push( gltfSampler );

			return outputJSON.samplers.length - 1;
F
Fernando Serrano 已提交
842

F
Fernando Serrano 已提交
843 844 845 846 847 848 849
		}

		/**
		 * Process texture
		 * @param  {Texture} map Map to process
		 * @return {Integer}     Index of the processed texture in the "textures" array
		 */
M
Mr.doob 已提交
850
		function processTexture( map ) {
F
Fernando Serrano 已提交
851

T
Takahiro 已提交
852
			if ( cachedData.textures.has( map ) ) {
T
Takahiro 已提交
853

T
Takahiro 已提交
854
				return cachedData.textures.get( map );
T
Takahiro 已提交
855 856 857

			}

M
Mugen87 已提交
858
			if ( ! outputJSON.textures ) {
F
Fernando Serrano 已提交
859

F
Fernando Serrano 已提交
860
				outputJSON.textures = [];
F
Fernando Serrano 已提交
861

F
Fernando Serrano 已提交
862 863 864
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
865

F
Fernando Serrano 已提交
866
				sampler: processSampler( map ),
M
Mugen87 已提交
867
				source: processImage( map.image, map.format, map.flipY )
F
Fernando Serrano 已提交
868

F
Fernando Serrano 已提交
869 870
			};

B
Bengt Ove Sannes 已提交
871
			if ( map.name ) {
B
Bengt Ove Sannes 已提交
872

B
Bengt Ove Sannes 已提交
873
				gltfTexture.name = map.name;
B
Bengt Ove Sannes 已提交
874

B
Bengt Ove Sannes 已提交
875 876
			}

F
Fernando Serrano 已提交
877 878
			outputJSON.textures.push( gltfTexture );

T
Takahiro 已提交
879
			var index = outputJSON.textures.length - 1;
T
Takahiro 已提交
880
			cachedData.textures.set( map, index );
T
Takahiro 已提交
881 882

			return index;
F
Fernando Serrano 已提交
883

F
Fernando Serrano 已提交
884 885 886 887 888 889
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
890
		 */
M
Mr.doob 已提交
891
		function processMaterial( material ) {
F
Fernando Serrano 已提交
892

T
Takahiro 已提交
893
			if ( cachedData.materials.has( material ) ) {
894

T
Takahiro 已提交
895
				return cachedData.materials.get( material );
896 897 898

			}

899
			if ( material.isShaderMaterial ) {
F
Fernando Serrano 已提交
900

901 902
				console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
				return null;
F
Fernando Serrano 已提交
903

F
Fernando Serrano 已提交
904
			}
F
Fernando Serrano 已提交
905

906
			if ( ! outputJSON.materials ) {
907

908
				outputJSON.materials = [];
909 910 911

			}

F
Fernando Serrano 已提交
912
			// @QUESTION Should we avoid including any attribute that has the default value?
913
			var gltfMaterial = {
F
Fernando Serrano 已提交
914

915
				pbrMetallicRoughness: {}
F
Fernando Serrano 已提交
916

917
			};
918

919
			if ( material.isMeshBasicMaterial ) {
920 921 922 923 924

				gltfMaterial.extensions = { KHR_materials_unlit: {} };

				extensionsUsed[ 'KHR_materials_unlit' ] = true;

925 926 927 928 929
			} else if ( material.isGLTFSpecularGlossinessMaterial ) {

				gltfMaterial.extensions = { KHR_materials_pbrSpecularGlossiness: {} };

				extensionsUsed[ 'KHR_materials_pbrSpecularGlossiness' ] = true;
930 931

			} else if ( ! material.isMeshStandardMaterial ) {
932 933 934 935 936

				console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );

			}

937 938
			// pbrMetallicRoughness.baseColorFactor
			var color = material.color.toArray().concat( [ material.opacity ] );
F
Fernando Serrano 已提交
939

M
Mugen87 已提交
940
			if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
941

942
				gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
943 944 945

			}

946
			if ( material.isMeshStandardMaterial ) {
947

948 949
				gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
950

951
			} else if ( material.isMeshBasicMaterial ) {
952 953 954 955

				gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;

M
Mr.doob 已提交
956
			} else {
957

M
Mugen87 已提交
958 959
				gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
F
Fernando Serrano 已提交
960

961
			}
962

963 964
			// pbrSpecularGlossiness diffuse, specular and glossiness factor
			if ( material.isGLTFSpecularGlossinessMaterial ) {
M
Mr.doob 已提交
965

966 967 968
				if ( gltfMaterial.pbrMetallicRoughness.baseColorFactor ) {

					gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor = gltfMaterial.pbrMetallicRoughness.baseColorFactor;
M
Mr.doob 已提交
969

970
				}
971 972 973 974 975 976

				var specularFactor = [ 1, 1, 1 ];
				material.specular.toArray( specularFactor, 0 );
				gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor = specularFactor;

				gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor = material.glossiness;
M
Mr.doob 已提交
977

978 979
			}

980 981 982 983 984
			// pbrMetallicRoughness.metallicRoughnessTexture
			if ( material.metalnessMap || material.roughnessMap ) {

				if ( material.metalnessMap === material.roughnessMap ) {

985 986 987
					var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
					applyTextureTransform( metalRoughMapDef, material.metalnessMap );
					gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
988 989 990 991 992 993 994 995 996

				} else {

					console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );

				}

			}

997 998 999 1000 1001 1002 1003 1004 1005 1006
			// pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
			if ( material.map ) {

				var baseColorMapDef = { index: processTexture( material.map ) };
				applyTextureTransform( baseColorMapDef, material.map );

				if ( material.isGLTFSpecularGlossinessMaterial ) {

					gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture = baseColorMapDef;

P
psoto 已提交
1007
				}
1008 1009

				gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
M
Mr.doob 已提交
1010

P
psoto 已提交
1011 1012
			}

1013
			// pbrSpecularGlossiness specular map
1014
			if ( material.isGLTFSpecularGlossinessMaterial && material.specularMap ) {
1015

1016 1017 1018
				var specularMapDef = { index: processTexture( material.specularMap ) };
				applyTextureTransform( specularMapDef, material.specularMap );
				gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture = specularMapDef;
1019

1020
			}
1021

1022
			if ( material.emissive ) {
1023 1024

				// emissiveFactor
1025
				var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
F
Fernando Serrano 已提交
1026

M
Mugen87 已提交
1027
				if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
1028 1029 1030

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
1031
				}
1032 1033 1034 1035

				// emissiveTexture
				if ( material.emissiveMap ) {

1036 1037 1038
					var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
					applyTextureTransform( emissiveMapDef, material.emissiveMap );
					gltfMaterial.emissiveTexture = emissiveMapDef;
1039 1040 1041 1042 1043 1044 1045 1046

				}

			}

			// normalTexture
			if ( material.normalMap ) {

1047
				var normalMapDef = { index: processTexture( material.normalMap ) };
1048

P
psoto 已提交
1049
				if ( material.normalScale && material.normalScale.x !== - 1 ) {
1050 1051 1052

					if ( material.normalScale.x !== material.normalScale.y ) {

M
Mugen87 已提交
1053
						console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
1054 1055 1056

					}

1057
					normalMapDef.scale = material.normalScale.x;
1058 1059 1060

				}

1061 1062 1063 1064
				applyTextureTransform( normalMapDef, material.normalMap );

				gltfMaterial.normalTexture = normalMapDef;

F
Fernando Serrano 已提交
1065 1066
			}

1067 1068 1069
			// occlusionTexture
			if ( material.aoMap ) {

M
Mugen87 已提交
1070
				var occlusionMapDef = {
1071 1072 1073
					index: processTexture( material.aoMap ),
					texCoord: 1
				};
1074

1075 1076
				if ( material.aoMapIntensity !== 1.0 ) {

1077
					occlusionMapDef.strength = material.aoMapIntensity;
1078 1079 1080

				}

1081 1082 1083 1084
				applyTextureTransform( occlusionMapDef, material.aoMap );

				gltfMaterial.occlusionTexture = occlusionMapDef;

1085 1086 1087
			}

			// alphaMode
M
Mr.doob 已提交
1088
			if ( material.transparent ) {
1089

M
Mr.doob 已提交
1090
				gltfMaterial.alphaMode = 'BLEND';
1091

M
Mr.doob 已提交
1092 1093 1094
			} else {

				if ( material.alphaTest > 0.0 ) {
1095

M
Mr.doob 已提交
1096
					gltfMaterial.alphaMode = 'MASK';
1097 1098 1099
					gltfMaterial.alphaCutoff = material.alphaTest;

				}
1100 1101 1102 1103

			}

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

F
Fernando Serrano 已提交
1106
				gltfMaterial.doubleSided = true;
1107

F
Fernando Serrano 已提交
1108 1109
			}

1110
			if ( material.name !== '' ) {
1111

F
Fernando Serrano 已提交
1112
				gltfMaterial.name = material.name;
1113

F
Fernando Serrano 已提交
1114 1115
			}

R
Robert Long 已提交
1116
			serializeUserData( material, gltfMaterial );
1117

F
Fernando Serrano 已提交
1118
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
1119

1120
			var index = outputJSON.materials.length - 1;
T
Takahiro 已提交
1121
			cachedData.materials.set( material, index );
1122 1123

			return index;
1124

F
Fernando Serrano 已提交
1125 1126 1127
		}

		/**
F
Fernando Serrano 已提交
1128 1129 1130
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
1131 1132
		 */
		function processMesh( mesh ) {
F
Fernando Serrano 已提交
1133

K
kinolaev 已提交
1134 1135
			var meshCacheKeyParts = [ mesh.geometry.uuid ];
			if ( Array.isArray( mesh.material ) ) {
1136

M
Mugen87 已提交
1137
				for ( var i = 0, l = mesh.material.length; i < l; i ++ ) {
K
kinolaev 已提交
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

					meshCacheKeyParts.push( mesh.material[ i ].uuid	);

				}

			} else {

				meshCacheKeyParts.push( mesh.material.uuid );

			}

			var meshCacheKey = meshCacheKeyParts.join( ':' );
			if ( cachedData.meshes.has( meshCacheKey ) ) {

				return cachedData.meshes.get( meshCacheKey );
1153 1154 1155

			}

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

M
Mr.doob 已提交
1158 1159
			var mode;

1160
			// Use the correct mode
1161
			if ( mesh.isLineSegments ) {
1162

1163
				mode = WEBGL_CONSTANTS.LINES;
1164

1165
			} else if ( mesh.isLineLoop ) {
1166

1167
				mode = WEBGL_CONSTANTS.LINE_LOOP;
1168

1169
			} else if ( mesh.isLine ) {
1170

1171
				mode = WEBGL_CONSTANTS.LINE_STRIP;
1172

1173
			} else if ( mesh.isPoints ) {
1174

1175
				mode = WEBGL_CONSTANTS.POINTS;
1176 1177 1178

			} else {

1179
				mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
L
linbingquan 已提交
1180

1181
			}
1182

1183
			if ( ! geometry.isBufferGeometry ) {
1184

1185 1186
				console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use THREE.BufferGeometry instead.' );
				geometry = new THREE.BufferGeometry().setFromObject( mesh );
1187 1188

			}
F
Fernando Serrano 已提交
1189

T
Takahiro 已提交
1190
			var gltfMesh = {};
1191

T
Takahiro 已提交
1192 1193 1194
			var attributes = {};
			var primitives = [];
			var targets = [];
F
Fernando Serrano 已提交
1195

F
Fernando Serrano 已提交
1196 1197
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
1198

F
Fernando Serrano 已提交
1199 1200
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
1201 1202 1203
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
1204

F
Fernando Serrano 已提交
1205 1206
			};

1207 1208 1209 1210 1211 1212
			var originalNormal = geometry.getAttribute( 'normal' );

			if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {

				console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );

1213
				geometry.setAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
1214 1215 1216

			}

1217
			// @QUESTION Detect if .vertexColors = true?
F
Fernando Serrano 已提交
1218
			// For every attribute create an accessor
D
Don McCurdy 已提交
1219
			var modifiedAttribute = null;
F
Fernando Serrano 已提交
1220 1221
			for ( var attributeName in geometry.attributes ) {

1222 1223 1224
				// Ignore morph target attributes, which are exported later.
				if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;

F
Fernando Serrano 已提交
1225
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
1226
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
D
Don McCurdy 已提交
1227

1228 1229
				// Prefix all geometry attributes except the ones specifically
				// listed in the spec; non-spec attributes are considered custom.
1230 1231 1232 1233 1234 1235
				var validVertexAttributes =
						/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
				if ( ! validVertexAttributes.test( attributeName ) ) {

					attributeName = '_' + attributeName;

1236 1237
				}

T
Takahiro 已提交
1238
				if ( cachedData.attributes.has( getUID( attribute ) ) ) {
1239

T
Takahiro 已提交
1240
					attributes[ attributeName ] = cachedData.attributes.get( getUID( attribute ) );
1241 1242 1243 1244
					continue;

				}

1245
				// JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
1246
				modifiedAttribute = null;
1247
				var array = attribute.array;
1248
				if ( attributeName === 'JOINTS_0' &&
1249 1250
					! ( array instanceof Uint16Array ) &&
					! ( array instanceof Uint8Array ) ) {
1251 1252

					console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
1253
					modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
1254 1255 1256

				}

1257 1258
				var accessor = processAccessor( modifiedAttribute || attribute, geometry );
				if ( accessor !== null ) {
D
Don McCurdy 已提交
1259

1260
					attributes[ attributeName ] = accessor;
T
Takahiro 已提交
1261
					cachedData.attributes.set( getUID( attribute ), accessor );
D
Don McCurdy 已提交
1262 1263 1264 1265 1266

				}

			}

1267
			if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
1268

1269 1270 1271 1272 1273 1274 1275
			// Skip if no exportable attributes found
			if ( Object.keys( attributes ).length === 0 ) {

				return null;

			}

D
Don McCurdy 已提交
1276 1277 1278
			// Morph targets
			if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {

1279
				var weights = [];
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
				var targetNames = [];
				var reverseDictionary = {};

				if ( mesh.morphTargetDictionary !== undefined ) {

					for ( var key in mesh.morphTargetDictionary ) {

						reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;

					}

				}

D
Don McCurdy 已提交
1293 1294 1295 1296
				for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {

					var target = {};

1297 1298
					var warned = false;

D
Don McCurdy 已提交
1299 1300
					for ( var attributeName in geometry.morphAttributes ) {

T
Takahiro 已提交
1301
						// glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
1302
						// Three.js doesn't support TANGENT yet.
T
Takahiro 已提交
1303 1304 1305

						if ( attributeName !== 'position' && attributeName !== 'normal' ) {

1306 1307 1308 1309 1310 1311 1312
							if ( ! warned ) {

								console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
								warned = true;

							}

T
Takahiro 已提交
1313 1314 1315 1316
							continue;

						}

D
Don McCurdy 已提交
1317
						var attribute = geometry.morphAttributes[ attributeName ][ i ];
1318
						var gltfAttributeName = attributeName.toUpperCase();
T
Takahiro 已提交
1319

1320
						// Three.js morph attribute has absolute values while the one of glTF has relative values.
T
Takahiro 已提交
1321 1322 1323 1324 1325
						//
						// glTF 2.0 Specification:
						// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets

						var baseAttribute = geometry.attributes[ attributeName ];
1326

T
Takahiro 已提交
1327
						if ( cachedData.attributes.has( getUID( attribute ) ) ) {
1328

T
Takahiro 已提交
1329
							target[ gltfAttributeName ] = cachedData.attributes.get( getUID( attribute ) );
1330 1331 1332 1333
							continue;

						}

T
Takahiro 已提交
1334
						// Clones attribute not to override
1335
						var relativeAttribute = attribute.clone();
T
Takahiro 已提交
1336

1337
						if ( ! geometry.morphTargetsRelative ) {
1338 1339 1340 1341 1342 1343 1344 1345

							for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {

								relativeAttribute.setXYZ(
									j,
									attribute.getX( j ) - baseAttribute.getX( j ),
									attribute.getY( j ) - baseAttribute.getY( j ),
									attribute.getZ( j ) - baseAttribute.getZ( j )
M
Mugen87 已提交
1346
								);
1347 1348

							}
T
Takahiro 已提交
1349 1350 1351

						}

1352
						target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
T
Takahiro 已提交
1353
						cachedData.attributes.set( getUID( baseAttribute ), target[ gltfAttributeName ] );
D
Don McCurdy 已提交
1354 1355 1356

					}

T
Takahiro 已提交
1357
					targets.push( target );
D
Don McCurdy 已提交
1358

1359
					weights.push( mesh.morphTargetInfluences[ i ] );
1360
					if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
1361

D
Don McCurdy 已提交
1362
				}
F
Fernando Serrano 已提交
1363

1364 1365
				gltfMesh.weights = weights;

1366 1367 1368 1369 1370 1371 1372
				if ( targetNames.length > 0 ) {

					gltfMesh.extras = {};
					gltfMesh.extras.targetNames = targetNames;

				}

F
Fernando Serrano 已提交
1373 1374
			}

1375
			var forceIndices = options.forceIndices;
T
Takahiro 已提交
1376
			var isMultiMaterial = Array.isArray( mesh.material );
1377

1378
			if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
1379

1380
			if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
1381 1382

				// temporal workaround.
1383
				console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
1384 1385 1386 1387
				forceIndices = true;

			}

1388
			var didForceIndices = false;
T
Takahiro 已提交
1389

1390
			if ( geometry.index === null && forceIndices ) {
T
Takahiro 已提交
1391

1392
				var indices = [];
T
Takahiro 已提交
1393

1394
				for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
T
Takahiro 已提交
1395 1396 1397 1398 1399

					indices[ i ] = i;

				}

1400
				geometry.setIndex( indices );
T
Takahiro 已提交
1401

1402
				didForceIndices = true;
T
Takahiro 已提交
1403 1404 1405

			}

F
Fernando Serrano 已提交
1406
			var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
1407
			var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
T
Takahiro 已提交
1408

1409
			for ( var i = 0, il = groups.length; i < il; i ++ ) {
T
Takahiro 已提交
1410 1411 1412 1413 1414 1415

				var primitive = {
					mode: mode,
					attributes: attributes,
				};

R
Robert Long 已提交
1416
				serializeUserData( geometry, primitive );
1417

T
Takahiro 已提交
1418 1419 1420 1421
				if ( targets.length > 0 ) primitive.targets = targets;

				if ( geometry.index !== null ) {

1422
					var cacheKey = getUID( geometry.index );
T
Takahiro 已提交
1423

T
Takahiro 已提交
1424
					if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
T
Takahiro 已提交
1425

1426
						cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
T
Takahiro 已提交
1427 1428

					}
1429 1430

					if ( cachedData.attributes.has( cacheKey ) ) {
1431

1432
						primitive.indices = cachedData.attributes.get( cacheKey );
1433 1434 1435 1436

					} else {

						primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
1437
						cachedData.attributes.set( cacheKey, primitive.indices );
1438 1439

					}
T
Takahiro 已提交
1440

G
Gary Oberbrunner 已提交
1441 1442
					if ( primitive.indices === null ) delete primitive.indices;

T
Takahiro 已提交
1443 1444
				}

1445
				var material = processMaterial( materials[ groups[ i ].materialIndex ] );
1446

1447
				if ( material !== null ) {
1448

1449
					primitive.material = material;
1450 1451

				}
T
Takahiro 已提交
1452

1453 1454
				primitives.push( primitive );

T
Takahiro 已提交
1455 1456
			}

1457
			if ( didForceIndices ) {
T
Takahiro 已提交
1458

1459
				geometry.setIndex( null );
T
Takahiro 已提交
1460 1461 1462 1463 1464

			}

			gltfMesh.primitives = primitives;

1465 1466 1467 1468 1469
			if ( ! outputJSON.meshes ) {

				outputJSON.meshes = [];

			}
F
Fernando Serrano 已提交
1470

F
Fernando Serrano 已提交
1471 1472
			outputJSON.meshes.push( gltfMesh );

1473
			var index = outputJSON.meshes.length - 1;
K
kinolaev 已提交
1474
			cachedData.meshes.set( meshCacheKey, index );
1475 1476

			return index;
M
Mugen87 已提交
1477

F
Fernando Serrano 已提交
1478 1479
		}

F
Fernando Serrano 已提交
1480 1481 1482 1483 1484 1485
		/**
		 * Process camera
		 * @param  {THREE.Camera} camera Camera to process
		 * @return {Integer}      Index of the processed mesh in the "camera" array
		 */
		function processCamera( camera ) {
F
Fernando Serrano 已提交
1486

M
Mugen87 已提交
1487
			if ( ! outputJSON.cameras ) {
F
Fernando Serrano 已提交
1488

F
Fernando Serrano 已提交
1489
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
1490

F
Fernando Serrano 已提交
1491 1492
			}

1493
			var isOrtho = camera.isOrthographicCamera;
F
Fernando Serrano 已提交
1494 1495

			var gltfCamera = {
F
Fernando Serrano 已提交
1496

F
Fernando Serrano 已提交
1497
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
1498

F
Fernando Serrano 已提交
1499 1500 1501 1502 1503 1504 1505 1506
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

					xmag: camera.right * 2,
					ymag: camera.top * 2,
1507 1508
					zfar: camera.far <= 0 ? 0.001 : camera.far,
					znear: camera.near < 0 ? 0 : camera.near
F
Fernando Serrano 已提交
1509

F
Fernando Serrano 已提交
1510
				};
F
Fernando Serrano 已提交
1511 1512 1513 1514 1515 1516

			} else {

				gltfCamera.perspective = {

					aspectRatio: camera.aspect,
M
Mugen87 已提交
1517
					yfov: THREE.MathUtils.degToRad( camera.fov ),
1518 1519
					zfar: camera.far <= 0 ? 0.001 : camera.far,
					znear: camera.near < 0 ? 0 : camera.near
F
Fernando Serrano 已提交
1520 1521 1522 1523 1524

				};

			}

1525
			if ( camera.name !== '' ) {
F
Fernando Serrano 已提交
1526

F
Fernando Serrano 已提交
1527
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
1528

F
Fernando Serrano 已提交
1529 1530 1531 1532 1533
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
M
Mugen87 已提交
1534

F
Fernando Serrano 已提交
1535 1536
		}

1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
		/**
		 * Creates glTF animation entry from AnimationClip object.
		 *
		 * Status:
		 * - Only properties listed in PATH_PROPERTIES may be animated.
		 *
		 * @param {THREE.AnimationClip} clip
		 * @param {THREE.Object3D} root
		 * @return {number}
		 */
M
Mugen87 已提交
1547
		function processAnimation( clip, root ) {
1548 1549 1550 1551 1552 1553 1554

			if ( ! outputJSON.animations ) {

				outputJSON.animations = [];

			}

1555
			clip = THREE.GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
1556 1557

			var tracks = clip.tracks;
1558 1559 1560
			var channels = [];
			var samplers = [];

1561
			for ( var i = 0; i < tracks.length; ++ i ) {
1562

1563
				var track = tracks[ i ];
1564 1565 1566 1567
				var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
				var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
				var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];

1568
				if ( trackBinding.objectName === 'bones' ) {
1569

1570 1571 1572 1573 1574 1575 1576 1577 1578
					if ( trackNode.isSkinnedMesh === true ) {

						trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );

					} else {

						trackNode = undefined;

					}
1579 1580 1581

				}

1582 1583 1584
				if ( ! trackNode || ! trackProperty ) {

					console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
1585
					return null;
1586 1587 1588

				}

D
Don McCurdy 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597
				var inputItemSize = 1;
				var outputItemSize = track.values.length / track.times.length;

				if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {

					outputItemSize /= trackNode.morphTargetInfluences.length;

				}

T
Takahiro 已提交
1598 1599
				var interpolation;

1600 1601
				// @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE

1602
				// Detecting glTF cubic spline interpolant by checking factory method's special property
1603 1604
				// GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
				// valid value from .getInterpolation().
1605
				if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
T
Takahiro 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623

					interpolation = 'CUBICSPLINE';

					// itemSize of CUBICSPLINE keyframe is 9
					// (VEC3 * 3: inTangent, splineVertex, and outTangent)
					// but needs to be stored as VEC3 so dividing by 3 here.
					outputItemSize /= 3;

				} else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {

					interpolation = 'STEP';

				} else {

					interpolation = 'LINEAR';

				}

1624 1625
				samplers.push( {

D
Don McCurdy 已提交
1626 1627
					input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
					output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
T
Takahiro 已提交
1628
					interpolation: interpolation
1629 1630 1631 1632 1633 1634 1635

				} );

				channels.push( {

					sampler: samplers.length - 1,
					target: {
T
Takahiro 已提交
1636
						node: nodeMap.get( trackNode ),
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
						path: trackProperty
					}

				} );

			}

			outputJSON.animations.push( {

				name: clip.name || 'clip_' + outputJSON.animations.length,
				samplers: samplers,
				channels: channels

			} );

			return outputJSON.animations.length - 1;

		}

D
Don McCurdy 已提交
1656 1657
		function processSkin( object ) {

T
Takahiro 已提交
1658
			var node = outputJSON.nodes[ nodeMap.get( object ) ];
D
Don McCurdy 已提交
1659 1660

			var skeleton = object.skeleton;
1661 1662 1663

			if ( skeleton === undefined ) return null;

D
Don McCurdy 已提交
1664 1665
			var rootJoint = object.skeleton.bones[ 0 ];

1666
			if ( rootJoint === undefined ) return null;
D
Don McCurdy 已提交
1667 1668 1669 1670 1671 1672

			var joints = [];
			var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );

			for ( var i = 0; i < skeleton.bones.length; ++ i ) {

T
Takahiro 已提交
1673
				joints.push( nodeMap.get( skeleton.bones[ i ] ) );
D
Don McCurdy 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688

				skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );

			}

			if ( outputJSON.skins === undefined ) {

				outputJSON.skins = [];

			}

			outputJSON.skins.push( {

				inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
				joints: joints,
T
Takahiro 已提交
1689
				skeleton: nodeMap.get( rootJoint )
D
Don McCurdy 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698

			} );

			var skinIndex = node.skin = outputJSON.skins.length - 1;

			return skinIndex;

		}

1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
		function processLight( light ) {

			var lightDef = {};

			if ( light.name ) lightDef.name = light.name;

			lightDef.color = light.color.toArray();

			lightDef.intensity = light.intensity;

			if ( light.isDirectionalLight ) {

				lightDef.type = 'directional';

			} else if ( light.isPointLight ) {

				lightDef.type = 'point';
D
Don McCurdy 已提交
1716
				if ( light.distance > 0 ) lightDef.range = light.distance;
1717 1718 1719 1720

			} else if ( light.isSpotLight ) {

				lightDef.type = 'spot';
D
Don McCurdy 已提交
1721
				if ( light.distance > 0 ) lightDef.range = light.distance;
1722
				lightDef.spot = {};
M
Mugen87 已提交
1723
				lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
				lightDef.spot.outerConeAngle = light.angle;

			}

			if ( light.decay !== undefined && light.decay !== 2 ) {

				console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
					+ 'and expects light.decay=2.' );

			}

			if ( light.target
					&& ( light.target.parent !== light
					 || light.target.position.x !== 0
					 || light.target.position.y !== 0
M
Mugen87 已提交
1739
					 || light.target.position.z !== - 1 ) ) {
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751

				console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
					+ 'make light.target a child of the light with position 0,0,-1.' );

			}

			var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
			lights.push( lightDef );
			return lights.length - 1;

		}

F
Fernando Serrano 已提交
1752 1753 1754 1755 1756
		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
M
Mr.doob 已提交
1757
		function processNode( object ) {
F
Fernando Serrano 已提交
1758

M
Mugen87 已提交
1759
			if ( ! outputJSON.nodes ) {
F
Fernando Serrano 已提交
1760

F
Fernando Serrano 已提交
1761
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
1762

F
Fernando Serrano 已提交
1763 1764
			}

F
Fernando Serrano 已提交
1765 1766 1767
			var gltfNode = {};

			if ( options.trs ) {
F
Fernando Serrano 已提交
1768

F
Fernando Serrano 已提交
1769 1770 1771 1772
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

M
Mugen87 已提交
1773
				if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
1774

F
Fernando Serrano 已提交
1775
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
1776

F
Fernando Serrano 已提交
1777 1778
				}

M
Mugen87 已提交
1779
				if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
F
Fernando Serrano 已提交
1780

D
Don McCurdy 已提交
1781
					gltfNode.translation = position;
F
Fernando Serrano 已提交
1782

F
Fernando Serrano 已提交
1783 1784
				}

M
Mugen87 已提交
1785
				if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
F
Fernando Serrano 已提交
1786

F
Fernando Serrano 已提交
1787
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
1788

F
Fernando Serrano 已提交
1789 1790 1791
				}

			} else {
F
Fernando Serrano 已提交
1792

M
Mr.doob 已提交
1793 1794 1795 1796
				if ( object.matrixAutoUpdate ) {

					object.updateMatrix();

1797 1798
				}

M
Mugen87 已提交
1799
				if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
1800

F
Fernando Serrano 已提交
1801
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
1802

F
Fernando Serrano 已提交
1803
				}
F
Fernando Serrano 已提交
1804

F
Fernando Serrano 已提交
1805 1806
			}

1807
			// We don't export empty strings name because it represents no-name in Three.js.
1808
			if ( object.name !== '' ) {
F
Fernando Serrano 已提交
1809

C
Christopher Cook 已提交
1810
				gltfNode.name = String( object.name );
F
Fernando Serrano 已提交
1811

F
Fernando Serrano 已提交
1812 1813
			}

R
Robert Long 已提交
1814
			serializeUserData( object, gltfNode );
1815

1816
			if ( object.isMesh || object.isLine || object.isPoints ) {
F
Fernando Serrano 已提交
1817

1818 1819
				var mesh = processMesh( object );

1820
				if ( mesh !== null ) {
1821 1822 1823 1824

					gltfNode.mesh = mesh;

				}
F
Fernando Serrano 已提交
1825

1826
			} else if ( object.isCamera ) {
F
Fernando Serrano 已提交
1827

F
Fernando Serrano 已提交
1828
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
1829

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
			} else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {

				if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {

					outputJSON.extensions = outputJSON.extensions || {};
					outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
					extensionsUsed[ 'KHR_lights_punctual' ] = true;

				}

				gltfNode.extensions = gltfNode.extensions || {};
				gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };

			} else if ( object.isLight ) {

1845
				console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
1846 1847
				return null;

F
Fernando Serrano 已提交
1848 1849
			}

1850
			if ( object.isSkinnedMesh ) {
D
Don McCurdy 已提交
1851 1852 1853 1854 1855

				skins.push( object );

			}

F
Fernando Serrano 已提交
1856
			if ( object.children.length > 0 ) {
F
Fernando Serrano 已提交
1857

1858
				var children = [];
F
Fernando Serrano 已提交
1859 1860

				for ( var i = 0, l = object.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
1861

F
Fernando Serrano 已提交
1862
					var child = object.children[ i ];
F
Fernando Serrano 已提交
1863

1864 1865
					if ( child.visible || options.onlyVisible === false ) {

1866 1867
						var node = processNode( child );

1868
						if ( node !== null ) {
1869

1870
							children.push( node );
1871 1872

						}
F
Fernando Serrano 已提交
1873

F
Fernando Serrano 已提交
1874
					}
F
Fernando Serrano 已提交
1875

F
Fernando Serrano 已提交
1876
				}
F
Fernando Serrano 已提交
1877

1878 1879 1880 1881 1882 1883 1884
				if ( children.length > 0 ) {

					gltfNode.children = children;

				}


F
Fernando Serrano 已提交
1885 1886 1887 1888
			}

			outputJSON.nodes.push( gltfNode );

T
Takahiro 已提交
1889 1890
			var nodeIndex = outputJSON.nodes.length - 1;
			nodeMap.set( object, nodeIndex );
1891 1892

			return nodeIndex;
F
Fernando Serrano 已提交
1893

F
Fernando Serrano 已提交
1894 1895 1896
		}

		/**
F
Fernando Serrano 已提交
1897
		 * Process Scene
F
Fernando Serrano 已提交
1898 1899 1900
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
1901

M
Mugen87 已提交
1902
			if ( ! outputJSON.scenes ) {
F
Fernando Serrano 已提交
1903

F
Fernando Serrano 已提交
1904 1905
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
1906

F
Fernando Serrano 已提交
1907 1908
			}

1909
			var gltfScene = {};
F
Fernando Serrano 已提交
1910

1911
			if ( scene.name !== '' ) {
F
Fernando Serrano 已提交
1912

F
Fernando Serrano 已提交
1913
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
1914

F
Fernando Serrano 已提交
1915 1916
			}

F
Fernando Serrano 已提交
1917
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
1918

1919 1920
			var nodes = [];

F
Fernando Serrano 已提交
1921
			for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
1922

F
Fernando Serrano 已提交
1923 1924
				var child = scene.children[ i ];

1925
				if ( child.visible || options.onlyVisible === false ) {
F
Fernando Serrano 已提交
1926

1927 1928
					var node = processNode( child );

1929
					if ( node !== null ) {
1930

1931
						nodes.push( node );
1932 1933

					}
1934 1935 1936

				}

1937
			}
1938

1939
			if ( nodes.length > 0 ) {
F
Fernando Serrano 已提交
1940

1941
				gltfScene.nodes = nodes;
F
Fernando Serrano 已提交
1942

F
Fernando Serrano 已提交
1943
			}
F
Fernando Serrano 已提交
1944

R
Robert Long 已提交
1945 1946
			serializeUserData( scene, gltfScene );

F
Fernando Serrano 已提交
1947 1948
		}

1949 1950 1951 1952
		/**
		 * Creates a THREE.Scene to hold a list of objects and parse it
		 * @param  {Array} objects List of objects to process
		 */
M
Mr.doob 已提交
1953
		function processObjects( objects ) {
1954 1955

			var scene = new THREE.Scene();
1956
			scene.name = 'AuxScene';
1957

M
Mugen87 已提交
1958
			for ( var i = 0; i < objects.length; i ++ ) {
1959

1960 1961 1962
				// We push directly to children instead of calling `add` to prevent
				// modify the .parent and break its original scene and hierarchy
				scene.children.push( objects[ i ] );
1963 1964 1965 1966 1967 1968 1969

			}

			processScene( scene );

		}

1970
		function processInput( input ) {
1971

1972
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
1973

1974
			var objectsWithoutScene = [];
M
Mr.doob 已提交
1975

M
Mugen87 已提交
1976
			for ( var i = 0; i < input.length; i ++ ) {
F
Fernando Serrano 已提交
1977

1978
				if ( input[ i ] instanceof THREE.Scene ) {
1979 1980 1981

					processScene( input[ i ] );

1982
				} else {
1983

1984
					objectsWithoutScene.push( input[ i ] );
1985

1986
				}
F
Fernando Serrano 已提交
1987

F
Fernando Serrano 已提交
1988
			}
F
Fernando Serrano 已提交
1989

1990
			if ( objectsWithoutScene.length > 0 ) {
1991

1992
				processObjects( objectsWithoutScene );
1993 1994

			}
F
Fernando Serrano 已提交
1995

D
Don McCurdy 已提交
1996 1997 1998 1999 2000 2001
			for ( var i = 0; i < skins.length; ++ i ) {

				processSkin( skins[ i ] );

			}

2002 2003 2004 2005 2006 2007
			for ( var i = 0; i < options.animations.length; ++ i ) {

				processAnimation( options.animations[ i ], input[ 0 ] );

			}

F
Fernando Serrano 已提交
2008
		}
F
Fernando Serrano 已提交
2009

D
Don McCurdy 已提交
2010
		processInput( input );
F
Fernando Serrano 已提交
2011

2012
		Promise.all( pending ).then( function () {
F
Fernando Serrano 已提交
2013

2014 2015
			// Merge buffers.
			var blob = new Blob( buffers, { type: 'application/octet-stream' } );
2016

2017 2018 2019 2020
			// Declare extensions.
			var extensionsUsedList = Object.keys( extensionsUsed );
			if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;

2021 2022
			// Update bytelength of the single buffer.
			if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) outputJSON.buffers[ 0 ].byteLength = blob.size;
2023

2024
			if ( options.binary === true ) {
F
Fernando Serrano 已提交
2025

2026
				// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
2027

2028 2029 2030
				var GLB_HEADER_BYTES = 12;
				var GLB_HEADER_MAGIC = 0x46546C67;
				var GLB_VERSION = 2;
2031

2032 2033 2034
				var GLB_CHUNK_PREFIX_BYTES = 8;
				var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
				var GLB_CHUNK_TYPE_BIN = 0x004E4942;
2035

2036 2037 2038
				var reader = new window.FileReader();
				reader.readAsArrayBuffer( blob );
				reader.onloadend = function () {
2039

2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
					// Binary chunk.
					var binaryChunk = getPaddedArrayBuffer( reader.result );
					var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
					binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
					binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );

					// JSON chunk.
					var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
					var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
					jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
					jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );

					// GLB header.
					var header = new ArrayBuffer( GLB_HEADER_BYTES );
					var headerView = new DataView( header );
					headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
					headerView.setUint32( 4, GLB_VERSION, true );
					var totalByteLength = GLB_HEADER_BYTES
						+ jsonChunkPrefix.byteLength + jsonChunk.byteLength
						+ binaryChunkPrefix.byteLength + binaryChunk.byteLength;
					headerView.setUint32( 8, totalByteLength, true );

					var glbBlob = new Blob( [
						header,
						jsonChunkPrefix,
						jsonChunk,
						binaryChunkPrefix,
						binaryChunk
					], { type: 'application/octet-stream' } );

					var glbReader = new window.FileReader();
					glbReader.readAsArrayBuffer( glbBlob );
					glbReader.onloadend = function () {

						onDone( glbReader.result );
2075

2076
					};
2077

2078
				};
F
Fernando Serrano 已提交
2079

2080
			} else {
2081

2082
				if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
2083

2084
					var reader = new window.FileReader();
2085 2086
					reader.readAsDataURL( blob );
					reader.onloadend = function () {
2087

2088 2089 2090
						var base64data = reader.result;
						outputJSON.buffers[ 0 ].uri = base64data;
						onDone( outputJSON );
2091

2092
					};
F
Fernando Serrano 已提交
2093

2094
				} else {
F
Fernando Serrano 已提交
2095

2096
					onDone( outputJSON );
F
Fernando Serrano 已提交
2097

2098
				}
2099

2100
			}
2101

2102
		} );
2103

F
Fernando Serrano 已提交
2104
	}
M
Mr.doob 已提交
2105

D
Don McCurdy 已提交
2106
};
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205

THREE.GLTFExporter.Utils = {

	insertKeyframe: function ( track, time ) {

		var tolerance = 0.001; // 1ms
		var valueSize = track.getValueSize();

		var times = new track.TimeBufferType( track.times.length + 1 );
		var values = new track.ValueBufferType( track.values.length + valueSize );
		var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );

		var index;

		if ( track.times.length === 0 ) {

			times[ 0 ] = time;

			for ( var i = 0; i < valueSize; i ++ ) {

				values[ i ] = 0;

			}

			index = 0;

		} else if ( time < track.times[ 0 ] ) {

			if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;

			times[ 0 ] = time;
			times.set( track.times, 1 );

			values.set( interpolant.evaluate( time ), 0 );
			values.set( track.values, valueSize );

			index = 0;

		} else if ( time > track.times[ track.times.length - 1 ] ) {

			if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {

				return track.times.length - 1;

			}

			times[ times.length - 1 ] = time;
			times.set( track.times, 0 );

			values.set( track.values, 0 );
			values.set( interpolant.evaluate( time ), track.values.length );

			index = times.length - 1;

		} else {

			for ( var i = 0; i < track.times.length; i ++ ) {

				if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;

				if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {

					times.set( track.times.slice( 0, i + 1 ), 0 );
					times[ i + 1 ] = time;
					times.set( track.times.slice( i + 1 ), i + 2 );

					values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
					values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
					values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );

					index = i + 1;

					break;

				}

			}

		}

		track.times = times;
		track.values = values;

		return index;

	},

	mergeMorphTargetTracks: function ( clip, root ) {

		var tracks = [];
		var mergedTracks = {};
		var sourceTracks = clip.tracks;

		for ( var i = 0; i < sourceTracks.length; ++ i ) {

			var sourceTrack = sourceTracks[ i ];
			var sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
			var sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );

2206
			if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
2207

2208
				// Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
				tracks.push( sourceTrack );
				continue;

			}

			if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
				&& sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {

				if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {

					// This should never happen, because glTF morph target animations
					// affect all targets already.
					throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );

				}

				console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );

				sourceTrack = sourceTrack.clone();
A
aardgoose 已提交
2228
				sourceTrack.setInterpolation( THREE.InterpolateLinear );
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

			}

			var targetCount = sourceTrackNode.morphTargetInfluences.length;
			var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];

			if ( targetIndex === undefined ) {

				throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );

			}

			var mergedTrack;

			// If this is the first time we've seen this object, create a new
			// track to store merged keyframe data for each morph target.
			if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {

				mergedTrack = sourceTrack.clone();

				var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );

				for ( var j = 0; j < mergedTrack.times.length; j ++ ) {

					values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];

				}

				mergedTrack.name = '.morphTargetInfluences';
				mergedTrack.values = values;

				mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
				tracks.push( mergedTrack );

				continue;

			}

			var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );

			mergedTrack = mergedTracks[ sourceTrackNode.uuid ];

			// For every existing keyframe of the merged track, write a (possibly
			// interpolated) value from the source track.
			for ( var j = 0; j < mergedTrack.times.length; j ++ ) {

				mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );

			}

			// For every existing keyframe of the source track, write a (possibly
			// new) keyframe to the merged track. Values from the previous loop may
			// be written again, but keyframes are de-duplicated.
			for ( var j = 0; j < sourceTrack.times.length; j ++ ) {

				var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
				mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];

			}

		}

		clip.tracks = tracks;

		return clip;

	}

};