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

THREE.WebGLRenderer = function ( parameters ) {

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

	parameters = parameters || {};

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

18
	_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
19
	_depth = parameters.depth !== undefined ? parameters.depth : true,
M
Mr.doob 已提交
20
	_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
21 22
	_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
	_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
M
Mr.doob 已提交
23
	_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
M
Mr.doob 已提交
24

M
Mr.doob 已提交
25
	var lights = [];
M
Mr.doob 已提交
26

O
OpenShift guest 已提交
27
	var opaqueObjects = [];
M
Mr.doob 已提交
28
	var opaqueObjectsLastIndex = - 1;
29
	var transparentObjects = [];
M
Mr.doob 已提交
30
	var transparentObjectsLastIndex = - 1;
31

32 33
	var morphInfluences = new Float32Array( 8 );

M
Mr.doob 已提交
34 35 36
	var sprites = [];
	var lensFlares = [];

M
Mr.doob 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	// 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;

T
tschw 已提交
53 54 55 56 57
	// user-defined clipping

	this.clippingPlanes = [];
	this.localClippingEnabled = false;

M
Mr.doob 已提交
58 59
	// physically based shading

60
	this.gammaFactor = 2.0;	// for backwards compatibility
M
Mr.doob 已提交
61 62 63
	this.gammaInput = false;
	this.gammaOutput = false;

64 65
	// physical lights

66
	this.physicallyCorrectLights = false;
67

B
Ben Houston 已提交
68 69 70 71 72 73
	// tone mapping

	this.toneMapping = THREE.LinearToneMapping;
	this.toneMappingExposure = 1.0;
	this.toneMappingWhitePoint = 1.0;

M
Mr.doob 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
	// morphs

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

	// flags

	this.autoScaleCubemaps = true;

	// internal properties

	var _this = this,

	// internal state cache

	_currentProgram = null,
90
	_currentRenderTarget = null,
M
Mr.doob 已提交
91
	_currentFramebuffer = null,
92
	_currentMaterialId = - 1,
93
	_currentGeometryProgram = '',
M
Mr.doob 已提交
94 95
	_currentCamera = null,

96 97 98 99 100
	_currentScissor = new THREE.Vector4(),
	_currentScissorTest = null,

	_currentViewport = new THREE.Vector4(),

101 102
	//

M
Mr.doob 已提交
103 104
	_usedTextureUnits = 0,

M
Mr.doob 已提交
105 106 107 108 109 110 111 112 113 114 115
	//

	_clearColor = new THREE.Color( 0x000000 ),
	_clearAlpha = 0,

	_width = _canvas.width,
	_height = _canvas.height,

	_pixelRatio = 1,

	_scissor = new THREE.Vector4( 0, 0, _width, _height ),
116 117
	_scissorTest = false,

M
Mr.doob 已提交
118
	_viewport = new THREE.Vector4( 0, 0, _width, _height ),
119

M
Mr.doob 已提交
120 121 122 123
	// frustum

	_frustum = new THREE.Frustum(),

T
tschw 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	// clipping

	_clippingEnabled = false,
	_localClippingEnabled = false,
	_clipRenderingShadows = false,

	_numClippingPlanes = 0,
	_clippingPlanesUniform = {
			type: '4fv', value: null, needsUpdate: false },

	_globalClippingState = null,
	_numGlobalClippingPlanes = 0,

	_matrix3 = new THREE.Matrix3(),
	_sphere = new THREE.Sphere(),
	_plane = new THREE.Plane(),


M
Mr.doob 已提交
142
	// camera matrices cache
M
Mr.doob 已提交
143 144 145 146 147 148 149 150 151

	_projScreenMatrix = new THREE.Matrix4(),

	_vector3 = new THREE.Vector3(),

	// light arrays cache

	_lights = {

152 153
		hash: '',

M
Mr.doob 已提交
154
		ambient: [ 0, 0, 0 ],
M
Mr.doob 已提交
155
		directional: [],
156 157
		directionalShadowMap: [],
		directionalShadowMatrix: [],
M
Mr.doob 已提交
158
		spot: [],
159 160
		spotShadowMap: [],
		spotShadowMatrix: [],
M
Mr.doob 已提交
161
		point: [],
162 163
		pointShadowMap: [],
		pointShadowMatrix: [],
164 165
		hemi: [],

166
		shadows: []
M
Mr.doob 已提交
167

168 169
	},

M
Mr.doob 已提交
170 171
	// info

172
	_infoMemory = {
173 174

		geometries: 0,
T
tschw 已提交
175
		textures: 0
176 177 178

	},

179
	_infoRender = {
180 181 182 183 184 185

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

M
Mr.doob 已提交
186 187
	};

M
Mr.doob 已提交
188
	this.info = {
189

M
Mr.doob 已提交
190 191
		render: _infoRender,
		memory: _infoMemory,
192
		programs: null
M
Mr.doob 已提交
193 194

	};
195

196

M
Mr.doob 已提交
197 198 199 200
	// initialize

	var _gl;

M
Mr.doob 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	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 已提交
216
			if ( _canvas.getContext( 'webgl' ) !== null ) {
217 218 219 220 221 222 223 224

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

			} else {

				throw 'Error creating WebGL context.';

			}
M
Mr.doob 已提交
225 226 227

		}

228 229 230 231 232 233 234 235 236 237 238 239
		// Some experimental-webgl implementations do not have getShaderPrecisionFormat

		if ( _gl.getShaderPrecisionFormat === undefined ) {

			_gl.getShaderPrecisionFormat = function () {

				return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };

			};

		}

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

M
Mr.doob 已提交
242 243
	} catch ( error ) {

244
		console.error( 'THREE.WebGLRenderer: ' + error );
M
Mr.doob 已提交
245 246 247

	}

248
	var _isWebGL2 = (typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext);
249 250
	var extensions = new THREE.WebGLExtensions( _gl );

251
	extensions.get( 'WEBGL_depth_texture' );
252 253
	extensions.get( 'OES_texture_float' );
	extensions.get( 'OES_texture_float_linear' );
254 255
	extensions.get( 'OES_texture_half_float' );
	extensions.get( 'OES_texture_half_float_linear' );
256
	extensions.get( 'OES_standard_derivatives' );
B
Ben Adams 已提交
257
	extensions.get( 'ANGLE_instanced_arrays' );
258

259 260
	if ( extensions.get( 'OES_element_index_uint' ) ) {

261
		THREE.BufferGeometry.MaxIndex = 4294967296;
262 263 264

	}

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

267 268 269
	var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
	var properties = new THREE.WebGLProperties();
	var objects = new THREE.WebGLObjects( _gl, properties, this.info );
G
gero3 已提交
270
	var programCache = new THREE.WebGLPrograms( this, capabilities );
M
Mr.doob 已提交
271
	var lightCache = new THREE.WebGLLights();
272

273 274
	this.info.programs = programCache.programs;

275 276
	var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
	var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
277

M
Mr.doob 已提交
278 279
	//

280 281
	function getTargetPixelRatio() {

282
		return _currentRenderTarget === null ? _pixelRatio : 1;
283 284 285

	}

286
	function glClearColor( r, g, b, a ) {
287 288 289

		if ( _premultipliedAlpha === true ) {

290
			r *= a; g *= a; b *= a;
291 292 293

		}

M
Mr.doob 已提交
294
		state.clearColor( r, g, b, a );
295

296
	}
297

298
	function setDefaultGLState() {
M
Mr.doob 已提交
299

M
Mr.doob 已提交
300
		state.init();
M
Mr.doob 已提交
301

302 303
		state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
		state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
M
Mr.doob 已提交
304

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

307
	}
308

309
	function resetGLState() {
310 311 312 313

		_currentProgram = null;
		_currentCamera = null;

314
		_currentGeometryProgram = '';
315 316
		_currentMaterialId = - 1;

M
Mr.doob 已提交
317 318
		state.reset();

319
	}
M
Mr.doob 已提交
320 321 322 323

	setDefaultGLState();

	this.context = _gl;
M
Mr.doob 已提交
324
	this.capabilities = capabilities;
325
	this.extensions = extensions;
326
	this.properties = properties;
M
Mr.doob 已提交
327
	this.state = state;
M
Mr.doob 已提交
328

M
Mr.doob 已提交
329 330
	// shadow map

331
	var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
M
Mr.doob 已提交
332

333
	this.shadowMap = shadowMap;
M
Mr.doob 已提交
334

M
Mr.doob 已提交
335

M
Mr.doob 已提交
336 337 338 339 340
	// Plugins

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

M
Mr.doob 已提交
341 342 343 344 345 346 347 348
	// API

	this.getContext = function () {

		return _gl;

	};

349 350 351 352 353 354
	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

355 356 357 358 359 360
	this.forceContextLoss = function () {

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

	};

361
	this.getMaxAnisotropy = ( function () {
M
Mr.doob 已提交
362

363
		var value;
M
Mr.doob 已提交
364

365
		return function getMaxAnisotropy() {
366

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

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

M
Mr.doob 已提交
371
			if ( extension !== null ) {
372

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

M
Mr.doob 已提交
375 376 377 378 379
			} else {

				value = 0;

			}
380 381 382

			return value;

M
Mr.doob 已提交
383
		};
384 385

	} )();
M
Mr.doob 已提交
386 387 388

	this.getPrecision = function () {

G
gero3 已提交
389
		return capabilities.precision;
M
Mr.doob 已提交
390 391 392

	};

393 394
	this.getPixelRatio = function () {

395
		return _pixelRatio;
396 397 398 399 400

	};

	this.setPixelRatio = function ( value ) {

401 402 403 404 405
		if ( value === undefined ) return;

		_pixelRatio = value;

		this.setSize( _viewport.z, _viewport.w, false );
406 407 408

	};

409 410 411
	this.getSize = function () {

		return {
412 413
			width: _width,
			height: _height
414 415 416 417
		};

	};

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

420 421 422
		_width = width;
		_height = height;

423 424
		_canvas.width = width * _pixelRatio;
		_canvas.height = height * _pixelRatio;
425

426
		if ( updateStyle !== false ) {
427

G
gero3 已提交
428 429
			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';
430

G
gero3 已提交
431
		}
M
Mr.doob 已提交
432

433
		this.setViewport( 0, 0, width, height );
M
Mr.doob 已提交
434 435 436 437 438

	};

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

439
		state.viewport( _viewport.set( x, y, width, height ) );
M
Mr.doob 已提交
440 441 442

	};

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

445
		state.scissor( _scissor.set( x, y, width, height ) );
M
Mr.doob 已提交
446 447 448

	};

449 450
	this.setScissorTest = function ( boolean ) {

451
		state.setScissorTest( _scissorTest = boolean );
M
Mr.doob 已提交
452 453 454 455 456

	};

	// Clearing

M
Mr.doob 已提交
457
	this.getClearColor = function () {
M
Mr.doob 已提交
458

M
Mr.doob 已提交
459
		return _clearColor;
M
Mr.doob 已提交
460 461 462

	};

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

M
Mr.doob 已提交
465
		_clearColor.set( color );
466

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

469
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
470 471 472

	};

