WebGLRenderer.js 81.7 KB
Newer Older
M
Mr.doob 已提交
1 2 3 4 5 6 7 8 9
/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

THREE.WebGLRenderer = function ( parameters ) {

10
	console.log( 'THREE.WebGLRenderer', THREE.REVISION );
M
Mr.doob 已提交
11 12 13 14

	parameters = parameters || {};

	var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
15
	_context = parameters.context !== undefined ? parameters.context : null,
M
Mr.doob 已提交
16

M
Mr.doob 已提交
17 18
	_width = _canvas.width,
	_height = _canvas.height,
19

20 21
	pixelRatio = 1,

22
	_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
23
	_depth = parameters.depth !== undefined ? parameters.depth : true,
M
Mr.doob 已提交
24
	_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
25 26
	_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
	_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
M
Mr.doob 已提交
27 28
	_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,

29 30
	_clearColor = new THREE.Color( 0x000000 ),
	_clearAlpha = 0;
M
Mr.doob 已提交
31

M
Mr.doob 已提交
32
	var lights = [];
M
Mr.doob 已提交
33

O
OpenShift guest 已提交
34
	var opaqueObjects = [];
M
Marius Kintel 已提交
35
	var opaqueObjectsLastIndex = - 1;
36
	var transparentObjects = [];
M
Marius Kintel 已提交
37
	var transparentObjectsLastIndex = - 1;
38

39 40
	var morphInfluences = new Float32Array( 8 );

41

M
Mr.doob 已提交
42 43 44
	var sprites = [];
	var lensFlares = [];

M
Mr.doob 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	// public properties

	this.domElement = _canvas;
	this.context = null;

	// clearing

	this.autoClear = true;
	this.autoClearColor = true;
	this.autoClearDepth = true;
	this.autoClearStencil = true;

	// scene graph

	this.sortObjects = true;

	// physically based shading

63
	this.gammaFactor = 2.0;	// for backwards compatibility
M
Mr.doob 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
	this.gammaInput = false;
	this.gammaOutput = false;

	// morphs

	this.maxMorphTargets = 8;
	this.maxMorphNormals = 4;

	// flags

	this.autoScaleCubemaps = true;

	// internal properties

	var _this = this,

	// internal state cache

	_currentProgram = null,
	_currentFramebuffer = null,
84
	_currentMaterialId = - 1,
85
	_currentGeometryProgram = '',
M
Mr.doob 已提交
86 87 88 89 90 91
	_currentCamera = null,

	_usedTextureUnits = 0,

	_viewportX = 0,
	_viewportY = 0,
92 93
	_viewportWidth = _canvas.width,
	_viewportHeight = _canvas.height,
M
Mr.doob 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	_currentWidth = 0,
	_currentHeight = 0,

	// frustum

	_frustum = new THREE.Frustum(),

	 // camera matrices cache

	_projScreenMatrix = new THREE.Matrix4(),

	_vector3 = new THREE.Vector3(),

	// light arrays cache

	_direction = new THREE.Vector3(),

	_lightsNeedUpdate = true,

	_lights = {

		ambient: [ 0, 0, 0 ],
G
gero3 已提交
116
		directional: { length: 0, colors: [], positions: [] },
M
Mr.doob 已提交
117 118
		point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
		spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
G
gero3 已提交
119
		hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
M
Mr.doob 已提交
120

121 122
	},

M
Mr.doob 已提交
123 124
	// info

125
	_infoMemory = {
126 127

		geometries: 0,
T
tschw 已提交
128
		textures: 0
129 130 131

	},

132
	_infoRender = {
133 134 135 136 137 138

		calls: 0,
		vertices: 0,
		faces: 0,
		points: 0

M
Mr.doob 已提交
139 140
	};

M
Mr.doob 已提交
141
	this.info = {
142

M
Mr.doob 已提交
143 144
		render: _infoRender,
		memory: _infoMemory,
145
		programs: null
M
Mr.doob 已提交
146 147

	};
148

149

M
Mr.doob 已提交
150 151 152 153
	// initialize

	var _gl;

M
Mr.doob 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	try {

		var attributes = {
			alpha: _alpha,
			depth: _depth,
			stencil: _stencil,
			antialias: _antialias,
			premultipliedAlpha: _premultipliedAlpha,
			preserveDrawingBuffer: _preserveDrawingBuffer
		};

		_gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );

		if ( _gl === null ) {

G
gero3 已提交
169
			if ( _canvas.getContext( 'webgl' ) !== null ) {
170 171 172 173 174 175 176 177

				throw 'Error creating WebGL context with your selected attributes.';

			} else {

				throw 'Error creating WebGL context.';

			}
M
Mr.doob 已提交
178 179 180

		}

D
dubejf 已提交
181
		_canvas.addEventListener( 'webglcontextlost', onContextLost, false );
182

M
Mr.doob 已提交
183 184
	} catch ( error ) {

185
		console.error( 'THREE.WebGLRenderer: ' + error );
M
Mr.doob 已提交
186 187 188

	}

189 190
	var extensions = new THREE.WebGLExtensions( _gl );

191 192
	extensions.get( 'OES_texture_float' );
	extensions.get( 'OES_texture_float_linear' );
193 194
	extensions.get( 'OES_texture_half_float' );
	extensions.get( 'OES_texture_half_float_linear' );
195
	extensions.get( 'OES_standard_derivatives' );
B
Ben Adams 已提交
196
	extensions.get( 'ANGLE_instanced_arrays' );
197

198 199
	if ( extensions.get( 'OES_element_index_uint' ) ) {

200
		THREE.BufferGeometry.MaxIndex = 4294967296;
201 202 203

	}

M
Mr.doob 已提交
204
	var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
M
Mr.doob 已提交
205

206 207 208
	var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
	var properties = new THREE.WebGLProperties();
	var objects = new THREE.WebGLObjects( _gl, properties, this.info );
G
gero3 已提交
209
	var programCache = new THREE.WebGLPrograms( this, capabilities );
210

211 212
	this.info.programs = programCache.programs;

213 214
	var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
	var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
215

M
Mr.doob 已提交
216 217
	//

218
	function glClearColor( r, g, b, a ) {
219 220 221

		if ( _premultipliedAlpha === true ) {

222
			r *= a; g *= a; b *= a;
223 224 225

		}

226 227
		_gl.clearColor( r, g, b, a );

228
	}
229

230
	function setDefaultGLState() {
M
Mr.doob 已提交
231

M
Mr.doob 已提交
232
		state.init();
M
Mr.doob 已提交
233 234 235

		_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );

236
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
237

238
	}
239

240
	function resetGLState() {
241 242 243 244

		_currentProgram = null;
		_currentCamera = null;

245
		_currentGeometryProgram = '';
246 247 248 249
		_currentMaterialId = - 1;

		_lightsNeedUpdate = true;

M
Mr.doob 已提交
250 251
		state.reset();

252
	}
M
Mr.doob 已提交
253 254 255 256

	setDefaultGLState();

	this.context = _gl;
M
Mr.doob 已提交
257
	this.capabilities = capabilities;
258
	this.extensions = extensions;
M
Mr.doob 已提交
259
	this.state = state;
M
Mr.doob 已提交
260

M
Mr.doob 已提交
261 262
	// shadow map

M
Mr.doob 已提交
263
	var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
M
Mr.doob 已提交
264

265
	this.shadowMap = shadowMap;
M
Mr.doob 已提交
266

M
Mr.doob 已提交
267

M
Mr.doob 已提交
268 269 270 271 272
	// Plugins

	var spritePlugin = new THREE.SpritePlugin( this, sprites );
	var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );

M
Mr.doob 已提交
273 274 275 276 277 278 279 280
	// API

	this.getContext = function () {

		return _gl;

	};

281 282 283 284 285 286
	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

287 288 289 290 291 292
	this.forceContextLoss = function () {

		extensions.get( 'WEBGL_lose_context' ).loseContext();

	};

293
	this.getMaxAnisotropy = ( function () {
M
Mr.doob 已提交
294

295
		var value;
M
Mr.doob 已提交
296

297
		return function getMaxAnisotropy() {
298

M
Mr.doob 已提交
299
			if ( value !== undefined ) return value;
300

M
Mr.doob 已提交
301
			var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
302

M
Mr.doob 已提交
303
			if ( extension !== null ) {
304

M
Mr.doob 已提交
305
				value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
306

M
Mr.doob 已提交
307 308 309 310 311
			} else {

				value = 0;

			}
312 313 314 315 316 317

			return value;

		}

	} )();
M
Mr.doob 已提交
318 319 320

	this.getPrecision = function () {

G
gero3 已提交
321
		return capabilities.precision;
M
Mr.doob 已提交
322 323 324

	};

325 326 327 328 329 330 331 332
	this.getPixelRatio = function () {

		return pixelRatio;

	};

	this.setPixelRatio = function ( value ) {

333
		if ( value !== undefined ) pixelRatio = value;
334 335 336

	};

337 338 339 340 341 342 343 344 345
	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

346
	this.setSize = function ( width, height, updateStyle ) {
M
Mr.doob 已提交
347

348 349 350
		_width = width;
		_height = height;

351 352
		_canvas.width = width * pixelRatio;
		_canvas.height = height * pixelRatio;
353

354
		if ( updateStyle !== false ) {
355

G
gero3 已提交
356 357
			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';
358

G
gero3 已提交
359
		}
M
Mr.doob 已提交
360

361
		this.setViewport( 0, 0, width, height );
M
Mr.doob 已提交
362 363 364 365 366

	};

	this.setViewport = function ( x, y, width, height ) {

367 368
		_viewportX = x * pixelRatio;
		_viewportY = y * pixelRatio;
M
Mr.doob 已提交
369

370 371
		_viewportWidth = width * pixelRatio;
		_viewportHeight = height * pixelRatio;
M
Mr.doob 已提交
372 373 374 375 376

		_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );

	};

377 378
	this.getViewport = function ( dimensions ) {

379 380
		dimensions.x = _viewportX / pixelRatio;
		dimensions.y = _viewportY / pixelRatio;
381

382 383
		dimensions.z = _viewportWidth / pixelRatio;
		dimensions.w = _viewportHeight / pixelRatio;
384 385 386

	};

M
Mr.doob 已提交
387 388
	this.setScissor = function ( x, y, width, height ) {

389
		_gl.scissor(
390 391 392 393
			x * pixelRatio,
			y * pixelRatio,
			width * pixelRatio,
			height * pixelRatio
394
		);
M
Mr.doob 已提交
395 396 397

	};

398
	this.enableScissorTest = function ( boolean ) {
M
Mr.doob 已提交
399

M
Mr.doob 已提交
400
		state.setScissorTest( boolean );
M
Mr.doob 已提交
401 402 403 404 405

	};

	// Clearing

M
Mr.doob 已提交
406
	this.getClearColor = function () {
M
Mr.doob 已提交
407

M
Mr.doob 已提交
408
		return _clearColor;
M
Mr.doob 已提交
409 410 411

	};

M
Mr.doob 已提交
412
	this.setClearColor = function ( color, alpha ) {
M
Mr.doob 已提交
413

M
Mr.doob 已提交
414
		_clearColor.set( color );
415

M
Mr.doob 已提交
416
		_clearAlpha = alpha !== undefined ? alpha : 1;
M
Mr.doob 已提交
417

418
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
419 420 421

	};

M
Mr.doob 已提交
422
	this.getClearAlpha = function () {
M
Mr.doob 已提交
423

M
Mr.doob 已提交
424
		return _clearAlpha;
M
Mr.doob 已提交
425 426 427

	};

M
Mr.doob 已提交
428
	this.setClearAlpha = function ( alpha ) {
M
Mr.doob 已提交
429

M
Mr.doob 已提交
430
		_clearAlpha = alpha;
M
Mr.doob 已提交
431

432
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
433 434 435 436 437 438 439 440 441 442 443 444

	};

	this.clear = function ( color, depth, stencil ) {

		var bits = 0;

		if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
		if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
		if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;

		_gl.clear( bits );
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

	};

	this.clearColor = function () {

		_gl.clear( _gl.COLOR_BUFFER_BIT );

	};

	this.clearDepth = function () {

		_gl.clear( _gl.DEPTH_BUFFER_BIT );

	};

	this.clearStencil = function () {

		_gl.clear( _gl.STENCIL_BUFFER_BIT );
M
Mr.doob 已提交
463 464 465 466 467 468 469 470 471 472

	};

	this.clearTarget = function ( renderTarget, color, depth, stencil ) {

		this.setRenderTarget( renderTarget );
		this.clear( color, depth, stencil );

	};

M
Mr.doob 已提交
473 474
	// Reset

475
	this.resetGLState = resetGLState;
M
Mr.doob 已提交
476

D
dubejf 已提交
477 478 479 480 481 482
	this.dispose = function() {

		_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );

	};