M
Mr.doob 已提交
473
	this.getClearAlpha = function () {
M
Mr.doob 已提交
474

M
Mr.doob 已提交
475
		return _clearAlpha;
M
Mr.doob 已提交
476 477 478

	};

M
Mr.doob 已提交
479
	this.setClearAlpha = function ( alpha ) {
M
Mr.doob 已提交
480

M
Mr.doob 已提交
481
		_clearAlpha = alpha;
M
Mr.doob 已提交
482

483
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
484 485 486 487 488 489 490 491 492 493 494 495

	};

	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 );
496 497 498 499 500

	};

	this.clearColor = function () {

M
Mr.doob 已提交
501
		this.clear( true, false, false );
502 503 504 505 506

	};

	this.clearDepth = function () {

M
Mr.doob 已提交
507
		this.clear( false, true, false );
508 509 510 511 512

	};

	this.clearStencil = function () {

M
Mr.doob 已提交
513
		this.clear( false, false, true );
M
Mr.doob 已提交
514 515 516 517 518 519 520 521 522 523

	};

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

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

	};

M
Mr.doob 已提交
524 525
	// Reset

526
	this.resetGLState = resetGLState;
M
Mr.doob 已提交
527

D
dubejf 已提交
528 529 530 531 532 533
	this.dispose = function() {

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

	};

M
Mr.doob 已提交
534
	// Events
M
Mr.doob 已提交
535

D
dubejf 已提交
536 537 538 539 540 541 542 543 544
	function onContextLost( event ) {

		event.preventDefault();

		resetGLState();
		setDefaultGLState();

		properties.clear();

M
Mr.doob 已提交
545
	}
D
dubejf 已提交
546

547
	function onTextureDispose( event ) {
M
Mr.doob 已提交
548 549 550 551 552 553 554

		var texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

555
		_infoMemory.textures --;
M
Mr.doob 已提交
556 557


558
	}
M
Mr.doob 已提交
559

560
	function onRenderTargetDispose( event ) {
M
Mr.doob 已提交
561 562 563 564 565 566 567

		var renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

568
		_infoMemory.textures --;
M
Mr.doob 已提交
569

570
	}
M
Mr.doob 已提交
571

572
	function onMaterialDispose( event ) {
M
Mr.doob 已提交
573 574 575 576 577 578 579

		var material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

580
	}
M
Mr.doob 已提交
581 582 583

	// Buffer deallocation

584
	function deallocateTexture( texture ) {
M
Mr.doob 已提交
585

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

588
		if ( texture.image && textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
589 590 591

			// cube texture

592
			_gl.deleteTexture( textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
593

594 595 596 597
		} else {

			// 2D texture

598
			if ( textureProperties.__webglInit === undefined ) return;
599

600
			_gl.deleteTexture( textureProperties.__webglTexture );
601

M
Mr.doob 已提交
602 603
		}

604
		// remove all webgl properties
605
		properties.delete( texture );
606

607
	}
M
Mr.doob 已提交
608

609
	function deallocateRenderTarget( renderTarget ) {
M
Mr.doob 已提交
610

611
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
612
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
613

614
		if ( ! renderTarget ) return;
M
Mr.doob 已提交
615

616 617 618 619 620 621 622 623 624 625 626
		if ( textureProperties.__webglTexture !== undefined ) {

			_gl.deleteTexture( textureProperties.__webglTexture );

		}

		if ( renderTarget.depthTexture ) {

			renderTarget.depthTexture.dispose();

		}
M
Mr.doob 已提交
627

M
Mr.doob 已提交
628 629 630 631
		if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

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

632
				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
633
				if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
M
Mr.doob 已提交
634 635 636 637 638

			}

		} else {

639
			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
640
			if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
M
Mr.doob 已提交
641 642 643

		}

M
Mr.doob 已提交
644
		properties.delete( renderTarget.texture );
D
Daosheng Mu 已提交
645
		properties.delete( renderTarget );
M
Mr.doob 已提交
646

647
	}
M
Mr.doob 已提交
648

649
	function deallocateMaterial( material ) {
M
Mr.doob 已提交
650

651 652 653 654
		releaseMaterialProgramReference( material );

		properties.delete( material );

655
	}
656 657


658
	function releaseMaterialProgramReference( material ) {
659

660
		var programInfo = properties.get( material ).program;
M
Mr.doob 已提交
661 662 663

		material.program = undefined;

664
		if ( programInfo !== undefined ) {
M
Mr.doob 已提交
665

666
			programCache.releaseProgram( programInfo );
M
Mr.doob 已提交
667

M
Mr.doob 已提交
668 669
		}

670
	}
M
Mr.doob 已提交
671 672 673 674 675

	// Buffer rendering

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

676
		state.initAttributes();
677

678
		var buffers = properties.get( object );
679

680 681 682 683
		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 已提交
684

685
		var attributes = program.getAttributes();
686

M
Mr.doob 已提交
687 688
		if ( object.hasPositions ) {

689
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
M
Mr.doob 已提交
690
			_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
691

692 693
			state.enableAttribute( attributes.position );
			_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
694 695 696 697 698

		}

		if ( object.hasNormals ) {

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

W
WestLangley 已提交
701
			if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
M
Mr.doob 已提交
702

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

705
					var array = object.normalArray;
M
Mr.doob 已提交
706

707 708 709
					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 已提交
710

711 712 713
					array[ i + 0 ] = nx;
					array[ i + 1 ] = ny;
					array[ i + 2 ] = nz;
M
Mr.doob 已提交
714

715 716 717
					array[ i + 3 ] = nx;
					array[ i + 4 ] = ny;
					array[ i + 5 ] = nz;
M
Mr.doob 已提交
718

719 720 721
					array[ i + 6 ] = nx;
					array[ i + 7 ] = ny;
					array[ i + 8 ] = nz;
M
Mr.doob 已提交
722 723 724 725 726 727

				}

			}

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

729
			state.enableAttribute( attributes.normal );
730

731
			_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
732 733 734 735 736

		}

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

737
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
M
Mr.doob 已提交
738
			_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
739

740
			state.enableAttribute( attributes.uv );
741

742
			_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
743 744 745 746 747

		}

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

748
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
M
Mr.doob 已提交
749
			_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
750

751
			state.enableAttribute( attributes.color );
752

753
			_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
754 755 756

		}

757
		state.disableUnusedAttributes();
758

M
Mr.doob 已提交
759 760 761 762 763 764
		_gl.drawArrays( _gl.TRIANGLES, 0, object.count );

		object.count = 0;

	};

765
	this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
766

M
Mr.doob 已提交
767 768
		setMaterial( material );

769
		var program = setProgram( camera, fog, material, object );
M
Mr.doob 已提交
770

M
Mr.doob 已提交
771 772
		var updateBuffers = false;
		var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
M
Mr.doob 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

		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 ] );

			}

796
			activeInfluences.sort( absNumericalSort );
M
Mr.doob 已提交
797 798 799 800 801 802 803

			if ( activeInfluences.length > 8 ) {

				activeInfluences.length = 8;

			}

804 805
			var morphAttributes = geometry.morphAttributes;

M
Mr.doob 已提交
806 807 808 809 810 811 812
			for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {

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

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

813
					var index = influence[ 1 ];
M
Mr.doob 已提交
814

815 816
					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 已提交
817 818 819

				} else {

820 821
					if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
					if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
M
Mr.doob 已提交
822 823 824 825 826

				}

			}

T
tschw 已提交
827 828
			program.getUniforms().setValue(
					_gl, 'morphTargetInfluences', morphInfluences );
M
Mr.doob 已提交
829 830 831 832 833

			updateBuffers = true;

		}

834 835
		//

836
		var index = geometry.index;
837 838
		var position = geometry.attributes.position;

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

841
			index = objects.getWireframeAttribute( geometry );
842 843 844

		}

845 846
		var renderer;

847
		if ( index !== null ) {
848

849 850
			renderer = indexedBufferRenderer;
			renderer.setIndex( index );
851

852
		} else {
853

854
			renderer = bufferRenderer;
855

856
		}
M
Mr.doob 已提交
857

858
		if ( updateBuffers ) {
M
Mr.doob 已提交
859

860
			setupVertexAttributes( material, program, geometry );
M
Mr.doob 已提交
861

862
			if ( index !== null ) {
863

864
				_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
865 866 867

			}

868
		}
869

870 871
		//

M
Mr.doob 已提交
872 873
		var dataStart = 0;
		var dataCount = Infinity;
874

M
Mr.doob 已提交
875
		if ( index !== null ) {
876

M
Mr.doob 已提交
877
			dataCount = index.count;
878

M
Mr.doob 已提交
879
		} else if ( position !== undefined ) {
880

M
Mr.doob 已提交
881
			dataCount = position.count;
882

M
Mr.doob 已提交
883
		}
884

M
Mr.doob 已提交
885 886
		var rangeStart = geometry.drawRange.start;
		var rangeCount = geometry.drawRange.count;
887

M
Mr.doob 已提交
888 889
		var groupStart = group !== null ? group.start : 0;
		var groupCount = group !== null ? group.count : Infinity;
890

M
Mr.doob 已提交
891 892 893 894 895 896
		var drawStart = Math.max( dataStart, rangeStart, groupStart );
		var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;

		var drawCount = Math.max( 0, drawEnd - drawStart + 1 );

		//
897

898
		if ( object instanceof THREE.Mesh ) {
899

900
			if ( material.wireframe === true ) {
901

902
				state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
903
				renderer.setMode( _gl.LINES );
904

905
			} else {
M
Mr.doob 已提交
906 907

				switch ( object.drawMode ) {
908

B
Ben Adams 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921
					case THREE.TrianglesDrawMode:
						renderer.setMode( _gl.TRIANGLES );
						break;

					case THREE.TriangleStripDrawMode:
						renderer.setMode( _gl.TRIANGLE_STRIP );
						break;

					case THREE.TriangleFanDrawMode:
						renderer.setMode( _gl.TRIANGLE_FAN );
						break;

				}
922

923
			}
924

925

926
		} else if ( object instanceof THREE.Line ) {
927

928
			var lineWidth = material.linewidth;
929

930
			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
931

932
			state.setLineWidth( lineWidth * getTargetPixelRatio() );
933

934
			if ( object instanceof THREE.LineSegments ) {
935

936
				renderer.setMode( _gl.LINES );
937

938
			} else {
939

940
				renderer.setMode( _gl.LINE_STRIP );
941 942

			}
M
Mr.doob 已提交
943

944
		} else if ( object instanceof THREE.Points ) {
945 946

			renderer.setMode( _gl.POINTS );
947 948

		}
949

J
jfranc 已提交
950
		if ( geometry instanceof THREE.InstancedBufferGeometry ) {
M
Mr.doob 已提交
951 952 953

			if ( geometry.maxInstancedCount > 0 ) {

J
jfranc 已提交
954
				renderer.renderInstances( geometry, drawStart, drawCount );
M
Mr.doob 已提交
955

J
jfranc 已提交
956
			}
957 958 959

		} else {

M
Mr.doob 已提交
960
			renderer.render( drawStart, drawCount );
961

M
Mr.doob 已提交
962 963 964 965
		}

	};

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