M
Mr.doob 已提交
483
	// Events
M
Mr.doob 已提交
484

D
dubejf 已提交
485 486 487 488 489 490 491 492 493 494 495
	function onContextLost( event ) {

		event.preventDefault();

		resetGLState();
		setDefaultGLState();

		properties.clear();

	};

496
	function onTextureDispose( event ) {
M
Mr.doob 已提交
497 498 499 500 501 502 503

		var texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

504
		_infoMemory.textures --;
M
Mr.doob 已提交
505 506


507
	}
M
Mr.doob 已提交
508

509
	function onRenderTargetDispose( event ) {
M
Mr.doob 已提交
510 511 512 513 514 515 516

		var renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

517
		_infoMemory.textures --;
M
Mr.doob 已提交
518

519
	}
M
Mr.doob 已提交
520

521
	function onMaterialDispose( event ) {
M
Mr.doob 已提交
522 523 524 525 526 527 528

		var material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

529
	}
M
Mr.doob 已提交
530 531 532

	// Buffer deallocation

533
	function deallocateTexture( texture ) {
M
Mr.doob 已提交
534

535
		var textureProperties = properties.get( texture );
M
Mr.doob 已提交
536

537
		if ( texture.image && textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
538 539 540

			// cube texture

541
			_gl.deleteTexture( textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
542

543 544 545 546
		} else {

			// 2D texture

547
			if ( textureProperties.__webglInit === undefined ) return;
548

549
			_gl.deleteTexture( textureProperties.__webglTexture );
550

M
Mr.doob 已提交
551 552
		}

553
		// remove all webgl properties
554
		properties.delete( texture );
555

556
	}
M
Mr.doob 已提交
557

558
	function deallocateRenderTarget( renderTarget ) {
M
Mr.doob 已提交
559

560
		var renderTargetProperties = properties.get( renderTarget );
561
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
562

563
		if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
M
Mr.doob 已提交
564

565
		_gl.deleteTexture( textureProperties.__webglTexture );
M
Mr.doob 已提交
566

M
Mr.doob 已提交
567 568 569 570
		if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

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

571 572
				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
				_gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
M
Mr.doob 已提交
573 574 575 576 577

			}

		} else {

578 579
			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
			_gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
M
Mr.doob 已提交
580 581 582

		}

583
		properties.delete( renderTarget.texture );
D
Daosheng Mu 已提交
584
		properties.delete( renderTarget );
M
Mr.doob 已提交
585

586
	}
M
Mr.doob 已提交
587

588
	function deallocateMaterial( material ) {
M
Mr.doob 已提交
589

590 591 592 593
		releaseMaterialProgramReference( material );

		properties.delete( material );

594
	}
595 596


597
	function releaseMaterialProgramReference( material ) {
598

599
		var programInfo = properties.get( material ).program;
M
Mr.doob 已提交
600 601 602

		material.program = undefined;

603
		if ( programInfo !== undefined ) {
M
Mr.doob 已提交
604

605
			programCache.releaseProgram( programInfo );
M
Marius Kintel 已提交
606

M
Mr.doob 已提交
607 608
		}

609
	}
M
Mr.doob 已提交
610 611 612 613 614

	// Buffer rendering

	this.renderBufferImmediate = function ( object, program, material ) {

615
		state.initAttributes();
616

617
		var buffers = properties.get( object );
618

619 620 621 622
		if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
		if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
		if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
		if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
M
Mr.doob 已提交
623

624
		var attributes = program.getAttributes();
625

M
Mr.doob 已提交
626 627
		if ( object.hasPositions ) {

628
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
M
Mr.doob 已提交
629
			_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
630

631 632
			state.enableAttribute( attributes.position );
			_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
633 634 635 636 637

		}

		if ( object.hasNormals ) {

638
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
M
Mr.doob 已提交
639

640
			if ( material.type !== 'MeshPhongMaterial' && material.shading === THREE.FlatShading ) {
M
Mr.doob 已提交
641

642
				for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
M
Mr.doob 已提交
643

644
					var array = object.normalArray;
M
Mr.doob 已提交
645

646 647 648
					var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
					var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
					var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
M
Mr.doob 已提交
649

650 651 652
					array[ i + 0 ] = nx;
					array[ i + 1 ] = ny;
					array[ i + 2 ] = nz;
M
Mr.doob 已提交
653

654 655 656
					array[ i + 3 ] = nx;
					array[ i + 4 ] = ny;
					array[ i + 5 ] = nz;
M
Mr.doob 已提交
657

658 659 660
					array[ i + 6 ] = nx;
					array[ i + 7 ] = ny;
					array[ i + 8 ] = nz;
M
Mr.doob 已提交
661 662 663 664 665 666

				}

			}

			_gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
667

668
			state.enableAttribute( attributes.normal );
669

670
			_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
671 672 673 674 675

		}

		if ( object.hasUvs && material.map ) {

676
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
M
Mr.doob 已提交
677
			_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
678

679
			state.enableAttribute( attributes.uv );
680

681
			_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
682 683 684 685 686

		}

		if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {

687
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
M
Mr.doob 已提交
688
			_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
689

690
			state.enableAttribute( attributes.color );
691

692
			_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
693 694 695

		}

696
		state.disableUnusedAttributes();
697

M
Mr.doob 已提交
698 699 700 701 702 703
		_gl.drawArrays( _gl.TRIANGLES, 0, object.count );

		object.count = 0;

	};

704 705
	this.renderBufferDirect = function ( camera, lights, fog, geometry, material, object, group ) {

M
Mr.doob 已提交
706 707 708 709
		setMaterial( material );

		var program = setProgram( camera, lights, fog, material, object );

M
Mr.doob 已提交
710 711
		var updateBuffers = false;
		var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
M
Mr.doob 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

		if ( geometryProgram !== _currentGeometryProgram ) {

			_currentGeometryProgram = geometryProgram;
			updateBuffers = true;

		}

		// morph targets

		var morphTargetInfluences = object.morphTargetInfluences;

		if ( morphTargetInfluences !== undefined ) {

			var activeInfluences = [];

			for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {

				var influence = morphTargetInfluences[ i ];
				activeInfluences.push( [ influence, i ] );

			}

			activeInfluences.sort( numericalSort );

			if ( activeInfluences.length > 8 ) {

				activeInfluences.length = 8;

			}

743 744
			var morphAttributes = geometry.morphAttributes;

M
Mr.doob 已提交
745 746 747 748 749 750 751
			for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {

				var influence = activeInfluences[ i ];
				morphInfluences[ i ] = influence[ 0 ];

				if ( influence[ 0 ] !== 0 ) {

752
					var index = influence[ 1 ];
M
Mr.doob 已提交
753

754 755
					if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
					if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
M
Mr.doob 已提交
756 757 758

				} else {

759 760
					if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
					if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
M
Mr.doob 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

				}

			}

			var uniforms = program.getUniforms();

			if ( uniforms.morphTargetInfluences !== null ) {

				_gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );

			}

			updateBuffers = true;

		}

M
Mr.doob 已提交
778 779
		//

780
		var index = geometry.index;
781 782
		var position = geometry.attributes.position;

783 784
		if ( material.wireframe === true ) {

785
			index = objects.getWireframeAttribute( geometry );
786 787 788

		}

789 790
		var renderer;

791
		if ( index !== null ) {
792

793 794
			renderer = indexedBufferRenderer;
			renderer.setIndex( index );
795

796
		} else {
797

798
			renderer = bufferRenderer;
799

800
		}
M
Mr.doob 已提交
801

802
		if ( updateBuffers ) {
M
Mr.doob 已提交
803

804
			setupVertexAttributes( material, program, geometry );
M
Mr.doob 已提交
805

806
			if ( index !== null ) {
807

808
				_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
809 810 811

			}

812
		}
813

814
		if ( group === null ) {
815

816
			var count;
817

818
			if ( index !== null ) {
819

820
				count = index.array.length;
821

822
			} else {
823

824
				count = position.count;
825

826
			}
827

828 829
			var drawRange = geometry.drawRange;

830
			group = {
831 832
				start: drawRange.start,
				count: Math.min( drawRange.count, count )
833
			};
834 835

		}
836

837
		if ( object instanceof THREE.Mesh ) {
838

839
			if ( material.wireframe === true ) {
840

841 842
				state.setLineWidth( material.wireframeLinewidth * pixelRatio );
				renderer.setMode( _gl.LINES );
843

844
			} else {
845

846
				renderer.setMode( _gl.TRIANGLES );
847

848
			}
849

850
			if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
851

852
				renderer.renderInstances( geometry );
853

854
			} else {
855

856
				renderer.render( group.start, group.count );
857

858
			}
859

860
		} else if ( object instanceof THREE.Line ) {
861

862
			var lineWidth = material.linewidth;
863

864
			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
865

866
			state.setLineWidth( lineWidth * pixelRatio );
867

868
			if ( object instanceof THREE.LineSegments ) {
869

870
				renderer.setMode( _gl.LINES );
871

872
			} else {
873

874
				renderer.setMode( _gl.LINE_STRIP );
875 876

			}
M
Mr.doob 已提交
877

878
			renderer.render( group.start, group.count );
879

880
		} else if ( object instanceof THREE.Points ) {
881 882

			renderer.setMode( _gl.POINTS );
883
			renderer.render( group.start, group.count );
884

M
Mr.doob 已提交
885 886 887 888
		}

	};

889
	function setupVertexAttributes( material, program, geometry, startIndex ) {
M
Mr.doob 已提交
890

M
Mr.doob 已提交
891
		var extension;
B
Ben Adams 已提交
892

M
Mr.doob 已提交
893
		if ( geometry instanceof THREE.InstancedBufferGeometry ) {
B
Ben Adams 已提交
894

M
Mr.doob 已提交
895
			extension = extensions.get( 'ANGLE_instanced_arrays' );
B
Ben Adams 已提交
896

M
Mr.doob 已提交
897
			if ( extension === null ) {
B
Ben Adams 已提交
898

899
				console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
M
Mr.doob 已提交
900
				return;
B
Ben Adams 已提交
901

M
Mr.doob 已提交
902 903 904
			}

		}
B
Ben Adams 已提交
905

906 907
		if ( startIndex === undefined ) startIndex = 0;

908 909
		state.initAttributes();

910
		var geometryAttributes = geometry.attributes;
911

912
		var programAttributes = program.getAttributes();
913

914
		var materialDefaultAttributeValues = material.defaultAttributeValues;
915

916
		for ( var name in programAttributes ) {
917

918
			var programAttribute = programAttributes[ name ];
M
Mr.doob 已提交
919

M
Mr.doob 已提交
920
			if ( programAttribute >= 0 ) {
M
Mr.doob 已提交
921

922
				var geometryAttribute = geometryAttributes[ name ];
923

M
Mr.doob 已提交
924
				if ( geometryAttribute !== undefined ) {
M
Mr.doob 已提交
925

926
					var size = geometryAttribute.itemSize;
G
gero3 已提交
927
					var buffer = objects.getAttributeBuffer( geometryAttribute );
928

B
Ben Adams 已提交
929
					if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
930

M
Mr.doob 已提交
931 932 933 934 935
						var data = geometryAttribute.data;
						var stride = data.stride;
						var offset = geometryAttribute.offset;

						if ( data instanceof THREE.InstancedInterleavedBuffer ) {
M
Mr.doob 已提交
936

937
							state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
B
Ben Adams 已提交
938

M
Mr.doob 已提交
939
							if ( geometry.maxInstancedCount === undefined ) {
940

D
dubejf 已提交
941
								geometry.maxInstancedCount = data.meshPerAttribute * data.count;
B
Ben Adams 已提交
942

M
Mr.doob 已提交
943
							}
B
Ben Adams 已提交
944

945
						} else {
B
Ben Adams 已提交
946

947
							state.enableAttribute( programAttribute );
B
Ben Adams 已提交
948

949
						}
950

951
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
952 953 954
						_gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );

					} else {
B
Ben Adams 已提交
955

M
Mr.doob 已提交
956
						if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
B
Ben Adams 已提交
957

958
							state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
B
Ben Adams 已提交
959

M
Mr.doob 已提交
960
							if ( geometry.maxInstancedCount === undefined ) {
B
Ben Adams 已提交
961

D
dubejf 已提交
962
								geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
B
Ben Adams 已提交
963

M
Mr.doob 已提交
964
							}
B
Ben Adams 已提交
965

966 967 968 969
						} else {

							state.enableAttribute( programAttribute );

M
Mr.doob 已提交
970
						}
B
Ben Adams 已提交
971

972 973 974
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
						_gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32

B
Ben Adams 已提交
975
					}
M
Mr.doob 已提交
976

977 978
				} else if ( materialDefaultAttributeValues !== undefined ) {

T
tschw 已提交
979
					var value = materialDefaultAttributeValues[ name ];
980

981
					if ( value !== undefined ) {
M
Mr.doob 已提交
982

983
						switch ( value.length ) {
M
Mr.doob 已提交
984

985 986 987
							case 2:
								_gl.vertexAttrib2fv( programAttribute, value );
								break;
M
Mr.doob 已提交
988

989 990 991
							case 3:
								_gl.vertexAttrib3fv( programAttribute, value );
								break;
M
Mr.doob 已提交
992

993 994 995
							case 4:
								_gl.vertexAttrib4fv( programAttribute, value );
								break;
996

997 998
							default:
								_gl.vertexAttrib1fv( programAttribute, value );
999 1000

						}
M
Mr.doob 已提交
1001 1002 1003 1004 1005 1006 1007 1008

					}

				}

			}

		}
1009

1010
		state.disableUnusedAttributes();
1011

M
Mr.doob 已提交
1012 1013
	}

M
Mr.doob 已提交
1014 1015
	// Sorting

1016 1017 1018 1019 1020 1021
	function numericalSort ( a, b ) {

		return b[ 0 ] - a[ 0 ];

	}

M
Mr.doob 已提交
1022 1023
	function painterSortStable ( a, b ) {

U
unconed 已提交
1024
		if ( a.object.renderOrder !== b.object.renderOrder ) {
1025

U
unconed 已提交
1026
			return a.object.renderOrder - b.object.renderOrder;
1027

M
Mr.doob 已提交
1028
		} else if ( a.material.id !== b.material.id ) {
M
Mr.doob 已提交
1029

M
Mr.doob 已提交
1030
			return a.material.id - b.material.id;
1031 1032

		} else if ( a.z !== b.z ) {
M
Mr.doob 已提交
1033

M
Mr.doob 已提交
1034
			return a.z - b.z;
M
Mr.doob 已提交
1035 1036 1037

		} else {

1038
			return a.id - b.id;
M
Mr.doob 已提交
1039 1040 1041

		}

1042
	}
M
Mr.doob 已提交
1043

1044 1045
	function reversePainterSortStable ( a, b ) {

U
unconed 已提交
1046
		if ( a.object.renderOrder !== b.object.renderOrder ) {
1047

U
unconed 已提交
1048
			return a.object.renderOrder - b.object.renderOrder;
1049 1050

		} if ( a.z !== b.z ) {
1051

M
Mr.doob 已提交
1052
			return b.z - a.z;
1053 1054 1055 1056 1057 1058 1059

		} else {

			return a.id - b.id;

		}

1060
	}
1061

M
Mr.doob 已提交
1062 1063 1064 1065 1066 1067
	// Rendering

	this.render = function ( scene, camera, renderTarget, forceClear ) {

		if ( camera instanceof THREE.Camera === false ) {

1068
			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
M
Mr.doob 已提交
1069 1070 1071 1072
			return;

		}

M
Mr.doob 已提交
1073
		var fog = scene.fog;
M
Mr.doob 已提交
1074 1075 1076

		// reset caching for this frame

1077
		_currentGeometryProgram = '';
1078
		_currentMaterialId = - 1;
1079
		_currentCamera = null;
M
Mr.doob 已提交
1080 1081 1082 1083
		_lightsNeedUpdate = true;

		// update scene graph

1084
		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
M
Mr.doob 已提交
1085 1086 1087

		// update camera matrices and frustum

1088
		if ( camera.parent === null ) camera.updateMatrixWorld();
M
Mr.doob 已提交
1089 1090 1091 1092 1093 1094

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
		_frustum.setFromMatrix( _projScreenMatrix );

M
Mr.doob 已提交
1095
		lights.length = 0;
1096

M
Marius Kintel 已提交
1097 1098
		opaqueObjectsLastIndex = - 1;
		transparentObjectsLastIndex = - 1;
M
Mr.doob 已提交
1099

M
Mr.doob 已提交
1100 1101 1102
		sprites.length = 0;
		lensFlares.length = 0;

1103
		projectObject( scene );
M
Mr.doob 已提交
1104

1105 1106 1107
		opaqueObjects.length = opaqueObjectsLastIndex + 1;
		transparentObjects.length = transparentObjectsLastIndex + 1;

M
Mr.doob 已提交
1108
		if ( _this.sortObjects === true ) {
1109 1110 1111

			opaqueObjects.sort( painterSortStable );
			transparentObjects.sort( reversePainterSortStable );
M
Mr.doob 已提交
1112

1113 1114
		}

M
Mr.doob 已提交
1115
		//
M
Mr.doob 已提交
1116

1117
		shadowMap.render( scene );
M
Mr.doob 已提交
1118 1119 1120

		//

1121 1122 1123 1124
		_infoRender.calls = 0;
		_infoRender.vertices = 0;
		_infoRender.faces = 0;
		_infoRender.points = 0;
M
Mr.doob 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133

		this.setRenderTarget( renderTarget );

		if ( this.autoClear || forceClear ) {

			this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );

		}

1134
		//
M
Mr.doob 已提交
1135 1136 1137

		if ( scene.overrideMaterial ) {

1138
			var overrideMaterial = scene.overrideMaterial;
M
Mr.doob 已提交
1139

1140 1141
			renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
			renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
1142

M
Mr.doob 已提交
1143 1144 1145 1146
		} else {

			// opaque pass (front-to-back order)

M
Mr.doob 已提交
1147
			state.setBlending( THREE.NoBlending );
1148
			renderObjects( opaqueObjects, camera, lights, fog );
M
Mr.doob 已提交
1149 1150 1151

			// transparent pass (back-to-front order)

1152
			renderObjects( transparentObjects, camera, lights, fog );
M
Mr.doob 已提交
1153 1154 1155 1156 1157

		}

		// custom render plugins (post pass)

M
Mr.doob 已提交
1158 1159
		spritePlugin.render( scene, camera );
		lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
M
Mr.doob 已提交
1160 1161

		// Generate mipmap if we're using any kind of mipmap filtering
M
Marius Kintel 已提交
1162

1163
		if ( renderTarget ) {
M
Marius Kintel 已提交
1164

1165
			var texture = renderTarget.texture;
1166
			var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
M
Marius Kintel 已提交
1167 1168
			if ( texture.generateMipmaps && isTargetPowerOfTwo && texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {

1169
				 updateRenderTargetMipmap( renderTarget );
M
Marius Kintel 已提交
1170

1171
			}
M
Marius Kintel 已提交
1172

M
Mr.doob 已提交
1173 1174 1175 1176
		}

		// Ensure depth buffer writing is enabled so it can be cleared on next render

M
Mr.doob 已提交
1177 1178
		state.setDepthTest( true );
		state.setDepthWrite( true );
1179
		state.setColorWrite( true );
M
Mr.doob 已提交
1180 1181 1182 1183

		// _gl.finish();

	};
M
Mr.doob 已提交
1184

M
Mr.doob 已提交
1185 1186
	function pushRenderItem( object, geometry, material, z, group ) {

1187
		var array, index;
M
Mr.doob 已提交
1188

1189
		// allocate the next position in the appropriate array
M
Mr.doob 已提交
1190 1191 1192

		if ( material.transparent ) {

1193 1194
			array = transparentObjects;
			index = ++ transparentObjectsLastIndex;
M
Mr.doob 已提交
1195 1196 1197

		} else {

1198 1199 1200 1201 1202
			array = opaqueObjects;
			index = ++ opaqueObjectsLastIndex;

		}

1203 1204
		// recycle existing render item or grow the array

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
		var renderItem = array[ index ];

		if ( renderItem !== undefined ) {

			renderItem.id = object.id;
			renderItem.object = object;
			renderItem.geometry = geometry;
			renderItem.material = material;
			renderItem.z = _vector3.z;
			renderItem.group = group;
M
Mr.doob 已提交
1215 1216 1217

		} else {

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
			renderItem = {
				id: object.id,
				object: object,
				geometry: geometry,
				material: material,
				z: _vector3.z,
				group: group
			};

			// assert( index === array.length );
			array.push( renderItem );
M
Mr.doob 已提交
1229 1230 1231 1232 1233

		}

	}

1234
	function projectObject( object ) {
M
Mr.doob 已提交
1235

M
Mr.doob 已提交
1236
		if ( object.visible === false ) return;
M
Mr.doob 已提交
1237

1238
		if ( object instanceof THREE.Light ) {
M
Mr.doob 已提交
1239

1240
			lights.push( object );
M
Mr.doob 已提交
1241

1242
		} else if ( object instanceof THREE.Sprite ) {
M
Mr.doob 已提交
1243

1244
			sprites.push( object );
M
Mr.doob 已提交
1245

1246
		} else if ( object instanceof THREE.LensFlare ) {
M
Mr.doob 已提交
1247

1248
			lensFlares.push( object );
M
Mr.doob 已提交
1249

1250
		} else if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1251

1252 1253 1254 1255 1256 1257 1258 1259
			if ( _this.sortObjects === true ) {

				_vector3.setFromMatrixPosition( object.matrixWorld );
				_vector3.applyProjection( _projScreenMatrix );

			}

			pushRenderItem( object, null, object.material, _vector3.z, null );
1260

1261
		} else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
M
Mr.doob 已提交
1262

1263
			if ( object instanceof THREE.SkinnedMesh ) {
M
Mr.doob 已提交
1264

1265
				object.skeleton.update();
M
Mr.doob 已提交
1266

1267
			}
1268

1269
			if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
1270

1271
				var material = object.material;
1272

1273
				if ( material.visible === true ) {
1274

M
Mr.doob 已提交
1275 1276 1277 1278 1279 1280 1281
					if ( _this.sortObjects === true ) {

						_vector3.setFromMatrixPosition( object.matrixWorld );
						_vector3.applyProjection( _projScreenMatrix );

					}

M
Mr.doob 已提交
1282 1283
					var geometry = objects.update( object );

1284
					if ( material instanceof THREE.MeshFaceMaterial ) {
1285

M
Mr.doob 已提交
1286
						var groups = geometry.groups;
1287
						var materials = material.materials;
1288

M
Mr.doob 已提交
1289
						for ( var i = 0, l = groups.length; i < l; i ++ ) {
1290

M
Mr.doob 已提交
1291 1292
							var group = groups[ i ];
							var groupMaterial = materials[ group.materialIndex ];
1293

M
Mr.doob 已提交
1294
							if ( groupMaterial.visible === true ) {
1295

M
Mr.doob 已提交
1296
								pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
M
Mr.doob 已提交
1297

M
Mr.doob 已提交
1298
							}
M
Mr.doob 已提交
1299

M
Mr.doob 已提交
1300
						}
M
Mr.doob 已提交
1301

1302
					} else {
1303

1304
						pushRenderItem( object, geometry, material, _vector3.z, null );
O
OpenShift guest 已提交
1305

1306
					}
M
Mr.doob 已提交
1307

1308
				}
M
Mr.doob 已提交
1309

1310
			}
M
Mr.doob 已提交
1311

M
Mr.doob 已提交
1312
		}
M
Mr.doob 已提交
1313

M
Mr.doob 已提交
1314
		var children = object.children;
M
Mr.doob 已提交
1315

M
Mr.doob 已提交
1316 1317 1318
		for ( var i = 0, l = children.length; i < l; i ++ ) {

			projectObject( children[ i ] );
M
Mr.doob 已提交
1319

1320
		}
1321

1322
	}
M
Mr.doob 已提交
1323

1324
	function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
M
Mr.doob 已提交
1325

M
Mr.doob 已提交
1326
		for ( var i = 0, l = renderList.length; i < l; i ++ ) {
M
Mr.doob 已提交
1327

1328
			var renderItem = renderList[ i ];
M
Mr.doob 已提交
1329

1330
			var object = renderItem.object;
M
Mr.doob 已提交
1331 1332 1333
			var geometry = renderItem.geometry;
			var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
			var group = renderItem.group;
M
Mr.doob 已提交
1334

1335 1336
			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
M
Mr.doob 已提交
1337

1338
			if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1339

M
Marius Kintel 已提交
1340
				setMaterial( material );
M
Mr.doob 已提交
1341

M
Marius Kintel 已提交
1342
				var program = setProgram( camera, lights, fog, material, object );
M
Mr.doob 已提交
1343

M
Marius Kintel 已提交
1344
				_currentGeometryProgram = '';
M
Mr.doob 已提交
1345

M
Marius Kintel 已提交
1346
				object.render( function ( object ) {
M
Mr.doob 已提交
1347

M
Marius Kintel 已提交
1348
					_this.renderBufferImmediate( object, program, material );
M
Mr.doob 已提交
1349

M
Marius Kintel 已提交
1350
				} );
M
Mr.doob 已提交
1351

1352
			} else {
M
Mr.doob 已提交
1353

1354
				_this.renderBufferDirect( camera, lights, fog, geometry, material, object, group );
M
Mr.doob 已提交
1355

1356
			}
M
Mr.doob 已提交
1357