M
Mr.doob 已提交
968
		var extension;
B
Ben Adams 已提交
969

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

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

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

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

M
Mr.doob 已提交
979 980 981
			}

		}
B
Ben Adams 已提交
982

983 984
		if ( startIndex === undefined ) startIndex = 0;

985 986
		state.initAttributes();

987
		var geometryAttributes = geometry.attributes;
988

989
		var programAttributes = program.getAttributes();
990

991
		var materialDefaultAttributeValues = material.defaultAttributeValues;
992

993
		for ( var name in programAttributes ) {
994

995
			var programAttribute = programAttributes[ name ];
M
Mr.doob 已提交
996

M
Mr.doob 已提交
997
			if ( programAttribute >= 0 ) {
M
Mr.doob 已提交
998

999
				var geometryAttribute = geometryAttributes[ name ];
1000

M
Mr.doob 已提交
1001
				if ( geometryAttribute !== undefined ) {
M
Mr.doob 已提交
1002

1003
					var type = _gl.FLOAT;
1004
					var array = geometryAttribute.array;
1005 1006
					var normalized = geometryAttribute.normalized;

1007 1008
					if ( array instanceof Float32Array ) {

1009
						type = _gl.FLOAT;
1010 1011 1012 1013 1014 1015 1016

					} else if ( array instanceof Float64Array ) {

						console.warn("Unsupported data buffer format: Float64Array");

					} else if ( array instanceof Uint16Array ) {

1017 1018
						type = _gl.UNSIGNED_SHORT;

1019 1020
					} else if ( array instanceof Int16Array ) {

1021
						type = _gl.SHORT;
1022 1023 1024

					} else if ( array instanceof Uint32Array ) {

1025
						type = _gl.UNSIGNED_INT;
1026 1027 1028

					} else if ( array instanceof Int32Array ) {

1029
						type = _gl.INT;
1030 1031 1032

					} else if ( array instanceof Int8Array ) {

1033
						type = _gl.BYTE;
1034 1035 1036

					} else if ( array instanceof Uint8Array ) {

1037
						type = _gl.UNSIGNED_BYTE;
1038 1039

					}
1040

1041
					var size = geometryAttribute.itemSize;
G
gero3 已提交
1042
					var buffer = objects.getAttributeBuffer( geometryAttribute );
1043

B
Ben Adams 已提交
1044
					if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
1045

M
Mr.doob 已提交
1046 1047 1048 1049 1050
						var data = geometryAttribute.data;
						var stride = data.stride;
						var offset = geometryAttribute.offset;

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

M
Mr.doob 已提交
1052
							state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
B
Ben Adams 已提交
1053

M
Mr.doob 已提交
1054
							if ( geometry.maxInstancedCount === undefined ) {
1055

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

M
Mr.doob 已提交
1058
							}
B
Ben Adams 已提交
1059

M
Mr.doob 已提交
1060
						} else {
B
Ben Adams 已提交
1061

M
Mr.doob 已提交
1062
							state.enableAttribute( programAttribute );
B
Ben Adams 已提交
1063

M
Mr.doob 已提交
1064
						}
B
Ben Adams 已提交
1065

M
Mr.doob 已提交
1066
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
1067
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
B
Ben Adams 已提交
1068

M
Mr.doob 已提交
1069
					} else {
B
Ben Adams 已提交
1070

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

M
Mr.doob 已提交
1073
							state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
B
Ben Adams 已提交
1074

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

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

M
Mr.doob 已提交
1079
							}
B
Ben Adams 已提交
1080

M
Mr.doob 已提交
1081 1082 1083 1084
						} else {

							state.enableAttribute( programAttribute );

M
Mr.doob 已提交
1085
						}
B
Ben Adams 已提交
1086

M
Mr.doob 已提交
1087
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
1088
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
M
Mr.doob 已提交
1089

B
Ben Adams 已提交
1090
					}
M
Mr.doob 已提交
1091

1092 1093
				} else if ( materialDefaultAttributeValues !== undefined ) {

T
tschw 已提交
1094
					var value = materialDefaultAttributeValues[ name ];
1095

1096
					if ( value !== undefined ) {
M
Mr.doob 已提交
1097

1098
						switch ( value.length ) {
M
Mr.doob 已提交
1099

1100 1101 1102
							case 2:
								_gl.vertexAttrib2fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1103

1104 1105 1106
							case 3:
								_gl.vertexAttrib3fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1107

1108 1109 1110
							case 4:
								_gl.vertexAttrib4fv( programAttribute, value );
								break;
1111

1112 1113
							default:
								_gl.vertexAttrib1fv( programAttribute, value );
1114 1115

						}
M
Mr.doob 已提交
1116 1117 1118 1119 1120 1121 1122 1123

					}

				}

			}

		}
1124

1125
		state.disableUnusedAttributes();
1126

M
Mr.doob 已提交
1127 1128
	}

M
Mr.doob 已提交
1129 1130
	// Sorting

1131
	function absNumericalSort( a, b ) {
1132

1133
		return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
1134 1135 1136

	}

M
Mr.doob 已提交
1137 1138
	function painterSortStable ( a, b ) {

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

U
unconed 已提交
1141
			return a.object.renderOrder - b.object.renderOrder;
1142

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

M
Mr.doob 已提交
1145
			return a.material.id - b.material.id;
1146 1147

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

M
Mr.doob 已提交
1149
			return a.z - b.z;
M
Mr.doob 已提交
1150 1151 1152

		} else {

1153
			return a.id - b.id;
M
Mr.doob 已提交
1154 1155 1156

		}

1157
	}
M
Mr.doob 已提交
1158

1159 1160
	function reversePainterSortStable ( a, b ) {

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

U
unconed 已提交
1163
			return a.object.renderOrder - b.object.renderOrder;
1164 1165

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

M
Mr.doob 已提交
1167
			return b.z - a.z;
1168 1169 1170 1171 1172 1173 1174

		} else {

			return a.id - b.id;

		}

1175
	}
1176

M
Mr.doob 已提交
1177 1178 1179 1180 1181 1182
	// Rendering

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

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

1183
			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
M
Mr.doob 已提交
1184 1185 1186 1187
			return;

		}

M
Mr.doob 已提交
1188
		var fog = scene.fog;
M
Mr.doob 已提交
1189 1190 1191

		// reset caching for this frame

1192
		_currentGeometryProgram = '';
1193
		_currentMaterialId = - 1;
1194
		_currentCamera = null;
M
Mr.doob 已提交
1195 1196 1197

		// update scene graph

1198
		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
M
Mr.doob 已提交
1199 1200 1201

		// update camera matrices and frustum

1202
		if ( camera.parent === null ) camera.updateMatrixWorld();
M
Mr.doob 已提交
1203 1204 1205 1206 1207 1208

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

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

M
Mr.doob 已提交
1209
		lights.length = 0;
1210

M
Mr.doob 已提交
1211 1212
		opaqueObjectsLastIndex = - 1;
		transparentObjectsLastIndex = - 1;
1213

M
Mr.doob 已提交
1214 1215 1216
		sprites.length = 0;
		lensFlares.length = 0;

T
tschw 已提交
1217 1218
		setupGlobalClippingPlanes( this.clippingPlanes, camera );

1219
		projectObject( scene, camera );
M
Mr.doob 已提交
1220

T
tschw 已提交
1221

1222 1223 1224
		opaqueObjects.length = opaqueObjectsLastIndex + 1;
		transparentObjects.length = transparentObjectsLastIndex + 1;

M
Mr.doob 已提交
1225
		if ( _this.sortObjects === true ) {
1226 1227 1228

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

1230 1231
		}

M
Mr.doob 已提交
1232
		//
M
Mr.doob 已提交
1233

T
tschw 已提交
1234 1235 1236 1237 1238 1239 1240
		if ( _clippingEnabled ) {

			_clipRenderingShadows = true;
			setupClippingPlanes( null );

		}

1241 1242
		setupShadows( lights );

M
Mr.doob 已提交
1243
		shadowMap.render( scene, camera );
M
Mr.doob 已提交
1244

1245 1246
		setupLights( lights, camera );

T
tschw 已提交
1247 1248 1249 1250 1251 1252 1253
		if ( _clippingEnabled ) {

			_clipRenderingShadows = false;
			resetGlobalClippingState();

		}

M
Mr.doob 已提交
1254 1255
		//

1256 1257 1258 1259
		_infoRender.calls = 0;
		_infoRender.vertices = 0;
		_infoRender.faces = 0;
		_infoRender.points = 0;
M
Mr.doob 已提交
1260

1261 1262 1263 1264 1265 1266
		if ( renderTarget === undefined ) {

			renderTarget = null;

		}

M
Mr.doob 已提交
1267 1268 1269 1270 1271 1272 1273 1274
		this.setRenderTarget( renderTarget );

		if ( this.autoClear || forceClear ) {

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

		}

1275
		//
M
Mr.doob 已提交
1276 1277 1278

		if ( scene.overrideMaterial ) {

1279
			var overrideMaterial = scene.overrideMaterial;
M
Mr.doob 已提交
1280

1281 1282
			renderObjects( opaqueObjects, camera, fog, overrideMaterial );
			renderObjects( transparentObjects, camera, fog, overrideMaterial );
1283

M
Mr.doob 已提交
1284 1285 1286 1287
		} else {

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

M
Mr.doob 已提交
1288
			state.setBlending( THREE.NoBlending );
1289
			renderObjects( opaqueObjects, camera, fog );
M
Mr.doob 已提交
1290 1291 1292

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

1293
			renderObjects( transparentObjects, camera, fog );
M
Mr.doob 已提交
1294 1295 1296 1297 1298

		}

		// custom render plugins (post pass)

M
Mr.doob 已提交
1299
		spritePlugin.render( scene, camera );
1300
		lensFlarePlugin.render( scene, camera, _currentViewport );
M
Mr.doob 已提交
1301 1302 1303

		// Generate mipmap if we're using any kind of mipmap filtering

M
Mr.doob 已提交
1304 1305 1306
		if ( renderTarget ) {

			var texture = renderTarget.texture;
M
Mr.doob 已提交
1307

M
Mr.doob 已提交
1308 1309 1310 1311 1312
			if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
					texture.minFilter !== THREE.NearestFilter &&
					texture.minFilter !== THREE.LinearFilter ) {

				updateRenderTargetMipmap( renderTarget );
M
Mr.doob 已提交
1313 1314

			}
M
Mr.doob 已提交
1315 1316 1317

		}

1318
		// Ensure depth buffer writing is enabled so it can be cleared on next render
M
Mr.doob 已提交
1319

M
Mr.doob 已提交
1320 1321
		state.setDepthTest( true );
		state.setDepthWrite( true );
1322
		state.setColorWrite( true );
M
Mr.doob 已提交
1323 1324 1325 1326

		// _gl.finish();

	};
M
Mr.doob 已提交
1327

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

1330
		var array, index;
M
Mr.doob 已提交
1331

1332
		// allocate the next position in the appropriate array