1358
		}
M
Mr.doob 已提交
1359

1360
	}
G
gero3 已提交
1361

1362
	function initMaterial( material, lights, fog, object ) {
M
Mr.doob 已提交
1363

1364
		var materialProperties = properties.get( material );
G
gero3 已提交
1365 1366

		var parameters = programCache.getParameters( material, lights, fog, object );
G
gero3 已提交
1367
		var code = programCache.getProgramCode( material, parameters );
G
gero3 已提交
1368

1369
		var program = materialProperties.program;
T
tschw 已提交
1370
		var programChange = true;
1371

1372
		if ( program === undefined ) {
B
Ben Adams 已提交
1373

M
Mr.doob 已提交
1374 1375
			// new material
			material.addEventListener( 'dispose', onMaterialDispose );
B
Ben Adams 已提交
1376

1377
		} else if ( program.code !== code ) {
B
Ben Adams 已提交
1378

M
Mr.doob 已提交
1379
			// changed glsl or parameters
1380
			releaseMaterialProgramReference( material );
B
Ben Adams 已提交
1381

G
gero3 已提交
1382
		} else if ( parameters.shaderID !== undefined ) {
B
Ben Adams 已提交
1383

T
tschw 已提交
1384
			// same glsl and uniform list
T
tschw 已提交
1385 1386
			return;

T
tschw 已提交
1387
		} else {
B
Ben Adams 已提交
1388

T
tschw 已提交
1389 1390
			// only rebuild uniform list
			programChange = false;
B
Ben Adams 已提交
1391 1392 1393

		}

1394
		if ( programChange ) {
B
Ben Adams 已提交
1395

1396
			if ( parameters.shaderID ) {
B
Ben Adams 已提交
1397

1398
				var shader = THREE.ShaderLib[ parameters.shaderID ];
B
Ben Adams 已提交
1399

1400 1401 1402 1403 1404 1405
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};
B
Ben Adams 已提交
1406

1407
			} else {
B
Ben Adams 已提交
1408

1409 1410 1411 1412 1413 1414
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};
G
gero3 已提交
1415

1416
			}
G
gero3 已提交
1417

1418
			material.__webglShader = materialProperties.__webglShader;
G
gero3 已提交
1419

1420
			program = programCache.acquireProgram( material, parameters, code );
B
Ben Adams 已提交
1421

1422 1423
			materialProperties.program = program;
			material.program = program;
1424 1425 1426

		}

1427
		var attributes = program.getAttributes();
M
Mr.doob 已提交
1428 1429 1430 1431 1432

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

1433
			for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
M
Mr.doob 已提交
1434

M
Mr.doob 已提交
1435
				if ( attributes[ 'morphTarget' + i ] >= 0 ) {
M
Mr.doob 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

1449
			for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
M
Mr.doob 已提交
1450

M
Mr.doob 已提交
1451
				if ( attributes[ 'morphNormal' + i ] >= 0 ) {
M
Mr.doob 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460

					material.numSupportedMorphNormals ++;

				}

			}

		}

1461
		materialProperties.uniformsList = [];
M
Mr.doob 已提交
1462

1463
		var uniformLocations = materialProperties.program.getUniforms();
M
Mr.doob 已提交
1464

1465
		for ( var u in materialProperties.__webglShader.uniforms ) {
M
Mr.doob 已提交
1466

1467
			var location = uniformLocations[ u ];
1468 1469

			if ( location ) {
G
gero3 已提交
1470

1471
				materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
G
gero3 已提交
1472

1473
			}
M
Mr.doob 已提交
1474 1475 1476

		}

M
Mr.doob 已提交
1477
	}
M
Mr.doob 已提交
1478

1479 1480
	function setMaterial( material ) {

M
Mr.doob 已提交
1481 1482
		setMaterialFaces( material );

1483 1484
		if ( material.transparent === true ) {

M
Mr.doob 已提交
1485
			state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
1486

1487 1488 1489 1490
		} else {

			state.setBlending( THREE.NoBlending );

1491 1492
		}

B
Ben Adams 已提交
1493
		state.setDepthFunc( material.depthFunc );
M
Mr.doob 已提交
1494 1495
		state.setDepthTest( material.depthTest );
		state.setDepthWrite( material.depthWrite );
1496
		state.setColorWrite( material.colorWrite );
M
Mr.doob 已提交
1497
		state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
1498 1499 1500

	}

M
Mr.doob 已提交
1501 1502
	function setMaterialFaces( material ) {

1503
		material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
1504 1505 1506 1507
		state.setFlipSided( material.side === THREE.BackSide );

	}

M
Mr.doob 已提交
1508 1509 1510 1511
	function setProgram( camera, lights, fog, material, object ) {

		_usedTextureUnits = 0;

1512
		var materialProperties = properties.get( material );
1513

1514
		if ( material.needsUpdate || ! materialProperties.program ) {
M
Mr.doob 已提交
1515

1516
			initMaterial( material, lights, fog, object );
M
Mr.doob 已提交
1517 1518 1519 1520
			material.needsUpdate = false;

		}

1521
		var refreshProgram = false;
M
Mr.doob 已提交
1522
		var refreshMaterial = false;
1523
		var refreshLights = false;
M
Mr.doob 已提交
1524

1525
		var program = materialProperties.program,
1526
			p_uniforms = program.getUniforms(),
1527
			m_uniforms = materialProperties.__webglShader.uniforms;
M
Mr.doob 已提交
1528

1529
		if ( program.id !== _currentProgram ) {
M
Mr.doob 已提交
1530

1531 1532
			_gl.useProgram( program.program );
			_currentProgram = program.id;
M
Mr.doob 已提交
1533

1534
			refreshProgram = true;
M
Mr.doob 已提交
1535
			refreshMaterial = true;
1536
			refreshLights = true;
M
Mr.doob 已提交
1537 1538 1539 1540 1541

		}

		if ( material.id !== _currentMaterialId ) {

G
gero3 已提交
1542
			if ( _currentMaterialId === - 1 ) refreshLights = true;
M
Mr.doob 已提交
1543
			_currentMaterialId = material.id;
1544

M
Mr.doob 已提交
1545 1546 1547 1548
			refreshMaterial = true;

		}

1549
		if ( refreshProgram || camera !== _currentCamera ) {
M
Mr.doob 已提交
1550 1551 1552

			_gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );

G
gero3 已提交
1553
			if ( capabilities.logarithmicDepthBuffer ) {
1554

1555
				_gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
1556 1557 1558 1559

			}


M
Mr.doob 已提交
1560 1561
			if ( camera !== _currentCamera ) _currentCamera = camera;

1562 1563 1564 1565 1566 1567 1568
			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

			if ( material instanceof THREE.ShaderMaterial ||
				 material instanceof THREE.MeshPhongMaterial ||
				 material.envMap ) {

1569
				if ( p_uniforms.cameraPosition !== undefined ) {
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

					_vector3.setFromMatrixPosition( camera.matrixWorld );
					_gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );

				}

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1580
				 material instanceof THREE.MeshBasicMaterial ||
1581 1582 1583
				 material instanceof THREE.ShaderMaterial ||
				 material.skinning ) {

1584
				if ( p_uniforms.viewMatrix !== undefined ) {
1585 1586

					_gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
M
Mr.doob 已提交
1587

1588 1589 1590 1591
				}

			}

M
Mr.doob 已提交
1592 1593 1594 1595 1596 1597 1598 1599
		}

		// skinning uniforms must be set even if material didn't change
		// auto-setting of texture unit for bone texture must go before other textures
		// not sure why, but otherwise weird things happen

		if ( material.skinning ) {

1600
			if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
1601 1602 1603 1604 1605

				_gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );

			}

1606
			if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
1607 1608 1609 1610 1611

				_gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );

			}

1612
			if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
M
Mr.doob 已提交
1613

1614
				if ( p_uniforms.boneTexture !== undefined ) {
M
Mr.doob 已提交
1615 1616 1617 1618

					var textureUnit = getTextureUnit();

					_gl.uniform1i( p_uniforms.boneTexture, textureUnit );
1619
					_this.setTexture( object.skeleton.boneTexture, textureUnit );
M
Mr.doob 已提交
1620 1621 1622

				}

1623
				if ( p_uniforms.boneTextureWidth !== undefined ) {
1624

1625
					_gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
1626 1627 1628

				}

1629
				if ( p_uniforms.boneTextureHeight !== undefined ) {
1630

1631
					_gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
1632 1633 1634

				}

1635
			} else if ( object.skeleton && object.skeleton.boneMatrices ) {
M
Mr.doob 已提交
1636

1637
				if ( p_uniforms.boneGlobalMatrices !== undefined ) {
M
Mr.doob 已提交
1638

1639
					_gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
M
Mr.doob 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662

				}

			}

		}

		if ( refreshMaterial ) {

			// refresh uniforms common to several materials

			if ( fog && material.fog ) {

				refreshUniformsFog( m_uniforms, fog );

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
				 material.lights ) {

				if ( _lightsNeedUpdate ) {

1663
					refreshLights = true;
T
tschw 已提交
1664
					setupLights( lights, camera );
M
Mr.doob 已提交
1665
					_lightsNeedUpdate = false;
G
gero3 已提交
1666

M
Mr.doob 已提交
1667 1668
				}

1669
				if ( refreshLights ) {
G
gero3 已提交
1670

1671
					refreshUniformsLights( m_uniforms, _lights );
1672
					markUniformsLightsNeedsUpdate( m_uniforms, true );
G
gero3 已提交
1673

1674
				} else {
G
gero3 已提交
1675

1676
					markUniformsLightsNeedsUpdate( m_uniforms, false );
G
gero3 已提交
1677

1678
				}
M
Mr.doob 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700

			}

			if ( material instanceof THREE.MeshBasicMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
				 material instanceof THREE.MeshPhongMaterial ) {

				refreshUniformsCommon( m_uniforms, material );

			}

			// refresh single material specific uniforms

			if ( material instanceof THREE.LineBasicMaterial ) {

				refreshUniformsLine( m_uniforms, material );

			} else if ( material instanceof THREE.LineDashedMaterial ) {

				refreshUniformsLine( m_uniforms, material );
				refreshUniformsDash( m_uniforms, material );

1701
			} else if ( material instanceof THREE.PointsMaterial ) {
M
Mr.doob 已提交
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

				refreshUniformsParticle( m_uniforms, material );

			} else if ( material instanceof THREE.MeshPhongMaterial ) {

				refreshUniformsPhong( m_uniforms, material );

			} else if ( material instanceof THREE.MeshDepthMaterial ) {

				m_uniforms.mNear.value = camera.near;
				m_uniforms.mFar.value = camera.far;
				m_uniforms.opacity.value = material.opacity;

			} else if ( material instanceof THREE.MeshNormalMaterial ) {

				m_uniforms.opacity.value = material.opacity;

			}

			if ( object.receiveShadow && ! material._shadowPass ) {

1723
				refreshUniformsShadow( m_uniforms, lights, camera );
M
Mr.doob 已提交
1724 1725 1726 1727 1728

			}

			// load common uniforms

1729
			loadUniformsGeneric( materialProperties.uniformsList );
M
Mr.doob 已提交
1730 1731 1732 1733 1734

		}

		loadUniformsMatrices( p_uniforms, object );

1735
		if ( p_uniforms.modelMatrix !== undefined ) {
M
Mr.doob 已提交
1736 1737

			_gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
M
Mr.doob 已提交
1738

M
Mr.doob 已提交
1739 1740 1741 1742
		}

		return program;

M
Mr.doob 已提交
1743
	}
M
Mr.doob 已提交
1744 1745 1746 1747 1748 1749 1750

	// Uniforms (refresh uniforms objects)

	function refreshUniformsCommon ( uniforms, material ) {

		uniforms.opacity.value = material.opacity;

1751
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
1752

1753
		if ( material.emissive ) {
M
Mr.doob 已提交
1754

1755
			uniforms.emissive.value = material.emissive;
M
Mr.doob 已提交
1756 1757 1758

		}

1759 1760 1761
		uniforms.map.value = material.map;
		uniforms.specularMap.value = material.specularMap;
		uniforms.alphaMap.value = material.alphaMap;
M
Mr.doob 已提交
1762

1763
		if ( material.aoMap ) {
1764

1765 1766
			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;
1767 1768 1769

		}

M
Mr.doob 已提交
1770
		// uv repeat and offset setting priorities
M
Mr.doob 已提交
1771 1772 1773 1774 1775
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
1776
		// 6. emissive map
M
Mr.doob 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787

		var uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

1788 1789 1790 1791
		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

M
Mr.doob 已提交
1792 1793 1794 1795 1796 1797 1798 1799
		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

1800 1801 1802 1803
		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

1804 1805 1806 1807
		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

M
Mr.doob 已提交
1808 1809 1810 1811
		}

		if ( uvScaleMap !== undefined ) {

1812
			if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) uvScaleMap = uvScaleMap.texture;
M
Mr.doob 已提交
1813 1814 1815 1816 1817 1818 1819 1820
			var offset = uvScaleMap.offset;
			var repeat = uvScaleMap.repeat;

			uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

		}

		uniforms.envMap.value = material.envMap;
1821
		uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
M
Mr.doob 已提交
1822

1823
		uniforms.reflectivity.value = material.reflectivity;
M
Mr.doob 已提交
1824 1825
		uniforms.refractionRatio.value = material.refractionRatio;

M
Mr.doob 已提交
1826
	}
M
Mr.doob 已提交
1827 1828 1829 1830 1831 1832

	function refreshUniformsLine ( uniforms, material ) {

		uniforms.diffuse.value = material.color;
		uniforms.opacity.value = material.opacity;

M
Mr.doob 已提交
1833
	}
M
Mr.doob 已提交
1834 1835 1836 1837 1838 1839 1840

	function refreshUniformsDash ( uniforms, material ) {

		uniforms.dashSize.value = material.dashSize;
		uniforms.totalSize.value = material.dashSize + material.gapSize;
		uniforms.scale.value = material.scale;

M
Mr.doob 已提交
1841
	}
M
Mr.doob 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851

	function refreshUniformsParticle ( uniforms, material ) {

		uniforms.psColor.value = material.color;
		uniforms.opacity.value = material.opacity;
		uniforms.size.value = material.size;
		uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.

		uniforms.map.value = material.map;

1852 1853 1854 1855 1856 1857 1858 1859 1860
		if ( material.map !== null ) {

			var offset = material.map.offset;
			var repeat = material.map.repeat;

			uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

		}

M
Mr.doob 已提交
1861
	}
M
Mr.doob 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877

	function refreshUniformsFog ( uniforms, fog ) {

		uniforms.fogColor.value = fog.color;

		if ( fog instanceof THREE.Fog ) {

			uniforms.fogNear.value = fog.near;
			uniforms.fogFar.value = fog.far;

		} else if ( fog instanceof THREE.FogExp2 ) {

			uniforms.fogDensity.value = fog.density;

		}

M
Mr.doob 已提交
1878
	}
M
Mr.doob 已提交
1879 1880 1881

	function refreshUniformsPhong ( uniforms, material ) {

1882
		uniforms.specular.value = material.specular;
M
Mr.doob 已提交
1883 1884
		uniforms.shininess.value = material.shininess;

1885 1886 1887 1888
		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;
M
Mr.doob 已提交
1889

1890
		}
1891

1892
		if ( material.emissiveMap ) {
1893

1894
			uniforms.emissiveMap.value = material.emissiveMap;
1895

1896
		}
M
Mr.doob 已提交
1897

1898 1899 1900 1901
		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
M
Mr.doob 已提交
1902

1903
		}
M
Mr.doob 已提交
1904

1905 1906 1907 1908 1909 1910
		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );

		}
M
Mr.doob 已提交
1911

1912 1913 1914 1915 1916
		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;
1917

1918
		}
1919 1920 1921

	}

M
Mr.doob 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
	function refreshUniformsLights ( uniforms, lights ) {

		uniforms.ambientLightColor.value = lights.ambient;

		uniforms.directionalLightColor.value = lights.directional.colors;
		uniforms.directionalLightDirection.value = lights.directional.positions;

		uniforms.pointLightColor.value = lights.point.colors;
		uniforms.pointLightPosition.value = lights.point.positions;
		uniforms.pointLightDistance.value = lights.point.distances;
M
Mr.doob 已提交
1932
		uniforms.pointLightDecay.value = lights.point.decays;
M
Mr.doob 已提交
1933 1934 1935 1936 1937 1938 1939

		uniforms.spotLightColor.value = lights.spot.colors;
		uniforms.spotLightPosition.value = lights.spot.positions;
		uniforms.spotLightDistance.value = lights.spot.distances;
		uniforms.spotLightDirection.value = lights.spot.directions;
		uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
		uniforms.spotLightExponent.value = lights.spot.exponents;
M
Mr.doob 已提交
1940
		uniforms.spotLightDecay.value = lights.spot.decays;
M
Mr.doob 已提交
1941 1942 1943 1944 1945

		uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
		uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
		uniforms.hemisphereLightDirection.value = lights.hemi.positions;

M
Mr.doob 已提交
1946
	}
M
Mr.doob 已提交
1947

1948 1949
	// If uniforms are marked as clean, they don't need to be loaded to the GPU.

M
Mr.doob 已提交
1950
	function markUniformsLightsNeedsUpdate ( uniforms, value ) {
1951

M
Mr.doob 已提交
1952
		uniforms.ambientLightColor.needsUpdate = value;
1953

M
Mr.doob 已提交
1954 1955
		uniforms.directionalLightColor.needsUpdate = value;
		uniforms.directionalLightDirection.needsUpdate = value;
1956

M
Mr.doob 已提交
1957 1958 1959 1960
		uniforms.pointLightColor.needsUpdate = value;
		uniforms.pointLightPosition.needsUpdate = value;
		uniforms.pointLightDistance.needsUpdate = value;
		uniforms.pointLightDecay.needsUpdate = value;
1961

M
Mr.doob 已提交
1962 1963 1964 1965 1966 1967 1968
		uniforms.spotLightColor.needsUpdate = value;
		uniforms.spotLightPosition.needsUpdate = value;
		uniforms.spotLightDistance.needsUpdate = value;
		uniforms.spotLightDirection.needsUpdate = value;
		uniforms.spotLightAngleCos.needsUpdate = value;
		uniforms.spotLightExponent.needsUpdate = value;
		uniforms.spotLightDecay.needsUpdate = value;
1969

M
Mr.doob 已提交
1970 1971 1972
		uniforms.hemisphereLightSkyColor.needsUpdate = value;
		uniforms.hemisphereLightGroundColor.needsUpdate = value;
		uniforms.hemisphereLightDirection.needsUpdate = value;
1973

M
Mr.doob 已提交
1974
	}
1975

1976
	function refreshUniformsShadow ( uniforms, lights, camera ) {
M
Mr.doob 已提交
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

		if ( uniforms.shadowMatrix ) {

			var j = 0;

			for ( var i = 0, il = lights.length; i < il; i ++ ) {

				var light = lights[ i ];

				if ( ! light.castShadow ) continue;

1988
				if ( light instanceof THREE.PointLight || light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) {
1989

1990
					if ( light instanceof THREE.PointLight ) {
1991 1992

						// for point lights we set the sign of the shadowDarkness uniform to be negative
1993
						uniforms.shadowDarkness.value[ j ] = - light.shadowDarkness;
1994

1995
					} else {
M
Marius Kintel 已提交
1996

1997
						uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
M
Mark Kellogg 已提交
1998

1999
					}
M
Mr.doob 已提交
2000

2001
					uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
2002
					uniforms.shadowMap.value[ j ] =  light.shadowMap;
M
Mr.doob 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
					uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
					uniforms.shadowBias.value[ j ] = light.shadowBias;

					j ++;

				}

			}

		}

M
Mr.doob 已提交
2014
	}
M
Mr.doob 已提交
2015 2016 2017 2018 2019

	// Uniforms (load to GPU)

	function loadUniformsMatrices ( uniforms, object ) {

2020
		_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
M
Mr.doob 已提交
2021 2022 2023

		if ( uniforms.normalMatrix ) {

2024
			_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
M
Mr.doob 已提交
2025 2026 2027

		}

M
Mr.doob 已提交
2028
	}
M
Mr.doob 已提交
2029 2030 2031 2032 2033

	function getTextureUnit() {

		var textureUnit = _usedTextureUnits;

G
gero3 已提交
2034
		if ( textureUnit >= capabilities.maxTextures ) {
M
Mr.doob 已提交
2035

G
gero3 已提交
2036
			console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
M
Mr.doob 已提交
2037 2038 2039 2040 2041 2042 2043

		}

		_usedTextureUnits += 1;

		return textureUnit;

M
Mr.doob 已提交
2044
	}
M
Mr.doob 已提交
2045

2046
	function loadUniformsGeneric ( uniforms ) {
M
Mr.doob 已提交
2047

M
Mr.doob 已提交
2048
		var texture, textureUnit;
M
Mr.doob 已提交
2049

M
Mr.doob 已提交
2050 2051 2052
		for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {

			var uniform = uniforms[ j ][ 0 ];
M
Mr.doob 已提交
2053

2054 2055
			// needsUpdate property is not added to all uniforms.
			if ( uniform.needsUpdate === false ) continue;
2056

M
Mr.doob 已提交
2057 2058
			var type = uniform.type;
			var value = uniform.value;
2059
			var location = uniforms[ j ][ 1 ];
M
Mr.doob 已提交
2060

2061
			switch ( type ) {
M
Mr.doob 已提交
2062

2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
				case '1i':
					_gl.uniform1i( location, value );
					break;

				case '1f':
					_gl.uniform1f( location, value );
					break;

				case '2f':
					_gl.uniform2f( location, value[ 0 ], value[ 1 ] );
					break;

				case '3f':
					_gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
					break;

				case '4f':
					_gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
					break;

				case '1iv':
					_gl.uniform1iv( location, value );
					break;

				case '3iv':
					_gl.uniform3iv( location, value );
					break;

				case '1fv':
					_gl.uniform1fv( location, value );
					break;

				case '2fv':
					_gl.uniform2fv( location, value );
					break;

				case '3fv':
					_gl.uniform3fv( location, value );
					break;

				case '4fv':
					_gl.uniform4fv( location, value );
					break;

				case 'Matrix3fv':
					_gl.uniformMatrix3fv( location, false, value );
					break;

				case 'Matrix4fv':
					_gl.uniformMatrix4fv( location, false, value );
					break;

				//

M
Mr.doob 已提交
2117
				case 'i':
M
Mr.doob 已提交
2118

2119 2120
					// single integer
					_gl.uniform1i( location, value );
M
Mr.doob 已提交
2121

2122
					break;
M
Mr.doob 已提交
2123

2124
				case 'f':
M
Mr.doob 已提交
2125

2126 2127
					// single float
					_gl.uniform1f( location, value );
M
Mr.doob 已提交
2128

2129
					break;
M
Mr.doob 已提交
2130

2131
				case 'v2':
M
Mr.doob 已提交
2132

2133 2134
					// single THREE.Vector2
					_gl.uniform2f( location, value.x, value.y );
M
Mr.doob 已提交
2135

2136
					break;
M
Mr.doob 已提交
2137

2138
				case 'v3':
M
Mr.doob 已提交
2139

2140 2141
					// single THREE.Vector3
					_gl.uniform3f( location, value.x, value.y, value.z );
M
Mr.doob 已提交
2142

2143
					break;
M
Mr.doob 已提交
2144

M
Mr.doob 已提交
2145
				case 'v4':
M
Mr.doob 已提交
2146

2147 2148
					// single THREE.Vector4
					_gl.uniform4f( location, value.x, value.y, value.z, value.w );
M
Mr.doob 已提交
2149

2150
					break;
M
Mr.doob 已提交
2151

2152
				case 'c':
M
Mr.doob 已提交
2153

2154 2155
					// single THREE.Color
					_gl.uniform3f( location, value.r, value.g, value.b );
M
Mr.doob 已提交
2156

2157
					break;
M
Mr.doob 已提交
2158

2159
				case 'iv1':
M
Mr.doob 已提交
2160

2161 2162
					// flat array of integers (JS or typed array)
					_gl.uniform1iv( location, value );
M
Mr.doob 已提交
2163

2164
					break;
M
Mr.doob 已提交
2165

2166
				case 'iv':
M
Mr.doob 已提交
2167

2168 2169
					// flat array of integers with 3 x N size (JS or typed array)
					_gl.uniform3iv( location, value );
M
Mr.doob 已提交
2170

2171
					break;
M
Mr.doob 已提交
2172

2173
				case 'fv1':
M
Mr.doob 已提交
2174

2175 2176
					// flat array of floats (JS or typed array)
					_gl.uniform1fv( location, value );
M
Mr.doob 已提交
2177

2178
					break;
M
Mr.doob 已提交
2179

2180
				case 'fv':
M
Mr.doob 已提交
2181

2182 2183
					// flat array of floats with 3 x N size (JS or typed array)
					_gl.uniform3fv( location, value );
M
Mr.doob 已提交
2184

2185
					break;
M
Mr.doob 已提交
2186

2187
				case 'v2v':
M
Mr.doob 已提交
2188

2189
					// array of THREE.Vector2
M
Mr.doob 已提交
2190

2191
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2192

2193
						uniform._array = new Float32Array( 2 * value.length );
M
Mr.doob 已提交
2194

2195
					}
M
Mr.doob 已提交
2196

M
Mr.doob 已提交
2197
					for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
M
Mr.doob 已提交
2198

M
Mr.doob 已提交
2199 2200
						uniform._array[ i2 + 0 ] = value[ i ].x;
						uniform._array[ i2 + 1 ] = value[ i ].y;
M
Mr.doob 已提交
2201

2202
					}
M
Mr.doob 已提交
2203

2204
					_gl.uniform2fv( location, uniform._array );
M
Mr.doob 已提交
2205

2206
					break;
M
Mr.doob 已提交
2207

2208
				case 'v3v':
M
Mr.doob 已提交
2209

2210
					// array of THREE.Vector3
M
Mr.doob 已提交
2211

2212
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2213

2214
						uniform._array = new Float32Array( 3 * value.length );
M
Mr.doob 已提交
2215

2216
					}