M
Mr.doob 已提交
1333 1334 1335

		if ( material.transparent ) {

1336 1337
			array = transparentObjects;
			index = ++ transparentObjectsLastIndex;
M
Mr.doob 已提交
1338 1339 1340

		} else {

1341 1342 1343 1344 1345
			array = opaqueObjects;
			index = ++ opaqueObjectsLastIndex;

		}

1346 1347
		// recycle existing render item or grow the array

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
		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 已提交
1358 1359 1360

		} else {

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
			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 已提交
1372 1373 1374 1375 1376

		}

	}

T
tschw 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
	function isObjectViewable( object ) {

		var geometry = object.geometry;

		if ( geometry.boundingSphere === null )
			geometry.computeBoundingSphere();

		var sphere = _sphere.
				copy( geometry.boundingSphere ).
				applyMatrix4( object.matrixWorld );

		if ( ! _frustum.intersectsSphere( sphere ) ) return false;
		if ( _numClippingPlanes === 0 ) return true;

		var planes = _this.clippingPlanes,

			center = sphere.center,
			negRad = - sphere.radius,
			i = 0;

		do {

			// out when deeper than radius in the negative halfspace
			if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;

		} while ( ++ i !== _numClippingPlanes );

		return true;

	}

1408
	function projectObject( object, camera ) {
M
Mr.doob 已提交
1409

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

1412
		if ( object.layers.test( camera.layers ) ) {
M
Mr.doob 已提交
1413

1414
			if ( object instanceof THREE.Light ) {
M
Mr.doob 已提交
1415

1416
				lights.push( object );
M
Mr.doob 已提交
1417

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

T
tschw 已提交
1420
				if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
1421 1422 1423 1424

					sprites.push( object );

				}
M
Mr.doob 已提交
1425

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

1428
				lensFlares.push( object );
M
Mr.doob 已提交
1429

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

1432
				if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1433

1434 1435
					_vector3.setFromMatrixPosition( object.matrixWorld );
					_vector3.applyProjection( _projScreenMatrix );
M
Mr.doob 已提交
1436

1437
				}
1438

1439
				pushRenderItem( object, null, object.material, _vector3.z, null );
M
Mr.doob 已提交
1440

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

1443
				if ( object instanceof THREE.SkinnedMesh ) {
M
Mr.doob 已提交
1444

1445
					object.skeleton.update();
1446

1447
				}
1448

T
tschw 已提交
1449
				if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
1450

1451
					var material = object.material;
1452

1453
					if ( material.visible === true ) {
M
Mr.doob 已提交
1454

1455
						if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1456

1457 1458 1459 1460
							_vector3.setFromMatrixPosition( object.matrixWorld );
							_vector3.applyProjection( _projScreenMatrix );

						}
M
Mr.doob 已提交
1461

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

S
SUNAG 已提交
1464
						if ( material instanceof THREE.MultiMaterial ) {
1465

1466 1467
							var groups = geometry.groups;
							var materials = material.materials;
1468

1469
							for ( var i = 0, l = groups.length; i < l; i ++ ) {
1470

1471 1472
								var group = groups[ i ];
								var groupMaterial = materials[ group.materialIndex ];
1473

1474
								if ( groupMaterial.visible === true ) {
1475

1476 1477 1478
									pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );

								}
M
Mr.doob 已提交
1479

M
Mr.doob 已提交
1480
							}
M
Mr.doob 已提交
1481

1482
						} else {
M
Mr.doob 已提交
1483

1484
							pushRenderItem( object, geometry, material, _vector3.z, null );
1485

1486
						}
O
OpenShift guest 已提交
1487

1488
					}
M
Mr.doob 已提交
1489

1490
				}
M
Mr.doob 已提交
1491

1492
			}
M
Mr.doob 已提交
1493

M
Mr.doob 已提交
1494
		}
M
Mr.doob 已提交
1495

M
Mr.doob 已提交
1496
		var children = object.children;
M
Mr.doob 已提交
1497

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

1500
			projectObject( children[ i ], camera );
M
Mr.doob 已提交
1501

1502
		}
1503

1504
	}
M
Mr.doob 已提交
1505

1506
	function renderObjects( renderList, camera, fog, overrideMaterial ) {
M
Mr.doob 已提交
1507

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

1510
			var renderItem = renderList[ i ];
M
Mr.doob 已提交
1511

1512
			var object = renderItem.object;
M
Mr.doob 已提交
1513 1514 1515
			var geometry = renderItem.geometry;
			var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
			var group = renderItem.group;
M
Mr.doob 已提交
1516

1517 1518
			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
M
Mr.doob 已提交
1519

M
Mr.doob 已提交
1520
			if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1521

M
Mr.doob 已提交
1522
				setMaterial( material );
M
Mr.doob 已提交
1523

1524
				var program = setProgram( camera, fog, material, object );
M
Mr.doob 已提交
1525

M
Mr.doob 已提交
1526
				_currentGeometryProgram = '';
M
Mr.doob 已提交
1527

M
Mr.doob 已提交
1528
				object.render( function ( object ) {
M
Mr.doob 已提交
1529

M
Mr.doob 已提交
1530
					_this.renderBufferImmediate( object, program, material );
M
Mr.doob 已提交
1531

M
Mr.doob 已提交
1532
				} );
1533

M
Mr.doob 已提交
1534
			} else {
M
Mr.doob 已提交
1535

1536
				_this.renderBufferDirect( camera, fog, geometry, material, object, group );
M
Mr.doob 已提交
1537

M
Mr.doob 已提交
1538
			}
M
Mr.doob 已提交
1539

1540
		}
M
Mr.doob 已提交
1541

1542
	}
G
gero3 已提交
1543

1544
	function initMaterial( material, fog, object ) {
M
Mr.doob 已提交
1545

1546
		var materialProperties = properties.get( material );
G
gero3 已提交
1547

T
tschw 已提交
1548 1549 1550
		var parameters = programCache.getParameters(
				material, _lights, fog, _numClippingPlanes, object );

G
gero3 已提交
1551
		var code = programCache.getProgramCode( material, parameters );
G
gero3 已提交
1552

1553
		var program = materialProperties.program;
T
tschw 已提交
1554
		var programChange = true;
1555

1556
		if ( program === undefined ) {
B
Ben Adams 已提交
1557

M
Mr.doob 已提交
1558 1559
			// new material
			material.addEventListener( 'dispose', onMaterialDispose );
B
Ben Adams 已提交
1560

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

M
Mr.doob 已提交
1563
			// changed glsl or parameters
1564
			releaseMaterialProgramReference( material );
B
Ben Adams 已提交
1565

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

T
tschw 已提交
1568
			// same glsl and uniform list
T
tschw 已提交
1569 1570
			return;

T
tschw 已提交
1571
		} else {
B
Ben Adams 已提交
1572

T
tschw 已提交
1573 1574
			// only rebuild uniform list
			programChange = false;
B
Ben Adams 已提交
1575 1576 1577

		}

1578
		if ( programChange ) {
B
Ben Adams 已提交
1579

1580
			if ( parameters.shaderID ) {
B
Ben Adams 已提交
1581

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

1584 1585 1586 1587 1588 1589
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};
B
Ben Adams 已提交
1590

1591
			} else {
B
Ben Adams 已提交
1592

1593 1594 1595 1596 1597 1598
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};
G
gero3 已提交
1599

1600
			}
G
gero3 已提交
1601

1602
			material.__webglShader = materialProperties.__webglShader;
G
gero3 已提交
1603

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

1606 1607
			materialProperties.program = program;
			material.program = program;
1608 1609 1610

		}

1611
		var attributes = program.getAttributes();
M
Mr.doob 已提交
1612 1613 1614 1615 1616

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

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

M
Mr.doob 已提交
1619
				if ( attributes[ 'morphTarget' + i ] >= 0 ) {
M
Mr.doob 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

M
Mr.doob 已提交
1633
			for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
M
Mr.doob 已提交
1634

M
Mr.doob 已提交
1635
				if ( attributes[ 'morphNormal' + i ] >= 0 ) {
M
Mr.doob 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644

					material.numSupportedMorphNormals ++;

				}

			}

		}

T
tschw 已提交
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
		var uniforms = materialProperties.__webglShader.uniforms;

		if ( ! ( material instanceof THREE.ShaderMaterial ) &&
				! ( material instanceof THREE.RawShaderMaterial ) ||
				material.clipping === true ) {

			materialProperties.numClippingPlanes = _numClippingPlanes;
			uniforms.clippingPlanes = _clippingPlanesUniform;

		}

1656 1657
		if ( material instanceof THREE.MeshPhongMaterial ||
				material instanceof THREE.MeshLambertMaterial ||
1658
				material instanceof THREE.MeshStandardMaterial ||
1659 1660
				material.lights ) {

1661 1662
			// store the light setup it was created for

1663 1664
			materialProperties.lightsHash = _lights.hash;

1665 1666 1667 1668 1669
			// wire up the material to this renderer's lighting state

			uniforms.ambientLightColor.value = _lights.ambient;
			uniforms.directionalLights.value = _lights.directional;
			uniforms.spotLights.value = _lights.spot;
M
Mr.doob 已提交
1670
			uniforms.pointLights.value = _lights.point;
1671 1672
			uniforms.hemisphereLights.value = _lights.hemi;

1673 1674 1675 1676 1677 1678
			uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
			uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
			uniforms.spotShadowMap.value = _lights.spotShadowMap;
			uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
			uniforms.pointShadowMap.value = _lights.pointShadowMap;
			uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
1679

1680 1681
		}

T
tschw 已提交
1682 1683 1684
		var progUniforms = materialProperties.program.getUniforms(),
			uniformsList =
					THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
A
arose 已提交
1685

T
tschw 已提交
1686 1687 1688
		materialProperties.uniformsList = uniformsList;
		materialProperties.dynamicUniforms =
				THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms );
A
arose 已提交
1689

M
Mr.doob 已提交
1690
	}
M
Mr.doob 已提交
1691

1692 1693
	function setMaterial( material ) {

M
Mr.doob 已提交
1694 1695
		setMaterialFaces( material );

1696 1697
		if ( material.transparent === true ) {

1698
			state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
1699

1700 1701 1702 1703
		} else {

			state.setBlending( THREE.NoBlending );

1704 1705
		}

B
Ben Adams 已提交
1706
		state.setDepthFunc( material.depthFunc );
M
Mr.doob 已提交
1707 1708
		state.setDepthTest( material.depthTest );
		state.setDepthWrite( material.depthWrite );
1709
		state.setColorWrite( material.colorWrite );
M
Mr.doob 已提交
1710
		state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
1711 1712 1713

	}

M
Mr.doob 已提交
1714 1715
	function setMaterialFaces( material ) {

1716
		material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
1717 1718 1719 1720
		state.setFlipSided( material.side === THREE.BackSide );

	}

1721
	function setProgram( camera, fog, material, object ) {
M
Mr.doob 已提交
1722 1723 1724

		_usedTextureUnits = 0;

1725
		var materialProperties = properties.get( material );
1726

T
tschw 已提交
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
		if ( _clippingEnabled ) {

			if ( _localClippingEnabled || camera !== _currentCamera ) {

				var useCache =
						camera === _currentCamera &&
						material.id === _currentMaterialId;

				// we might want to call this function with some ClippingGroup
				// object instead of the material, once it becomes feasible
				// (#8465, #8379)
				setClippingState(
						material.clippingPlanes, material.clipShadows,
						camera, materialProperties, useCache );

			}

			if ( materialProperties.numClippingPlanes !== undefined &&
				materialProperties.numClippingPlanes !== _numClippingPlanes ) {

				material.needsUpdate = true;

			}

		}

1753 1754 1755 1756 1757 1758
		if ( materialProperties.program === undefined ) {

			material.needsUpdate = true;

		}

1759 1760
		if ( materialProperties.lightsHash !== undefined &&
			materialProperties.lightsHash !== _lights.hash ) {
1761 1762 1763 1764 1765 1766

			material.needsUpdate = true;

		}

		if ( material.needsUpdate ) {
M
Mr.doob 已提交
1767

1768
			initMaterial( material, fog, object );
M
Mr.doob 已提交
1769 1770 1771 1772
			material.needsUpdate = false;

		}

1773
		var refreshProgram = false;
M
Mr.doob 已提交
1774
		var refreshMaterial = false;
1775
		var refreshLights = false;
M
Mr.doob 已提交
1776

1777
		var program = materialProperties.program,
1778
			p_uniforms = program.getUniforms(),
1779
			m_uniforms = materialProperties.__webglShader.uniforms;
M
Mr.doob 已提交
1780

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

1783 1784
			_gl.useProgram( program.program );
			_currentProgram = program.id;
M
Mr.doob 已提交
1785

1786
			refreshProgram = true;
M
Mr.doob 已提交
1787
			refreshMaterial = true;
1788
			refreshLights = true;
M
Mr.doob 已提交
1789 1790 1791 1792 1793 1794

		}

		if ( material.id !== _currentMaterialId ) {

			_currentMaterialId = material.id;
1795

M
Mr.doob 已提交
1796 1797 1798 1799
			refreshMaterial = true;

		}

1800
		if ( refreshProgram || camera !== _currentCamera ) {
M
Mr.doob 已提交
1801

T
tschw 已提交
1802
			p_uniforms.set( _gl, camera, 'projectionMatrix' );
M
Mr.doob 已提交
1803

G
gero3 已提交
1804
			if ( capabilities.logarithmicDepthBuffer ) {
1805

T
tschw 已提交
1806 1807
				p_uniforms.setValue( _gl, 'logDepthBufFC',
						2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
1808 1809 1810 1811

			}


1812 1813 1814 1815 1816 1817 1818 1819 1820
			if ( camera !== _currentCamera ) {

				_currentCamera = camera;

				// lighting uniforms depend on the camera so enforce an update
				// now, in case this material supports lights - or later, when
				// the next material that does gets activated:

				refreshMaterial = true;		// set to true on material change
T
tschw 已提交
1821
				refreshLights = true;		// remains set until update done
1822 1823

			}
M
Mr.doob 已提交
1824

1825 1826 1827 1828 1829
			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

			if ( material instanceof THREE.ShaderMaterial ||
				 material instanceof THREE.MeshPhongMaterial ||
1830
				 material instanceof THREE.MeshStandardMaterial ||
1831 1832
				 material.envMap ) {

T
tschw 已提交
1833 1834 1835
				var uCamPos = p_uniforms.map.cameraPosition;

				if ( uCamPos !== undefined ) {
1836

T
tschw 已提交
1837 1838
					uCamPos.setValue( _gl,
							_vector3.setFromMatrixPosition( camera.matrixWorld ) );
1839 1840 1841 1842 1843 1844 1845

				}

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1846
				 material instanceof THREE.MeshBasicMaterial ||
1847
				 material instanceof THREE.MeshStandardMaterial ||
1848 1849 1850
				 material instanceof THREE.ShaderMaterial ||
				 material.skinning ) {

T
tschw 已提交
1851
				p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
1852 1853 1854

			}

T
tschw 已提交
1855 1856
			p_uniforms.set( _gl, _this, 'toneMappingExposure' );
			p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
M
Mr.doob 已提交
1857

M
Mr.doob 已提交
1858 1859 1860 1861 1862 1863 1864 1865
		}

		// 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 ) {

T
tschw 已提交
1866 1867
			p_uniforms.setOptional( _gl, object, 'bindMatrix' );
			p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
1868

T
tschw 已提交
1869
			var skeleton = object.skeleton;
1870

T
tschw 已提交
1871
			if ( skeleton ) {
1872

T
tschw 已提交
1873
				if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
M
Mr.doob 已提交
1874

T
tschw 已提交
1875 1876 1877
					p_uniforms.set( _gl, skeleton, 'boneTexture' );
					p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
					p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
M
Mr.doob 已提交
1878

T
tschw 已提交
1879
				} else {
M
Mr.doob 已提交
1880

T
tschw 已提交
1881
					p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
M
Mr.doob 已提交
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

				}

			}

		}

		if ( refreshMaterial ) {

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1893
				 material instanceof THREE.MeshStandardMaterial ||
M
Mr.doob 已提交
1894 1895
				 material.lights ) {

1896
				// the current material requires lighting info
M
Mr.doob 已提交
1897

T
tschw 已提交
1898 1899 1900 1901 1902 1903
				// note: all lighting uniforms are always set correctly
				// they simply reference the renderer's state for their
				// values
				//
				// use the current material's .needsUpdate flags to set
				// the GL state when required
M
Mr.doob 已提交
1904

T
tschw 已提交
1905
				markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
G
gero3 已提交
1906

T
tschw 已提交
1907
			}
G
gero3 已提交
1908

T
tschw 已提交
1909
			// refresh uniforms common to several materials
G
gero3 已提交
1910

T
tschw 已提交
1911
			if ( fog && material.fog ) {
G
gero3 已提交
1912

T
tschw 已提交
1913
				refreshUniformsFog( m_uniforms, fog );
M
Mr.doob 已提交
1914 1915 1916 1917 1918

			}

			if ( material instanceof THREE.MeshBasicMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
W
WestLangley 已提交
1919
				 material instanceof THREE.MeshPhongMaterial ||
W
WestLangley 已提交
1920 1921
				 material instanceof THREE.MeshStandardMaterial ||
				 material instanceof THREE.MeshDepthMaterial ) {
M
Mr.doob 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937

				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 );

1938
			} else if ( material instanceof THREE.PointsMaterial ) {
M
Mr.doob 已提交
1939

M
Mr.doob 已提交
1940
				refreshUniformsPoints( m_uniforms, material );
M
Mr.doob 已提交
1941

1942 1943 1944 1945
			} else if ( material instanceof THREE.MeshLambertMaterial ) {

				refreshUniformsLambert( m_uniforms, material );

M
Mr.doob 已提交
1946 1947 1948 1949
			} else if ( material instanceof THREE.MeshPhongMaterial ) {

				refreshUniformsPhong( m_uniforms, material );

W
WestLangley 已提交
1950 1951 1952 1953
			} else if ( material instanceof THREE.MeshPhysicalMaterial ) {

				refreshUniformsPhysical( m_uniforms, material );

1954
			} else if ( material instanceof THREE.MeshStandardMaterial ) {
W
WestLangley 已提交
1955

1956
				refreshUniformsStandard( m_uniforms, material );
W
WestLangley 已提交
1957

M
Mr.doob 已提交
1958 1959
			} else if ( material instanceof THREE.MeshDepthMaterial ) {

1960 1961 1962 1963 1964 1965 1966 1967
				if ( material.displacementMap ) {

					m_uniforms.displacementMap.value = material.displacementMap;
					m_uniforms.displacementScale.value = material.displacementScale;
					m_uniforms.displacementBias.value = material.displacementBias;

				}

M
Mr.doob 已提交
1968 1969 1970 1971 1972 1973
			} else if ( material instanceof THREE.MeshNormalMaterial ) {

				m_uniforms.opacity.value = material.opacity;

			}

T
tschw 已提交
1974 1975
			THREE.WebGLUniforms.upload(
					_gl, materialProperties.uniformsList, m_uniforms, _this );
A
arose 已提交
1976 1977 1978

		}

M
Mr.doob 已提交
1979

T
tschw 已提交
1980
		// common matrices
M
Mr.doob 已提交
1981

T
tschw 已提交
1982 1983 1984
		p_uniforms.set( _gl, object, 'modelViewMatrix' );
		p_uniforms.set( _gl, object, 'normalMatrix' );
		p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
A
arose 已提交
1985 1986


T
tschw 已提交
1987
		// dynamic uniforms
A
arose 已提交
1988

T
tschw 已提交
1989
		var dynUniforms = materialProperties.dynamicUniforms;
A
arose 已提交
1990

T
tschw 已提交
1991
		if ( dynUniforms !== null ) {
A
arose 已提交
1992

T
tschw 已提交
1993 1994
			THREE.WebGLUniforms.evalDynamic(
					dynUniforms, m_uniforms, object, camera );
A
arose 已提交
1995

T
tschw 已提交
1996
			THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
A
arose 已提交
1997 1998 1999

		}

T
tschw 已提交
2000
		return program;
A
arose 已提交
2001 2002 2003

	}

M
Mr.doob 已提交
2004 2005 2006 2007 2008 2009
	// Uniforms (refresh uniforms objects)

	function refreshUniformsCommon ( uniforms, material ) {

		uniforms.opacity.value = material.opacity;

2010
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
2011

2012
		if ( material.emissive ) {
M
Mr.doob 已提交
2013

2014
			uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
M
Mr.doob 已提交
2015 2016 2017

		}

2018 2019 2020
		uniforms.map.value = material.map;
		uniforms.specularMap.value = material.specularMap;
		uniforms.alphaMap.value = material.alphaMap;
M
Mr.doob 已提交
2021

2022
		if ( material.aoMap ) {
2023

2024 2025
			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;
2026 2027 2028

		}

M
Mr.doob 已提交
2029
		// uv repeat and offset setting priorities
M
Mr.doob 已提交
2030 2031 2032 2033 2034
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
2035
		// 6. emissive map
M
Mr.doob 已提交
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046

		var uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

2047 2048 2049 2050
		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

M
Mr.doob 已提交
2051 2052 2053 2054 2055 2056 2057 2058
		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

2059 2060 2061 2062 2063 2064 2065 2066
		} else if ( material.roughnessMap ) {

			uvScaleMap = material.roughnessMap;

		} else if ( material.metalnessMap ) {

			uvScaleMap = material.metalnessMap;

2067 2068 2069 2070
		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

2071 2072 2073 2074
		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

M
Mr.doob 已提交
2075 2076 2077 2078
		}

		if ( uvScaleMap !== undefined ) {

M
Mr.doob 已提交
2079 2080 2081 2082 2083 2084
			if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {

				uvScaleMap = uvScaleMap.texture;

			}

M
Mr.doob 已提交
2085 2086 2087 2088 2089 2090 2091 2092
			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;
2093
		uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
M
Mr.doob 已提交
2094

2095
		uniforms.reflectivity.value = material.reflectivity;
M
Mr.doob 已提交
2096 2097
		uniforms.refractionRatio.value = material.refractionRatio;

M
Mr.doob 已提交
2098
	}