M
Mr.doob 已提交
2217

M
Mr.doob 已提交
2218
					for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
R
Ryan Tsao 已提交
2219

M
Mr.doob 已提交
2220 2221 2222
						uniform._array[ i3 + 0 ] = value[ i ].x;
						uniform._array[ i3 + 1 ] = value[ i ].y;
						uniform._array[ i3 + 2 ] = value[ i ].z;
R
Ryan Tsao 已提交
2223

2224
					}
R
Ryan Tsao 已提交
2225

2226
					_gl.uniform3fv( location, uniform._array );
R
Ryan Tsao 已提交
2227

2228
					break;
R
Ryan Tsao 已提交
2229

2230
				case 'v4v':
R
Ryan Tsao 已提交
2231

2232
					// array of THREE.Vector4
R
Ryan Tsao 已提交
2233

2234
					if ( uniform._array === undefined ) {
R
Ryan Tsao 已提交
2235

2236
						uniform._array = new Float32Array( 4 * value.length );
R
Ryan Tsao 已提交
2237

2238
					}
M
Mr.doob 已提交
2239

M
Mr.doob 已提交
2240
					for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
M
Mr.doob 已提交
2241

M
Mr.doob 已提交
2242 2243 2244 2245
						uniform._array[ i4 + 0 ] = value[ i ].x;
						uniform._array[ i4 + 1 ] = value[ i ].y;
						uniform._array[ i4 + 2 ] = value[ i ].z;
						uniform._array[ i4 + 3 ] = value[ i ].w;
M
Mr.doob 已提交
2246

2247
					}
M
Mr.doob 已提交
2248

2249
					_gl.uniform4fv( location, uniform._array );
M
Mr.doob 已提交
2250

2251
					break;
M
Mr.doob 已提交
2252

2253
				case 'm3':
M
Mr.doob 已提交
2254

2255 2256
					// single THREE.Matrix3
					_gl.uniformMatrix3fv( location, false, value.elements );
M
Mr.doob 已提交
2257

2258
					break;
M
Mr.doob 已提交
2259

2260
				case 'm3v':
M
Mr.doob 已提交
2261

2262
					// array of THREE.Matrix3
M
Mr.doob 已提交
2263

2264
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2265

2266
						uniform._array = new Float32Array( 9 * value.length );
M
Mr.doob 已提交
2267

2268
					}
M
Mr.doob 已提交
2269

2270
					for ( var i = 0, il = value.length; i < il; i ++ ) {
M
Mr.doob 已提交
2271

2272
						value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
M
Mr.doob 已提交
2273

2274
					}
M
Mr.doob 已提交
2275

2276
					_gl.uniformMatrix3fv( location, false, uniform._array );
M
Mr.doob 已提交
2277

2278
					break;
M
Mr.doob 已提交
2279

2280
				case 'm4':
M
Mr.doob 已提交
2281

2282 2283
					// single THREE.Matrix4
					_gl.uniformMatrix4fv( location, false, value.elements );
M
Mr.doob 已提交
2284

2285
					break;
M
Mr.doob 已提交
2286

2287
				case 'm4v':
M
Mr.doob 已提交
2288

2289
					// array of THREE.Matrix4
M
Mr.doob 已提交
2290

2291
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2292

2293
						uniform._array = new Float32Array( 16 * value.length );
M
Mr.doob 已提交
2294

2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
					}

					for ( var i = 0, il = value.length; i < il; i ++ ) {

						value[ i ].flattenToArrayOffset( uniform._array, i * 16 );

					}

					_gl.uniformMatrix4fv( location, false, uniform._array );

					break;
M
Mr.doob 已提交
2306

2307
				case 't':
M
Mr.doob 已提交
2308

2309
					// single THREE.Texture (2d or cube)
M
Mr.doob 已提交
2310

2311 2312 2313 2314
					texture = value;
					textureUnit = getTextureUnit();

					_gl.uniform1i( location, textureUnit );
M
Mr.doob 已提交
2315

2316
					if ( ! texture ) continue;
M
Mr.doob 已提交
2317

2318
					if ( texture instanceof THREE.CubeTexture ||
G
gero3 已提交
2319 2320 2321
						 ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

						// CompressedTexture can have Array in image :/
M
Mr.doob 已提交
2322

2323
						setCubeTexture( texture, textureUnit );
M
Mr.doob 已提交
2324

2325 2326
					} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {

2327 2328 2329 2330 2331
						setCubeTextureDynamic( texture.texture, textureUnit );

					} else if ( texture instanceof THREE.WebGLRenderTarget ) {

						_this.setTexture( texture.texture, textureUnit );
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342

					} else {

						_this.setTexture( texture, textureUnit );

					}

					break;

				case 'tv':

2343
					// array of THREE.Texture (2d or cube)
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364

					if ( uniform._array === undefined ) {

						uniform._array = [];

					}

					for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {

						uniform._array[ i ] = getTextureUnit();

					}

					_gl.uniform1iv( location, uniform._array );

					for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {

						texture = uniform.value[ i ];
						textureUnit = uniform._array[ i ];

						if ( ! texture ) continue;
2365

2366
						if ( texture instanceof THREE.CubeTexture ||
2367 2368 2369
						   ( texture.image instanceof Array && texture.image.length === 6 ) ) {

							// CompressedTexture can have Array in image :/
2370

2371 2372
							setCubeTexture( texture, textureUnit );

2373 2374 2375 2376
						} else if ( texture instanceof THREE.WebGLRenderTarget ) {

							_this.setTexture( texture.texture, textureUnit );

2377 2378
						} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {

2379
							setCubeTextureDynamic( texture.texture, textureUnit );
2380 2381 2382 2383 2384 2385

						} else {

							_this.setTexture( texture, textureUnit );

						}
2386 2387 2388 2389 2390 2391

					}

					break;

				default:
2392

2393
					console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
2394

M
Mr.doob 已提交
2395 2396 2397 2398
			}

		}

M
Mr.doob 已提交
2399
	}
M
Mr.doob 已提交
2400 2401 2402

	function setColorLinear( array, offset, color, intensity ) {

M
Mr.doob 已提交
2403
		array[ offset + 0 ] = color.r * intensity;
M
Mr.doob 已提交
2404 2405 2406
		array[ offset + 1 ] = color.g * intensity;
		array[ offset + 2 ] = color.b * intensity;

M
Mr.doob 已提交
2407
	}
M
Mr.doob 已提交
2408

T
tschw 已提交
2409
	function setupLights ( lights, camera ) {
M
Mr.doob 已提交
2410

B
brason 已提交
2411
		var l, ll, light,
M
Mr.doob 已提交
2412 2413
		r = 0, g = 0, b = 0,
		color, skyColor, groundColor,
B
brason 已提交
2414
		intensity,
M
Mr.doob 已提交
2415 2416 2417 2418
		distance,

		zlights = _lights,

T
tschw 已提交
2419 2420
		viewMatrix = camera.matrixWorldInverse,

M
Mr.doob 已提交
2421 2422 2423 2424 2425 2426
		dirColors = zlights.directional.colors,
		dirPositions = zlights.directional.positions,

		pointColors = zlights.point.colors,
		pointPositions = zlights.point.positions,
		pointDistances = zlights.point.distances,
M
Mr.doob 已提交
2427
		pointDecays = zlights.point.decays,
M
Mr.doob 已提交
2428 2429 2430 2431 2432 2433 2434

		spotColors = zlights.spot.colors,
		spotPositions = zlights.spot.positions,
		spotDistances = zlights.spot.distances,
		spotDirections = zlights.spot.directions,
		spotAnglesCos = zlights.spot.anglesCos,
		spotExponents = zlights.spot.exponents,
M
Mr.doob 已提交
2435
		spotDecays = zlights.spot.decays,
M
Mr.doob 已提交
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469

		hemiSkyColors = zlights.hemi.skyColors,
		hemiGroundColors = zlights.hemi.groundColors,
		hemiPositions = zlights.hemi.positions,

		dirLength = 0,
		pointLength = 0,
		spotLength = 0,
		hemiLength = 0,

		dirCount = 0,
		pointCount = 0,
		spotCount = 0,
		hemiCount = 0,

		dirOffset = 0,
		pointOffset = 0,
		spotOffset = 0,
		hemiOffset = 0;

		for ( l = 0, ll = lights.length; l < ll; l ++ ) {

			light = lights[ l ];

			if ( light.onlyShadow ) continue;

			color = light.color;
			intensity = light.intensity;
			distance = light.distance;

			if ( light instanceof THREE.AmbientLight ) {

				if ( ! light.visible ) continue;

2470 2471 2472
				r += color.r;
				g += color.g;
				b += color.b;
M
Mr.doob 已提交
2473 2474 2475 2476 2477 2478 2479

			} else if ( light instanceof THREE.DirectionalLight ) {

				dirCount += 1;

				if ( ! light.visible ) continue;

2480 2481
				_direction.setFromMatrixPosition( light.matrixWorld );
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
M
Mr.doob 已提交
2482
				_direction.sub( _vector3 );
T
tschw 已提交
2483
				_direction.transformDirection( viewMatrix );
M
Mr.doob 已提交
2484 2485 2486

				dirOffset = dirLength * 3;

M
Mr.doob 已提交
2487
				dirPositions[ dirOffset + 0 ] = _direction.x;
M
Mr.doob 已提交
2488 2489 2490
				dirPositions[ dirOffset + 1 ] = _direction.y;
				dirPositions[ dirOffset + 2 ] = _direction.z;

2491
				setColorLinear( dirColors, dirOffset, color, intensity );
M
Mr.doob 已提交
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502

				dirLength += 1;

			} else if ( light instanceof THREE.PointLight ) {

				pointCount += 1;

				if ( ! light.visible ) continue;

				pointOffset = pointLength * 3;

2503
				setColorLinear( pointColors, pointOffset, color, intensity );
M
Mr.doob 已提交
2504

2505
				_vector3.setFromMatrixPosition( light.matrixWorld );
T
tschw 已提交
2506
				_vector3.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2507

M
Mr.doob 已提交
2508
				pointPositions[ pointOffset + 0 ] = _vector3.x;
M
Mr.doob 已提交
2509 2510 2511
				pointPositions[ pointOffset + 1 ] = _vector3.y;
				pointPositions[ pointOffset + 2 ] = _vector3.z;

M
Mr.doob 已提交
2512
				// distance is 0 if decay is 0, because there is no attenuation at all.
M
Mr.doob 已提交
2513
				pointDistances[ pointLength ] = distance;
M
Mr.doob 已提交
2514
				pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525

				pointLength += 1;

			} else if ( light instanceof THREE.SpotLight ) {

				spotCount += 1;

				if ( ! light.visible ) continue;

				spotOffset = spotLength * 3;

2526
				setColorLinear( spotColors, spotOffset, color, intensity );
M
Mr.doob 已提交
2527

G
gero3 已提交
2528
				_direction.setFromMatrixPosition( light.matrixWorld );
T
tschw 已提交
2529
				_vector3.copy( _direction ).applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2530

T
tschw 已提交
2531 2532 2533
				spotPositions[ spotOffset + 0 ] = _vector3.x;
				spotPositions[ spotOffset + 1 ] = _vector3.y;
				spotPositions[ spotOffset + 2 ] = _vector3.z;
M
Mr.doob 已提交
2534 2535 2536

				spotDistances[ spotLength ] = distance;

2537
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
M
Mr.doob 已提交
2538
				_direction.sub( _vector3 );
T
tschw 已提交
2539
				_direction.transformDirection( viewMatrix );
M
Mr.doob 已提交
2540

M
Mr.doob 已提交
2541
				spotDirections[ spotOffset + 0 ] = _direction.x;
M
Mr.doob 已提交
2542 2543 2544 2545 2546
				spotDirections[ spotOffset + 1 ] = _direction.y;
				spotDirections[ spotOffset + 2 ] = _direction.z;

				spotAnglesCos[ spotLength ] = Math.cos( light.angle );
				spotExponents[ spotLength ] = light.exponent;
M
Mr.doob 已提交
2547
				spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2548 2549 2550 2551 2552 2553 2554 2555 2556

				spotLength += 1;

			} else if ( light instanceof THREE.HemisphereLight ) {

				hemiCount += 1;

				if ( ! light.visible ) continue;

2557
				_direction.setFromMatrixPosition( light.matrixWorld );
T
tschw 已提交
2558
				_direction.transformDirection( viewMatrix );
M
Mr.doob 已提交
2559 2560 2561

				hemiOffset = hemiLength * 3;

M
Mr.doob 已提交
2562
				hemiPositions[ hemiOffset + 0 ] = _direction.x;
M
Mr.doob 已提交
2563 2564 2565 2566 2567 2568
				hemiPositions[ hemiOffset + 1 ] = _direction.y;
				hemiPositions[ hemiOffset + 2 ] = _direction.z;

				skyColor = light.color;
				groundColor = light.groundColor;

2569 2570
				setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
				setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
M
Mr.doob 已提交
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595

				hemiLength += 1;

			}

		}

		// null eventual remains from removed lights
		// (this is to avoid if in shader)

		for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
		for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
		for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
		for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
		for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;

		zlights.directional.length = dirLength;
		zlights.point.length = pointLength;
		zlights.spot.length = spotLength;
		zlights.hemi.length = hemiLength;

		zlights.ambient[ 0 ] = r;
		zlights.ambient[ 1 ] = g;
		zlights.ambient[ 2 ] = b;

M
Mr.doob 已提交
2596
	}