M
Mr.doob 已提交
2099 2100 2101 2102 2103 2104

	function refreshUniformsLine ( uniforms, material ) {

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

M
Mr.doob 已提交
2105
	}
M
Mr.doob 已提交
2106 2107 2108 2109 2110 2111 2112

	function refreshUniformsDash ( uniforms, material ) {

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

M
Mr.doob 已提交
2113
	}
M
Mr.doob 已提交
2114

M
Mr.doob 已提交
2115
	function refreshUniformsPoints ( uniforms, material ) {
M
Mr.doob 已提交
2116

2117
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
2118
		uniforms.opacity.value = material.opacity;
2119
		uniforms.size.value = material.size * _pixelRatio;
T
tschw 已提交
2120
		uniforms.scale.value = _canvas.clientHeight * 0.5;
M
Mr.doob 已提交
2121 2122 2123

		uniforms.map.value = material.map;

2124 2125 2126 2127 2128 2129 2130 2131 2132
		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 已提交
2133
	}
M
Mr.doob 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149

	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 已提交
2150
	}
M
Mr.doob 已提交
2151

2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
	function refreshUniformsLambert ( uniforms, material ) {

		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

	}

M
Mr.doob 已提交
2169 2170
	function refreshUniformsPhong ( uniforms, material ) {

2171
		uniforms.specular.value = material.specular;
M
Mr.doob 已提交
2172
		uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
M
Mr.doob 已提交
2173

2174 2175 2176 2177
		if ( material.lightMap ) {

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

2179
		}
2180

2181
		if ( material.emissiveMap ) {
2182

2183
			uniforms.emissiveMap.value = material.emissiveMap;
2184

2185
		}
M
Mr.doob 已提交
2186

2187 2188 2189 2190
		if ( material.bumpMap ) {

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

2192
		}
M
Mr.doob 已提交
2193

2194 2195 2196 2197 2198 2199
		if ( material.normalMap ) {

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

		}
M
Mr.doob 已提交
2200

2201 2202 2203 2204 2205
		if ( material.displacementMap ) {

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

2207
		}
2208 2209 2210

	}

2211
	function refreshUniformsStandard ( uniforms, material ) {
W
WestLangley 已提交
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271

		uniforms.roughness.value = material.roughness;
		uniforms.metalness.value = material.metalness;

		if ( material.roughnessMap ) {

			uniforms.roughnessMap.value = material.roughnessMap;

		}

		if ( material.metalnessMap ) {

			uniforms.metalnessMap.value = material.metalnessMap;

		}

		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;

		}

		if ( material.normalMap ) {

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

		}

		if ( material.displacementMap ) {

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

		}

		if ( material.envMap ) {

			//uniforms.envMap.value = material.envMap; // part of uniforms common
			uniforms.envMapIntensity.value = material.envMapIntensity;

		}

	}

W
WestLangley 已提交
2272 2273 2274 2275 2276 2277
	function refreshUniformsPhysical ( uniforms, material ) {

		refreshUniformsStandard( uniforms, material );

	}

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

M
Mr.doob 已提交
2280
	function markUniformsLightsNeedsUpdate ( uniforms, value ) {
2281

M
Mr.doob 已提交
2282
		uniforms.ambientLightColor.needsUpdate = value;
2283

B
Ben Houston 已提交
2284 2285 2286 2287
		uniforms.directionalLights.needsUpdate = value;
		uniforms.pointLights.needsUpdate = value;
		uniforms.spotLights.needsUpdate = value;
		uniforms.hemisphereLights.needsUpdate = value;
2288

M
Mr.doob 已提交
2289
	}
2290

T
tschw 已提交
2291
	// Lighting
M
Mr.doob 已提交
2292

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
	function setupShadows ( lights ) {

		var lightShadowsLength = 0;

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

			var light = lights[ i ];

			if ( light.castShadow ) {

				_lights.shadows[ lightShadowsLength ++ ] = light;

			}

		}

		_lights.shadows.length = lightShadowsLength;

	}

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

B
brason 已提交
2315
		var l, ll, light,
M
Mr.doob 已提交
2316
		r = 0, g = 0, b = 0,
B
Ben Houston 已提交
2317
		color,
B
brason 已提交
2318
		intensity,
M
Mr.doob 已提交
2319 2320
		distance,

2321
		viewMatrix = camera.matrixWorldInverse,
M
Mr.doob 已提交
2322

M
Mr.doob 已提交
2323
		directionalLength = 0,
M
Mr.doob 已提交
2324 2325
		pointLength = 0,
		spotLength = 0,
2326
		hemiLength = 0;
M
Mr.doob 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337

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

			light = lights[ l ];

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

			if ( light instanceof THREE.AmbientLight ) {

2338 2339 2340
				r += color.r * intensity;
				g += color.g * intensity;
				b += color.b * intensity;
M
Mr.doob 已提交
2341 2342 2343

			} else if ( light instanceof THREE.DirectionalLight ) {

M
Mr.doob 已提交
2344
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2345

2346
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
M
Mr.doob 已提交
2347
				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
2348
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
M
Mr.doob 已提交
2349 2350 2351
				uniforms.direction.sub( _vector3 );
				uniforms.direction.transformDirection( viewMatrix );

2352
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2353

2354
				if ( light.castShadow ) {
M
Mr.doob 已提交
2355

2356 2357 2358
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2359

2360 2361
				}

2362 2363
				_lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
				_lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
2364
				_lights.directional[ directionalLength ++ ] = uniforms;
M
Mr.doob 已提交
2365

M
Mr.doob 已提交
2366
			} else if ( light instanceof THREE.SpotLight ) {
M
Mr.doob 已提交
2367

M
Mr.doob 已提交
2368
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2369 2370 2371

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2372

M
Mr.doob 已提交
2373 2374 2375 2376 2377 2378 2379 2380
				uniforms.color.copy( color ).multiplyScalar( intensity );
				uniforms.distance = distance;

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
				uniforms.direction.sub( _vector3 );
				uniforms.direction.transformDirection( viewMatrix );

2381 2382
				uniforms.coneCos = Math.cos( light.angle );
				uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
M
Mr.doob 已提交
2383
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2384

2385
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2386

2387 2388
				if ( light.castShadow ) {

2389 2390 2391
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2392

2393 2394
				}

2395 2396
				_lights.spotShadowMap[ spotLength ] = light.shadow.map;
				_lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
M
Mr.doob 已提交
2397
				_lights.spot[ spotLength ++ ] = uniforms;
2398

M
Mr.doob 已提交
2399
			} else if ( light instanceof THREE.PointLight ) {
M
Mr.doob 已提交
2400

M
Mr.doob 已提交
2401
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2402

M
Mr.doob 已提交
2403 2404
				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2405

M
Mr.doob 已提交
2406 2407
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				uniforms.distance = light.distance;
M
Mr.doob 已提交
2408 2409
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;

2410
				uniforms.shadow = light.castShadow;
2411

M
Mr.doob 已提交
2412
				if ( light.castShadow ) {
2413

2414 2415 2416 2417 2418
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;

				}
2419

2420
				_lights.pointShadowMap[ pointLength ] = light.shadow.map;
2421

2422 2423 2424
				if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {

					_lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
2425

2426 2427
				}

2428 2429 2430 2431 2432
				// for point lights we set the shadow matrix to be a translation-only matrix
				// equal to inverse of the light's position
				_vector3.setFromMatrixPosition( light.matrixWorld ).negate();
				_lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );

M
Mr.doob 已提交
2433
				_lights.point[ pointLength ++ ] = uniforms;
2434

M
Mr.doob 已提交
2435 2436
			} else if ( light instanceof THREE.HemisphereLight ) {

M
Mr.doob 已提交
2437
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2438 2439 2440 2441

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				uniforms.direction.transformDirection( viewMatrix );
				uniforms.direction.normalize();
M
Mr.doob 已提交
2442

M
Mr.doob 已提交
2443 2444
				uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
				uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
M
Mr.doob 已提交
2445

M
Mr.doob 已提交
2446
				_lights.hemi[ hemiLength ++ ] = uniforms;
M
Mr.doob 已提交
2447 2448 2449 2450 2451

			}

		}

M
Mr.doob 已提交
2452 2453 2454
		_lights.ambient[ 0 ] = r;
		_lights.ambient[ 1 ] = g;
		_lights.ambient[ 2 ] = b;
M
Mr.doob 已提交
2455

M
Mr.doob 已提交
2456 2457
		_lights.directional.length = directionalLength;
		_lights.spot.length = spotLength;
2458
		_lights.point.length = pointLength;
M
Mr.doob 已提交
2459
		_lights.hemi.length = hemiLength;
2460

2461
		_lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
2462

M
Mr.doob 已提交
2463
	}
M
Mr.doob 已提交
2464

T
tschw 已提交
2465
	// Clipping
T
tschw 已提交
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582

	function setupGlobalClippingPlanes( planes, camera ) {

		_clippingEnabled =
				_this.clippingPlanes.length !== 0 ||
				_this.localClippingEnabled ||
				// enable state of previous frame - the clipping code has to
				// run another frame in order to reset the state:
				_numGlobalClippingPlanes !== 0 ||
				_localClippingEnabled;

		_localClippingEnabled = _this.localClippingEnabled;

		_globalClippingState = setupClippingPlanes( planes, camera, 0 );
		_numGlobalClippingPlanes = planes !== null ? planes.length : 0;

	}

	function setupClippingPlanes( planes, camera, dstOffset, skipTransform ) {

		var nPlanes = planes !== null ? planes.length : 0,
			dstArray = null;

		if ( nPlanes !== 0 ) {

			dstArray = _clippingPlanesUniform.value;

			if ( skipTransform !== true || dstArray === null ) {

				var flatSize = dstOffset + nPlanes * 4,
					viewMatrix = camera.matrixWorldInverse,
					viewNormalMatrix = _matrix3.getNormalMatrix( viewMatrix );

				if ( dstArray === null || dstArray.length < flatSize ) {

					dstArray = new Float32Array( flatSize );

				}

				for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {

					var plane = _plane.copy( planes[ i ] ).
							applyMatrix4( viewMatrix, viewNormalMatrix );

					plane.normal.toArray( dstArray, i4 );
					dstArray[ i4 + 3 ] = plane.constant;

				}

			}

			_clippingPlanesUniform.value = dstArray;
			_clippingPlanesUniform.needsUpdate = true;

		}

		_numClippingPlanes = nPlanes;
		return dstArray;

	}

	function resetGlobalClippingState() {

		if ( _clippingPlanesUniform.value !== _globalClippingState ) {

			_clippingPlanesUniform.value = _globalClippingState;
			_clippingPlanesUniform.needsUpdate = _numGlobalClippingPlanes > 0;

		}

		_numClippingPlanes = _numGlobalClippingPlanes;

	}

	function setClippingState( planes, clipShadows, camera, cache, fromCache ) {

		if ( ! _localClippingEnabled ||
				planes === null || planes.length === 0 ||
				_clipRenderingShadows && ! clipShadows ) {
			// there's no local clipping

			if ( _clipRenderingShadows ) {
				// there's no global clipping

				setupClippingPlanes( null );

			} else {

				resetGlobalClippingState();
			}

		} else {

			var nGlobal = _clipRenderingShadows ? 0 : _numGlobalClippingPlanes,
				lGlobal = nGlobal * 4,

				dstArray = cache.clippingState || null;

			_clippingPlanesUniform.value = dstArray; // ensure unique state

			dstArray = setupClippingPlanes(
					planes, camera, lGlobal, fromCache );

			for ( var i = 0; i !== lGlobal; ++ i ) {

				dstArray[ i ] = _globalClippingState[ i ];

			}

			cache.clippingState = dstArray;
			_numClippingPlanes += nGlobal;

		}

	}