M
Mr.doob 已提交
2597 2598 2599 2600 2601 2602 2603

	// GL state setting

	this.setFaceCulling = function ( cullFace, frontFaceDirection ) {

		if ( cullFace === THREE.CullFaceNone ) {

2604
			state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631

		} else {

			if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {

				_gl.frontFace( _gl.CW );

			} else {

				_gl.frontFace( _gl.CCW );

			}

			if ( cullFace === THREE.CullFaceBack ) {

				_gl.cullFace( _gl.BACK );

			} else if ( cullFace === THREE.CullFaceFront ) {

				_gl.cullFace( _gl.FRONT );

			} else {

				_gl.cullFace( _gl.FRONT_AND_BACK );

			}

2632
			state.enable( _gl.CULL_FACE );
M
Mr.doob 已提交
2633 2634 2635 2636 2637 2638 2639 2640 2641

		}

	};

	// Textures

	function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {

2642 2643
		var extension;

M
Mr.doob 已提交
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
		if ( isImagePowerOfTwo ) {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );

		} else {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
M
Mr.doob 已提交
2656 2657 2658

			if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {

2659
				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
M
Mr.doob 已提交
2660

2661
			}
M
Mr.doob 已提交
2662 2663 2664 2665

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );

M
Mr.doob 已提交
2666 2667
			if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {

2668
				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
M
Mr.doob 已提交
2669

2670
			}
M
Mr.doob 已提交
2671

M
Mr.doob 已提交
2672 2673
		}

2674 2675
		extension = extensions.get( 'EXT_texture_filter_anisotropic' );

2676
		if ( extension ) {
M
Mr.doob 已提交
2677

2678 2679
			if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
			if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
M
Mr.doob 已提交
2680

2681
			if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
M
Mr.doob 已提交
2682

2683
				_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
2684
				properties.get( texture ).__currentAnisotropy = texture.anisotropy;
M
Mr.doob 已提交
2685 2686 2687 2688 2689

			}

		}

M
Mr.doob 已提交
2690
	}
M
Mr.doob 已提交
2691

2692
	function uploadTexture( textureProperties, texture, slot ) {
2693

2694
		if ( textureProperties.__webglInit === undefined ) {
2695

2696
			textureProperties.__webglInit = true;
2697 2698 2699 2700 2701

			texture.__webglInit = true;

			texture.addEventListener( 'dispose', onTextureDispose );

2702
			textureProperties.__webglTexture = _gl.createTexture();
2703

2704
			_infoMemory.textures ++;
2705 2706

		}
M
Mr.doob 已提交
2707

B
Ben Adams 已提交
2708
		state.activeTexture( _gl.TEXTURE0 + slot );
2709
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
M
Mr.doob 已提交
2710

H
Henri Astre 已提交
2711 2712 2713 2714
		_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
		_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
		_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );

G
gero3 已提交
2715
		texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
2716

2717 2718 2719 2720
		var image = texture.image;
		var isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
		var glFormat = paramThreeToGL( texture.format );
		var glType = paramThreeToGL( texture.type );
M
Mr.doob 已提交
2721

H
Henri Astre 已提交
2722
		setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
M
Mr.doob 已提交
2723

H
Henri Astre 已提交
2724
		var mipmap, mipmaps = texture.mipmaps;
M
Mr.doob 已提交
2725

H
Henri Astre 已提交
2726
		if ( texture instanceof THREE.DataTexture ) {
M
Mr.doob 已提交
2727

H
Henri Astre 已提交
2728 2729 2730
			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels
M
Mr.doob 已提交
2731

H
Henri Astre 已提交
2732 2733 2734
			if ( mipmaps.length > 0 && isImagePowerOfTwo ) {

				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2735

H
Henri Astre 已提交
2736
					mipmap = mipmaps[ i ];
2737
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
2738

H
Henri Astre 已提交
2739
				}
M
Mr.doob 已提交
2740

H
Henri Astre 已提交
2741
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2742

H
Henri Astre 已提交
2743
			} else {
M
Mr.doob 已提交
2744

2745
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
M
Mr.doob 已提交
2746

H
Henri Astre 已提交
2747
			}
M
Mr.doob 已提交
2748

H
Henri Astre 已提交
2749
		} else if ( texture instanceof THREE.CompressedTexture ) {
M
Mr.doob 已提交
2750

H
Henri Astre 已提交
2751
			for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2752

H
Henri Astre 已提交
2753
				mipmap = mipmaps[ i ];
M
Mr.doob 已提交
2754

2755
				if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
M
Mr.doob 已提交
2756

2757
					if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
M
Mr.doob 已提交
2758

2759
						state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
M
Mr.doob 已提交
2760

2761
					} else {
M
Mr.doob 已提交
2762

2763
						console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
M
Mr.doob 已提交
2764

2765
					}
M
Mr.doob 已提交
2766

H
Henri Astre 已提交
2767
				} else {
M
Mr.doob 已提交
2768

2769
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
2770

M
Mr.doob 已提交
2771 2772
				}

H
Henri Astre 已提交
2773 2774
			}

G
gero3 已提交
2775 2776 2777
		} else {

			// regular Texture (image, video, canvas)
H
Henri Astre 已提交
2778 2779 2780 2781 2782 2783

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
M
Mr.doob 已提交
2784

2785
				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2786 2787

					mipmap = mipmaps[ i ];
2788
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
M
Mr.doob 已提交
2789 2790 2791

				}

H
Henri Astre 已提交
2792
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2793

H
Henri Astre 已提交
2794
			} else {
M
Mr.doob 已提交
2795

2796
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
M
Mr.doob 已提交
2797

H
Henri Astre 已提交
2798
			}
M
Mr.doob 已提交
2799

H
Henri Astre 已提交
2800
		}
M
Mr.doob 已提交
2801

H
Henri Astre 已提交
2802
		if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
M
Mr.doob 已提交
2803

2804
		textureProperties.__version = texture.version;
M
Mr.doob 已提交
2805

B
Ben Adams 已提交
2806
		if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
2807

2808
	}
M
Mr.doob 已提交
2809

H
Henri Astre 已提交
2810
	this.setTexture = function ( texture, slot ) {
M
Mr.doob 已提交
2811

2812 2813 2814
		var textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
M
Mr.doob 已提交
2815

2816
			var image = texture.image;
M
Mr.doob 已提交
2817

2818 2819
			if ( image === undefined ) {

2820
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
2821 2822 2823 2824
				return;

			}

2825
			if ( image.complete === false ) {
M
Mr.doob 已提交
2826

2827
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
2828 2829 2830 2831
				return;

			}

2832
			uploadTexture( textureProperties, texture, slot );
2833
			return;
M
Mr.doob 已提交
2834 2835 2836

		}

B
Ben Adams 已提交
2837
		state.activeTexture( _gl.TEXTURE0 + slot );
2838
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
2839

M
Mr.doob 已提交
2840 2841 2842 2843
	};

	function clampToMaxSize ( image, maxSize ) {

2844
		if ( image.width > maxSize || image.height > maxSize ) {
M
Mr.doob 已提交
2845

2846 2847
			// Warning: Scaling through the canvas will only work with images that use
			// premultiplied alpha.
M
Mr.doob 已提交
2848

2849
			var scale = maxSize / Math.max( image.width, image.height );
M
Mr.doob 已提交
2850

2851 2852 2853
			var canvas = document.createElement( 'canvas' );
			canvas.width = Math.floor( image.width * scale );
			canvas.height = Math.floor( image.height * scale );
M
Mr.doob 已提交
2854

2855 2856
			var context = canvas.getContext( '2d' );
			context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
M
Mr.doob 已提交
2857

2858
			console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
M
Mr.doob 已提交
2859

2860 2861 2862
			return canvas;

		}
M
Mr.doob 已提交
2863

2864
		return image;
M
Mr.doob 已提交
2865 2866 2867 2868 2869

	}

	function setCubeTexture ( texture, slot ) {

2870
		var textureProperties = properties.get( texture );
2871

M
Mr.doob 已提交
2872 2873
		if ( texture.image.length === 6 ) {

2874
			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
M
Mr.doob 已提交
2875

2876
				if ( ! textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
2877

2878 2879
					texture.addEventListener( 'dispose', onTextureDispose );

2880
					textureProperties.__image__webglTextureCube = _gl.createTexture();
M
Mr.doob 已提交
2881

2882
					_infoMemory.textures ++;
M
Mr.doob 已提交
2883 2884 2885

				}

B
Ben Adams 已提交
2886
				state.activeTexture( _gl.TEXTURE0 + slot );
2887
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
2888 2889 2890

				_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );

M
Mr.doob 已提交
2891 2892
				var isCompressed = texture instanceof THREE.CompressedTexture;
				var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
M
Mr.doob 已提交
2893 2894 2895 2896 2897

				var cubeImage = [];

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

2898
					if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
M
Mr.doob 已提交
2899

G
gero3 已提交
2900
						cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
M
Mr.doob 已提交
2901 2902 2903

					} else {

2904
						cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
M
Mr.doob 已提交
2905 2906 2907 2908 2909

					}

				}

2910 2911 2912 2913
				var image = cubeImage[ 0 ];
				var isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
				var glFormat = paramThreeToGL( texture.format );
				var glType = paramThreeToGL( texture.type );
M
Mr.doob 已提交
2914 2915 2916 2917 2918

				setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );

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

2919
					if ( ! isCompressed ) {
M
Mr.doob 已提交
2920

M
Mr.doob 已提交
2921
						if ( isDataTexture ) {
2922

2923
							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
2924

M
Mr.doob 已提交
2925
						} else {
2926

2927
							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
2928

M
Mr.doob 已提交
2929 2930
						}

2931
					} else {
2932

M
Mr.doob 已提交
2933 2934
						var mipmap, mipmaps = cubeImage[ i ].mipmaps;

2935
						for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
M
Mr.doob 已提交
2936 2937

							mipmap = mipmaps[ j ];
M
Mr.doob 已提交
2938

2939
							if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
M
Mr.doob 已提交
2940

2941
								if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
M
Mr.doob 已提交
2942

2943
									state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
M
Mr.doob 已提交
2944

2945
								} else {
M
Mr.doob 已提交
2946

2947
									console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
M
Mr.doob 已提交
2948

2949
								}
M
Mr.doob 已提交
2950

2951
							} else {
M
Mr.doob 已提交
2952

2953
								state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
2954

2955
							}
M
Mr.doob 已提交
2956

2957
						}
M
Mr.doob 已提交
2958

M
Mr.doob 已提交
2959
					}
M
Mr.doob 已提交
2960

M
Mr.doob 已提交
2961 2962 2963 2964 2965 2966 2967 2968
				}

				if ( texture.generateMipmaps && isImagePowerOfTwo ) {

					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

				}

2969
				textureProperties.__version = texture.version;
M
Mr.doob 已提交
2970

B
Ben Adams 已提交
2971
				if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
2972 2973 2974

			} else {

B
Ben Adams 已提交
2975
				state.activeTexture( _gl.TEXTURE0 + slot );
2976
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
2977 2978 2979 2980 2981

			}

		}

M
Mr.doob 已提交
2982
	}
M
Mr.doob 已提交
2983 2984 2985

	function setCubeTextureDynamic ( texture, slot ) {

B
Ben Adams 已提交
2986
		state.activeTexture( _gl.TEXTURE0 + slot );
2987
		state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
M
Mr.doob 已提交
2988

M
Mr.doob 已提交
2989
	}