M
Mr.doob 已提交
2583 2584 2585 2586 2587 2588
	// GL state setting

	this.setFaceCulling = function ( cullFace, frontFaceDirection ) {

		if ( cullFace === THREE.CullFaceNone ) {

2589
			state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616

		} 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 );

			}

2617
			state.enable( _gl.CULL_FACE );
M
Mr.doob 已提交
2618 2619 2620 2621 2622 2623 2624

		}

	};

	// Textures

T
tschw 已提交
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
	function allocTextureUnit() {

		var textureUnit = _usedTextureUnits;

		if ( textureUnit >= capabilities.maxTextures ) {

			console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );

		}

		_usedTextureUnits += 1;

		return textureUnit;

	}

M
Mr.doob 已提交
2641
	function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
M
Mr.doob 已提交
2642

2643 2644
		var extension;

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

			_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 已提交
2657 2658 2659

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

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

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

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

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

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

2671
			}
M
Mr.doob 已提交
2672

M
Mr.doob 已提交
2673 2674
		}

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

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

2679 2680
			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 已提交
2681

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

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

			}

		}

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

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

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

2697
			textureProperties.__webglInit = true;
2698 2699 2700

			texture.addEventListener( 'dispose', onTextureDispose );

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

2703
			_infoMemory.textures ++;
2704 2705

		}
M
Mr.doob 已提交
2706

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

H
Henri Astre 已提交
2710 2711 2712 2713
		_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 );

2714
		var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
2715

2716
		if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
M
Mr.doob 已提交
2717

2718
			image = makePowerOfTwo( image );
M
Mr.doob 已提交
2719 2720 2721

		}

M
Mr.doob 已提交
2722
		var isPowerOfTwoImage = isPowerOfTwo( image ),
H
Henri Astre 已提交
2723 2724
		glFormat = paramThreeToGL( texture.format ),
		glType = paramThreeToGL( texture.type );
M
Mr.doob 已提交
2725

M
Mr.doob 已提交
2726
		setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
M
Mr.doob 已提交
2727

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

2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
		if ( texture instanceof THREE.DepthTexture ) {

			// populate depth texture with dummy data

			var internalFormat = _gl.DEPTH_COMPONENT;

			if ( texture.type === THREE.FloatType ) {

				if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
				internalFormat = _gl.DEPTH_COMPONENT32F;

			} else if ( _isWebGL2 ) {

				// WebGL 2.0 requires signed internalformat for glTexImage2D
				internalFormat = _gl.DEPTH_COMPONENT16;

			}

			state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );

		} else if ( texture instanceof THREE.DataTexture ) {
M
Mr.doob 已提交
2751

H
Henri Astre 已提交
2752 2753 2754
			// 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 已提交
2755

M
Mr.doob 已提交
2756
			if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
H
Henri Astre 已提交
2757 2758

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

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

H
Henri Astre 已提交
2763
				}
M
Mr.doob 已提交
2764

H
Henri Astre 已提交
2765
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2766

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

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

H
Henri Astre 已提交
2771
			}
M
Mr.doob 已提交
2772

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

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

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

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

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

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

2785
					} else {
M
Mr.doob 已提交
2786

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

2789
					}
M
Mr.doob 已提交
2790

H
Henri Astre 已提交
2791
				} else {
M
Mr.doob 已提交
2792

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

M
Mr.doob 已提交
2795 2796
				}

H
Henri Astre 已提交
2797 2798
			}

G
gero3 已提交
2799 2800 2801
		} else {

			// regular Texture (image, video, canvas)
H
Henri Astre 已提交
2802 2803 2804 2805 2806

			// 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 已提交
2807
			if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
M
Mr.doob 已提交
2808

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

					mipmap = mipmaps[ i ];
2812
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
M
Mr.doob 已提交
2813 2814 2815

				}

H
Henri Astre 已提交
2816
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2817

H
Henri Astre 已提交
2818
			} else {
M
Mr.doob 已提交
2819

2820
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
M
Mr.doob 已提交
2821

H
Henri Astre 已提交
2822
			}
M
Mr.doob 已提交
2823

H
Henri Astre 已提交
2824
		}
M
Mr.doob 已提交
2825

M
Mr.doob 已提交
2826
		if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
M
Mr.doob 已提交
2827

2828
		textureProperties.__version = texture.version;
M
Mr.doob 已提交
2829

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

2832
	}
M
Mr.doob 已提交
2833

T
tschw 已提交
2834 2835 2836
	function setTexture2D( texture, slot ) {

		if ( texture instanceof THREE.WebGLRenderTarget ) texture = texture.texture;
M
Mr.doob 已提交
2837

2838 2839 2840
		var textureProperties = properties.get( texture );

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

2842
			var image = texture.image;
M
Mr.doob 已提交
2843

2844 2845
			if ( image === undefined ) {

2846
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
2847 2848 2849 2850
				return;

			}

2851
			if ( image.complete === false ) {
M
Mr.doob 已提交
2852

2853
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
2854 2855 2856 2857
				return;

			}

2858
			uploadTexture( textureProperties, texture, slot );
2859

2860
			return;
M
Mr.doob 已提交
2861 2862 2863

		}

B
Ben Adams 已提交
2864
		state.activeTexture( _gl.TEXTURE0 + slot );
2865
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
2866

M
Michael Herzog 已提交
2867
	}
M
Mr.doob 已提交
2868 2869 2870

	function clampToMaxSize ( image, maxSize ) {

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

2873 2874
			// Warning: Scaling through the canvas will only work with images that use
			// premultiplied alpha.
M
Mr.doob 已提交
2875

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

2878 2879 2880
			var canvas = document.createElement( 'canvas' );
			canvas.width = Math.floor( image.width * scale );
			canvas.height = Math.floor( image.height * scale );
M
Mr.doob 已提交
2881

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

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

2887 2888 2889
			return canvas;

		}
M
Mr.doob 已提交
2890

2891
		return image;
M
Mr.doob 已提交
2892 2893 2894

	}

M
Mr.doob 已提交
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
	function isPowerOfTwo( image ) {

		return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );

	}

	function textureNeedsPowerOfTwo( texture ) {

		if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
		if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;

		return false;

	}

	function makePowerOfTwo( image ) {

		if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {

			var canvas = document.createElement( 'canvas' );
			canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
			canvas.height = THREE.Math.nearestPowerOfTwo( image.height );

			var context = canvas.getContext( '2d' );
			context.drawImage( image, 0, 0, canvas.width, canvas.height );

			console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );

			return canvas;

		}

		return image;

	}

M
Mr.doob 已提交
2931 2932
	function setCubeTexture ( texture, slot ) {

2933
		var textureProperties = properties.get( texture );
2934

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

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

2939
				if ( ! textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
2940

2941 2942
					texture.addEventListener( 'dispose', onTextureDispose );

2943
					textureProperties.__image__webglTextureCube = _gl.createTexture();
M
Mr.doob 已提交
2944

2945
					_infoMemory.textures ++;
M
Mr.doob 已提交
2946 2947 2948

				}

B
Ben Adams 已提交
2949
				state.activeTexture( _gl.TEXTURE0 + slot );
2950
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
2951 2952 2953

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

M
Mr.doob 已提交
2954 2955
				var isCompressed = texture instanceof THREE.CompressedTexture;
				var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
M
Mr.doob 已提交
2956 2957 2958 2959 2960

				var cubeImage = [];

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

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

G
gero3 已提交
2963
						cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
M
Mr.doob 已提交
2964 2965 2966

					} else {

2967
						cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
M
Mr.doob 已提交
2968 2969 2970 2971 2972 2973

					}

				}

				var image = cubeImage[ 0 ],
M
Mr.doob 已提交
2974
				isPowerOfTwoImage = isPowerOfTwo( image ),
M
Mr.doob 已提交
2975 2976 2977
				glFormat = paramThreeToGL( texture.format ),
				glType = paramThreeToGL( texture.type );

M
Mr.doob 已提交
2978
				setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
M
Mr.doob 已提交
2979 2980 2981

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

2982
					if ( ! isCompressed ) {
M
Mr.doob 已提交
2983

M
Mr.doob 已提交
2984
						if ( isDataTexture ) {
2985

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

M
Mr.doob 已提交
2988
						} else {
2989

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

M
Mr.doob 已提交
2992 2993
						}

2994
					} else {
2995

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

2998
						for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
M
Mr.doob 已提交
2999 3000

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

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

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

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

3008
								} else {
M
Mr.doob 已提交
3009

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

3012
								}
M
Mr.doob 已提交
3013

3014
							} else {
M
Mr.doob 已提交
3015

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

3018
							}
M
Mr.doob 已提交
3019

3020
						}
M
Mr.doob 已提交
3021

M
Mr.doob 已提交
3022
					}
M
Mr.doob 已提交
3023

M
Mr.doob 已提交
3024 3025
				}

M
Mr.doob 已提交
3026
				if ( texture.generateMipmaps && isPowerOfTwoImage ) {
M
Mr.doob 已提交
3027 3028 3029 3030 3031

					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

				}

3032
				textureProperties.__version = texture.version;
M
Mr.doob 已提交
3033

B
Ben Adams 已提交
3034
				if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
3035 3036 3037

			} else {

B
Ben Adams 已提交
3038
				state.activeTexture( _gl.TEXTURE0 + slot );
3039
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
3040 3041 3042 3043 3044

			}

		}

M
Mr.doob 已提交
3045
	}
M
Mr.doob 已提交
3046 3047 3048

	function setCubeTextureDynamic ( texture, slot ) {

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

M
Mr.doob 已提交
3052
	}
M
Mr.doob 已提交
3053

T
tschw 已提交
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
	var setTextureWarned = false;
	this.setTexture = function( texture, slot ) {

		if ( ! setTextureWarned ) {

			console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, " +
				"use setTexture2D instead." );
			setTextureWarned = true;

		}

		setTexture2D( texture, slot );

	};

	this.allocTextureUnit = allocTextureUnit;
	this.setTexture2D = setTexture2D;
	this.setTextureCube = function( texture, slot ) {

		if ( texture instanceof THREE.CubeTexture ||
			 ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

			// CompressedTexture can have Array in image :/

			setCubeTexture( texture, slot );

		} else {
			// assumed: texture instanceof THREE.WebGLRenderTargetCube

			setCubeTextureDynamic( texture.texture, slot );

		}

	};

M
Mr.doob 已提交
3089 3090
	// Render targets

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

3094 3095 3096
		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 已提交
3097
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
3098 3099
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
M
Mr.doob 已提交
3100

M
Mr.doob 已提交
3101
	}
M
Mr.doob 已提交
3102

3103 3104
	// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
	function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
M
Mr.doob 已提交
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119

		_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 {

3120
			// FIXME: We don't support !depth !stencil
M
Mr.doob 已提交
3121 3122 3123 3124
			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );

		}

3125
		_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
M
Mr.doob 已提交
3126

M
Mr.doob 已提交
3127
	}
M
Mr.doob 已提交
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 3156 3157 3158
	// Setup resources for a Depth Texture for a FBO (needs an extension)
	function setupDepthTexture ( framebuffer, renderTarget ) {

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
		if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');

		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );

		if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) {

			throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');

		}

		// upload an empty depth texture with framebuffer size
		if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
				renderTarget.depthTexture.image.width !== renderTarget.width ||
				renderTarget.depthTexture.image.height !== renderTarget.height ) {
			renderTarget.depthTexture.image.width = renderTarget.width;
			renderTarget.depthTexture.image.height = renderTarget.height;
			renderTarget.depthTexture.needsUpdate = true;
		}

		_this.setTexture( renderTarget.depthTexture, 0 );

		var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );

	}

3159
	// Setup GL resources for a non-texture depth buffer
M
Marius Kintel 已提交
3160
	function setupDepthRenderbuffer( renderTarget ) {
M
Mr.doob 已提交
3161

3162
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
3163 3164

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
M
Mr.doob 已提交
3165

3166
		if ( renderTarget.depthTexture ) {
M
Mr.doob 已提交
3167

3168
			if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
M
Mr.doob 已提交
3169

3170 3171 3172
			setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );

		} else {
M
Mr.doob 已提交
3173

3174
			if ( isCube ) {
M
Mr.doob 已提交
3175

3176
				renderTargetProperties.__webglDepthbuffer = [];
B
Ben Adams 已提交
3177

3178 3179 3180 3181 3182
				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 已提交
3183

3184 3185 3186 3187 3188 3189 3190 3191 3192
				}

			} else {

				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
				renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
				setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );

			}
M
Mr.doob 已提交
3193

3194
		}
M
Mr.doob 已提交
3195

M
Marius Kintel 已提交
3196
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
M
Mr.doob 已提交
3197

M
Mr.doob 已提交
3198
	}
M
Mr.doob 已提交
3199

3200
	// Set up GL resources for the render target
M
Marius Kintel 已提交
3201
	function setupRenderTarget( renderTarget ) {
M
Mr.doob 已提交
3202

3203 3204
		var renderTargetProperties = properties.get( renderTarget );
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
3205

3206
		renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
M
Mr.doob 已提交
3207

3208
		textureProperties.__webglTexture = _gl.createTexture();
M
Mr.doob 已提交
3209

3210
		_infoMemory.textures ++;
M
Mr.doob 已提交
3211

3212 3213
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
		var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
M
Mr.doob 已提交
3214

3215
		// Setup framebuffer
M
Mr.doob 已提交
3216

3217
		if ( isCube ) {
M
Mr.doob 已提交
3218

3219
			renderTargetProperties.__webglFramebuffer = [];
M
Mr.doob 已提交
3220

3221
			for ( var i = 0; i < 6; i ++ ) {
M
Mr.doob 已提交
3222

3223
				renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
M
Mr.doob 已提交
3224

3225
			}
M
Mr.doob 已提交
3226

3227
		} else {
M
Mr.doob 已提交
3228

3229
			renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
M
Mr.doob 已提交
3230

3231
		}
M
Mr.doob 已提交
3232

3233
		// Setup color buffer
M
Mr.doob 已提交
3234

3235
		if ( isCube ) {
M
Mr.doob 已提交
3236

3237 3238
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
M
Mr.doob 已提交
3239

3240
			for ( var i = 0; i < 6; i ++ ) {
M
Mr.doob 已提交
3241

3242
				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
M
Mr.doob 已提交
3243 3244 3245

			}

3246 3247
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
M
Mr.doob 已提交
3248

3249
		} else {
M
Mr.doob 已提交
3250

3251 3252 3253
			state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
			setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
M
Mr.doob 已提交
3254

3255 3256
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
			state.bindTexture( _gl.TEXTURE_2D, null );
M
Mr.doob 已提交
3257

3258
		}
M
Mr.doob 已提交
3259

3260
		// Setup depth and stencil buffers
3261

3262
		if ( renderTarget.depthBuffer ) {
M
Mr.doob 已提交
3263

M
Marius Kintel 已提交
3264
			setupDepthRenderbuffer( renderTarget );
M
Mr.doob 已提交
3265

3266
		}
M
Mr.doob 已提交
3267

3268
	}
M
Mr.doob 已提交
3269

3270 3271 3272 3273
	this.getCurrentRenderTarget = function() {

		return _currentRenderTarget;

M
Michael Herzog 已提交
3274
	};
3275

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

3278 3279
		_currentRenderTarget = renderTarget;

3280
		if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
M
Mr.doob 已提交
3281

M
Marius Kintel 已提交
3282
			setupRenderTarget( renderTarget );
M
Mr.doob 已提交
3283 3284 3285

		}

3286
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
3287
		var framebuffer;
M
Mr.doob 已提交
3288 3289 3290

		if ( renderTarget ) {

3291
			var renderTargetProperties = properties.get( renderTarget );
F
Fordy 已提交
3292

M
Mr.doob 已提交
3293 3294
			if ( isCube ) {

3295
				framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
M
Mr.doob 已提交
3296 3297 3298

			} else {

3299
				framebuffer = renderTargetProperties.__webglFramebuffer;
M
Mr.doob 已提交
3300 3301 3302

			}

3303 3304
			_currentScissor.copy( renderTarget.scissor );
			_currentScissorTest = renderTarget.scissorTest;
3305

3306
			_currentViewport.copy( renderTarget.viewport );
M
Mr.doob 已提交
3307 3308 3309 3310 3311

		} else {

			framebuffer = null;

3312
			_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
3313
			_currentScissorTest = _scissorTest;
3314

3315
			_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
M
Mr.doob 已提交
3316 3317 3318

		}

M
Mr.doob 已提交
3319
		if ( _currentFramebuffer !== framebuffer ) {
M
Mr.doob 已提交
3320 3321 3322 3323 3324 3325

			_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
			_currentFramebuffer = framebuffer;

		}

3326 3327
		state.scissor( _currentScissor );
		state.setScissorTest( _currentScissorTest );
3328

3329
		state.viewport( _currentViewport );
3330

M
Mr.doob 已提交
3331 3332 3333
		if ( isCube ) {

			var textureProperties = properties.get( renderTarget.texture );
3334
			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
M
Mr.doob 已提交
3335 3336 3337

		}

M
Mr.doob 已提交
3338 3339
	};

M
Mr.doob 已提交
3340
	this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
3341

M
Mr.doob 已提交
3342
		if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
3343

3344
			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
G
gero3 已提交
3345
			return;
3346

G
gero3 已提交
3347
		}
3348

M
Mr.doob 已提交
3349
		var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
3350

M
Mr.doob 已提交
3351
		if ( framebuffer ) {
3352

G
gero3 已提交
3353
			var restore = false;
3354

M
Mr.doob 已提交
3355
			if ( framebuffer !== _currentFramebuffer ) {
3356

M
Mr.doob 已提交
3357
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
3358

G
gero3 已提交
3359
				restore = true;
3360

G
gero3 已提交
3361
			}
3362

M
Mr.doob 已提交
3363
			try {
3364

M
Mr.doob 已提交
3365
				var texture = renderTarget.texture;
3366

M
Michael Herzog 已提交
3367
				if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
3368

M
Mr.doob 已提交
3369 3370
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
					return;
3371

M
Mr.doob 已提交
3372
				}
3373

M
Michael Herzog 已提交
3374 3375 3376 3377
				if ( texture.type !== THREE.UnsignedByteType &&
				     paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) &&
				     ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) &&
				     ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
3378

M
Mr.doob 已提交
3379 3380
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
					return;
3381

M
Mr.doob 已提交
3382
				}
3383

M
Mr.doob 已提交
3384
				if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
3385

3386 3387 3388 3389 3390 3391 3392
					// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)

					if ( ( x > 0 && x <= ( renderTarget.width - width ) ) && ( y > 0 && y <= ( renderTarget.height - height ) ) ) {

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

					}
3393

M
Mr.doob 已提交
3394
				} else {
M
Mr.doob 已提交
3395

M
Mr.doob 已提交
3396 3397 3398
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

				}
M
Mr.doob 已提交
3399

M
Mr.doob 已提交
3400
			} finally {
M
Mr.doob 已提交
3401

M
Mr.doob 已提交
3402 3403 3404
				if ( restore ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
M
Mr.doob 已提交
3405

M
Mr.doob 已提交
3406 3407 3408
				}

			}
M
Mr.doob 已提交
3409 3410 3411

		}

M
Mr.doob 已提交
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
	};

	function updateRenderTargetMipmap( renderTarget ) {

		var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
		var texture = properties.get( renderTarget.texture ).__webglTexture;

		state.bindTexture( target, texture );
		_gl.generateMipmap( target );
		state.bindTexture( target, null );

M
Mr.doob 已提交
3423
	}
M
Mr.doob 已提交
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436

	// 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 已提交
3437
	}
M
Mr.doob 已提交
3438 3439 3440 3441 3442

	// Map three.js constants to WebGL constants

	function paramThreeToGL ( p ) {

3443 3444
		var extension;

M
Mr.doob 已提交
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
		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;

3469 3470 3471 3472 3473 3474 3475 3476
		extension = extensions.get( 'OES_texture_half_float' );

		if ( extension !== null ) {

			if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;

		}

M
Mr.doob 已提交
3477 3478 3479 3480 3481
		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;
3482
		if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT;
M
Mr.doob 已提交
3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500

		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;

3501
		extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
M
Mr.doob 已提交
3502

3503 3504 3505 3506 3507 3508
		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 已提交
3509 3510 3511

		}

3512 3513 3514
		extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

		if ( extension !== null ) {
P
Pierre Lepers 已提交
3515

3516 3517 3518 3519
			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 已提交
3520 3521 3522

		}

3523 3524 3525 3526 3527 3528 3529 3530
		extension = extensions.get( 'WEBGL_compressed_texture_etc1' );

		if ( extension !== null ) {

			if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;

		}

3531 3532 3533
		extension = extensions.get( 'EXT_blend_minmax' );

		if ( extension !== null ) {
3534

3535 3536
			if ( p === THREE.MinEquation ) return extension.MIN_EXT;
			if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
3537 3538 3539

		}

M
Mr.doob 已提交
3540 3541
		return 0;

M
Mr.doob 已提交
3542
	}
M
Mr.doob 已提交
3543 3544

};