M
Mr.doob 已提交
2990 2991 2992

	// Render targets

2993 2994
	// Setup storage for target texture and bind it to correct framebuffer
	function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
M
Mr.doob 已提交
2995

2996 2997 2998
		var glFormat = paramThreeToGL( renderTarget.texture.format );
		var glType = paramThreeToGL( renderTarget.texture.type );
		state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
M
Mr.doob 已提交
2999
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
3000 3001
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
M
Mr.doob 已提交
3002

M
Mr.doob 已提交
3003
	}
M
Mr.doob 已提交
3004

3005 3006
	// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
	function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
M
Mr.doob 已提交
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016

		_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );

		if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
		} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
		} else {
3017
			// FIXME: We don't support !depth !stencil
M
Mr.doob 已提交
3018 3019 3020
			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
		}

3021
		_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
M
Mr.doob 已提交
3022
	}
M
Mr.doob 已提交
3023

3024 3025 3026 3027
	// Setup GL resources for a non-texture depth buffer
	function setupDepthRenderbuffer(renderTarget) {
		
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
3028 3029

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
3030 3031 3032 3033 3034 3035
		if ( isCube ) {
			renderTargetProperties.__webglDepthbuffer = [];
			for ( var i = 0; i < 6; i ++ ) {
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ]);
				renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
				setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
M
Mr.doob 已提交
3036
			}
3037 3038 3039 3040 3041 3042 3043 3044
		}
		else {
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
			renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
			setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
		}
		_gl.bindFramebuffer(_gl.FRAMEBUFFER, null );
	};
M
Mr.doob 已提交
3045

3046 3047 3048 3049
	// Set up GL resources for the render target
	function setupRenderTarget(renderTarget) {
		var renderTargetProperties = properties.get( renderTarget );
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
3050

3051 3052 3053 3054 3055
		renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
		
		textureProperties.__webglTexture = _gl.createTexture();
		
		_infoMemory.textures ++;
M
Mr.doob 已提交
3056

3057 3058 3059 3060
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
		var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
		var glFormat = paramThreeToGL( renderTarget.texture.format );
		var glType = paramThreeToGL( renderTarget.texture.type );
M
Mr.doob 已提交
3061

3062 3063 3064
		//
		// Setup framebuffer
		//
M
Mr.doob 已提交
3065

3066 3067 3068 3069 3070 3071 3072 3073
		if ( isCube ) {
			renderTargetProperties.__webglFramebuffer = [];
			for ( var i = 0; i < 6; i ++ ) {
				renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
			}
		} else {
			renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
		}
M
Mr.doob 已提交
3074

3075 3076 3077 3078 3079 3080 3081 3082
		//
		// Setup color buffer
		//
		if ( isCube ) {
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
			for ( var i = 0; i < 6; i ++ ) {
				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
M
Mr.doob 已提交
3083
			}
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
			
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
			
		} else {
			state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
			setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
			
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
			state.bindTexture( _gl.TEXTURE_2D, null );
		}
		
		//
		// Setup depth and stencil buffers
		//
		if ( renderTarget.depthBuffer ) {
			setupDepthRenderbuffer(renderTarget);
		}
M
Mr.doob 已提交
3103

3104 3105 3106
	}

	this.setRenderTarget = function ( renderTarget ) {
M
Mr.doob 已提交
3107

3108 3109
		if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
			setupRenderTarget(renderTarget);
M
Mr.doob 已提交
3110 3111
		}

3112
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
M
Mr.doob 已提交
3113 3114 3115 3116
		var framebuffer, width, height, vx, vy;

		if ( renderTarget ) {

3117
			var renderTargetProperties = properties.get( renderTarget );
F
Fordy 已提交
3118

M
Mr.doob 已提交
3119 3120
			if ( isCube ) {

3121
				framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
M
Mr.doob 已提交
3122 3123 3124

			} else {

3125
				framebuffer = renderTargetProperties.__webglFramebuffer;
M
Mr.doob 已提交
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155

			}

			width = renderTarget.width;
			height = renderTarget.height;

			vx = 0;
			vy = 0;

		} else {

			framebuffer = null;

			width = _viewportWidth;
			height = _viewportHeight;

			vx = _viewportX;
			vy = _viewportY;

		}

		if ( framebuffer !== _currentFramebuffer ) {

			_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
			_gl.viewport( vx, vy, width, height );

			_currentFramebuffer = framebuffer;

		}

3156
		if ( isCube ) {
M
Mark Kellogg 已提交
3157

3158 3159
			var textureProperties = properties.get( renderTarget.texture );
			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0,  _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
M
Mark Kellogg 已提交
3160

3161 3162
		}

M
Mr.doob 已提交
3163 3164 3165 3166 3167
		_currentWidth = width;
		_currentHeight = height;

	};

3168
	this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
3169

G
gero3 已提交
3170
		if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
3171

3172
			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
G
gero3 已提交
3173
			return;
3174

G
gero3 已提交
3175
		}
3176

3177
		if ( properties.get( renderTarget ).__webglFramebuffer ) {
3178

G
gero3 已提交
3179
			var restore = false;
3180

3181
			if ( properties.get( renderTarget ).__webglFramebuffer !== _currentFramebuffer ) {
3182

3183
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, properties.get( renderTarget ).__webglFramebuffer );
3184

G
gero3 已提交
3185
				restore = true;
3186

G
gero3 已提交
3187
			}
3188

3189
			if ( renderTarget.texture.format !== THREE.RGBAFormat && paramThreeToGL( renderTarget.texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
3190 3191 3192 3193 3194 3195

				console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
				return;

			}

3196
			if ( renderTarget.texture.type !== THREE.UnsignedByteType && paramThreeToGL( renderTarget.texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) ) {
3197 3198 3199 3200 3201 3202

				console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
				return;

			}

G
gero3 已提交
3203
			if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
3204

3205
				_gl.readPixels( x, y, width, height, paramThreeToGL( renderTarget.texture.format ), paramThreeToGL( renderTarget.texture.type ), buffer );
3206

G
gero3 已提交
3207
			} else {
3208

3209
				console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
3210

G
gero3 已提交
3211
			}
3212

G
gero3 已提交
3213
			if ( restore ) {
3214

G
gero3 已提交
3215
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
3216

G
gero3 已提交
3217
			}
3218

G
gero3 已提交
3219
		}
3220 3221 3222

	};

3223
	function updateRenderTargetMipmap( renderTarget ) {
M
Mr.doob 已提交
3224

3225
		var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
3226
		var texture = properties.get( renderTarget.texture ).__webglTexture;
M
Mr.doob 已提交
3227

3228 3229 3230
		state.bindTexture( target, texture );
		_gl.generateMipmap( target );
		state.bindTexture( target, null );
M
Mr.doob 已提交
3231

M
Mr.doob 已提交
3232
	}
M
Mr.doob 已提交
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245

	// Fallback filters for non-power-of-2 textures

	function filterFallback ( f ) {

		if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {

			return _gl.NEAREST;

		}

		return _gl.LINEAR;

M
Mr.doob 已提交
3246
	}
M
Mr.doob 已提交
3247 3248 3249 3250 3251

	// Map three.js constants to WebGL constants

	function paramThreeToGL ( p ) {

3252 3253
		var extension;

M
Mr.doob 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
		if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
		if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
		if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;

		if ( p === THREE.NearestFilter ) return _gl.NEAREST;
		if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
		if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;

		if ( p === THREE.LinearFilter ) return _gl.LINEAR;
		if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
		if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;

		if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
		if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
		if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
		if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;

		if ( p === THREE.ByteType ) return _gl.BYTE;
		if ( p === THREE.ShortType ) return _gl.SHORT;
		if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
		if ( p === THREE.IntType ) return _gl.INT;
		if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
		if ( p === THREE.FloatType ) return _gl.FLOAT;

3278 3279 3280 3281 3282 3283 3284 3285
		extension = extensions.get( 'OES_texture_half_float' );

		if ( extension !== null ) {

			if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;

		}

M
Mr.doob 已提交
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308
		if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
		if ( p === THREE.RGBFormat ) return _gl.RGB;
		if ( p === THREE.RGBAFormat ) return _gl.RGBA;
		if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
		if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;

		if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
		if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
		if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;

		if ( p === THREE.ZeroFactor ) return _gl.ZERO;
		if ( p === THREE.OneFactor ) return _gl.ONE;
		if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
		if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
		if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
		if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
		if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
		if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;

		if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
		if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
		if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;

3309
		extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
M
Mr.doob 已提交
3310

3311 3312 3313 3314 3315 3316
		if ( extension !== null ) {

			if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
			if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
			if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
			if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
M
Mr.doob 已提交
3317 3318 3319

		}

3320 3321 3322
		extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

		if ( extension !== null ) {
P
Pierre Lepers 已提交
3323

3324 3325 3326 3327
			if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
			if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
			if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
			if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
P
Pierre Lepers 已提交
3328 3329 3330

		}

3331 3332 3333
		extension = extensions.get( 'EXT_blend_minmax' );

		if ( extension !== null ) {
3334

3335 3336
			if ( p === THREE.MinEquation ) return extension.MIN_EXT;
			if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
3337 3338 3339

		}

M
Mr.doob 已提交
3340 3341
		return 0;

M
Mr.doob 已提交
3342
	}
M
Mr.doob 已提交
3343

M
Mr.doob 已提交
3344
	// DEPRECATED
3345

3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387
	this.supportsFloatTextures = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
		return extensions.get( 'OES_texture_float' );

	};

	this.supportsHalfFloatTextures = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
		return extensions.get( 'OES_texture_half_float' );

	};

	this.supportsStandardDerivatives = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
		return extensions.get( 'OES_standard_derivatives' );

	};

	this.supportsCompressedTextureS3TC = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
		return extensions.get( 'WEBGL_compressed_texture_s3tc' );

	};

	this.supportsCompressedTexturePVRTC = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
		return extensions.get( 'WEBGL_compressed_texture_pvrtc' );

	};

	this.supportsBlendMinMax = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
		return extensions.get( 'EXT_blend_minmax' );

	};

3388 3389
	this.supportsVertexTextures = function () {

G
gero3 已提交
3390
		return capabilities.vertexTextures;
3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402

	};

	this.supportsInstancedArrays = function () {

		console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
		return extensions.get( 'ANGLE_instanced_arrays' );

	};

	//

M
Mr.doob 已提交
3403 3404
	this.initMaterial = function () {

3405
		console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
M
Mr.doob 已提交
3406 3407

	};
M
Mr.doob 已提交
3408

M
Mr.doob 已提交
3409
	this.addPrePlugin = function () {
M
Mr.doob 已提交
3410

3411
		console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
M
Mr.doob 已提交
3412 3413 3414 3415 3416

	};

	this.addPostPlugin = function () {

3417
		console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
M
Mr.doob 已提交
3418 3419

	};
M
Mr.doob 已提交
3420

M
Mr.doob 已提交
3421 3422
	this.updateShadowMap = function () {

3423
		console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
M
Mr.doob 已提交
3424 3425 3426

	};

3427 3428 3429
	Object.defineProperties( this, {
		shadowMapEnabled: {
			get: function () {
G
gero3 已提交
3430

M
Mr.doob 已提交
3431
				return shadowMap.enabled;
G
gero3 已提交
3432

3433 3434
			},
			set: function ( value ) {
G
gero3 已提交
3435

3436
				console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
M
Mr.doob 已提交
3437
				shadowMap.enabled = value;
G
gero3 已提交
3438

3439 3440 3441 3442
			}
		},
		shadowMapType: {
			get: function () {
G
gero3 已提交
3443

M
Mr.doob 已提交
3444
				return shadowMap.type;
G
gero3 已提交
3445

3446 3447
			},
			set: function ( value ) {
G
gero3 已提交
3448

3449
				console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
M
Mr.doob 已提交
3450
				shadowMap.type = value;
G
gero3 已提交
3451

3452 3453 3454 3455
			}
		},
		shadowMapCullFace: {
			get: function () {
G
gero3 已提交
3456

M
Mr.doob 已提交
3457
				return shadowMap.cullFace;
G
gero3 已提交
3458

3459 3460
			},
			set: function ( value ) {
G
gero3 已提交
3461

3462
				console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
M
Mr.doob 已提交
3463
				shadowMap.cullFace = value;
G
gero3 已提交
3464

3465 3466 3467 3468
			}
		},
		shadowMapDebug: {
			get: function () {
G
gero3 已提交
3469

M
Mr.doob 已提交
3470
				return shadowMap.debug;
G
gero3 已提交
3471

3472 3473
			},
			set: function ( value ) {
G
gero3 已提交
3474

3475
				console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
M
Mr.doob 已提交
3476
				shadowMap.debug = value;
G
gero3 已提交
3477

3478 3479 3480 3481
			}
		}
	} );

M
Mr.doob 已提交
3482
};