Browse Source

Merge branch 'dev' into shadow-filtering

alteredq 12 years ago
parent
commit
9c8c639f9c
100 changed files with 4132 additions and 2472 deletions
  1. 725 672
      build/three.js
  2. 180 155
      build/three.min.js
  3. 2 2
      docs/api/core/Projector.html
  4. 11 14
      docs/api/extras/core/Curve.html
  5. 2 2
      docs/api/extras/geometries/ExtrudeGeometry.html
  6. 1 1
      docs/api/extras/geometries/IcosahedronGeometry.html
  7. 1 1
      docs/api/extras/geometries/LatheGeometry.html
  8. 1 1
      docs/api/extras/geometries/OctahedronGeometry.html
  9. 1 1
      docs/api/extras/geometries/PlaneGeometry.html
  10. 1 1
      docs/api/extras/geometries/PolyhedronGeometry.html
  11. 1 1
      docs/api/extras/geometries/TetrahedronGeometry.html
  12. 1 1
      docs/api/extras/geometries/TextGeometry.html
  13. 1 1
      docs/api/extras/geometries/TorusGeometry.html
  14. 1 1
      docs/api/extras/geometries/TorusKnotGeometry.html
  15. 5 4
      docs/api/extras/modifiers/SubdivisionModifier.html
  16. 1 1
      docs/api/extras/objects/LensFlare.html
  17. 4 2
      docs/api/materials/ShaderMaterial.html
  18. 1 1
      docs/api/textures/DataTexture.html
  19. 1 1
      docs/api/textures/Texture.html
  20. 36 4
      docs/index.html
  21. 1 1
      docs/list.js
  22. 6 2
      editor/js/ui/Viewport.js
  23. 2 2
      examples/canvas_interactive_cubes.html
  24. 2 2
      examples/canvas_interactive_cubes_tween.html
  25. 2 2
      examples/canvas_interactive_particles.html
  26. 5 5
      examples/canvas_interactive_voxelpainter.html
  27. 0 417
      examples/js/DeferredHelper.js
  28. 260 146
      examples/js/ShaderDeferred.js
  29. 12 12
      examples/js/UVsUtils.js
  30. 2 2
      examples/js/loaders/ColladaLoader.js
  31. 1 1
      examples/js/loaders/OBJLoader.js
  32. 1 1
      examples/js/loaders/OBJMTLLoader.js
  33. 4 4
      examples/js/loaders/UTF8Loader.js
  34. 3 3
      examples/js/loaders/ctm/CTMLoader.js
  35. 22 10
      examples/js/postprocessing/EffectComposer.js
  36. 5 5
      examples/js/renderers/CSS3DRenderer.js
  37. 1 1
      examples/js/renderers/DOMRenderer.js
  38. 574 0
      examples/js/renderers/WebGLDeferredRenderer.js
  39. 1 1
      examples/misc_controls_pointerlock.html
  40. 2 2
      examples/webgl_interactive_cubes.html
  41. 6 6
      examples/webgl_interactive_draggablecubes.html
  42. 4 4
      examples/webgl_interactive_voxelpainter.html
  43. 45 38
      examples/webgl_lights_deferred_morphs.html
  44. 80 39
      examples/webgl_lights_deferred_pointlights.html
  45. 3 6
      examples/webgl_marching_cubes.html
  46. 4 7
      examples/webgl_materials_cubemap_dynamic.html
  47. 2 2
      examples/webgl_materials_video.html
  48. 8 10
      examples/webgl_postprocessing.html
  49. 3 6
      examples/webgl_shading_physical.html
  50. 14 12
      src/core/BufferGeometry.js
  51. 17 69
      src/core/Geometry.js
  52. 4 5
      src/core/Object3D.js
  53. 1 1
      src/core/Projector.js
  54. 0 285
      src/core/Ray.js
  55. 255 0
      src/core/Raycaster.js
  56. 0 49
      src/core/UV.js
  57. 25 40
      src/extras/FontUtils.js
  58. 12 18
      src/extras/GeometryUtils.js
  59. 10 22
      src/extras/core/Curve.js
  60. 3 3
      src/extras/geometries/CircleGeometry.js
  61. 1 1
      src/extras/geometries/ConvexGeometry.js
  62. 4 4
      src/extras/geometries/CubeGeometry.js
  63. 3 3
      src/extras/geometries/CylinderGeometry.js
  64. 11 11
      src/extras/geometries/ExtrudeGeometry.js
  65. 5 5
      src/extras/geometries/LatheGeometry.js
  66. 4 4
      src/extras/geometries/ParametricGeometry.js
  67. 4 4
      src/extras/geometries/PlaneGeometry.js
  68. 4 4
      src/extras/geometries/PolyhedronGeometry.js
  69. 2 2
      src/extras/geometries/SphereGeometry.js
  70. 1 1
      src/extras/geometries/TorusGeometry.js
  71. 4 4
      src/extras/geometries/TorusKnotGeometry.js
  72. 4 4
      src/extras/geometries/TubeGeometry.js
  73. 19 19
      src/extras/modifiers/SubdivisionModifier.js
  74. 7 7
      src/loaders/BinaryLoader.js
  75. 2 2
      src/loaders/JSONLoader.js
  76. 6 0
      src/loaders/Loader.js
  77. 257 240
      src/loaders/SceneLoader.js
  78. 4 5
      src/materials/Material.js
  79. 270 0
      src/math/Box2.js
  80. 295 0
      src/math/Box3.js
  81. 0 0
      src/math/Clock.js
  82. 0 0
      src/math/Color.js
  83. 19 18
      src/math/Frustum.js
  84. 15 0
      src/math/Math.js
  85. 0 0
      src/math/Matrix3.js
  86. 0 0
      src/math/Matrix4.js
  87. 152 0
      src/math/Plane.js
  88. 0 0
      src/math/Quaternion.js
  89. 161 0
      src/math/Ray.js
  90. 0 0
      src/math/Rectangle.js
  91. 132 0
      src/math/Sphere.js
  92. 0 0
      src/math/Spline.js
  93. 10 0
      src/math/UV.js
  94. 89 0
      src/math/Vector2.js
  95. 91 2
      src/math/Vector3.js
  96. 157 1
      src/math/Vector4.js
  97. 0 0
      src/math/Vertex.js
  98. 2 2
      src/renderers/WebGLRenderTarget.js
  99. 14 14
      src/renderers/WebGLRenderer.js
  100. 4 7
      src/renderers/WebGLShaders.js

File diff suppressed because it is too large
+ 725 - 672
build/three.js


File diff suppressed because it is too large
+ 180 - 155
build/three.min.js


+ 2 - 2
docs/api/core/Projector.html

@@ -23,9 +23,9 @@
 
 		<h3>.unprojectVector( [page:Vector3 vector], [page:Camera camera] ) [page:Vector3]</h3>
 
-		<h3>.pickingRay( [page:Vector3 vector], [page:Camera camera] ) [page:Ray]</h3>
+		<h3>.pickingRay( [page:Vector3 vector], [page:Camera camera] ) [page:Raycaster]</h3>
 		<div>
-		Translates a 2D point from NDC (<em>Normalized Device Coordinates</em>) to a [page:Ray] that can be used for picking. NDC range from [-1..1] in x (left to right) and [1.0 .. -1.0] in y (top to bottom).
+		Translates a 2D point from NDC (<em>Normalized Device Coordinates</em>) to a [page:Raycaster] that can be used for picking. NDC range from [-1..1] in x (left to right) and [1.0 .. -1.0] in y (top to bottom).
 		</div>
 
 		<h3>.projectScene( [page:Scene scene], [page:Camera camera], [page:Boolean sort] ) [page:Object]</h3>

+ 11 - 14
docs/api/extras/core/Curve.html

@@ -9,7 +9,7 @@
 	<body>
 		<h1>[name]</h1>
 
-		<div class="desc">todo</div>
+		<div class="desc">An extensible curve object which contains methods for interpolation</div>
 
 
 		<h2>Constructor</h2>
@@ -25,37 +25,34 @@
 		<h2>Methods</h2>
 
 		<h3>.getPoint ( t )</h3>
-		<div>todo</div>
+		<div>Returns a vector for point t of the curve where t is between 0 and 1</div>
 
 		<h3>.getPointAt ( u )</h3>
-		<div>todo</div>
+		<div>Returns a vector for point at relative position in curve according to arc length</div>
 
 		<h3>.getPoints ( divisions )</h3>
-		<div>todo</div>
+		<div>Get sequence of points using getPoint( t ) </div>
 
 		<h3>.getSpacedPoints ( divisions )</h3>
-		<div>todo</div>
+		<div>Get sequence of equi-spaced points using getPointAt( u )</div>
 
 		<h3>.getLength ()</h3>
-		<div>todo</div>
+		<div>Get total curve arc length</div>
 
 		<h3>.getLengths ( divisions )</h3>
-		<div>todo</div>
+		<div>Get list of cumulative segment lengths</div>
 
 		<h3>.updateArcLengths ()</h3>
-		<div>todo</div>
+		<div>Update the cumlative segment distance cache</div>
 
 		<h3>.getUtoTmapping ( u, distance )</h3>
-		<div>todo</div>
-
-		<h3>.getNormalVector ( t )</h3>
-		<div>todo</div>
+		<div>Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance</div>
 
 		<h3>.getTangent ( t )</h3>
-		<div>todo</div>
+		<div>Returns a unit vector tangent at t. If the subclassed curve do not implement its tangent derivation, 2 points a small delta apart will be used to find its gradient which seems to give a reasonable approximation</div>
 
 		<h3>.getTangentAt ( u )</h3>
-		<div>todo</div>
+		<div>Returns tangent at equidistance point u on the curve</div>
 
 
 		<h2>Source</h2>

+ 2 - 2
docs/api/extras/geometries/ExtrudeGeometry.html

@@ -9,12 +9,12 @@
 	<body>
 		<h1>[name]</h1>
 
-		<div class="desc">todo</div>
+		<div class="desc">Creates extruded geometry from a path shape</div>
 
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( shapes, options )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/IcosahedronGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( radius, detail )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/LatheGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( points, steps, angle )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/OctahedronGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( radius, detail )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/PlaneGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( width, height, widthSegments, heightSegments )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/PolyhedronGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( vertices, faces, radius, detail )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/TetrahedronGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( radius, detail )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/TextGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( text, parameters )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/TorusGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( radius, tube, radialSegments, tubularSegments, arc )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/extras/geometries/TorusKnotGeometry.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( radius, tube, radialSegments, tubularSegments, arc )</h3>
 
 
 		<h2>Properties</h2>

+ 5 - 4
docs/api/extras/modifiers/SubdivisionModifier.html

@@ -9,17 +9,18 @@
 	<body>
 		<h1>[name]</h1>
 
-		<div class="desc">todo</div>
+		<div class="desc">Applies Catmull-Clark Subdivision Surfaces for creating smooth geometry meshes</div>
 
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( subdivisions )</h3>
 
 
 		<h2>Properties</h2>
 
 		<h3>.subdivisions</h3>
+		<div>Number of time subdivision will be applied</div>
 
 		<h3>.useOldVertexColors</h3>
 
@@ -30,10 +31,10 @@
 		<h2>Methods</h2>
 
 		<h3>.modify ( geometry )</h3>
-		<div>todo</div>
+		<div>Modifies the geometry by running subdivision surfaces. This calls .smooth() internally</div>
 
 		<h3>.smooth ( oldGeometry )</h3>
-		<div>todo</div>
+		<div>Performs an iteration of Catmull-Clark Subdivision</div>
 
 
 

+ 1 - 1
docs/api/extras/objects/LensFlare.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( texture, size, distance, blending, color )</h3>
 
 
 		<h2>Properties</h2>

+ 4 - 2
docs/api/materials/ShaderMaterial.html

@@ -11,12 +11,14 @@
 
 		<h1>[name]</h1>
 
-		<div class="desc">todo</div>
+		<div class="desc">Material rendered with custom shaders</div>
 
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( parameters )
+
+</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/textures/DataTexture.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy )</h3>
 
 
 		<h2>Properties</h2>

+ 1 - 1
docs/api/textures/Texture.html

@@ -14,7 +14,7 @@
 
 		<h2>Constructor</h2>
 
-		<h3>[name]()</h3>
+		<h3>[name]( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )</h3>
 
 
 		<h2>Properties</h2>

+ 36 - 4
docs/index.html

@@ -104,6 +104,9 @@
 
 			var html = '<h1><a href="http://threejs.org">three.js</a><span style="font-size: 50%; vertical-align: super;"> r' + REVISION + '</span></h1>';
 
+			var DELIMITER = '/';
+			var nameCategoryMap = {};
+
 			for ( var section in list ) {
 
 				html += '<h2>' + section + '</h2>';
@@ -122,6 +125,12 @@
 
 						html += '<li><a href="javascript:goTo(\'' + section + '\', \'' + category + '\', \'' + page[ 0 ] + '\')">' + page[ 0 ] + '</a></li>';
 
+						nameCategoryMap[page[0]] = {
+							section: section,
+							category: category,
+							name: page[0]
+						};
+
 					}
 
 					html += '</ul>';
@@ -134,13 +143,36 @@
 
 			panel.innerHTML += html;
 
+			function encodeUrl( path ) {
+
+				return path.replace(/\ \/\ /g, '.').replace(/\ /g, '_');
+
+			}
+
+			function decodeUrl( path ) {
+
+				return path.replace(/_/g, ' ').replace(/\./g, ' / ');
+
+			}
+
 			// Page loading
 
 			function goTo( section, category, name ) {
 
-				window.document.title = 'three.js - documentation - ' + section + ' - ' + name;
+				// Fully resolve links that only provide a name
+				if(arguments.length == 1) {
+					var location = nameCategoryMap[section];
+					section = location.section;
+					category = location.category;
+					name = location.name;
+				}
+
+				var title = 'three.js - documentation - ' + section + ' - ' + name;
+				var url = encodeUrl(section) + DELIMITER + encodeUrl( category ) + DELIMITER + encodeUrl(name);
+
+				window.location.hash = url;
+				window.document.title = title;
 
-				window.location.hash = section + '/' + category + '/' + name.replace(/\ /g, '-');
 
 				viewer.src = pages[ section ][ category ][ name ] + '.html';
 
@@ -148,8 +180,8 @@
 
 			function goToHash() {
 
-				var hash = window.location.hash.substring( 1 ).split('/');
-				goTo( hash[0], hash[1], hash[2].replace(/\-/g, ' ') );
+				var hash = window.location.hash.substring( 1 ).split(DELIMITER);
+				goTo( decodeUrl(hash[0]), decodeUrl(hash[1]), decodeUrl(hash[2]) );
 
 			}
 

+ 1 - 1
docs/list.js

@@ -26,7 +26,7 @@ var list = {
 			[ "Object3D", "api/core/Object3D" ],
 			[ "Projector", "api/core/Projector" ],
 			[ "Quaternion", "api/core/Quaternion" ],
-			[ "Ray", "api/core/Ray" ],
+			[ "Raycaster", "api/core/Raycaster" ],
 			[ "Rectangle", "api/core/Rectangle" ],
 			[ "Spline", "api/core/Spline" ],
 			[ "UV", "api/core/UV" ],

+ 6 - 2
editor/js/ui/Viewport.js

@@ -66,7 +66,7 @@ var Viewport = function ( signals ) {
 	intersectionPlane.visible = false;
 	sceneHelpers.add( intersectionPlane );
 
-	var ray = new THREE.Ray();
+	var ray = new THREE.Raycaster();
 	var projector = new THREE.Projector();
 	var offset = new THREE.Vector3();
 
@@ -714,7 +714,7 @@ var Viewport = function ( signals ) {
 		defaultScene.add( defaultCamera );
 
 		signals.sceneAdded.dispatch( defaultScene, defaultCamera, defaultBgColor );
-		signals.objectSelected.dispatch( defaultScene.properties.defaultSelection );
+		signals.objectSelected.dispatch( defaultCamera );
 
 	} );
 
@@ -872,6 +872,8 @@ var Viewport = function ( signals ) {
 
 		var scene = new THREE.Scene();
 
+		/*
+
 		// create lights
 
 		var light1 = new THREE.DirectionalLight( 0xffffff, 0.8 );
@@ -925,6 +927,8 @@ var Viewport = function ( signals ) {
 		scene.add( light4 );
 		scene.add( mesh );
 
+		*/
+
 		return scene;
 
 	}

+ 2 - 2
examples/canvas_interactive_cubes.html

@@ -122,9 +122,9 @@
 				var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
-				var intersects = ray.intersectObjects( objects );
+				var intersects = raycaster.intersectObjects( objects );
 
 				if ( intersects.length > 0 ) {
 

+ 2 - 2
examples/canvas_interactive_cubes_tween.html

@@ -101,9 +101,9 @@
 				var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 

+ 2 - 2
examples/canvas_interactive_particles.html

@@ -149,9 +149,9 @@
 				var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 

+ 5 - 5
examples/canvas_interactive_voxelpainter.html

@@ -24,7 +24,7 @@
 			var container, stats;
 			var camera, scene, renderer;
 			var projector, plane;
-			var mouse2D, mouse3D, ray, theta = 45,
+			var mouse2D, mouse3D, raycaster, theta = 45,
 			isShiftDown = false, isCtrlDown = false,
 			target = new THREE.Vector3( 0, 200, 0 );
 			var ROLLOVERED;
@@ -82,7 +82,7 @@
 				scene.add( plane );
 
 				mouse2D = new THREE.Vector3( 0, 10000, 0.5 );
-				ray = new THREE.Ray( camera.position, null );
+				raycaster = new THREE.Raycaster( camera.position, null );
 
 				// Lights
 
@@ -141,9 +141,9 @@
 				mouse2D.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
 
 				mouse3D = projector.unprojectVector( mouse2D.clone(), camera );
-				ray.direction = mouse3D.subSelf( camera.position ).normalize();
+				raycaster.direction = mouse3D.subSelf( camera.position ).normalize();
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 
@@ -160,7 +160,7 @@
 
 				event.preventDefault();
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 

+ 0 - 417
examples/js/DeferredHelper.js

@@ -1,417 +0,0 @@
-/**
- * @author alteredq / http://alteredqualia.com/
- * @author MPanknin / http://www.redplant.de/
- */
-
-THREE.DeferredHelper = function ( parameters ) {
-
-	var width = parameters.width;
-	var height = parameters.height;
-
-	var scene = parameters.scene;
-	var camera = parameters.camera;
-	var renderer = parameters.renderer;
-
-	// scene for light proxy geometry
-
-	var lightScene = new THREE.Scene();
-	lightNode = new THREE.Object3D();
-	lightScene.add( lightNode );
-
-	// scene for the coloured emitter spheres
-
-	var emitterScene = new THREE.Scene();
-	emitterNode = new THREE.Object3D();
-	emitterScene.add( emitterNode );
-
-	//
-
-	var black = new THREE.Color( 0x000000 );
-
-	var colorShader = THREE.ShaderDeferred[ "color" ];
-	var normalShader = THREE.ShaderDeferred[ "normals" ];
-	var bumpShader = THREE.ShaderDeferred[ "bump" ];
-	var clipDepthShader = THREE.ShaderDeferred[ "clipDepth" ];
-
-	//
-
-	var unlitShader = THREE.ShaderDeferred[ "unlit" ];
-	var lightShader = THREE.ShaderDeferred[ "light" ];
-	var compositeShader = THREE.ShaderDeferred[ "composite" ];
-
-	unlitShader.uniforms[ "viewWidth" ].value = width;
-	unlitShader.uniforms[ "viewHeight" ].value = height;
-
-	lightShader.uniforms[ "viewWidth" ].value = width;
-	lightShader.uniforms[ "viewHeight" ].value = height;
-
-	//
-
-	var compColor, compNormal, compDepth, compLightBuffer, compFinal, compEmitter, compositePass;
-
-	//
-
-	var defaultNormalMaterial = new THREE.ShaderMaterial( {
-
-		uniforms:       THREE.UniformsUtils.clone( normalShader.uniforms ),
-		vertexShader:   normalShader.vertexShader,
-		fragmentShader: normalShader.fragmentShader
-
-	} );
-
-	var defaultDepthMaterial = new THREE.ShaderMaterial( {
-
-		uniforms:       THREE.UniformsUtils.clone( clipDepthShader.uniforms ),
-		vertexShader:   clipDepthShader.vertexShader,
-		fragmentShader: clipDepthShader.fragmentShader
-
-	} );
-
-	//
-
-	var rtParamsFloatLinear = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
-								format: THREE.RGBAFormat, type: THREE.FloatType };
-
-	var rtParamsFloatNearest = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, stencilBuffer: false,
-								 format: THREE.RGBAFormat, type: THREE.FloatType };
-
-	var rtParamsUByte = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
-						  format: THREE.RGBFormat, type: THREE.UnsignedByteType };
-
-	//
-
-	this.addDeferredMaterials = function ( object ) {
-
-		object.traverse( function( node ) {
-
-			if ( !node.material ) return;
-
-			var originalMaterial = node.material;
-
-			// color material
-			// 	diffuse color
-			//	specular color
-			//	shininess
-			//	diffuse map
-			//	vertex colors
-			//	alphaTest
-			// 	morphs
-
-			var uniforms = THREE.UniformsUtils.clone( colorShader.uniforms );
-			var defines = { "USE_MAP": !! originalMaterial.map, "GAMMA_INPUT": true };
-
-			var material = new THREE.ShaderMaterial( {
-
-				fragmentShader: colorShader.fragmentShader,
-				vertexShader: 	colorShader.vertexShader,
-				uniforms: 		uniforms,
-				defines: 		defines,
-				shading:		originalMaterial.shading
-
-			} );
-
-			var diffuse = originalMaterial.color;
-			var specular = originalMaterial.specular !== undefined ? originalMaterial.specular : black;
-			var shininess = originalMaterial.shininess !== undefined ? originalMaterial.shininess : 1;
-
-			uniforms.diffuse.value.copy( diffuse );
-			uniforms.specular.value.copy( specular );
-			uniforms.shininess.value = shininess;
-
-			uniforms.map.value = originalMaterial.map;
-
-			material.vertexColors = originalMaterial.vertexColors;
-			material.morphTargets = originalMaterial.morphTargets;
-			material.morphNormals = originalMaterial.morphNormals;
-
-			material.alphaTest = originalMaterial.alphaTest;
-
-			if ( originalMaterial.bumpMap ) {
-
-				var offset = originalMaterial.bumpMap.offset;
-				var repeat = originalMaterial.bumpMap.repeat;
-
-				uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
-
-			}
-
-			node.properties.colorMaterial = material;
-
-			// normal material
-			//	vertex normals
-			//	morph normals
-			//	bump map
-			//	bump scale
-
-			if ( originalMaterial.bumpMap ) {
-
-				var uniforms = THREE.UniformsUtils.clone( bumpShader.uniforms );
-
-				var normalMaterial = new THREE.ShaderMaterial( {
-
-					uniforms: 		uniforms,
-					vertexShader: 	bumpShader.vertexShader,
-					fragmentShader: bumpShader.fragmentShader,
-					defines:		{ "USE_BUMPMAP": true }
-
-				} );
-
-				uniforms.bumpMap.value = originalMaterial.bumpMap;
-				uniforms.bumpScale.value = originalMaterial.bumpScale;
-
-				var offset = originalMaterial.bumpMap.offset;
-				var repeat = originalMaterial.bumpMap.repeat;
-
-				uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
-
-				node.properties.normalMaterial = normalMaterial;
-
-			} else if ( originalMaterial.morphTargets ) {
-
-				var normalMaterial = new THREE.ShaderMaterial( {
-
-					uniforms:       THREE.UniformsUtils.clone( normalShader.uniforms ),
-					vertexShader:   normalShader.vertexShader,
-					fragmentShader: normalShader.fragmentShader,
-					shading:		originalMaterial.shading
-
-				} );
-
-				normalMaterial.morphTargets = originalMaterial.morphTargets;
-				normalMaterial.morphNormals = originalMaterial.morphNormals;
-
-				node.properties.normalMaterial = normalMaterial;
-
-			} else {
-
-				node.properties.normalMaterial = defaultNormalMaterial;
-
-			}
-
-			// depth material
-
-			if ( originalMaterial.morphTargets ) {
-
-				var depthMaterial = new THREE.ShaderMaterial( {
-
-					uniforms:       THREE.UniformsUtils.clone( clipDepthShader.uniforms ),
-					vertexShader:   clipDepthShader.vertexShader,
-					fragmentShader: clipDepthShader.fragmentShader
-
-				} );
-
-				depthMaterial.morphTargets = originalMaterial.morphTargets;
-
-				node.properties.depthMaterial = depthMaterial;
-
-			} else {
-
-				node.properties.depthMaterial = defaultDepthMaterial;
-
-			}
-
-		} );
-
-	};
-
-	this.createRenderTargets = function ( ) {
-
-		// g-buffers
-
-		var rtColor   = new THREE.WebGLRenderTarget( width, height, rtParamsFloatNearest );
-		var rtNormal  = new THREE.WebGLRenderTarget( width, height, rtParamsFloatLinear );
-		var rtDepth   = new THREE.WebGLRenderTarget( width, height, rtParamsFloatLinear );
-		var rtLight   = new THREE.WebGLRenderTarget( width, height, rtParamsFloatLinear );
-		var rtEmitter = new THREE.WebGLRenderTarget( width, height, rtParamsUByte );
-		var rtFinal   = new THREE.WebGLRenderTarget( width, height, rtParamsUByte );
-
-		rtColor.generateMipmaps = false;
-		rtNormal.generateMipmaps = false;
-		rtDepth.generateMipmaps = false;
-		rtLight.generateMipmaps = false;
-		rtEmitter.generateMipmaps = false;
-		rtFinal.generateMipmaps = false;
-
-		// composers
-
-		var passColor = new THREE.RenderPass( scene, camera );
-		compColor = new THREE.EffectComposer( renderer, rtColor );
-		compColor.addPass( passColor );
-
-		var passNormal = new THREE.RenderPass( scene, camera );
-		compNormal = new THREE.EffectComposer( renderer, rtNormal );
-		compNormal.addPass( passNormal );
-
-		var passDepth = new THREE.RenderPass( scene, camera );
-		compDepth = new THREE.EffectComposer( renderer, rtDepth );
-		compDepth.addPass( passDepth );
-
-		var passEmitter = new THREE.RenderPass( emitterScene, camera );
-		compEmitter = new THREE.EffectComposer( renderer, rtEmitter );
-		compEmitter.addPass( passEmitter );
-
-		var passLight = new THREE.RenderPass( lightScene, camera );
-		compLightBuffer = new THREE.EffectComposer( renderer, rtLight );
-		compLightBuffer.addPass( passLight );
-
-		//
-
-		lightShader.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
-		lightShader.uniforms[ 'samplerNormals' ].value = compNormal.renderTarget2;
-		lightShader.uniforms[ 'samplerDepth' ].value = compDepth.renderTarget2;
-		lightShader.uniforms[ 'samplerLightBuffer' ].value = rtLight;
-
-		compositeShader.uniforms[ 'samplerLightBuffer' ].value = compLightBuffer.renderTarget2;
-		compositeShader.uniforms[ 'samplerEmitter' ].value = compEmitter.renderTarget2;
-
-		// composite
-
-		var compositePass = new THREE.ShaderPass( compositeShader );
-		compositePass.needsSwap = true;
-
-		var effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
-		effectFXAA.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
-
-		var effectColor = new THREE.ShaderPass( THREE.ColorCorrectionShader );
-		effectColor.renderToScreen = true;
-
-		effectColor.uniforms[ 'powRGB' ].value.set( 1, 1, 1 );
-		effectColor.uniforms[ 'mulRGB' ].value.set( 2, 2, 2 );
-
-		compFinal = new THREE.EffectComposer( renderer, rtFinal );
-		compFinal.addPass( compositePass );
-		compFinal.addPass( effectFXAA );
-		compFinal.addPass( effectColor );
-
-	};
-
-	this.addDeferredLights = function ( lights, additiveSpecular ) {
-
-		var geometryEmitter = new THREE.SphereGeometry( 0.7, 7, 7 );
-
-		for ( var i = 0, il = lights.length; i < il; i ++ ) {
-
-			var light = lights[ i ];
-
-			// setup material
-
-			var materialLight = new THREE.ShaderMaterial( {
-
-				uniforms:       THREE.UniformsUtils.clone( lightShader.uniforms ),
-				vertexShader:   lightShader.vertexShader,
-				fragmentShader: lightShader.fragmentShader,
-				defines:		{ "ADDITIVE_SPECULAR": additiveSpecular },
-
-				blending:		THREE.AdditiveBlending,
-				depthWrite:		false,
-				transparent:	true
-
-			} );
-
-			materialLight.uniforms[ "lightPos" ].value = light.position;
-			materialLight.uniforms[ "lightRadius" ].value = light.distance;
-			materialLight.uniforms[ "lightIntensity" ].value = light.intensity;
-			materialLight.uniforms[ "lightColor" ].value = light.color;
-
-			// setup proxy geometry for this light
-
-			var geometryLight = new THREE.SphereGeometry( light.distance, 16, 8 );
-			var meshLight = new THREE.Mesh( geometryLight, materialLight );
-			meshLight.position = light.position;
-			lightNode.add( meshLight );
-
-			// create emitter sphere
-
-			var matEmitter = new THREE.ShaderMaterial( {
-
-				uniforms:       THREE.UniformsUtils.clone( unlitShader.uniforms ),
-				vertexShader:   unlitShader.vertexShader,
-				fragmentShader: unlitShader.fragmentShader
-
-			} );
-
-			matEmitter.uniforms[ "samplerDepth" ].value = compDepth.renderTarget2;
-			matEmitter.uniforms[ "lightColor" ].value = light.color;
-
-			var meshEmitter = new THREE.Mesh( geometryEmitter, matEmitter );
-			meshEmitter.position = light.position;
-			emitterNode.add( meshEmitter );
-
-			// add emitter to light node
-
-			meshLight.properties.emitter = meshEmitter;
-
-		}
-
-	};
-
-	this.render = function () {
-
-		// -----------------------------
-		// g-buffer color
-		// -----------------------------
-
-		scene.traverse( function( node ) {
-
-			if ( node.material ) node.material = node.properties.colorMaterial;
-
-		} );
-
-		compColor.render();
-
-		// -----------------------------
-		// g-buffer depth
-		// -----------------------------
-
-		scene.traverse( function( node ) {
-
-			if ( node.material ) node.material = node.properties.depthMaterial;
-
-		} );
-
-		compDepth.render();
-
-		// -----------------------------
-		// g-buffer normals
-		// -----------------------------
-
-		scene.traverse( function( node ) {
-
-			if ( node.material ) node.material = node.properties.normalMaterial;
-
-		} );
-
-		compNormal.render();
-
-		// -----------------------------
-		// emitter pass
-		// -----------------------------
-
-		compEmitter.render();
-
-		// -----------------------------
-		// light pass
-		// -----------------------------
-
-		camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
-
-		for ( var i = 0, il = lightNode.children.length; i < il; i ++ ) {
-
-			var uniforms = lightNode.children[ i ].material.uniforms;
-
-			uniforms[ "matProjInverse" ].value = camera.projectionMatrixInverse;
-			uniforms[ "matView" ].value = camera.matrixWorldInverse;
-
-		}
-
-		compLightBuffer.render();
-
-		// -----------------------------
-		// composite pass
-		// -----------------------------
-
-		compFinal.render( 0.1 );
-
-	};
-
-};

+ 260 - 146
examples/js/ShaderDeferred.js

@@ -17,8 +17,11 @@ THREE.ShaderDeferred = {
 			THREE.UniformsLib[ "shadowmap" ],
 
 			{
-				"specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
-				"shininess": { type: "f", value: 30 }
+				"emissive" :  { type: "c", value: new THREE.Color( 0x000000 ) },
+				"specular" :  { type: "c", value: new THREE.Color( 0x111111 ) },
+				"shininess":  { type: "f", value: 30 },
+				"wrapAround": 		{ type: "f", value: 1 },
+				"additiveSpecular": { type: "f", value: 1 }
 			}
 
 		] ),
@@ -27,7 +30,10 @@ THREE.ShaderDeferred = {
 
 			"uniform vec3 diffuse;",
 			"uniform vec3 specular;",
+			"uniform vec3 emissive;",
 			"uniform float shininess;",
+			"uniform float wrapAround;",
+			"uniform float additiveSpecular;",
 
 			THREE.ShaderChunk[ "color_pars_fragment" ],
 			THREE.ShaderChunk[ "map_pars_fragment" ],
@@ -64,21 +70,33 @@ THREE.ShaderDeferred = {
 
 				THREE.ShaderChunk[ "fog_fragment" ],
 
+				//
+
+				"const float compressionScale = 0.999;",
+
 				// diffuse color
 
-				"gl_FragColor.x = vec3_to_float( 0.999 * gl_FragColor.xyz );",
+				"gl_FragColor.x = vec3_to_float( compressionScale * gl_FragColor.xyz );",
 
 				// specular color
 
-				"gl_FragColor.y = vec3_to_float( 0.999 * specular );",
+				"gl_FragColor.y = additiveSpecular * vec3_to_float( compressionScale * specular );",
 
 				// shininess
 
-				"gl_FragColor.z = shininess;",
+				"gl_FragColor.z = wrapAround * shininess;",
+
+				// emissive color
 
-				// free
+				"#ifdef USE_MAP",
 
-				"gl_FragColor.w = 0.0;",
+					"gl_FragColor.w = vec3_to_float( compressionScale * emissive * texelColor.xyz );",
+
+				"#else",
+
+					"gl_FragColor.w = vec3_to_float( compressionScale * emissive );",
+
+				"#endif",
 
 			"}"
 
@@ -123,60 +141,62 @@ THREE.ShaderDeferred = {
 
 	},
 
-	"clipDepth" : {
+	"normalDepth" : {
 
-		uniforms: { },
+		uniforms: {
 
-		fragmentShader : [
+			bumpMap: 	  { type: "t", value: null },
+			bumpScale:	  { type: "f", value: 1 },
+			offsetRepeat: { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }
 
-			"varying vec4 clipPos;",
+		},
 
-			"void main() {",
+		fragmentShader : [
 
-				"gl_FragColor = vec4( clipPos.z / clipPos.w, 1.0, 1.0, 1.0 );",
+			"#ifdef USE_BUMPMAP",
 
-			"}"
+				"#extension GL_OES_standard_derivatives : enable\n",
 
-		].join("\n"),
+				"varying vec2 vUv;",
+				"varying vec3 vViewPosition;",
 
-		vertexShader : [
+				THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
 
-			"varying vec4 clipPos;",
+			"#endif",
 
-			THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
+			"varying vec3 normalView;",
+			"varying vec4 clipPos;",
 
 			"void main() {",
 
-				THREE.ShaderChunk[ "morphtarget_vertex" ],
-				THREE.ShaderChunk[ "default_vertex" ],
+				"vec3 normal = normalize( normalView );",
 
-				"clipPos = gl_Position;",
+				"#ifdef USE_BUMPMAP",
 
-			"}"
+					"normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
 
-		].join("\n")
+				"#endif",
 
-	},
+				"gl_FragColor.xyz = normal * 0.5 + 0.5;",
+				"gl_FragColor.w = clipPos.z / clipPos.w;",
 
-	"normals" : {
+			"}"
 
-		uniforms: { },
+		].join("\n"),
 
-		fragmentShader : [
+		vertexShader : [
 
 			"varying vec3 normalView;",
+			"varying vec4 clipPos;",
 
-			"void main() {",
-
-				"gl_FragColor = vec4( vec3( normalView * 0.5 + 0.5 ), 1.0 );",
+			"#ifdef USE_BUMPMAP",
 
-			"}"
+				"varying vec2 vUv;",
+				"varying vec3 vViewPosition;",
 
-		].join("\n"),
+				"uniform vec4 offsetRepeat;",
 
-		vertexShader : [
-
-			"varying vec3 normalView;",
+			"#endif",
 
 			THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
 
@@ -202,37 +222,40 @@ THREE.ShaderDeferred = {
 
 				"normalView = normalize( normalMatrix * objectNormal );",
 
+				"#ifdef USE_BUMPMAP",
+
+					"vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
+					"vViewPosition = -mvPosition.xyz;",
+
+				"#endif",
+
+				"clipPos = gl_Position;",
+
 			"}"
 
 		].join("\n")
 
 	},
 
-	"bump" : {
+	"composite" : {
 
 		uniforms: {
 
-			bumpMap: 	  { type: "t", value: null },
-			bumpScale:	  { type: "f", value: 1 },
-			offsetRepeat: { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }
+			samplerLight: 	{ type: "t", value: null },
+			brightness:		{ type: "f", value: 1 }
 
 		},
 
 		fragmentShader : [
 
-			"#extension GL_OES_standard_derivatives : enable\n",
-
-			"varying vec3 normalView;",
-			"varying vec2 vUv;",
-			"varying vec3 vViewPosition;",
-
-			THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
+			"varying vec2 texCoord;",
+			"uniform sampler2D samplerLight;",
+			"uniform float brightness;",
 
 			"void main() {",
 
-				"vec3 normal = normalize( normalView );",
-				"normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
-				"gl_FragColor = vec4( vec3( normal * 0.5 + 0.5 ), 1.0 );",
+				"vec3 color = texture2D( samplerLight, texCoord ).xyz;",
+				"gl_FragColor = vec4( brightness * sqrt( color ), 1.0 );",
 
 			"}"
 
@@ -240,19 +263,13 @@ THREE.ShaderDeferred = {
 
 		vertexShader : [
 
-			"varying vec3 normalView;",
-			"varying vec2 vUv;",
-			"varying vec3 vViewPosition;",
-
-			"uniform vec4 offsetRepeat;",
+			"varying vec2 texCoord;",
 
 			"void main() {",
 
-				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
-				"gl_Position = projectionMatrix * mvPosition;",
-				"normalView = normalize( normalMatrix * normal );",
-				"vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
-				"vViewPosition = -mvPosition.xyz;",
+				"vec4 pos = vec4( sign( position.xy ), 0.0, 1.0 );",
+				"texCoord = pos.xy * vec2( 0.5 ) + 0.5;",
+				"gl_Position = pos;",
 
 			"}"
 
@@ -260,83 +277,150 @@ THREE.ShaderDeferred = {
 
 	},
 
-	"unlit" : {
+	"pointLight" : {
 
 		uniforms: {
 
-			samplerDepth: { type: "t", value: null },
-			viewWidth:    { type: "f", value: 800 },
-			viewHeight:   { type: "f", value: 600 },
-			lightColor:   { type: "c", value: new THREE.Color( 0x000000 ) }
+			samplerNormalDepth: { type: "t", value: null },
+			samplerColor: 		{ type: "t", value: null },
+			matView: 		{ type: "m4", value: new THREE.Matrix4() },
+			matProjInverse: { type: "m4", value: new THREE.Matrix4() },
+			viewWidth: 		{ type: "f", value: 800 },
+			viewHeight: 	{ type: "f", value: 600 },
+			lightPos: 		{ type: "v3", value: new THREE.Vector3( 0, 0, 0 ) },
+			lightColor: 	{ type: "c", value: new THREE.Color( 0x000000 ) },
+			lightIntensity: { type: "f", value: 1.0 },
+			lightRadius: 	{ type: "f", value: 1.0 }
 
 		},
 
 		fragmentShader : [
 
+			"varying vec3 lightView;",
 			"varying vec4 clipPos;",
-			"uniform sampler2D samplerDepth;",
 
+			"uniform sampler2D samplerColor;",
+			"uniform sampler2D samplerNormalDepth;",
+
+			"uniform float lightRadius;",
+			"uniform float lightIntensity;",
 			"uniform float viewHeight;",
 			"uniform float viewWidth;",
 
 			"uniform vec3 lightColor;",
 
+			"uniform mat4 matProjInverse;",
+
+			"vec3 float_to_vec3( float data ) {",
+
+				"vec3 uncompressed;",
+				"uncompressed.x = fract( data );",
+				"float zInt = floor( data / 255.0 );",
+				"uncompressed.z = fract( zInt / 255.0 );",
+				"uncompressed.y = fract( floor( data - ( zInt * 255.0 ) ) / 255.0 );",
+				"return uncompressed;",
+
+			"}",
+
 			"void main() {",
 
 				"vec2 texCoord = gl_FragCoord.xy / vec2( viewWidth, viewHeight );",
-				"float z = texture2D( samplerDepth, texCoord ).x;",
-				"vec4 color = vec4( lightColor, 1.0 );",
-				"float depth = clipPos.z / clipPos.w;",
-				"if( depth > z && z > 0.0 ) color.w = 0.0;",
-				"gl_FragColor = color;",
 
-			"}"
+				"vec4 normalDepth = texture2D( samplerNormalDepth, texCoord );",
 
-		].join("\n"),
+				"float z = normalDepth.w;",
+				"float lightZ = clipPos.z / clipPos.w;",
 
-		vertexShader : [
+				"if ( z == 0.0 || lightZ > z ) discard;",
 
-			"varying vec4 clipPos;",
+				"float x = texCoord.x * 2.0 - 1.0;",
+				"float y = texCoord.y * 2.0 - 1.0;",
 
-			"void main() {",
+				"vec4 projectedPos = vec4( x, y, z, 1.0 );",
 
-				"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
-				"clipPos = gl_Position;",
+				"vec4 viewPos = matProjInverse * projectedPos;",
+				"viewPos.xyz /= viewPos.w;",
+				"viewPos.w = 1.0;",
 
-			"}"
+				"vec3 lightDir = lightView - viewPos.xyz;",
+				"float dist = length( lightDir );",
 
-		].join("\n")
+				"if ( dist > lightRadius ) discard;",
 
-	},
+				"lightDir = normalize( lightDir );",
 
-	"composite" : {
+				"float cutoff = 0.3;",
+				"float denom = dist/lightRadius + 1.0;",
+				"float attenuation = 1.0 / ( denom * denom );",
+				"attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );",
+				"attenuation = max( attenuation, 0.0 );",
+				"attenuation *= attenuation;",
 
-		uniforms: {
+				// normal
 
-			samplerLightBuffer: { type: "t", value: null },
-			samplerEmitter: 	{ type: "t", value: null }
+				"vec3 normal = normalDepth.xyz * 2.0 - 1.0;",
 
-		},
+				// color
 
-		fragmentShader : [
+				"vec4 colorMap = texture2D( samplerColor, texCoord );",
 
-			"varying vec2 texCoord;",
-			"uniform sampler2D samplerLightBuffer;",
-			"uniform sampler2D samplerEmitter;",
-			"uniform vec3 lightPos;",
+				"vec3 albedo = float_to_vec3( abs( colorMap.x ) );",
+				"vec3 specularColor = float_to_vec3( abs( colorMap.y ) );",
+				"float shininess = abs( colorMap.z );",
+				"float wrapAround = sign( colorMap.z );",
 
-			"void main() {",
+				// light
+
+				"vec3 diffuse;",
+
+				"float diffuseFull = max( dot( normal, lightDir ), 0.0 );",
+
+				"if ( wrapAround < 0.0 ) {",
+
+					// wrap around lighting
+
+					"float diffuseHalf = max( 0.5 + 0.5 * dot( normal, lightDir ), 0.0 );",
+
+					"const vec3 wrapRGB = vec3( 0.6, 0.2, 0.2 );",
+					"diffuse = mix( vec3( diffuseFull ), vec3( diffuseHalf ), wrapRGB );",
+
+				"} else {",
+
+					// simple lighting
+
+					"diffuse = vec3( diffuseFull );",
+
+				"}",
+
+				// specular
+
+				"vec3 halfVector = normalize( lightDir - normalize( viewPos.xyz ) );",
+				"float dotNormalHalf = max( dot( normal, halfVector ), 0.0 );",
+
+				// simple specular
+
+				//"vec3 specular = specularIntensity * max( pow( dotNormalHalf, shininess ), 0.0 ) * diffuse;",
+
+				// physically based specular
+
+				"float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
+
+				"vec3 schlick = specularColor + vec3( 1.0 - specularColor ) * pow( 1.0 - dot( lightDir, halfVector ), 5.0 );",
+				"vec3 specular = schlick * max( pow( dotNormalHalf, shininess ), 0.0 ) * diffuse * specularNormalization;",
+
+				// combine
+
+				"vec3 light = lightIntensity * lightColor;",
 
-				"vec3 color = texture2D( samplerLightBuffer, texCoord ).xyz;",
-				"vec3 emitter = texture2D( samplerEmitter, texCoord ).xyz;",
+				"float additiveSpecular = sign( colorMap.y );",
 
-				"if ( emitter != vec3( 0.0 ) ) {",
+				"if ( additiveSpecular < 0.0 ) {",
 
-					"gl_FragColor = vec4( emitter, 1.0 );",
+					"gl_FragColor = vec4( albedo * light * diffuse, attenuation ) + vec4( light * specular, attenuation );",
 
 				"} else {",
 
-					"gl_FragColor = vec4( sqrt( color ), 1.0 );",
+					"gl_FragColor = vec4( albedo * light * ( diffuse + specular ), attenuation );",
 
 				"}",
 
@@ -346,13 +430,17 @@ THREE.ShaderDeferred = {
 
 		vertexShader : [
 
-			"varying vec2 texCoord;",
+			"varying vec3 lightView;",
+			"varying vec4 clipPos;",
+			"uniform vec3 lightPos;",
+			"uniform mat4 matView;",
 
-			"void main() {",
+			"void main() { ",
 
-				"vec4 pos = vec4( sign( position.xy ), 0.0, 1.0 );",
-				"texCoord = pos.xy * vec2( 0.5 ) + 0.5;",
-				"gl_Position = pos;",
+				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
+				"gl_Position = projectionMatrix * mvPosition;",
+				"lightView = vec3( matView * vec4( lightPos, 1.0 ) );",
+				"clipPos = gl_Position;",
 
 			"}"
 
@@ -360,22 +448,19 @@ THREE.ShaderDeferred = {
 
 	},
 
-	"light" : {
+	"directionalLight" : {
 
 		uniforms: {
 
-			samplerLightBuffer: { type: "t", value: null },
-			samplerNormals: { type: "t", value: null },
-			samplerDepth: 	{ type: "t", value: null },
-			samplerColor: 	{ type: "t", value: null },
+			samplerNormalDepth: { type: "t", value: null },
+			samplerColor: 		{ type: "t", value: null },
 			matView: 		{ type: "m4", value: new THREE.Matrix4() },
 			matProjInverse: { type: "m4", value: new THREE.Matrix4() },
 			viewWidth: 		{ type: "f", value: 800 },
 			viewHeight: 	{ type: "f", value: 600 },
-			lightPos: 		{ type: "v3", value: new THREE.Vector3( 0, 0, 0 ) },
+			lightDir: 		{ type: "v3", value: new THREE.Vector3( 0, 1, 0 ) },
 			lightColor: 	{ type: "c", value: new THREE.Color( 0x000000 ) },
-			lightIntensity: { type: "f", value: 1.0 },
-			lightRadius: 	{ type: "f", value: 1.0 }
+			lightIntensity: { type: "f", value: 1.0 }
 
 		},
 
@@ -385,9 +470,7 @@ THREE.ShaderDeferred = {
 			"varying vec4 clipPos;",
 
 			"uniform sampler2D samplerColor;",
-			"uniform sampler2D samplerDepth;",
-			"uniform sampler2D samplerNormals;",
-			"uniform sampler2D samplerLightBuffer;",
+			"uniform sampler2D samplerNormalDepth;",
 
 			"uniform float lightRadius;",
 			"uniform float lightIntensity;",
@@ -413,19 +496,10 @@ THREE.ShaderDeferred = {
 
 				"vec2 texCoord = gl_FragCoord.xy / vec2( viewWidth, viewHeight );",
 
-				"float z = texture2D( samplerDepth, texCoord ).x;",
-				"float lightZ = clipPos.z / clipPos.w;",
-
-				/*
-				"if ( z == 0.0 ) {",
-
-					"gl_FragColor = vec4( vec3( 0.0 ), 1.0 );",
-					"return;",
-
-				"}",
-				*/
+				"vec4 normalDepth = texture2D( samplerNormalDepth, texCoord );",
+				"float z = normalDepth.w;",
 
-				"if ( z == 0.0 || lightZ > z ) discard;",
+				"if ( z == 0.0 ) discard;",
 
 				"float x = texCoord.x * 2.0 - 1.0;",
 				"float y = texCoord.y * 2.0 - 1.0;",
@@ -436,28 +510,15 @@ THREE.ShaderDeferred = {
 				"viewPos.xyz /= viewPos.w;",
 				"viewPos.w = 1.0;",
 
-				"vec3 lightDir = lightView - viewPos.xyz;",
-				"float dist = length( lightDir );",
-
-				"if ( dist > lightRadius ) discard;",
-
-				"lightDir = normalize( lightDir );",
-
-				"float cutoff = 0.3;",
-				"float denom = dist/lightRadius + 1.0;",
-				"float attenuation = 1.0 / ( denom * denom );",
-				"attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );",
-				"attenuation = max( attenuation, 0.0 );",
-				"attenuation *= attenuation;",
+				"vec3 lightDir = normalize( lightView );",
 
 				// normal
 
-				"vec3 normal = texture2D( samplerNormals, texCoord ).xyz * 2.0 - 1.0;",
+				"vec3 normal = normalDepth.xyz * 2.0 - 1.0;",
 
 				// color
 
 				"vec4 colorMap = texture2D( samplerColor, texCoord );",
-
 				"vec3 albedo = float_to_vec3( abs( colorMap.x ) );",
 				"vec3 specularColor = float_to_vec3( abs( colorMap.y ) );",
 				"float shininess = colorMap.z;",
@@ -467,7 +528,7 @@ THREE.ShaderDeferred = {
 				"float diffuseFull = max( dot( normal, lightDir ), 0.0 );",
 				"float diffuseHalf = max( 0.5 + 0.5 * dot( normal, lightDir ), 0.0 );",
 
-				"const vec3 wrapRGB = vec3( 0.6, 0.2, 0.2 );",
+				"const vec3 wrapRGB = vec3( 0.2, 0.2, 0.2 );",
 				"vec3 diffuse = mix( vec3 ( diffuseFull ), vec3( diffuseHalf ), wrapRGB );",
 
 				// simple lighting
@@ -477,7 +538,7 @@ THREE.ShaderDeferred = {
 
 				// specular
 
-				"vec3 halfVector = normalize( lightDir - normalize( viewPos.xyz ) );",
+				"vec3 halfVector = normalize( lightDir + normalize( viewPos.xyz ) );",
 				"float dotNormalHalf = max( dot( normal, halfVector ), 0.0 );",
 
 				// simple specular
@@ -497,11 +558,11 @@ THREE.ShaderDeferred = {
 
 				"#ifdef ADDITIVE_SPECULAR",
 
-					"gl_FragColor = vec4( albedo * light * diffuse, attenuation ) + vec4( light * specular, attenuation );",
+					"gl_FragColor = vec4( albedo * light * diffuse, 1.0 ) + vec4( light * specular, 1.0 );",
 
 				"#else",
 
-					"gl_FragColor = vec4( albedo * light * ( diffuse + specular ), attenuation );",
+					"gl_FragColor = vec4( albedo * light * ( diffuse + specular ), 1.0 );",
 
 				"#endif",
 
@@ -513,21 +574,74 @@ THREE.ShaderDeferred = {
 
 			"varying vec3 lightView;",
 			"varying vec4 clipPos;",
-			"uniform vec3 lightPos;",
+			"uniform vec3 lightDir;",
 			"uniform mat4 matView;",
 
 			"void main() { ",
 
 				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
 				"gl_Position = projectionMatrix * mvPosition;",
-				"lightView = vec3( matView * vec4( lightPos, 1.0 ) );",
+				"lightView = vec3( matView * vec4( lightDir, 0.0 ) );",
 				"clipPos = gl_Position;",
 
 			"}"
 
 		].join("\n")
 
-	}
+	},
+
+	"emissiveLight" : {
+
+		uniforms: {
+
+			samplerColor: 	{ type: "t", value: null },
+			viewWidth: 		{ type: "f", value: 800 },
+			viewHeight: 	{ type: "f", value: 600 },
+
+		},
+
+		fragmentShader : [
+
+			"uniform sampler2D samplerColor;",
+
+			"uniform float viewHeight;",
+			"uniform float viewWidth;",
+
+			"vec3 float_to_vec3( float data ) {",
 
+				"vec3 uncompressed;",
+				"uncompressed.x = fract( data );",
+				"float zInt = floor( data / 255.0 );",
+				"uncompressed.z = fract( zInt / 255.0 );",
+				"uncompressed.y = fract( floor( data - ( zInt * 255.0 ) ) / 255.0 );",
+				"return uncompressed;",
+
+			"}",
+
+			"void main() {",
+
+				"vec2 texCoord = gl_FragCoord.xy / vec2( viewWidth, viewHeight );",
+
+				"vec4 colorMap = texture2D( samplerColor, texCoord );",
+				"vec3 emissiveColor = float_to_vec3( abs( colorMap.w ) );",
+
+				"gl_FragColor = vec4( emissiveColor, 1.0 );",
+
+			"}"
+
+		].join("\n"),
+
+		vertexShader : [
+
+			"void main() { ",
+
+				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
+				"gl_Position = projectionMatrix * mvPosition;",
+
+			"}"
+
+		].join("\n")
+
+	}
 
 };

+ 12 - 12
examples/js/UVsUtils.js

@@ -39,10 +39,10 @@ THREE.UVsUtils.CylinderUVGenerator.prototype = {
         u1 *= this.uRepeat;
         u2 *= this.uRepeat;
         return [
-            new THREE.UV( u1, v1 ),
-            new THREE.UV( u2, v1 ),
-            new THREE.UV( u2, v2 ),
-            new THREE.UV( u1, v2 )
+            new THREE.Vector2( u1, v1 ),
+            new THREE.Vector2( u2, v1 ),
+            new THREE.Vector2( u2, v2 ),
+            new THREE.Vector2( u1, v2 )
         ];
     },
     
@@ -133,13 +133,13 @@ THREE.UVsDebug = function(geometry) {
         for (j = 0, jl = uv.length; j < jl; j++) {
             u = uv[j];
             
-            a.x += u.u;
-            a.y += u.v;
+            a.x += u.x;
+            a.y += u.y;
             
             if (j == 0) {
-                ctx.moveTo(u.u * width, u.v * height);
+                ctx.moveTo(u.x * width, u.y * height);
             } else {
-                ctx.lineTo(u.u * width, u.v * height);
+                ctx.lineTo(u.x * width, u.y * height);
             }
         }
         
@@ -160,10 +160,10 @@ THREE.UVsDebug = function(geometry) {
         // label uv edge orders
         for (j = 0, jl = uv.length; j < jl; j++) {
             u = uv[j];
-            b.set(u.u, u.v).subSelf(a).divideScalar(4);
+            b.set(u.x, u.y).subSelf(a).divideScalar(4);
             
-            b.x = u.u - b.x;
-            b.y = u.v - b.y;
+            b.x = u.x - b.x;
+            b.y = u.y - b.y;
             ctx.fillText(abc[j]
                 + ':' + faces[i][abc[j]], b.x * width, b.y * height);
         }
@@ -171,4 +171,4 @@ THREE.UVsDebug = function(geometry) {
     }
     
     return canvas;
-}
+}

+ 2 - 2
examples/js/loaders/ColladaLoader.js

@@ -2437,7 +2437,7 @@ THREE.ColladaLoader = function () {
 								ts = ts || { };
 								if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
 								// invert the V
-								ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
+								ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
 
 								break;
 
@@ -2498,7 +2498,7 @@ THREE.ColladaLoader = function () {
 							idx32 = vs[ ndx ] * numParams;
 							if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
 							// invert the V
-							ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
+							ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
 
 						}
 

+ 1 - 1
examples/js/loaders/OBJLoader.js

@@ -50,7 +50,7 @@ THREE.OBJLoader.prototype = {
 
 		function uv( u, v ) {
 
-			return new THREE.UV( u, v );
+			return new THREE.Vector2( u, v );
 
 		}
 

+ 1 - 1
examples/js/loaders/OBJMTLLoader.js

@@ -188,7 +188,7 @@ THREE.OBJMTLLoader.prototype = {
 
 		function uv( u, v ) {
 
-			return new THREE.UV( u, v );
+			return new THREE.Vector2( u, v );
 
 		}
 

+ 4 - 4
examples/js/loaders/UTF8Loader.js

@@ -265,9 +265,9 @@ THREE.UTF8Loader.GeometryCreator.prototype = {
     uv3: function ( where, u1, v1, u2, v2, u3, v3 ) {
 
         var uv = [];
-        uv.push( new THREE.UV( u1, v1 ) );
-        uv.push( new THREE.UV( u2, v2 ) );
-        uv.push( new THREE.UV( u3, v3 ) );
+        uv.push( new THREE.Vector2( u1, v1 ) );
+        uv.push( new THREE.Vector2( u2, v2 ) );
+        uv.push( new THREE.Vector2( u3, v3 ) );
         where.push( uv );
 
     }
@@ -957,4 +957,4 @@ function addListeners( dom, listeners ) {
         dom.addEventListener( key, listeners[ key ] );
 
     }
-}
+}

+ 3 - 3
examples/js/loaders/ctm/CTMLoader.js

@@ -621,9 +621,9 @@ THREE.CTMLoader.prototype.createModelClassic = function ( file, callback ) {
 	function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
 
 		var uv = [];
-		uv.push( new THREE.UV( u1, v1 ) );
-		uv.push( new THREE.UV( u2, v2 ) );
-		uv.push( new THREE.UV( u3, v3 ) );
+		uv.push( new THREE.Vector2( u1, v1 ) );
+		uv.push( new THREE.Vector2( u2, v2 ) );
+		uv.push( new THREE.Vector2( u3, v3 ) );
 		where.push( uv );
 
 	};

+ 22 - 10
examples/js/postprocessing/EffectComposer.js

@@ -6,19 +6,18 @@ THREE.EffectComposer = function ( renderer, renderTarget ) {
 
 	this.renderer = renderer;
 
-	this.renderTarget1 = renderTarget;
-
-	if ( this.renderTarget1 === undefined ) {
+	if ( renderTarget === undefined ) {
 
 		var width = window.innerWidth || 1;
 		var height = window.innerHeight || 1;
+		var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
 
-		this.renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
-		this.renderTarget1 = new THREE.WebGLRenderTarget( width, height, this.renderTargetParameters );
+		renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
 
 	}
 
-	this.renderTarget2 = this.renderTarget1.clone();
+	this.renderTarget1 = renderTarget;
+	this.renderTarget2 = renderTarget.clone();
 
 	this.writeBuffer = this.renderTarget1;
 	this.readBuffer = this.renderTarget2;
@@ -99,19 +98,32 @@ THREE.EffectComposer.prototype = {
 
 	reset: function ( renderTarget ) {
 
-		this.renderTarget1 = renderTarget;
+		if ( renderTarget === undefined ) {
 
-		if ( this.renderTarget1 === undefined ) {
+			renderTarget = this.renderTarget1.clone();
 
-			this.renderTarget1 = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, this.renderTargetParameters );
+			renderTarget.width = window.innerWidth;
+			renderTarget.height = window.innerHeight;
 
 		}
 
-		this.renderTarget2 = this.renderTarget1.clone();
+		this.renderTarget1 = renderTarget;
+		this.renderTarget2 = renderTarget.clone();
 
 		this.writeBuffer = this.renderTarget1;
 		this.readBuffer = this.renderTarget2;
 
+	},
+
+	setSize: function ( width, height ) {
+
+		var renderTarget = this.renderTarget1.clone();
+
+		renderTarget.width = width;
+		renderTarget.height = height;
+
+		this.reset( renderTarget );
+
 	}
 
 };

+ 5 - 5
examples/js/renderers/CSS3DRenderer.js

@@ -121,10 +121,10 @@ THREE.CSS3DRenderer = function () {
 			epsilon( elements[ 1 ] ) + ',' +
 			epsilon( elements[ 2 ] ) + ',' +
 			epsilon( elements[ 3 ] ) + ',' +
-			epsilon( elements[ 4 ] ) + ',' +
-			epsilon( elements[ 5 ] ) + ',' +
-			epsilon( elements[ 6 ] ) + ',' +
-			epsilon( elements[ 7 ] ) + ',' +
+			epsilon( - elements[ 4 ] ) + ',' +
+			epsilon( - elements[ 5 ] ) + ',' +
+			epsilon( - elements[ 6 ] ) + ',' +
+			epsilon( - elements[ 7 ] ) + ',' +
 			epsilon( elements[ 8 ] ) + ',' +
 			epsilon( elements[ 9 ] ) + ',' +
 			epsilon( elements[ 10 ] ) + ',' +
@@ -133,7 +133,7 @@ THREE.CSS3DRenderer = function () {
 			epsilon( elements[ 13 ] ) + ',' +
 			epsilon( elements[ 14 ] ) + ',' +
 			epsilon( elements[ 15 ] ) +
-		') scale3d(1,-1,1)';
+		')';
 
 	}
 

+ 1 - 1
examples/js/renderers/DOMRenderer.js

@@ -55,7 +55,7 @@ THREE.DOMRenderer = function () {
 
 			if ( element instanceof THREE.RenderableParticle && element.material instanceof THREE.ParticleDOMMaterial ) {
 
-				dom = element.material.domElement;
+				dom = element.material.element;
 
 				v1x = element.x * _widthHalf + _widthHalf - ( dom.offsetWidth >> 1 );
 				v1y = element.y * _heightHalf + _heightHalf - ( dom.offsetHeight >> 1 );

+ 574 - 0
examples/js/renderers/WebGLDeferredRenderer.js

@@ -0,0 +1,574 @@
+/**
+ * @author alteredq / http://alteredqualia.com/
+ * @author MPanknin / http://www.redplant.de/
+ */
+
+THREE.WebGLDeferredRenderer = function ( parameters ) {
+
+	var _this = this;
+
+	var width = parameters.width;
+	var height = parameters.height;
+	var scale = parameters.scale;
+
+	var scaledWidth = Math.floor( scale * width );
+	var scaledHeight = Math.floor( scale * height );
+
+	var brightness = parameters.brightness;
+
+	this.renderer = parameters.renderer;
+
+	if ( this.renderer === undefined ) {
+
+		this.renderer = new THREE.WebGLRenderer( { alpha: false } );
+		this.renderer.setSize( width, height );
+		this.renderer.setClearColorHex( 0x000000, 0 );
+
+		this.renderer.autoClear = false;
+
+	}
+
+	this.domElement = this.renderer.domElement;
+
+
+	//
+
+	var geometryLight = new THREE.SphereGeometry( 1, 16, 8 );
+
+	var black = new THREE.Color( 0x000000 );
+
+	var colorShader = THREE.ShaderDeferred[ "color" ];
+	var normalDepthShader = THREE.ShaderDeferred[ "normalDepth" ];
+
+	//
+
+	var emissiveLightShader = THREE.ShaderDeferred[ "emissiveLight" ];
+	var pointLightShader = THREE.ShaderDeferred[ "pointLight" ];
+	var directionalLightShader = THREE.ShaderDeferred[ "directionalLight" ];
+
+	var compositeShader = THREE.ShaderDeferred[ "composite" ];
+
+	//
+
+	var compColor, compNormal, compDepth, compLight, compFinal;
+	var passColor, passNormal, passDepth, passLightFullscreen, passLightProxy, compositePass;
+
+	var effectFXAA;
+
+	//
+
+	var lightSceneFullscreen, lightSceneProxy;
+	var lightMaterials = [];
+
+	//
+
+	var defaultNormalDepthMaterial = new THREE.ShaderMaterial( {
+
+		uniforms:       THREE.UniformsUtils.clone( normalDepthShader.uniforms ),
+		vertexShader:   normalDepthShader.vertexShader,
+		fragmentShader: normalDepthShader.fragmentShader
+
+	} );
+
+	//
+
+	var initDeferredMaterials = function ( object ) {
+
+		if ( object.material instanceof THREE.MeshFaceMaterial ) {
+
+			var colorMaterials = [];
+			var normalDepthMaterials = [];
+
+			var materials = object.material.materials;
+
+			for ( var i = 0, il = materials.length; i < il; i ++ ) {
+
+				var deferredMaterials = createDeferredMaterials( materials[ i ] );
+
+				colorMaterials.push( deferredMaterials.colorMaterial );
+				normalDepthMaterials.push( deferredMaterials.normalDepthMaterial );
+
+			}
+
+			object.properties.colorMaterial = new THREE.MeshFaceMaterial( colorMaterials );
+			object.properties.normalDepthMaterial = new THREE.MeshFaceMaterial( normalDepthMaterials );
+
+		} else {
+
+			var deferredMaterials = createDeferredMaterials( object.material );
+
+			object.properties.colorMaterial = deferredMaterials.colorMaterial;
+			object.properties.normalDepthMaterial = deferredMaterials.normalDepthMaterial;
+
+		}
+
+	};
+
+
+	var createDeferredMaterials = function ( originalMaterial ) {
+
+		var deferredMaterials = {};
+
+		// color material
+		// -----------------
+		// 	diffuse color
+		//	specular color
+		//	shininess
+		//	diffuse map
+		//	vertex colors
+		//	alphaTest
+		// 	morphs
+
+		var uniforms = THREE.UniformsUtils.clone( colorShader.uniforms );
+		var defines = { "USE_MAP": !! originalMaterial.map, "GAMMA_INPUT": true };
+
+		var material = new THREE.ShaderMaterial( {
+
+			fragmentShader: colorShader.fragmentShader,
+			vertexShader: 	colorShader.vertexShader,
+			uniforms: 		uniforms,
+			defines: 		defines,
+			shading:		originalMaterial.shading
+
+		} );
+
+		if ( originalMaterial instanceof THREE.MeshBasicMaterial ) {
+
+			var diffuse = black;
+			var emissive = originalMaterial.color;
+
+		} else {
+
+			var diffuse = originalMaterial.color;
+			var emissive = originalMaterial.emissive !== undefined ? originalMaterial.emissive : black;
+
+		}
+
+		var specular = originalMaterial.specular !== undefined ? originalMaterial.specular : black;
+		var shininess = originalMaterial.shininess !== undefined ? originalMaterial.shininess : 1;
+		var wrapAround = originalMaterial.wrapAround !== undefined ? ( originalMaterial.wrapAround ? -1 : 1 ) : 1;
+		var additiveSpecular = originalMaterial.metal !== undefined ? ( originalMaterial.metal ? 1 : -1 ) : -1;
+
+		uniforms.emissive.value.copy( emissive );
+		uniforms.diffuse.value.copy( diffuse );
+		uniforms.specular.value.copy( specular );
+		uniforms.shininess.value = shininess;
+		uniforms.wrapAround.value = wrapAround;
+		uniforms.additiveSpecular.value = additiveSpecular;
+
+		uniforms.map.value = originalMaterial.map;
+
+		material.vertexColors = originalMaterial.vertexColors;
+		material.morphTargets = originalMaterial.morphTargets;
+		material.morphNormals = originalMaterial.morphNormals;
+
+		material.alphaTest = originalMaterial.alphaTest;
+
+		if ( originalMaterial.bumpMap ) {
+
+			var offset = originalMaterial.bumpMap.offset;
+			var repeat = originalMaterial.bumpMap.repeat;
+
+			uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
+
+		}
+
+		deferredMaterials.colorMaterial = material;
+
+		// normal + depth material
+		// -----------------
+		//	vertex normals
+		//	morph normals
+		//	bump map
+		//	bump scale
+		//  clip depth
+
+		if ( originalMaterial.morphTargets || originalMaterial.bumpMap ) {
+
+			var uniforms = THREE.UniformsUtils.clone( normalDepthShader.uniforms );
+			var defines = { "USE_BUMPMAP": !!originalMaterial.bumpMap };
+
+			var normalDepthMaterial = new THREE.ShaderMaterial( {
+
+				uniforms:       uniforms,
+				vertexShader:   normalDepthShader.vertexShader,
+				fragmentShader: normalDepthShader.fragmentShader,
+				shading:		originalMaterial.shading,
+				defines:		defines,
+				blending:		THREE.NoBlending
+
+			} );
+
+			if ( originalMaterial.morphTargets ) {
+
+				normalDepthMaterial.morphTargets = originalMaterial.morphTargets;
+				normalDepthMaterial.morphNormals = originalMaterial.morphNormals;
+
+			}
+
+			if ( originalMaterial.bumpMap ) {
+
+				uniforms.bumpMap.value = originalMaterial.bumpMap;
+				uniforms.bumpScale.value = originalMaterial.bumpScale;
+
+				var offset = originalMaterial.bumpMap.offset;
+				var repeat = originalMaterial.bumpMap.repeat;
+
+				uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
+
+			}
+
+			deferredMaterials.normalDepthMaterial = normalDepthMaterial;
+
+		} else {
+
+			deferredMaterials.normalDepthMaterial = defaultNormalDepthMaterial;
+
+		}
+
+		return deferredMaterials;
+
+	};
+
+	var createDeferredPointLight = function ( light ) {
+
+		// setup light material
+
+		var materialLight = new THREE.ShaderMaterial( {
+
+			uniforms:       THREE.UniformsUtils.clone( pointLightShader.uniforms ),
+			vertexShader:   pointLightShader.vertexShader,
+			fragmentShader: pointLightShader.fragmentShader,
+
+			blending:		THREE.AdditiveBlending,
+			depthWrite:		false,
+			transparent:	true
+
+		} );
+
+		materialLight.uniforms[ "lightPos" ].value = light.position;
+		materialLight.uniforms[ "lightRadius" ].value = light.distance;
+		materialLight.uniforms[ "lightIntensity" ].value = light.intensity;
+		materialLight.uniforms[ "lightColor" ].value = light.color;
+
+		materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
+		materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
+
+		materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
+		materialLight.uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
+
+		// create light proxy mesh
+
+		var meshLight = new THREE.Mesh( geometryLight, materialLight );
+		meshLight.position = light.position;
+		meshLight.scale.multiplyScalar( light.distance );
+
+		// keep reference for size reset
+
+		lightMaterials.push( materialLight );
+
+		return meshLight;
+
+	};
+
+	var createDeferredDirectionalLight = function ( light ) {
+
+		// setup light material
+
+		var materialLight = new THREE.ShaderMaterial( {
+
+			uniforms:       THREE.UniformsUtils.clone( directionalLightShader.uniforms ),
+			vertexShader:   directionalLightShader.vertexShader,
+			fragmentShader: directionalLightShader.fragmentShader,
+
+			blending:		THREE.AdditiveBlending,
+			depthWrite:		false,
+			transparent:	true
+
+		} );
+
+		materialLight.uniforms[ "lightDir" ].value = light.position;
+		materialLight.uniforms[ "lightIntensity" ].value = light.intensity;
+		materialLight.uniforms[ "lightColor" ].value = light.color;
+
+		materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
+		materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
+
+		materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
+		materialLight.uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
+
+		// create light proxy mesh
+
+		var geometryLight = new THREE.PlaneGeometry( 2, 2 );
+		var meshLight = new THREE.Mesh( geometryLight, materialLight );
+
+		// keep reference for size reset
+
+		lightMaterials.push( materialLight );
+
+		return meshLight;
+
+	};
+
+	var createDeferredEmissiveLight = function () {
+
+		// setup light material
+
+		var materialLight = new THREE.ShaderMaterial( {
+
+			uniforms:       THREE.UniformsUtils.clone( emissiveLightShader.uniforms ),
+			vertexShader:   emissiveLightShader.vertexShader,
+			fragmentShader: emissiveLightShader.fragmentShader,
+			depthTest:		false,
+			depthWrite:		false,
+			blending:		THREE.NoBlending
+
+		} );
+
+
+		materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
+		materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
+
+		materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
+
+		// create light proxy mesh
+
+		var geometryLight = new THREE.PlaneGeometry( 2, 2 );
+		var meshLight = new THREE.Mesh( geometryLight, materialLight );
+
+		// keep reference for size reset
+
+		lightMaterials.push( materialLight );
+
+		return meshLight;
+
+	};
+
+	var initDeferredProperties = function ( object ) {
+
+		if ( object.properties.deferredInitialized ) return;
+
+		if ( object.material ) initDeferredMaterials( object );
+
+		if ( object instanceof THREE.PointLight ) {
+
+			var meshLight = createDeferredPointLight( object );
+			lightSceneProxy.add( meshLight );
+
+		} else if ( object instanceof THREE.DirectionalLight ) {
+
+			var meshLight = createDeferredDirectionalLight( object );
+			lightSceneFullscreen.add( meshLight );
+
+		}
+
+		object.properties.deferredInitialized = true;
+
+	};
+
+	//
+
+	var setMaterialColor = function ( object ) {
+
+		if ( object.material ) object.material = object.properties.colorMaterial;
+
+	};
+
+	var setMaterialNormalDepth = function ( object ) {
+
+		if ( object.material ) object.material = object.properties.normalDepthMaterial;
+
+	};
+
+	//
+
+	this.setSize = function ( width, height ) {
+
+		this.renderer.setSize( width, height );
+
+		scaledWidth = Math.floor( scale * width );
+		scaledHeight = Math.floor( scale * height );
+
+		compColor.setSize( scaledWidth, scaledHeight );
+		compNormalDepth.setSize( scaledWidth, scaledHeight );
+		compLight.setSize( scaledWidth, scaledHeight );
+		compFinal.setSize( scaledWidth, scaledHeight );
+
+		for ( var i = 0, il = lightMaterials.length; i < il; i ++ ) {
+
+			var uniforms = lightMaterials[ i ].uniforms;
+
+			uniforms[ "viewWidth" ].value = scaledWidth;
+			uniforms[ "viewHeight" ].value = scaledHeight;
+
+			uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
+
+			if ( uniforms[ 'samplerNormalDepth' ] ) {
+
+				uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
+
+			}
+
+		}
+
+		compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
+
+		effectFXAA.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
+
+	};
+
+	//
+
+	this.render = function ( scene, camera ) {
+
+		// setup deferred properties
+
+		if ( ! scene.properties.lightSceneProxy ) {
+
+			scene.properties.lightSceneProxy = new THREE.Scene();
+			scene.properties.lightSceneFullscreen = new THREE.Scene();
+
+			var meshLight = createDeferredEmissiveLight();
+			scene.properties.lightSceneFullscreen.add( meshLight );
+
+		}
+
+		lightSceneProxy = scene.properties.lightSceneProxy;
+		lightSceneFullscreen = scene.properties.lightSceneFullscreen;
+
+		passColor.camera = camera;
+		passNormalDepth.camera = camera;
+		passLightProxy.camera = camera;
+		passLightFullscreen.camera = THREE.EffectComposer.camera;
+
+		passColor.scene = scene;
+		passNormalDepth.scene = scene;
+		passLightFullscreen.scene = lightSceneFullscreen;
+		passLightProxy.scene = lightSceneProxy;
+
+		scene.traverse( initDeferredProperties );
+
+		// update scene graph only once per frame
+
+		this.renderer.autoUpdateScene = false;
+		scene.updateMatrixWorld();
+
+		// g-buffer color
+
+		scene.traverse( setMaterialColor );
+		compColor.render();
+
+		// g-buffer normals + depth
+
+		scene.traverse( setMaterialNormalDepth );
+		compNormalDepth.render();
+
+		this.renderer.autoUpdateScene = true;
+
+		// light pass
+
+		camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
+
+		for ( var i = 0, il = lightSceneProxy.children.length; i < il; i ++ ) {
+
+			var uniforms = lightSceneProxy.children[ i ].material.uniforms;
+
+			uniforms[ "matProjInverse" ].value = camera.projectionMatrixInverse;
+			uniforms[ "matView" ].value = camera.matrixWorldInverse;
+
+		}
+
+		for ( var i = 0, il = lightSceneFullscreen.children.length; i < il; i ++ ) {
+
+			var uniforms = lightSceneFullscreen.children[ i ].material.uniforms;
+
+			if ( uniforms[ "matView" ] ) uniforms[ "matView" ].value = camera.matrixWorldInverse;
+
+		}
+
+		compLight.render();
+
+		// composite pass
+
+		compFinal.render( 0.1 );
+
+	};
+
+	var createRenderTargets = function ( ) {
+
+		var rtParamsFloatLinear = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
+									format: THREE.RGBAFormat, type: THREE.FloatType };
+
+		var rtParamsFloatNearest = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, stencilBuffer: false,
+									 format: THREE.RGBAFormat, type: THREE.FloatType };
+
+		var rtParamsUByte = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
+							  format: THREE.RGBFormat, type: THREE.UnsignedByteType };
+
+		// g-buffers
+
+		var rtColor   = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatNearest );
+		var rtNormalDepth = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatLinear );
+		var rtLight   = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatLinear );
+		var rtFinal   = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsUByte );
+
+		rtColor.generateMipmaps = false;
+		rtNormalDepth.generateMipmaps = false;
+		rtLight.generateMipmaps = false;
+		rtFinal.generateMipmaps = false;
+
+		// color composer
+
+		passColor = new THREE.RenderPass();
+		passColor.clear = true;
+
+		compColor = new THREE.EffectComposer( _this.renderer, rtColor );
+		compColor.addPass( passColor );
+
+		// normal + depth composer
+
+		passNormalDepth = new THREE.RenderPass();
+		passNormalDepth.clear = true;
+
+		compNormalDepth = new THREE.EffectComposer( _this.renderer, rtNormalDepth );
+		compNormalDepth.addPass( passNormalDepth );
+
+		// light composer
+
+		passLightFullscreen = new THREE.RenderPass();
+		passLightFullscreen.clear = true;
+
+		passLightProxy = new THREE.RenderPass();
+		passLightProxy.clear = false;
+
+		compLight = new THREE.EffectComposer( _this.renderer, rtLight );
+		compLight.addPass( passLightFullscreen );
+		compLight.addPass( passLightProxy );
+
+		// final composer
+
+		compositePass = new THREE.ShaderPass( compositeShader );
+		compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
+		compositePass.uniforms[ 'brightness' ].value = brightness;
+		compositePass.material.blending = THREE.NoBlending;
+		compositePass.clear = true;
+
+		// FXAA
+
+		effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
+		effectFXAA.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
+		effectFXAA.renderToScreen = true;
+
+		//
+
+		compFinal = new THREE.EffectComposer( _this.renderer, rtFinal );
+		compFinal.addPass( compositePass );
+		compFinal.addPass( effectFXAA );
+
+	};
+
+	// init
+
+	createRenderTargets();
+
+};

+ 1 - 1
examples/misc_controls_pointerlock.html

@@ -192,7 +192,7 @@
 				controls = new THREE.PointerLockControls( camera );
 				scene.add( controls.getObject() );
 
-				ray = new THREE.Ray();
+				ray = new THREE.Raycaster();
 				ray.direction.set( 0, -1, 0 );
 
 				// floor

+ 2 - 2
examples/webgl_interactive_cubes.html

@@ -145,9 +145,9 @@
 				var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 

+ 6 - 6
examples/webgl_interactive_draggablecubes.html

@@ -159,19 +159,19 @@
 				var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
 
 				if ( SELECTED ) {
 
-					var intersects = ray.intersectObject( plane );
+					var intersects = raycaster.intersectObject( plane );
 					SELECTED.position.copy( intersects[ 0 ].point.subSelf( offset ) );
 					return;
 
 				}
 
 
-				var intersects = ray.intersectObjects( objects );
+				var intersects = raycaster.intersectObjects( objects );
 
 				if ( intersects.length > 0 ) {
 
@@ -208,9 +208,9 @@
 				var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
 				projector.unprojectVector( vector, camera );
 
-				var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
+				var raycaster = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );
 
-				var intersects = ray.intersectObjects( objects );
+				var intersects = raycaster.intersectObjects( objects );
 
 				if ( intersects.length > 0 ) {
 
@@ -218,7 +218,7 @@
 
 					SELECTED = intersects[ 0 ].object;
 
-					var intersects = ray.intersectObject( plane );
+					var intersects = raycaster.intersectObject( plane );
 					offset.copy( intersects[ 0 ].point ).subSelf( plane.position );
 
 					container.style.cursor = 'move';

+ 4 - 4
examples/webgl_interactive_voxelpainter.html

@@ -31,7 +31,7 @@
 			var container, stats;
 			var camera, scene, renderer;
 			var projector, plane, cube;
-			var mouse2D, mouse3D, ray,
+			var mouse2D, mouse3D, raycaster,
 			rollOveredFace, isShiftDown = false,
 			theta = 45, isCtrlDown = false;
 
@@ -196,7 +196,7 @@
 
 				event.preventDefault();
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 
@@ -276,9 +276,9 @@
 
 				}
 
-				ray = projector.pickingRay( mouse2D.clone(), camera );
+				raycaster = projector.pickingRay( mouse2D.clone(), camera );
 
-				var intersects = ray.intersectObjects( scene.children );
+				var intersects = raycaster.intersectObjects( scene.children );
 
 				if ( intersects.length > 0 ) {
 

+ 45 - 38
examples/webgl_lights_deferred_morphs.html

@@ -51,12 +51,11 @@
 
 		<script src="js/Detector.js"></script>
 
+		<script src="js/renderers/WebGLDeferredRenderer.js"></script>
 		<script src="js/ShaderDeferred.js"></script>
-		<script src="js/DeferredHelper.js"></script>
 
 		<script src="js/shaders/CopyShader.js"></script>
 		<script src="js/shaders/FXAAShader.js"></script>
-		<script src="js/shaders/ColorCorrectionShader.js"></script>
 
 		<script src="js/postprocessing/EffectComposer.js"></script>
 		<script src="js/postprocessing/RenderPass.js"></script>
@@ -73,12 +72,8 @@
 			var WIDTH = window.innerWidth;
 			var HEIGHT = window.innerHeight - 2 * MARGIN;
 
-			var SCALED_WIDTH = Math.floor( SCALE * WIDTH );
-			var SCALED_HEIGHT = Math.floor( SCALE * HEIGHT );
-
 			var NEAR = 1.0, FAR = 350.0;
 			var VIEW_ANGLE = 45;
-			var ASPECT = WIDTH / HEIGHT;
 
 			// controls
 
@@ -116,9 +111,7 @@
 
 				// renderer
 
-				renderer = new THREE.WebGLRenderer( { alpha: false } );
-				renderer.setSize( WIDTH, HEIGHT );
-				renderer.setClearColorHex( 0x000000, 1 );
+				renderer = new THREE.WebGLDeferredRenderer( { width: WIDTH, height: HEIGHT, scale: SCALE, brightness: 2 } );
 
 				renderer.domElement.style.position = "absolute";
 				renderer.domElement.style.top = MARGIN + "px";
@@ -129,7 +122,7 @@
 
 				// camera
 
-				camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
+				camera = new THREE.PerspectiveCamera( VIEW_ANGLE, WIDTH / HEIGHT, NEAR, FAR );
 				camera.position.z = 150;
 
 				// scene
@@ -149,11 +142,6 @@
 
 				clock = new THREE.Clock();
 
-				// deferred helper
-
-				deferredHelper = new THREE.DeferredHelper( { renderer: renderer, scene: scene, camera: camera, width: SCALED_WIDTH, height: SCALED_HEIGHT } );
-				deferredHelper.createRenderTargets();
-
 				// add lights
 
 				initLights();
@@ -165,22 +153,11 @@
 				// events
 
 				document.addEventListener( 'mousemove', onDocumentMouseMove, false );
+				window.addEventListener( 'resize', onWindowResize, false );
 
 			}
 
 
-			// -----------------------------
-
-			function addObject( object, y, scale ) {
-
-				deferredHelper.addDeferredMaterials( object );
-
-				object.position.y = y;
-				object.scale.set( scale, scale, scale );
-				scene.add( object );
-
-			}
-
 			// -----------------------------
 
 			function initLights() {
@@ -190,6 +167,7 @@
 				// front light
 
 				var light = new THREE.PointLight( 0xffffff, 1.5, 1.5 * distance );
+				scene.add( light );
 				lights.push( light );
 
 				// random lights
@@ -205,11 +183,26 @@
 					light.color.setRGB( c.x, c.y, c.z );
 					light.color.convertGammaToLinear();
 
+					scene.add( light );
 					lights.push( light );
 
 				}
 
-				deferredHelper.addDeferredLights( lights, true );
+				var geometry = new THREE.SphereGeometry( 0.7, 7, 7 );
+
+				for ( var i = 0; i < numLights; i ++ ) {
+
+					var light = lights[ i ];
+
+					var material = new THREE.MeshBasicMaterial();
+					material.color = light.color;
+
+					var emitter = new THREE.Mesh( geometry, material );
+					emitter.position = light.position;
+
+					scene.add( emitter );
+
+				}
 
 			}
 
@@ -222,28 +215,26 @@
 
 					geometry.computeMorphNormals();
 
-					var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x333333, shininess: 20, morphTargets: true, morphNormals: true, vertexColors: THREE.NoColors, shading: THREE.FlatShading } );
+					var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x333333, shininess: 20, wrapAround: true, morphTargets: true, morphNormals: true, vertexColors: THREE.NoColors, shading: THREE.FlatShading } );
 					var meshAnim = new THREE.MorphAnimMesh( geometry, material );
 
 					meshAnim.duration = 3000;
 					meshAnim.properties.delta = -13;
 
-					var s = 1;
-					meshAnim.scale.set( s, s, s );
-					meshAnim.position.x = 180;
-					meshAnim.position.z = -10;
+					meshAnim.scale.multiplyScalar( 50 );
+					meshAnim.position.set( 180, -48, -10 );
 					meshAnim.rotation.y = -Math.PI/2;
 
+					scene.add( meshAnim );
 					morphs.push( meshAnim );
 
-					addObject( meshAnim, -48, 50 );
-
 				} );
 
 				// add box
 
-				var object = generateBox();
-				addObject( object, 0, 8 );
+				var box = generateBox();
+				box.scale.multiplyScalar( 8 );
+				scene.add( box );
 
 			}
 
@@ -318,6 +309,21 @@
 
 			// -----------------------------
 
+			function onWindowResize( event ) {
+
+				windowHalfX = window.innerWidth / 2;
+				windowHalfY = window.innerHeight / 2;
+
+				WIDTH = window.innerWidth;
+				HEIGHT = window.innerHeight - 2 * MARGIN;
+
+				renderer.setSize( WIDTH, HEIGHT );
+
+				camera.aspect = WIDTH / HEIGHT;
+				camera.updateProjectionMatrix();
+
+			}
+
 			function onDocumentMouseMove( event ) {
 
 				mouseX = ( event.clientX - windowHalfX ) * 1;
@@ -391,8 +397,9 @@
 
 				camera.lookAt( target );
 
+				// render
 
-				deferredHelper.render();
+				renderer.render( scene, camera );
 
 			}
 

+ 80 - 39
examples/webgl_lights_deferred_pointlights.html

@@ -50,12 +50,11 @@
 		<script src="js/Detector.js"></script>
 		<script src="js/libs/stats.min.js"></script>
 
+		<script src="js/renderers/WebGLDeferredRenderer.js"></script>
 		<script src="js/ShaderDeferred.js"></script>
-		<script src="js/DeferredHelper.js"></script>
 
 		<script src="js/shaders/CopyShader.js"></script>
 		<script src="js/shaders/FXAAShader.js"></script>
-		<script src="js/shaders/ColorCorrectionShader.js"></script>
 
 		<script src="js/postprocessing/EffectComposer.js"></script>
 		<script src="js/postprocessing/RenderPass.js"></script>
@@ -77,12 +76,8 @@
 			var WIDTH = window.innerWidth;
 			var HEIGHT = window.innerHeight - 2 * MARGIN;
 
-			var SCALED_WIDTH = Math.floor( SCALE * WIDTH );
-			var SCALED_HEIGHT = Math.floor( SCALE * HEIGHT );
-
 			var NEAR = 1.0, FAR = 350.0;
 			var VIEW_ANGLE = 45;
-			var ASPECT = WIDTH / HEIGHT;
 
 			// controls
 
@@ -116,9 +111,7 @@
 
 				// renderer
 
-				renderer = new THREE.WebGLRenderer( { alpha: false } );
-				renderer.setSize( WIDTH, HEIGHT );
-				renderer.setClearColorHex( 0x000000, 1 );
+				renderer = new THREE.WebGLDeferredRenderer( { width: WIDTH, height: HEIGHT, scale: SCALE, brightness: 2 } );
 
 				renderer.domElement.style.position = "absolute";
 				renderer.domElement.style.top = MARGIN + "px";
@@ -129,7 +122,7 @@
 
 				// camera
 
-				camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
+				camera = new THREE.PerspectiveCamera( VIEW_ANGLE, WIDTH / HEIGHT, NEAR, FAR );
 				camera.position.z = 150;
 
 				// scene
@@ -149,11 +142,6 @@
 
 				clock = new THREE.Clock();
 
-				// deferred helper
-
-				deferredHelper = new THREE.DeferredHelper( { renderer: renderer, scene: scene, camera: camera, width: SCALED_WIDTH, height: SCALED_HEIGHT } );
-				deferredHelper.createRenderTargets();
-
 				// add lights
 
 				initLights();
@@ -165,19 +153,7 @@
 				// events
 
 				document.addEventListener( 'mousemove', onDocumentMouseMove, false );
-
-			}
-
-			// -----------------------------
-
-			function addObject( object, y, scale ) {
-
-				deferredHelper.addDeferredMaterials( object );
-
-				object.position.y = y;
-				object.scale.set( scale, scale, scale );
-
-				scene.add( object );
+				window.addEventListener( 'resize', onWindowResize, false );
 
 			}
 
@@ -190,6 +166,7 @@
 				// front light
 
 				var light = new THREE.PointLight( 0xffffff, 1.5, 1.5 * distance );
+				scene.add( light );
 				lights.push( light );
 
 				// random lights
@@ -205,11 +182,26 @@
 					light.color.setRGB( c.x, c.y, c.z );
 					light.color.convertGammaToLinear();
 
+					scene.add( light );
 					lights.push( light );
 
 				}
 
-				deferredHelper.addDeferredLights( lights, false );
+				var geometry = new THREE.SphereGeometry( 0.7, 7, 7 );
+
+				for ( var i = 0; i < numLights; i ++ ) {
+
+					var light = lights[ i ];
+
+					var material = new THREE.MeshBasicMaterial();
+					material.color = light.color;
+
+					var emitter = new THREE.Mesh( geometry, material );
+					emitter.position = light.position;
+
+					scene.add( emitter );
+
+				}
 
 			}
 
@@ -223,20 +215,22 @@
 
 				loader.load( "models/utf8/ben_dds.js", function ( object ) {
 
-					addObject( object, -75, 150 );
-					animate();
+					object.scale.multiplyScalar( 150 );
+					object.position.y = -75;
+					scene.add( object );
 
 				}, { normalizeRGB: true } );
 
 				loader.load( "models/utf8/WaltHi.js", function ( object ) {
 
-					addObject( object, -35, 1 );
-					animate();
+					object.position.y = -35;
+					scene.add( object );
 
 				}, { normalizeRGB: true } );
 
 				*/
 
+
 				var loader = new THREE.JSONLoader();
 				loader.load( "obj/leeperrysmith/LeePerrySmith.js", function( geometry, materials ) {
 
@@ -248,17 +242,45 @@
 					mapHeight.anisotropy = 4;
 					mapHeight.format = THREE.RGBFormat;
 
-					var material = new THREE.MeshPhongMaterial( { map: mapColor, bumpMap: mapHeight, bumpScale: 2.5, shininess: 75, specular: 0x090909 } );
+					var material = new THREE.MeshPhongMaterial( { map: mapColor, bumpMap: mapHeight, bumpScale: 2.5, shininess: 75, specular: 0x090909, wrapAround: true, metal: true } );
 
 					var object = new THREE.Mesh( geometry, material );
-					addObject( object, 0, 8 );
+					object.scale.multiplyScalar( 8 );
+					scene.add( object );
+
+				} );
+
+
+				var loader = new THREE.BinaryLoader();
+				loader.load( "obj/female02/Female02_bin.js", function( geometry, materials ) {
+
+					for ( var i = 0; i < materials.length; i ++ ) materials[ i ].wrapAround = true;
+
+					var object = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
+					object.position.x = -50;
+					object.position.y = -48;
+					object.scale.multiplyScalar( 0.45 );
+					scene.add( object );
+
+				} );
+
+				loader.load( "obj/male02/Male02_bin.js", function( geometry, materials ) {
+
+					for ( var i = 0; i < materials.length; i ++ ) materials[ i ].wrapAround = true;
+
+					var object = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
+					object.position.x = 50;
+					object.position.y = -48;
+					object.scale.multiplyScalar( 0.45 );
+					scene.add( object );
 
 				} );
 
 				// create box
 
-				var object = generateBox();
-				addObject( object, 0, 8 );
+				var box = generateBox();
+				box.scale.multiplyScalar( 8 );
+				scene.add( box );
 
 			}
 
@@ -284,7 +306,7 @@
 
 				var matPlane  = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, shininess:  50, bumpMap: mapHeight2, bumpScale: 0.5 } );
 				var matPlane2 = new THREE.MeshPhongMaterial( { color: 0x331919, specular: 0x111111, shininess:  50, bumpMap: mapHeight2, bumpScale: 1 } );
-				var matPlane3 = new THREE.MeshPhongMaterial( { color: 0x00aaff, specular: 0xffffff, shininess: 200, bumpMap: mapHeight3, bumpScale: 1.2 } );
+				var matPlane3 = new THREE.MeshPhongMaterial( { color: 0x00aaff, specular: 0xffffff, shininess: 200, bumpMap: mapHeight3, bumpScale: 1.2, wrapAround: true } );
 				var matPlane4 = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, shininess:  50, bumpMap: mapHeight3, bumpScale: 1 } );
 
 				// bottom
@@ -334,6 +356,21 @@
 
 			// -----------------------------
 
+			function onWindowResize( event ) {
+
+				windowHalfX = window.innerWidth / 2;
+				windowHalfY = window.innerHeight / 2;
+
+				WIDTH = window.innerWidth;
+				HEIGHT = window.innerHeight - 2 * MARGIN;
+
+				renderer.setSize( WIDTH, HEIGHT );
+
+				camera.aspect = WIDTH / HEIGHT;
+				camera.updateProjectionMatrix();
+
+			}
+
 			function onDocumentMouseMove( event ) {
 
 				mouseX = ( event.clientX - windowHalfX ) * 1;
@@ -381,6 +418,8 @@
 
 				}
 
+				// update camera
+
 				var delta = clock.getDelta();
 
 				targetX = mouseX * .001;
@@ -393,7 +432,9 @@
 
 				camera.lookAt( target );
 
-				deferredHelper.render();
+				// render
+
+				renderer.render( scene, camera );
 
 			}
 

+ 3 - 6
examples/webgl_marching_cubes.html

@@ -185,7 +185,7 @@
 
 			renderer.autoClear = false;
 
-			renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
+			var renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
 			renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
 
 			effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
@@ -235,14 +235,11 @@
 			SCREEN_WIDTH = window.innerWidth;
 			SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN;
 
-			renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
-
 			camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
 			camera.updateProjectionMatrix();
 
-			renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
-
-			composer.reset( renderTarget );
+			renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
+			composer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
 
 			hblur.uniforms[ 'h' ].value = 4 / SCREEN_WIDTH;
 			vblur.uniforms[ 'v' ].value = 4 / SCREEN_HEIGHT;

+ 4 - 7
examples/webgl_materials_cubemap_dynamic.html

@@ -100,7 +100,7 @@
 			var container, stats;
 
 			var camera, cameraTarget, scene, renderer;
-			var renderTarget, renderTargetParameters;
+			var renderTarget;
 
 			var spotLight, ambientLight;
 
@@ -412,7 +412,7 @@
 
 				renderer.autoClear = false;
 
-				renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
+				var renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
 				renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
 
 				effectSave = new THREE.SavePass( new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters ) );
@@ -768,14 +768,11 @@
 				SCREEN_WIDTH = window.innerWidth;
 				SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN;
 
-				renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
-
 				camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
 				camera.updateProjectionMatrix();
 
-				renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
-
-				composer.reset( renderTarget );
+				renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
+				composer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
 
 				hblur.uniforms[ 'h' ].value = 10.75 / SCREEN_WIDTH;
 				vblur.uniforms[ 'v' ].value = 10.75 / SCREEN_HEIGHT;

+ 2 - 2
examples/webgl_materials_video.html

@@ -214,8 +214,8 @@
 
 					for ( j = 0; j < uv.length; j++ ) {
 
-						uv[j].u = ( uv[j].u + offsetx ) * unitx;
-						uv[j].v = ( uv[j].v + offsety ) * unity;
+						uv[j].x = ( uv[j].x + offsetx ) * unitx;
+						uv[j].y = ( uv[j].y + offsety ) * unity;
 
 					}
 

+ 8 - 10
examples/webgl_postprocessing.html

@@ -83,8 +83,6 @@
 
 			var materialColor, material2D, quadBG, quadMask, renderScene;
 
-			var rtParameters;
-
 			var delta = 0.01;
 
 			init();
@@ -207,7 +205,7 @@
 
 				//
 
-				rtParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: true };
+				var rtParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: true };
 
 				var rtWidth  = width / 2;
 				var rtHeight = height / 2;
@@ -294,8 +292,6 @@
 				halfWidth = window.innerWidth / 2;
 				halfHeight = window.innerHeight / 2;
 
-				renderer.setSize( window.innerWidth, window.innerHeight );
-
 				cameraPerspective.aspect = window.innerWidth / window.innerHeight;
 				cameraPerspective.updateProjectionMatrix();
 
@@ -306,12 +302,14 @@
 
 				cameraOrtho.updateProjectionMatrix();
 
-				composerScene.reset( new THREE.WebGLRenderTarget( halfWidth * 2, halfHeight * 2, rtParameters ) );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+
+				composerScene.setSize( halfWidth * 2, halfHeight * 2 );
 
-				composer1.reset( new THREE.WebGLRenderTarget( halfWidth, halfHeight, rtParameters ) );
-				composer2.reset( new THREE.WebGLRenderTarget( halfWidth, halfHeight, rtParameters ) );
-				composer3.reset( new THREE.WebGLRenderTarget( halfWidth, halfHeight, rtParameters ) );
-				composer4.reset( new THREE.WebGLRenderTarget( halfWidth, halfHeight, rtParameters ) );
+				composer1.setSize( halfWidth, halfHeight );
+				composer2.setSize( halfWidth, halfHeight );
+				composer3.setSize( halfWidth, halfHeight );
+				composer4.setSize( halfWidth, halfHeight );
 
 				renderScene.uniforms[ "tDiffuse" ].value = composerScene.renderTarget2;
 

+ 3 - 6
examples/webgl_shading_physical.html

@@ -398,7 +398,7 @@
 
 				renderer.autoClear = false;
 
-				renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
+				var renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
 				renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
 
 				effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
@@ -497,14 +497,11 @@
 				SCREEN_WIDTH = window.innerWidth;
 				SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN;
 
-				renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
-
 				camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
 				camera.updateProjectionMatrix();
 
-				renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
-
-				composer.reset( renderTarget );
+				renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
+				composer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
 
 				hblur.uniforms[ 'h' ].value = 4 / SCREEN_WIDTH;
 				vblur.uniforms[ 'v' ].value = 4 / SCREEN_HEIGHT;

+ 14 - 12
src/core/BufferGeometry.js

@@ -4,8 +4,6 @@
 
 THREE.BufferGeometry = function () {
 
-	THREE.GeometryLibrary.push( this );
-
 	this.id = THREE.GeometryIdCount ++;
 
 	// attributes
@@ -31,6 +29,8 @@ THREE.BufferGeometry = function () {
 
 	this.morphTargets = [];
 
+	THREE.GeometryLibrary[ this.id ] = this;
+
 };
 
 THREE.BufferGeometry.prototype = {
@@ -71,12 +71,7 @@ THREE.BufferGeometry.prototype = {
 
 		if ( ! this.boundingBox ) {
 
-			this.boundingBox = {
-
-				min: new THREE.Vector3( Infinity, Infinity, Infinity ),
-				max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
-
-			};
+			this.boundingBox = new THREE.Box3();
 
 		}
 
@@ -87,7 +82,13 @@ THREE.BufferGeometry.prototype = {
 			var bb = this.boundingBox;
 			var x, y, z;
 
-			for ( var i = 0, il = positions.length; i < il; i += 3 ) {
+			if( positions.length >= 3 ) {
+				bb.min.x = bb.max.x = positions[ 0 ];
+				bb.min.y = bb.max.y = positions[ 1 ];
+				bb.min.z = bb.max.z = positions[ 2 ];
+			}
+
+			for ( var i = 3, il = positions.length; i < il; i += 3 ) {
 
 				x = positions[ i ];
 				y = positions[ i + 1 ];
@@ -140,7 +141,9 @@ THREE.BufferGeometry.prototype = {
 
 	computeBoundingSphere: function () {
 
-		if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
+		if ( ! this.boundingSphere ) {
+			this.boundingSphere = new THREE.Sphere();
+		}
 
 		var positions = this.attributes[ "position" ].array;
 
@@ -541,8 +544,7 @@ THREE.BufferGeometry.prototype = {
 
 	deallocate: function () {
 
-		var index = THREE.GeometryLibrary.indexOf( this );
-		if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
+		delete THREE.GeometryLibrary[ this.id ];
 
 	}
 

+ 17 - 69
src/core/Geometry.js

@@ -4,12 +4,11 @@
  * @author alteredq / http://alteredqualia.com/
  * @author mikael emtinger / http://gomo.se/
  * @author zz85 / http://www.lab4games.net/zz85/blog
+ * @author bhouston / http://exocortex.com
  */
 
 THREE.Geometry = function () {
 
-	THREE.GeometryLibrary.push( this );
-
 	this.id = THREE.GeometryIdCount ++;
 
 	this.name = '';
@@ -51,11 +50,13 @@ THREE.Geometry = function () {
 
 	this.buffersNeedUpdate = false;
 
+	THREE.GeometryLibrary[ this.id ] = this;
+
 };
 
 THREE.Geometry.prototype = {
 
-	constructor : THREE.Geometry,
+	constructor: THREE.Geometry,
 
 	applyMatrix: function ( matrix ) {
 
@@ -479,10 +480,10 @@ THREE.Geometry.prototype = {
 			z1 = vB.z - vA.z;
 			z2 = vC.z - vA.z;
 
-			s1 = uvB.u - uvA.u;
-			s2 = uvC.u - uvA.u;
-			t1 = uvB.v - uvA.v;
-			t2 = uvC.v - uvA.v;
+			s1 = uvB.x - uvA.x;
+			s2 = uvC.x - uvA.x;
+			t1 = uvB.y - uvA.y;
+			t2 = uvC.y - uvA.y;
 
 			r = 1.0 / ( s1 * t2 - s2 * t1 );
 			sdir.set( ( t2 * x1 - t1 * x2 ) * r,
@@ -578,60 +579,11 @@ THREE.Geometry.prototype = {
 
 		if ( ! this.boundingBox ) {
 
-			this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
-
-		}
-
-		if ( this.vertices.length > 0 ) {
-
-			var position, firstPosition = this.vertices[ 0 ];
-
-			this.boundingBox.min.copy( firstPosition );
-			this.boundingBox.max.copy( firstPosition );
-
-			var min = this.boundingBox.min,
-				max = this.boundingBox.max;
-
-			for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
-
-				position = this.vertices[ v ];
-
-				if ( position.x < min.x ) {
-
-					min.x = position.x;
-
-				} else if ( position.x > max.x ) {
-
-					max.x = position.x;
-
-				}
-
-				if ( position.y < min.y ) {
-
-					min.y = position.y;
-
-				} else if ( position.y > max.y ) {
-
-					max.y = position.y;
-
-				}
-
-				if ( position.z < min.z ) {
-
-					min.z = position.z;
-
-				} else if ( position.z > max.z ) {
-
-					max.z = position.z;
-
-				}
-
-			}
+			this.boundingBox = new THREE.Box3().setFromPoints( this.vertices );
 
 		} else {
 
-			this.boundingBox.min.set( 0, 0, 0 );
-			this.boundingBox.max.set( 0, 0, 0 );
+			this.boundingBox.setFromPoints( this.vertices );
 
 		}
 
@@ -639,19 +591,16 @@ THREE.Geometry.prototype = {
 
 	computeBoundingSphere: function () {
 
-		var maxRadiusSq = 0;
+		if ( ! this.boundingSphere ) {
 
-		if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
+			this.boundingSphere = new THREE.Sphere().setFromCenterAndPoints( new THREE.Vector3(), this.vertices );
 
-		for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
+		} else {
 
-			var radiusSq = this.vertices[ i ].lengthSq();
-			if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
+			this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
 
 		}
 
-		this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
-
 	},
 
 	/*
@@ -779,7 +728,7 @@ THREE.Geometry.prototype = {
 
 			for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
 
-				uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
+				uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
 
 			}
 
@@ -793,12 +742,11 @@ THREE.Geometry.prototype = {
 
 	deallocate: function () {
 
-		var index = THREE.GeometryLibrary.indexOf( this );
-		if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
+		delete THREE.GeometryLibrary[ this.id ];
 
 	}
 
 };
 
 THREE.GeometryIdCount = 0;
-THREE.GeometryLibrary = [];
+THREE.GeometryLibrary = {};

+ 4 - 5
src/core/Object3D.js

@@ -6,8 +6,6 @@
 
 THREE.Object3D = function () {
 
-	THREE.Object3DLibrary.push( this );
-
 	this.id = THREE.Object3DIdCount ++;
 
 	this.name = '';
@@ -49,6 +47,8 @@ THREE.Object3D = function () {
 
 	this._vector = new THREE.Vector3();
 
+	THREE.Object3DLibrary[ this.id ] = this;
+
 };
 
 
@@ -362,8 +362,7 @@ THREE.Object3D.prototype = {
 
 	deallocate: function () {
 
-		var index = THREE.Object3DLibrary.indexOf( this );
-		if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
+		delete THREE.Object3DLibrary[ this.id ];
 
 	}
 
@@ -373,4 +372,4 @@ THREE.Object3D.__m1 = new THREE.Matrix4();
 THREE.Object3D.defaultEulerOrder = 'XYZ',
 
 THREE.Object3DIdCount = 0;
-THREE.Object3DLibrary = [];
+THREE.Object3DLibrary = {};

+ 1 - 1
src/core/Projector.js

@@ -65,7 +65,7 @@ THREE.Projector = function() {
 		// find direction from vector to end
 		end.subSelf( vector ).normalize();
 
-		return new THREE.Ray( vector, end );
+		return new THREE.Raycaster( vector, end );
 
 	};
 

+ 0 - 285
src/core/Ray.js

@@ -1,285 +0,0 @@
-/**
- * @author mrdoob / http://mrdoob.com/
- */
-
-( function ( THREE ) {
-
-	THREE.Ray = function ( origin, direction, near, far ) {
-
-		this.origin = origin || new THREE.Vector3();
-		this.direction = direction || new THREE.Vector3();
-		this.near = near || 0;
-		this.far = far || Infinity;
-
-	};
-
-	var originCopy = new THREE.Vector3();
-
-	var localOriginCopy = new THREE.Vector3();
-	var localDirectionCopy = new THREE.Vector3();
-
-	var vector = new THREE.Vector3();
-	var normal = new THREE.Vector3();
-	var intersectPoint = new THREE.Vector3();
-
-	var inverseMatrix = new THREE.Matrix4();
-
-	var descSort = function ( a, b ) {
-
-		return a.distance - b.distance;
-
-	};
-
-	var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
-
-	var distanceFromIntersection = function ( origin, direction, position ) {
-
-		v0.sub( position, origin );
-
-		var dot = v0.dot( direction );
-
-		var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
-		var distance = position.distanceTo( intersect );
-
-		return distance;
-
-	};
-
-	// http://www.blackpawn.com/texts/pointinpoly/default.html
-
-	var pointInFace3 = function ( p, a, b, c ) {
-
-		v0.sub( c, a );
-		v1.sub( b, a );
-		v2.sub( p, a );
-
-		var dot00 = v0.dot( v0 );
-		var dot01 = v0.dot( v1 );
-		var dot02 = v0.dot( v2 );
-		var dot11 = v1.dot( v1 );
-		var dot12 = v1.dot( v2 );
-
-		var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
-		var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
-		var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
-
-		return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
-
-	};
-
-	var intersectObject = function ( object, ray, intersects ) {
-
-		if ( object instanceof THREE.Particle ) {
-
-			var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
-
-			if ( distance > object.scale.x ) {
-
-				return intersects;
-
-			}
-
-			intersects.push( {
-
-				distance: distance,
-				point: object.position,
-				face: null,
-				object: object
-
-			} );
-
-		} else if ( object instanceof THREE.Mesh ) {
-
-			// Checking boundingSphere
-
-			var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
-
-			// Checking distance to ray
-
-			var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
-
-			if ( distance > scaledRadius) {
-
-				return intersects;
-
-			}
-
-			// Checking faces
-
-			var geometry = object.geometry;
-			var vertices = geometry.vertices;
-
-			var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
-			var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
-
-			var side = object.material.side;
-
-			var a, b, c, d;
-			var precision = ray.precision;
-
-			object.matrixRotationWorld.extractRotation( object.matrixWorld );
-
-			originCopy.copy( ray.origin );
-
-			inverseMatrix.getInverse( object.matrixWorld );
-
-			localOriginCopy.copy( originCopy );
-			inverseMatrix.multiplyVector3( localOriginCopy );
-
-			localDirectionCopy.copy( ray.direction );
-			inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
-
-			for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
-
-				var face = geometry.faces[ f ];
-
-				var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
-
-				if ( material === undefined ) continue;
-
-				side = material.side;
-
-				vector.sub( face.centroid, localOriginCopy );
-
-				var normal = face.normal;
-				var dot = localDirectionCopy.dot( normal );
-
-				// bail if ray and plane are parallel
-
-				if ( Math.abs( dot ) < precision ) continue;
-
-				// calc distance to plane
-
-				var scalar = normal.dot( vector ) / dot;
-
-				// if negative distance, then plane is behind ray
-
-				if ( scalar < 0 ) continue;
-
-				if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
-
-					intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
-
-					if ( face instanceof THREE.Face3 ) {
-
-						a = vertices[ face.a ];
-						b = vertices[ face.b ];
-						c = vertices[ face.c ];
-
-						if ( pointInFace3( intersectPoint, a, b, c ) ) {
-
-							var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
-							distance = originCopy.distanceTo( point );
-
-							if ( distance < ray.near || distance > ray.far ) continue;
-
-							intersects.push( {
-
-								distance: distance,
-								point: point,
-								face: face,
-								faceIndex: f,
-								object: object
-
-							} );
-
-						}
-
-					} else if ( face instanceof THREE.Face4 ) {
-
-						a = vertices[ face.a ];
-						b = vertices[ face.b ];
-						c = vertices[ face.c ];
-						d = vertices[ face.d ];
-
-						if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
-
-							var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
-							distance = originCopy.distanceTo( point );
-
-							if ( distance < ray.near || distance > ray.far ) continue;
-
-							intersects.push( {
-
-								distance: distance,
-								point: point,
-								face: face,
-								faceIndex: f,
-								object: object
-
-							} );
-
-						}
-
-					}
-
-				}
-
-			}
-
-		}
-
-	};
-
-	var intersectDescendants = function ( object, ray, intersects ) {
-
-		var descendants = object.getDescendants();
-
-		for ( var i = 0, l = descendants.length; i < l; i ++ ) {
-
-			intersectObject( descendants[ i ], ray, intersects );
-
-		}
-	};
-
-	//
-
-	THREE.Ray.prototype.precision = 0.0001;
-
-	THREE.Ray.prototype.set = function ( origin, direction ) {
-
-		this.origin = origin;
-		this.direction = direction;
-
-	};
-
-	THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
-
-		var intersects = [];
-
-		if ( recursive === true ) {
-
-			intersectDescendants( object, this, intersects );
-
-		}
-
-		intersectObject( object, this, intersects );
-
-		intersects.sort( descSort );
-
-		return intersects;
-
-	};
-
-	THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
-
-		var intersects = [];
-
-		for ( var i = 0, l = objects.length; i < l; i ++ ) {
-
-			intersectObject( objects[ i ], this, intersects );
-
-			if ( recursive === true ) {
-
-				intersectDescendants( objects[ i ], this, intersects );
-
-			}
-		}
-
-		intersects.sort( descSort );
-
-		return intersects;
-
-	};
-
-}( THREE ) );

+ 255 - 0
src/core/Raycaster.js

@@ -0,0 +1,255 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+( function ( THREE ) {
+
+	THREE.Raycaster = function ( origin, direction, near, far ) {
+
+		this.ray = new THREE.Ray( origin, direction );
+		
+		// normalized ray.direction required for accurate distance calculations
+		if( this.ray.direction.length() > 0 ) {
+
+			this.ray.direction.normalize();
+
+		}
+
+		this.near = near || 0;
+		this.far = far || Infinity;
+
+	};
+
+	var sphere = new THREE.Sphere();
+	var localRay = new THREE.Ray();
+	var facePlane = new THREE.Plane();
+	var intersectPoint = new THREE.Vector3();
+
+	var inverseMatrix = new THREE.Matrix4();
+
+	var descSort = function ( a, b ) {
+
+		return a.distance - b.distance;
+
+	};
+
+	var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
+
+	// http://www.blackpawn.com/texts/pointinpoly/default.html
+
+	var pointInFace3 = function ( p, a, b, c ) {
+
+		v0.sub( c, a );
+		v1.sub( b, a );
+		v2.sub( p, a );
+
+		var dot00 = v0.dot( v0 );
+		var dot01 = v0.dot( v1 );
+		var dot02 = v0.dot( v2 );
+		var dot11 = v1.dot( v1 );
+		var dot12 = v1.dot( v2 );
+
+		var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
+		var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
+		var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
+
+		return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
+
+	};
+
+	var intersectObject = function ( object, raycaster, intersects ) {
+
+		if ( object instanceof THREE.Particle ) {
+
+			var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
+
+			if ( distance > object.scale.x ) {
+
+				return intersects;
+
+			}
+
+			intersects.push( {
+
+				distance: distance,
+				point: object.position,
+				face: null,
+				object: object
+
+			} );
+
+		} else if ( object instanceof THREE.Mesh ) {
+
+			// Checking boundingSphere distance to ray
+			sphere.set(
+				object.matrixWorld.getPosition(),
+				object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
+
+			if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
+
+				return intersects;
+
+			}
+
+			// Checking faces
+
+			var geometry = object.geometry;
+			var vertices = geometry.vertices;
+
+			var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
+			var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
+
+			var side = object.material.side;
+
+			var a, b, c, d;
+			var precision = raycaster.precision;
+
+			object.matrixRotationWorld.extractRotation( object.matrixWorld );
+
+			inverseMatrix.getInverse( object.matrixWorld );
+
+			localRay.copy( raycaster.ray ).transformSelf( inverseMatrix );
+	
+			for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
+
+				var face = geometry.faces[ f ];
+
+				var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
+
+				if ( material === undefined ) continue;
+				
+				facePlane.setFromNormalAndCoplanarPoint( face.normal, face.centroid );
+
+				var planeDistance = localRay.distanceToPlane( facePlane );
+	
+				// bail if raycaster and plane are parallel
+				if ( Math.abs( planeDistance ) < precision ) continue;
+	
+				// if negative distance, then plane is behind raycaster
+				if ( planeDistance < 0 ) continue;
+
+				// check if we hit the wrong side of a single sided face
+				side = material.side;
+				if( side !== THREE.DoubleSide ) {
+
+					var planeSign = localRay.direction.dot( facePlane.normal );
+
+					if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
+
+				}
+
+				// this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
+				if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
+				
+				intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
+
+				if ( face instanceof THREE.Face3 ) {
+
+					a = vertices[ face.a ];
+					b = vertices[ face.b ];
+					c = vertices[ face.c ];
+
+					if ( ! pointInFace3( intersectPoint, a, b, c ) ) continue;
+
+				} else if ( face instanceof THREE.Face4 ) {
+
+					a = vertices[ face.a ];
+					b = vertices[ face.b ];
+					c = vertices[ face.c ];
+					d = vertices[ face.d ];
+
+					if ( ( ! pointInFace3( intersectPoint, a, b, d ) ) &&
+						 ( ! pointInFace3( intersectPoint, b, c, d ) ) ) continue;
+
+				} else {
+
+					// This is added because if we call out of this if/else group when none of the cases
+					//    match it will add a point to the intersection list erroneously.
+					throw Error( "face type not supported" );
+
+				}
+
+				intersects.push( {
+
+					distance: planeDistance,	// this works because the original ray was normalized, and the transformed localRay wasn't
+					point: raycaster.ray.at( planeDistance ),
+					face: face,
+					faceIndex: f,
+					object: object
+
+				} );
+
+			}
+
+		}
+
+	};
+
+	var intersectDescendants = function ( object, raycaster, intersects ) {
+
+		var descendants = object.getDescendants();
+
+		for ( var i = 0, l = descendants.length; i < l; i ++ ) {
+
+			intersectObject( descendants[ i ], raycaster, intersects );
+
+		}
+	};
+
+	//
+
+	THREE.Raycaster.prototype.precision = 0.0001;
+
+	THREE.Raycaster.prototype.set = function ( origin, direction ) {
+
+		this.ray.set( origin, direction );
+
+		// normalized ray.direction required for accurate distance calculations
+		if( this.ray.direction.length() > 0 ) {
+
+			this.ray.direction.normalize();
+
+		}
+
+	};
+
+	THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
+
+		var intersects = [];
+
+		if ( recursive === true ) {
+
+			intersectDescendants( object, this, intersects );
+
+		}
+
+		intersectObject( object, this, intersects );
+
+		intersects.sort( descSort );
+
+		return intersects;
+
+	};
+
+	THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
+
+		var intersects = [];
+
+		for ( var i = 0, l = objects.length; i < l; i ++ ) {
+
+			intersectObject( objects[ i ], this, intersects );
+
+			if ( recursive === true ) {
+
+				intersectDescendants( objects[ i ], this, intersects );
+
+			}
+		}
+
+		intersects.sort( descSort );
+
+		return intersects;
+
+	};
+
+}( THREE ) );

+ 0 - 49
src/core/UV.js

@@ -1,49 +0,0 @@
-/**
- * @author mrdoob / http://mrdoob.com/
- */
-
-THREE.UV = function ( u, v ) {
-
-	this.u = u || 0;
-	this.v = v || 0;
-
-};
-
-THREE.UV.prototype = {
-
-	constructor: THREE.UV,
-
-	set: function ( u, v ) {
-
-		this.u = u;
-		this.v = v;
-
-		return this;
-
-	},
-
-	copy: function ( uv ) {
-
-		this.u = uv.u;
-		this.v = uv.v;
-
-		return this;
-
-	},
-
-	lerpSelf: function ( uv, alpha ) {
-
-		this.u += ( uv.u - this.u ) * alpha;
-		this.v += ( uv.v - this.v ) * alpha;
-
-		return this;
-
-	},
-
-	clone: function () {
-
-		return new THREE.UV( this.u, this.v );
-
-	}
-
-};

+ 25 - 40
src/extras/FontUtils.js

@@ -350,11 +350,6 @@ THREE.FontUtils.generateShapes = function( text, parameters ) {
 
 				/* output Triangle */
 
-				/*
-				result.push( contour[ a ] );
-				result.push( contour[ b ] );
-				result.push( contour[ c ] );
-				*/
 				result.push( [ contour[ a ],
 					contour[ b ],
 					contour[ c ] ] );
@@ -402,34 +397,6 @@ THREE.FontUtils.generateShapes = function( text, parameters ) {
 
 	};
 
-	// see if p is inside triangle abc
-
-	var insideTriangle = function( ax, ay,
-								   bx, by,
-								   cx, cy,
-								   px, py ) {
-
-		  var aX, aY, bX, bY;
-		  var cX, cY, apx, apy;
-		  var bpx, bpy, cpx, cpy;
-		  var cCROSSap, bCROSScp, aCROSSbp;
-
-		  aX = cx - bx;  aY = cy - by;
-		  bX = ax - cx;  bY = ay - cy;
-		  cX = bx - ax;  cY = by - ay;
-		  apx= px  -ax;  apy= py - ay;
-		  bpx= px - bx;  bpy= py - by;
-		  cpx= px - cx;  cpy= py - cy;
-
-		  aCROSSbp = aX*bpy - aY*bpx;
-		  cCROSSap = cX*apy - cY*apx;
-		  bCROSScp = bX*cpy - bY*cpx;
-
-		  return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
-
-	};
-
-
 	var snip = function ( contour, u, v, w, n, verts ) {
 
 		var p;
@@ -447,18 +414,36 @@ THREE.FontUtils.generateShapes = function( text, parameters ) {
 
 		if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
 
-			for ( p = 0; p < n; p++ ) {
+		var aX, aY, bX, bY, cX, cY;
+		var apx, apy, bpx, bpy, cpx, cpy;
+		var cCROSSap, bCROSScp, aCROSSbp;
+
+		aX = cx - bx;  aY = cy - by;
+		bX = ax - cx;  bY = ay - cy;
+		cX = bx - ax;  cY = by - ay;
+
+		for ( p = 0; p < n; p++ ) {
+
+			if( (p === u) || (p === v) || (p === w) ) continue;
 
-				if( (p == u) || (p == v) || (p == w) ) continue;
+			px = contour[ verts[ p ] ].x
+			py = contour[ verts[ p ] ].y
 
-				px = contour[ verts[ p ] ].x
-				py = contour[ verts[ p ] ].y
+			apx = px - ax;  apy = py - ay;
+			bpx = px - bx;  bpy = py - by;
+			cpx = px - cx;  cpy = py - cy;
 
-				if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
+			// see if p is inside triangle abc
 
-		  }
+			aCROSSbp = aX*bpy - aY*bpx;
+			cCROSSap = cX*apy - cY*apx;
+			bCROSScp = bX*cpy - bY*cpx;
+
+			if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
+
+		}
 
-		  return true;
+		return true;
 
 	};
 

+ 12 - 18
src/extras/GeometryUtils.js

@@ -102,7 +102,7 @@ THREE.GeometryUtils = {
 
 			for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
 
-				uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
+				uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
 
 			}
 
@@ -354,26 +354,19 @@ THREE.GeometryUtils = {
 
 	},
 
-	// Get triangle area (by Heron's formula)
-	// 	http://en.wikipedia.org/wiki/Heron%27s_formula
+	// Get triangle area (half of parallelogram)
+	//	http://mathworld.wolfram.com/TriangleArea.html
 
 	triangleArea: function ( vectorA, vectorB, vectorC ) {
 
-		var s, a, b, c,
-			tmp = THREE.GeometryUtils.__v1;
-
-		tmp.sub( vectorA, vectorB );
-		a = tmp.length();
-
-		tmp.sub( vectorA, vectorC );
-		b = tmp.length();
-
-		tmp.sub( vectorB, vectorC );
-		c = tmp.length();
+		var tmp1 = THREE.GeometryUtils.__v1,
+			tmp2 = THREE.GeometryUtils.__v2;
 
-		s = 0.5 * ( a + b + c );
+		tmp1.sub( vectorB, vectorA );
+		tmp2.sub( vectorC, vectorA );
+		tmp1.crossSelf( tmp2 );
 
-		return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
+		return 0.5 * tmp1.length();
 
 	},
 
@@ -412,8 +405,8 @@ THREE.GeometryUtils = {
 
 				// texture repeat
 
-				if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
-				if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
+				if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
+				if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
 
 			}
 
@@ -1045,3 +1038,4 @@ THREE.GeometryUtils = {
 THREE.GeometryUtils.random = THREE.Math.random16;
 
 THREE.GeometryUtils.__v1 = new THREE.Vector3();
+THREE.GeometryUtils.__v2 = new THREE.Vector3();

+ 10 - 22
src/extras/core/Curve.js

@@ -1,7 +1,7 @@
 /**
  * @author zz85 / http://www.lab4games.net/zz85/blog
  * Extensible curve object
- * 
+ *
  * Some common of Curve methods
  * .getPoint(t), getTangent(t)
  * .getPointAt(u), getTagentAt(u)
@@ -110,8 +110,8 @@ THREE.Curve.prototype.getLengths = function ( divisions ) {
 
 	if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
 
-	if ( this.cacheArcLengths 
-		&& ( this.cacheArcLengths.length == divisions + 1 ) 
+	if ( this.cacheArcLengths
+		&& ( this.cacheArcLengths.length == divisions + 1 )
 		&& !this.needsUpdate) {
 
 		//console.log( "cached", this.cacheArcLengths );
@@ -231,22 +231,10 @@ THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
 
 };
 
-
-// In 2D space, there are actually 2 normal vectors,
-// and in 3D space, infinte
-// TODO this should be depreciated.
-THREE.Curve.prototype.getNormalVector = function( t ) {
-
-	var vec = this.getTangent( t );
-
-	return new THREE.Vector2( -vec.y , vec.x );
-
-};
-
 // Returns a unit vector tangent at t
-// In case any sub curve does not implement its tangent / normal finding,
-// we get 2 points with a small delta and find a gradient of the 2 points
-// which seems to make a reasonable approximation
+// In case any sub curve does not implement its tangent derivation,
+// 2 points a small delta apart will be used to find its gradient
+// which seems to give a reasonable approximation
 
 THREE.Curve.prototype.getTangent = function( t ) {
 
@@ -261,7 +249,7 @@ THREE.Curve.prototype.getTangent = function( t ) {
 
 	var pt1 = this.getPoint( t1 );
 	var pt2 = this.getPoint( t2 );
-	
+
 	var vec = pt2.clone().subSelf(pt1);
 	return vec.normalize();
 
@@ -715,7 +703,7 @@ THREE.SplineCurve3 = THREE.Curve.create(
 // 	v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
 
 // 	return v;
-		
+
 // }
 
 /**************************************************************
@@ -741,7 +729,7 @@ THREE.ClosedSplineCurve3 = THREE.Curve.create(
 
         intPoint = Math.floor( point );
         weight = point - intPoint;
-            
+
         intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
         c[ 0 ] = ( intPoint - 1 ) % points.length;
         c[ 1 ] = ( intPoint ) % points.length;
@@ -751,7 +739,7 @@ THREE.ClosedSplineCurve3 = THREE.Curve.create(
         v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
         v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
         v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
-        
+
         return v;
 
     }

+ 3 - 3
src/extras/geometries/CircleGeometry.js

@@ -13,7 +13,7 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
     segments = segments !== undefined ? Math.max( 3, segments ) : 8;
 
     var i, uvs = [],
-    center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
+    center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
 
     this.vertices.push(center);
     uvs.push( centerUV );
@@ -26,7 +26,7 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
         vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
 
         this.vertices.push( vertex );
-        uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
+        uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
 
     }
 
@@ -46,7 +46,7 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
     this.computeCentroids();
     this.computeFaceNormals();
 
-    this.boundingSphere = { radius: radius };
+    this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
 
 };
 

+ 1 - 1
src/extras/geometries/ConvexGeometry.js

@@ -162,7 +162,7 @@ THREE.ConvexGeometry = function( vertices ) {
 	function vertexUv( vertex ) {
 
 		var mag = vertex.length();
-		return new THREE.UV( vertex.x / mag, vertex.y / mag );
+		return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
 
 	}
 

+ 4 - 4
src/extras/geometries/CubeGeometry.js

@@ -92,10 +92,10 @@ THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegme
 
 				scope.faces.push( face );
 				scope.faceVertexUvs[ 0 ].push( [
-							new THREE.UV( ix / gridX, 1 - iy / gridY ),
-							new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
-							new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
-							new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
+							new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
+							new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
+							new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
+							new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
 						] );
 
 			}

+ 3 - 3
src/extras/geometries/CylinderGeometry.js

@@ -36,7 +36,7 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegme
 			this.vertices.push( vertex );
 
 			verticesRow.push( this.vertices.length - 1 );
-			uvsRow.push( new THREE.UV( u, 1 - v ) );
+			uvsRow.push( new THREE.Vector2( u, 1 - v ) );
 
 		}
 
@@ -107,7 +107,7 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegme
 
 			var uv1 = uvs[ 0 ][ x ].clone();
 			var uv2 = uvs[ 0 ][ x + 1 ].clone();
-			var uv3 = new THREE.UV( uv2.u, 0 );
+			var uv3 = new THREE.Vector2( uv2.u, 0 );
 
 			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
 			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
@@ -134,7 +134,7 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegme
 
 			var uv1 = uvs[ y ][ x + 1 ].clone();
 			var uv2 = uvs[ y ][ x ].clone();
-			var uv3 = new THREE.UV( uv2.u, 1 );
+			var uv3 = new THREE.Vector2( uv2.u, 1 );
 
 			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
 			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

+ 11 - 11
src/extras/geometries/ExtrudeGeometry.js

@@ -674,9 +674,9 @@ THREE.ExtrudeGeometry.WorldUVGenerator = {
 			cy = geometry.vertices[ indexC ].y;
 
 		return [
-			new THREE.UV( ax, ay ),
-			new THREE.UV( bx, by ),
-			new THREE.UV( cx, cy )
+			new THREE.Vector2( ax, ay ),
+			new THREE.Vector2( bx, by ),
+			new THREE.Vector2( cx, cy )
 		];
 
 	},
@@ -709,17 +709,17 @@ THREE.ExtrudeGeometry.WorldUVGenerator = {
 
 		if ( Math.abs( ay - by ) < 0.01 ) {
 			return [
-				new THREE.UV( ax, 1 - az ),
-				new THREE.UV( bx, 1 - bz ),
-				new THREE.UV( cx, 1 - cz ),
-				new THREE.UV( dx, 1 - dz )
+				new THREE.Vector2( ax, 1 - az ),
+				new THREE.Vector2( bx, 1 - bz ),
+				new THREE.Vector2( cx, 1 - cz ),
+				new THREE.Vector2( dx, 1 - dz )
 			];
 		} else {
 			return [
-				new THREE.UV( ay, 1 - az ),
-				new THREE.UV( by, 1 - bz ),
-				new THREE.UV( cy, 1 - cz ),
-				new THREE.UV( dy, 1 - dz )
+				new THREE.Vector2( ay, 1 - az ),
+				new THREE.Vector2( by, 1 - bz ),
+				new THREE.Vector2( cy, 1 - cz ),
+				new THREE.Vector2( dy, 1 - dz )
 			];
 		}
 	}

+ 5 - 5
src/extras/geometries/LatheGeometry.js

@@ -46,11 +46,11 @@ THREE.LatheGeometry = function ( points, steps, angle ) {
 
 			this.faceVertexUvs[ 0 ].push( [
 
-				new THREE.UV( 1 - i / _steps, k / kl ),
-				new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
-				new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
-				new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
-				
+				new THREE.Vector2( 1 - i / _steps, k / kl ),
+				new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
+				new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
+				new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
+
 			] );
 
 		}

+ 4 - 4
src/extras/geometries/ParametricGeometry.js

@@ -49,10 +49,10 @@ THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
 			c = (i + 1) * sliceCount + j;
 			d = (i + 1) * sliceCount + j + 1;
 
-			uva = new THREE.UV( j / slices, i / stacks );
-			uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
-			uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
-			uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
+			uva = new THREE.Vector2( j / slices, i / stacks );
+			uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
+			uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
+			uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
 
 			if ( useTris ) {
 

+ 4 - 4
src/extras/geometries/PlaneGeometry.js

@@ -56,10 +56,10 @@ THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments )
 
 			this.faces.push( face );
 			this.faceVertexUvs[ 0 ].push( [
-				new THREE.UV( ix / gridX, 1 - iz / gridZ ),
-				new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
-				new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
-				new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
+				new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
+				new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
+				new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
+				new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
 			] );
 
 		}

+ 4 - 4
src/extras/geometries/PolyhedronGeometry.js

@@ -48,7 +48,7 @@ THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
 
 		var u = azimuth( vector ) / 2 / Math.PI + 0.5;
 		var v = inclination( vector ) / Math.PI + 0.5;
-		vertex.uv = new THREE.UV( u, 1 - v );
+		vertex.uv = new THREE.Vector2( u, 1 - v );
 
 		return vertex;
 
@@ -131,15 +131,15 @@ THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
 
 	function correctUV( uv, vector, azimuth ) {
 
-		if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
-		if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
+		if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
+		if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
 		return uv;
 
 	}
 
 	this.computeCentroids();
 
-	this.boundingSphere = { radius: radius };
+    this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
 
 };
 

+ 2 - 2
src/extras/geometries/SphereGeometry.js

@@ -37,7 +37,7 @@ THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStar
 			this.vertices.push( vertex );
 
 			verticesRow.push( this.vertices.length - 1 );
-			uvsRow.push( new THREE.UV( u, 1 - v ) );
+			uvsRow.push( new THREE.Vector2( u, 1 - v ) );
 
 		}
 
@@ -89,7 +89,7 @@ THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStar
 	this.computeCentroids();
 	this.computeFaceNormals();
 
-	this.boundingSphere = { radius: this.radius };
+    this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
 
 };
 

+ 1 - 1
src/extras/geometries/TorusGeometry.js

@@ -35,7 +35,7 @@ THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments,
 
 			this.vertices.push( vertex );
 
-			uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
+			uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
 			normals.push( vertex.clone().subSelf( center ).normalize() );
 
 		}

+ 4 - 4
src/extras/geometries/TorusKnotGeometry.js

@@ -67,10 +67,10 @@ THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegmen
 			var c = this.grid[ ip ][ jp ];
 			var d = this.grid[ i ][ jp ];
 
-			var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
-			var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
-			var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
-			var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
+			var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
+			var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
+			var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
+			var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
 
 			this.faces.push( new THREE.Face4( a, b, c, d ) );
 			this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );

+ 4 - 4
src/extras/geometries/TubeGeometry.js

@@ -115,10 +115,10 @@ THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, d
 			c = this.grid[ ip ][ jp ];
 			d = this.grid[ i ][ jp ];
 
-			uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
-			uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
-			uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
-			uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
+			uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
+			uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
+			uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
+			uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
 
 			this.faces.push( new THREE.Face4( a, b, c, d ) );
 			this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );

+ 19 - 19
src/extras/modifiers/SubdivisionModifier.js

@@ -336,21 +336,21 @@ THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
 
 		// Prepare subdivided uv
 
-		avgUv = new THREE.UV();
+		avgUv = new THREE.Vector2();
 
 		if ( face instanceof THREE.Face3 ) {
 
-			avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
-			avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
-			avgUv.u /= 3;
-			avgUv.v /= 3;
+			avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x;
+			avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y;
+			avgUv.x /= 3;
+			avgUv.y /= 3;
 
 		} else if ( face instanceof THREE.Face4 ) {
 
-			avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
-			avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
-			avgUv.u /= 4;
-			avgUv.v /= 4;
+			avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x + getUV( face.d, i ).x;
+			avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y + getUV( face.d, i ).y;
+			avgUv.x /= 4;
+			avgUv.y /= 4;
 
 		}
 
@@ -482,23 +482,23 @@ THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
 
 		// Prepare subdivided uv
 
-		avgUv = new THREE.UV();
+		avgUv = new THREE.Vector2();
 
-		avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
-		avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
-		avgUv.u /= 2;
-		avgUv.v /= 2;
+		avgUv.x = getUV(edgeVertexA, faceIndexA).x + getUV(edgeVertexB, faceIndexA).x;
+		avgUv.y = getUV(edgeVertexA, faceIndexA).y + getUV(edgeVertexB, faceIndexA).y;
+		avgUv.x /= 2;
+		avgUv.y /= 2;
 
 		addUV(edgePoints[i], faceIndexA, avgUv);
 
 		if (edge.length>=2) {
 			assert(edge.length == 2, 'did we plan for more than 2 edges?');
-			avgUv = new THREE.UV();
+			avgUv = new THREE.Vector2();
 
-			avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
-			avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
-			avgUv.u /= 2;
-			avgUv.v /= 2;
+			avgUv.x = getUV(edgeVertexA, faceIndexB).x + getUV(edgeVertexB, faceIndexB).x;
+			avgUv.y = getUV(edgeVertexA, faceIndexB).y + getUV(edgeVertexB, faceIndexB).y;
+			avgUv.x /= 2;
+			avgUv.y /= 2;
 
 			addUV(edgePoints[i], faceIndexB, avgUv);
 		}

+ 7 - 7
src/loaders/BinaryLoader.js

@@ -738,9 +738,9 @@ THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texture
 	function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
 
 		where.push( [
-			new THREE.UV( u1, v1 ),
-			new THREE.UV( u2, v2 ),
-			new THREE.UV( u3, v3 )
+			new THREE.Vector2( u1, v1 ),
+			new THREE.Vector2( u2, v2 ),
+			new THREE.Vector2( u3, v3 )
 		] );
 
 	};
@@ -748,10 +748,10 @@ THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texture
 	function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
 
 		where.push( [
-			new THREE.UV( u1, v1 ),
-			new THREE.UV( u2, v2 ),
-			new THREE.UV( u3, v3 ),
-			new THREE.UV( u4, v4 )
+			new THREE.Vector2( u1, v1 ),
+			new THREE.Vector2( u2, v2 ),
+			new THREE.Vector2( u3, v3 ),
+			new THREE.Vector2( u4, v4 )
 		] );
 	};
 

+ 2 - 2
src/loaders/JSONLoader.js

@@ -230,7 +230,7 @@ THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath
 					u = uvLayer[ uvIndex * 2 ];
 					v = uvLayer[ uvIndex * 2 + 1 ];
 
-					geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
+					geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
 
 				}
 
@@ -251,7 +251,7 @@ THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath
 						u = uvLayer[ uvIndex * 2 ];
 						v = uvLayer[ uvIndex * 2 + 1 ];
 
-						uvs[ j ] = new THREE.UV( u, v );
+						uvs[ j ] = new THREE.Vector2( u, v );
 
 					}
 

+ 6 - 0
src/loaders/Loader.js

@@ -420,6 +420,12 @@ THREE.Loader.prototype = {
 			var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
 			var material = new THREE.ShaderMaterial( parameters );
 
+			if ( mpars.transparent ) {
+
+				material.transparent = true;
+
+			}
+
 		} else {
 
 			var material = new THREE[ mtype ]( mpars );

+ 257 - 240
src/loaders/SceneLoader.js

@@ -69,10 +69,8 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	var urlBase = THREE.Loader.prototype.extractUrlBase( url );
 
-	var dg, dm, dc, df, dt,
-		g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
-		geometry, material, camera, fog,
-		texture, images,
+	var geometry, material, camera, fog,
+		texture, images, color,
 		light, hex, intensity,
 		counter_models, counter_textures,
 		total_models, total_textures,
@@ -168,45 +166,52 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	function handle_children( parent, children ) {
 
-		for ( var dd in children ) {
+		var mat, dst, pos, rot, scl, quat;
+
+		for ( var objID in children ) {
 
 			// check by id if child has already been handled,
 			// if not, create new object
 
-			if ( result.objects[ dd ] === undefined ) {
+			if ( result.objects[ objID ] === undefined ) {
 
-				var o = children[ dd ];
+				var objJSON = children[ objID ];
 
 				var object = null;
 
 				// meshes
 
-				if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
+				if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) && objJSON.loading === undefined ) {
+
+					var reservedTypes = { "type": 1, "url": 1, "material": 1,
+										  "position": 1, "rotation": 1, "scale" : 1,
+										  "visible": 1, "children": 1, "properties": 1,
+										  "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
 
 					var loaderParameters = {};
 
-					for ( var parType in g ) {
+					for ( var parType in objJSON ) {
 
-						if ( parType !== "type" && parType !== "url" ) {
+						if ( ! ( parType in reservedTypes ) ) {
 
-							loaderParameters[ parType ] = g[ parType ];
+							loaderParameters[ parType ] = objJSON[ parType ];
 
 						}
 
 					}
 
-					material = result.materials[ o.material ];
+					material = result.materials[ objJSON.material ];
 
-					o.loading = true;
+					objJSON.loading = true;
 
-					var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
+					var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
 
 					// OBJLoader
 
 					if ( loader.addEventListener ) {
 
-						loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
-						loader.load( get_url( o.url, data.urlBaseType ) );
+						loader.addEventListener( 'load', create_callback_hierachy( objID, parent, material, objJSON ) );
+						loader.load( get_url( objJSON.url, data.urlBaseType ) );
 
 					} else {
 
@@ -214,21 +219,21 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						if ( loader.options ) {
 
-							loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
+							loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
 
 						// UTF8Loader
 
 						} else {
 
-							loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
+							loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
 
 						}
 
 					}
 
-				} else if ( o.geometry !== undefined ) {
+				} else if ( objJSON.geometry !== undefined ) {
 
-					geometry = result.geometries[ o.geometry ];
+					geometry = result.geometries[ objJSON.geometry ];
 
 					// geometry already loaded
 
@@ -236,25 +241,25 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						var needsTangents = false;
 
-						material = result.materials[ o.material ];
+						material = result.materials[ objJSON.material ];
 						needsTangents = material instanceof THREE.ShaderMaterial;
 
-						p = o.position;
-						r = o.rotation;
-						q = o.quaternion;
-						s = o.scale;
-						m = o.matrix;
+						pos = objJSON.position;
+						rot = objJSON.rotation;
+						scl = objJSON.scale;
+						mat = objJSON.matrix;
+						quat = objJSON.quaternion;
 
 						// turn off quaternions, for the moment
 
-						q = 0;
+						quat = 0;
 
 						// use materials from the model file
 						// if there is no material specified in the object
 
-						if ( ! o.material ) {
+						if ( ! objJSON.material ) {
 
-							material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
+							material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
 
 						}
 
@@ -264,7 +269,7 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
 
-							material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
+							material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
 
 						}
 
@@ -284,29 +289,29 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						}
 
-						if ( o.skin ) {
+						if ( objJSON.skin ) {
 
 							object = new THREE.SkinnedMesh( geometry, material );
 
-						} else if ( o.morph ) {
+						} else if ( objJSON.morph ) {
 
 							object = new THREE.MorphAnimMesh( geometry, material );
 
-							if ( o.duration !== undefined ) {
+							if ( objJSON.duration !== undefined ) {
 
-								object.duration = o.duration;
+								object.duration = objJSON.duration;
 
 							}
 
-							if ( o.time !== undefined ) {
+							if ( objJSON.time !== undefined ) {
 
-								object.time = o.time;
+								object.time = objJSON.time;
 
 							}
 
-							if ( o.mirroredLoop !== undefined ) {
+							if ( objJSON.mirroredLoop !== undefined ) {
 
-								object.mirroredLoop = o.mirroredLoop;
+								object.mirroredLoop = objJSON.mirroredLoop;
 
 							}
 
@@ -322,64 +327,64 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						}
 
-						object.name = dd;
+						object.name = objID;
 
-						if ( m ) {
+						if ( mat ) {
 
 							object.matrixAutoUpdate = false;
 							object.matrix.set(
-								m[0], m[1], m[2], m[3],
-								m[4], m[5], m[6], m[7],
-								m[8], m[9], m[10], m[11],
-								m[12], m[13], m[14], m[15]
+								mat[0],  mat[1],  mat[2],  mat[3],
+								mat[4],  mat[5],  mat[6],  mat[7],
+								mat[8],  mat[9],  mat[10], mat[11],
+								mat[12], mat[13], mat[14], mat[15]
 							);
 
 						} else {
 
-							object.position.set( p[0], p[1], p[2] );
+							object.position.set( pos[0], pos[1], pos[2] );
 
-							if ( q ) {
+							if ( quat ) {
 
-								object.quaternion.set( q[0], q[1], q[2], q[3] );
+								object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
 								object.useQuaternion = true;
 
 							} else {
 
-								object.rotation.set( r[0], r[1], r[2] );
+								object.rotation.set( rot[0], rot[1], rot[2] );
 
 							}
 
-							object.scale.set( s[0], s[1], s[2] );
+							object.scale.set( scl[0], scl[1], scl[2] );
 
 						}
 
-						object.visible = o.visible;
-						object.castShadow = o.castShadow;
-						object.receiveShadow = o.receiveShadow;
+						object.visible = objJSON.visible;
+						object.castShadow = objJSON.castShadow;
+						object.receiveShadow = objJSON.receiveShadow;
 
 						parent.add( object );
 
-						result.objects[ dd ] = object;
+						result.objects[ objID ] = object;
 
 					}
 
 				// lights
 
-				} else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
+				} else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
 
-					hex = ( o.color !== undefined ) ? o.color : 0xffffff;
-					intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
+					hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
+					intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
 
-					if ( o.type === "DirectionalLight" ) {
+					if ( objJSON.type === "DirectionalLight" ) {
 
-						p = o.direction;
+						pos = objJSON.direction;
 
 						light = new THREE.DirectionalLight( hex, intensity );
-						light.position.set( p[0], p[1], p[2] );
+						light.position.set( pos[0], pos[1], pos[2] );
 
-						if ( o.target ) {
+						if ( objJSON.target ) {
 
-							target_array.push( { "object": light, "targetName" : o.target } );
+							target_array.push( { "object": light, "targetName" : objJSON.target } );
 
 							// kill existing default target
 							// otherwise it gets added to scene when parent gets added
@@ -388,15 +393,15 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 						}
 
-					} else if ( o.type === "PointLight" ) {
+					} else if ( objJSON.type === "PointLight" ) {
 
-						p = o.position;
-						d = o.distance;
+						pos = objJSON.position;
+						dst = objJSON.distance;
 
-						light = new THREE.PointLight( hex, intensity, d );
-						light.position.set( p[0], p[1], p[2] );
+						light = new THREE.PointLight( hex, intensity, dst );
+						light.position.set( pos[0], pos[1], pos[2] );
 
-					} else if ( o.type === "AmbientLight" ) {
+					} else if ( objJSON.type === "AmbientLight" ) {
 
 						light = new THREE.AmbientLight( hex );
 
@@ -404,86 +409,86 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 					parent.add( light );
 
-					light.name = dd;
-					result.lights[ dd ] = light;
-					result.objects[ dd ] = light;
+					light.name = objID;
+					result.lights[ objID ] = light;
+					result.objects[ objID ] = light;
 
 				// cameras
 
-				} else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
+				} else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
 
-					if ( o.type === "PerspectiveCamera" ) {
+					if ( objJSON.type === "PerspectiveCamera" ) {
 
-						camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
+						camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
 
-					} else if ( o.type === "OrthographicCamera" ) {
+					} else if ( objJSON.type === "OrthographicCamera" ) {
 
-						camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
+						camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
 
 					}
 
-					p = o.position;
-					camera.position.set( p[0], p[1], p[2] );
+					pos = objJSON.position;
+					camera.position.set( pos[0], pos[1], pos[2] );
 					parent.add( camera );
 
-					camera.name = dd;
-					result.cameras[ dd ] = camera;
-					result.objects[ dd ] = camera;
+					camera.name = objID;
+					result.cameras[ objID ] = camera;
+					result.objects[ objID ] = camera;
 
 				// pure Object3D
 
 				} else {
 
-					p = o.position;
-					r = o.rotation;
-					q = o.quaternion;
-					s = o.scale;
+					pos = objJSON.position;
+					rot = objJSON.rotation;
+					scl = objJSON.scale;
+					quat = objJSON.quaternion;
 
 					// turn off quaternions, for the moment
 
-					q = 0;
+					quat = 0;
 
 					object = new THREE.Object3D();
-					object.name = dd;
-					object.position.set( p[0], p[1], p[2] );
+					object.name = objID;
+					object.position.set( pos[0], pos[1], pos[2] );
 
-					if ( q ) {
+					if ( quat ) {
 
-						object.quaternion.set( q[0], q[1], q[2], q[3] );
+						object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
 						object.useQuaternion = true;
 
 					} else {
 
-						object.rotation.set( r[0], r[1], r[2] );
+						object.rotation.set( rot[0], rot[1], rot[2] );
 
 					}
 
-					object.scale.set( s[0], s[1], s[2] );
-					object.visible = ( o.visible !== undefined ) ? o.visible : false;
+					object.scale.set( scl[0], scl[1], scl[2] );
+					object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
 
 					parent.add( object );
 
-					result.objects[ dd ] = object;
-					result.empties[ dd ] = object;
+					result.objects[ objID ] = object;
+					result.empties[ objID ] = object;
 
 				}
 
 				if ( object ) {
 
-					if ( o.properties !== undefined )  {
+					if ( objJSON.properties !== undefined )  {
 
-						for ( var key in o.properties ) {
+						for ( var key in objJSON.properties ) {
 
-							var value = o.properties[ key ];
+							var value = objJSON.properties[ key ];
 							object.properties[ key ] = value;
 
 						}
 
 					}
 
-					if ( o.children !== undefined ) {
+					if ( objJSON.children !== undefined ) {
 
-						handle_children( object, o.children );
+						handle_children( object, objJSON.children );
 
 					}
 
@@ -503,12 +508,12 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	};
 
-	function handle_hierarchy( node, id, parent, material, o ) {
+	function handle_hierarchy( node, id, parent, material, obj ) {
 
-		var p = o.position;
-		var r = o.rotation;
-		var q = o.quaternion;
-		var s = o.scale;
+		var p = obj.position;
+		var r = obj.rotation;
+		var q = obj.quaternion;
+		var s = obj.scale;
 
 		node.position.set( p[0], p[1], p[2] );
 
@@ -689,24 +694,26 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	// fogs
 
-	for ( df in data.fogs ) {
+	var fogID, fogJSON;
 
-		f = data.fogs[ df ];
+	for ( fogID in data.fogs ) {
 
-		if ( f.type === "linear" ) {
+		fogJSON = data.fogs[ fogID ];
 
-			fog = new THREE.Fog( 0x000000, f.near, f.far );
+		if ( fogJSON.type === "linear" ) {
 
-		} else if ( f.type === "exp2" ) {
+			fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
 
-			fog = new THREE.FogExp2( 0x000000, f.density );
+		} else if ( fogJSON.type === "exp2" ) {
+
+			fog = new THREE.FogExp2( 0x000000, fogJSON.density );
 
 		}
 
-		c = f.color;
-		fog.color.setRGB( c[0], c[1], c[2] );
+		color = fogJSON.color;
+		fog.color.setRGB( color[0], color[1], color[2] );
 
-		result.fogs[ df ] = fog;
+		result.fogs[ fogID ] = fog;
 
 	}
 
@@ -716,11 +723,13 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	// count how many geometries will be loaded asynchronously
 
-	for ( dg in data.geometries ) {
+	var geoID, geoJSON;
+
+	for ( geoID in data.geometries ) {
 
-		g = data.geometries[ dg ];
+		geoJSON = data.geometries[ geoID ];
 
-		if ( g.type in this.geometryHandlerMap ) {
+		if ( geoJSON.type in this.geometryHandlerMap ) {
 
 			counter_models += 1;
 
@@ -732,11 +741,13 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	// count how many hierarchies will be loaded asynchronously
 
-	for ( var dd in data.objects ) {
+	var objID, objJSON;
 
-		var o = data.objects[ dd ];
+	for ( objID in data.objects ) {
 
-		if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
+		objJSON = data.objects[ objID ];
+
+		if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
 
 			counter_models += 1;
 
@@ -748,59 +759,60 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	total_models = counter_models;
 
-	for ( dg in data.geometries ) {
+	for ( geoID in data.geometries ) {
 
-		g = data.geometries[ dg ];
+		geoJSON = data.geometries[ geoID ];
 
-		if ( g.type === "cube" ) {
+		if ( geoJSON.type === "cube" ) {
 
-			geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type === "plane" ) {
+		} else if ( geoJSON.type === "plane" ) {
 
-			geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type === "sphere" ) {
+		} else if ( geoJSON.type === "sphere" ) {
 
-			geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type === "cylinder" ) {
+		} else if ( geoJSON.type === "cylinder" ) {
 
-			geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type === "torus" ) {
+		} else if ( geoJSON.type === "torus" ) {
 
-			geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type === "icosahedron" ) {
+		} else if ( geoJSON.type === "icosahedron" ) {
 
-			geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
-			result.geometries[ dg ] = geometry;
+			geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
+			result.geometries[ geoID ] = geometry;
 
-		} else if ( g.type in this.geometryHandlerMap ) {
+		} else if ( geoJSON.type in this.geometryHandlerMap ) {
 
 			var loaderParameters = {};
-			for ( var parType in g ) {
+
+			for ( var parType in geoJSON ) {
 
 				if ( parType !== "type" && parType !== "url" ) {
 
-					loaderParameters[ parType ] = g[ parType ];
+					loaderParameters[ parType ] = geoJSON[ parType ];
 
 				}
 
 			}
 
-			var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
-			loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
+			var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
+			loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
 
-		} else if ( g.type === "embedded" ) {
+		} else if ( geoJSON.type === "embedded" ) {
 
-			var modelJson = data.embeds[ g.id ],
+			var modelJson = data.embeds[ geoJSON.id ],
 				texture_path = "";
 
 			// pass metadata along to jsonLoader so it knows the format version
@@ -810,7 +822,7 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 			if ( modelJson ) {
 
 				var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
-				jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
+				jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
 
 			}
 
@@ -822,15 +834,17 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	// count how many textures will be loaded asynchronously
 
-	for ( dt in data.textures ) {
+	var textureID, textureJSON;
 
-		tt = data.textures[ dt ];
+	for ( textureID in data.textures ) {
 
-		if ( tt.url instanceof Array ) {
+		textureJSON = data.textures[ textureID ];
 
-			counter_textures += tt.url.length;
+		if ( textureJSON.url instanceof Array ) {
 
-			for( var n = 0; n < tt.url.length; n ++ ) {
+			counter_textures += textureJSON.url.length;
+
+			for( var n = 0; n < textureJSON.url.length; n ++ ) {
 
 				scope.onLoadStart();
 
@@ -848,24 +862,24 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	total_textures = counter_textures;
 
-	for ( dt in data.textures ) {
+	for ( textureID in data.textures ) {
 
-		tt = data.textures[ dt ];
+		textureJSON = data.textures[ textureID ];
 
-		if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined  ) {
+		if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined  ) {
 
-			tt.mapping = new THREE[ tt.mapping ]();
+			textureJSON.mapping = new THREE[ textureJSON.mapping ]();
 
 		}
 
-		if ( tt.url instanceof Array ) {
+		if ( textureJSON.url instanceof Array ) {
 
-			var count = tt.url.length;
+			var count = textureJSON.url.length;
 			var url_array = [];
 
 			for( var i = 0; i < count; i ++ ) {
 
-				url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
+				url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
 
 			}
 
@@ -873,196 +887,199 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 			if ( isCompressed ) {
 
-				texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
+				texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
 
 			} else {
 
-				texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
+				texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
 
 			}
 
 		} else {
 
-			var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
-			var fullUrl = get_url( tt.url, data.urlBaseType );
+			var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
+			var fullUrl = get_url( textureJSON.url, data.urlBaseType );
 			var textureCallback = generateTextureCallback( 1 );
 
 			if ( isCompressed ) {
 
-				texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
+				texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
 
 			} else {
 
-				texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
+				texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
 
 			}
 
-			if ( THREE[ tt.minFilter ] !== undefined )
-				texture.minFilter = THREE[ tt.minFilter ];
+			if ( THREE[ textureJSON.minFilter ] !== undefined )
+				texture.minFilter = THREE[ textureJSON.minFilter ];
 
-			if ( THREE[ tt.magFilter ] !== undefined )
-				texture.magFilter = THREE[ tt.magFilter ];
+			if ( THREE[ textureJSON.magFilter ] !== undefined )
+				texture.magFilter = THREE[ textureJSON.magFilter ];
 
-			if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
+			if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
 
-			if ( tt.repeat ) {
+			if ( textureJSON.repeat ) {
 
-				texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
+				texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
 
-				if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
-				if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
+				if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
+				if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
 
 			}
 
-			if ( tt.offset ) {
+			if ( textureJSON.offset ) {
 
-				texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
+				texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
 
 			}
 
 			// handle wrap after repeat so that default repeat can be overriden
 
-			if ( tt.wrap ) {
+			if ( textureJSON.wrap ) {
 
 				var wrapMap = {
 				"repeat" 	: THREE.RepeatWrapping,
 				"mirror"	: THREE.MirroredRepeatWrapping
 				}
 
-				if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
-				if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
+				if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
+				if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
 
 			}
 
 		}
 
-		result.textures[ dt ] = texture;
+		result.textures[ textureID ] = texture;
 
 	}
 
 	// materials
 
-	for ( dm in data.materials ) {
+	var matID, matJSON;
+	var parID;
+
+	for ( matID in data.materials ) {
 
-		m = data.materials[ dm ];
+		matJSON = data.materials[ matID ];
 
-		for ( pp in m.parameters ) {
+		for ( parID in matJSON.parameters ) {
 
-			if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
+			if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
 
-				m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
+				matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
 
-			} else if ( pp === "shading" ) {
+			} else if ( parID === "shading" ) {
 
-				m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
+				matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
 
-			} else if ( pp === "side" ) {
+			} else if ( parID === "side" ) {
 
-				if (  m.parameters[ pp ] == "double" ) {
+				if ( matJSON.parameters[ parID ] == "double" ) {
 
-					m.parameters[ pp ] = THREE.DoubleSide;
+					matJSON.parameters[ parID ] = THREE.DoubleSide;
 
-				} else if ( m.parameters[ pp ] == "back" ) {
+				} else if ( matJSON.parameters[ parID ] == "back" ) {
 
-					m.parameters[ pp ] = THREE.BackSide;
+					matJSON.parameters[ parID ] = THREE.BackSide;
 
 				} else {
 
-					m.parameters[ pp ] = THREE.FrontSide;
+					matJSON.parameters[ parID ] = THREE.FrontSide;
 
 				}
 
-			} else if ( pp === "blending" ) {
+			} else if ( parID === "blending" ) {
 
-				m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
+				matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
 
-			} else if ( pp === "combine" ) {
+			} else if ( parID === "combine" ) {
 
-				m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
+				matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
 
-			} else if ( pp === "vertexColors" ) {
+			} else if ( parID === "vertexColors" ) {
 
-				if ( m.parameters[ pp ] == "face" ) {
+				if ( matJSON.parameters[ parID ] == "face" ) {
 
-					m.parameters[ pp ] = THREE.FaceColors;
+					matJSON.parameters[ parID ] = THREE.FaceColors;
 
 				// default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
 
-				} else if ( m.parameters[ pp ] )   {
+				} else if ( matJSON.parameters[ parID ] )   {
 
-					m.parameters[ pp ] = THREE.VertexColors;
+					matJSON.parameters[ parID ] = THREE.VertexColors;
 
 				}
 
-			} else if ( pp === "wrapRGB" ) {
+			} else if ( parID === "wrapRGB" ) {
 
-				var v3 = m.parameters[ pp ];
-				m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
+				var v3 = matJSON.parameters[ parID ];
+				matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
 
 			}
 
 		}
 
-		if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
+		if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
 
-			m.parameters.transparent = true;
+			matJSON.parameters.transparent = true;
 
 		}
 
-		if ( m.parameters.normalMap ) {
+		if ( matJSON.parameters.normalMap ) {
 
 			var shader = THREE.ShaderUtils.lib[ "normal" ];
 			var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
 
-			var diffuse = m.parameters.color;
-			var specular = m.parameters.specular;
-			var ambient = m.parameters.ambient;
-			var shininess = m.parameters.shininess;
+			var diffuse = matJSON.parameters.color;
+			var specular = matJSON.parameters.specular;
+			var ambient = matJSON.parameters.ambient;
+			var shininess = matJSON.parameters.shininess;
 
-			uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
+			uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
 
-			if ( m.parameters.normalScale ) {
+			if ( matJSON.parameters.normalScale ) {
 
-				uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
+				uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
 
 			}
 
-			if ( m.parameters.map ) {
+			if ( matJSON.parameters.map ) {
 
-				uniforms[ "tDiffuse" ].value = m.parameters.map;
+				uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
 				uniforms[ "enableDiffuse" ].value = true;
 
 			}
 
-			if ( m.parameters.envMap ) {
+			if ( matJSON.parameters.envMap ) {
 
-				uniforms[ "tCube" ].value = m.parameters.envMap;
+				uniforms[ "tCube" ].value = matJSON.parameters.envMap;
 				uniforms[ "enableReflection" ].value = true;
-				uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
+				uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
 
 			}
 
-			if ( m.parameters.lightMap ) {
+			if ( matJSON.parameters.lightMap ) {
 
-				uniforms[ "tAO" ].value = m.parameters.lightMap;
+				uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
 				uniforms[ "enableAO" ].value = true;
 
 			}
 
-			if ( m.parameters.specularMap ) {
+			if ( matJSON.parameters.specularMap ) {
 
-				uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
+				uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
 				uniforms[ "enableSpecular" ].value = true;
 
 			}
 
-			if ( m.parameters.displacementMap ) {
+			if ( matJSON.parameters.displacementMap ) {
 
-				uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
+				uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
 				uniforms[ "enableDisplacement" ].value = true;
 
-				uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
-				uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
+				uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
+				uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
 
 			}
 
@@ -1072,9 +1089,9 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 			uniforms[ "uShininess" ].value = shininess;
 
-			if ( m.parameters.opacity ) {
+			if ( matJSON.parameters.opacity ) {
 
-				uniforms[ "uOpacity" ].value = m.parameters.opacity;
+				uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
 
 			}
 
@@ -1084,33 +1101,33 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 		} else {
 
-			material = new THREE[ m.type ]( m.parameters );
+			material = new THREE[ matJSON.type ]( matJSON.parameters );
 
 		}
 
-		result.materials[ dm ] = material;
+		result.materials[ matID ] = material;
 
 	}
 
 	// second pass through all materials to initialize MeshFaceMaterials
 	// that could be referring to other materials out of order
 
-	for ( dm in data.materials ) {
+	for ( matID in data.materials ) {
 
-		m = data.materials[ dm ];
+		matJSON = data.materials[ matID ];
 
-		if ( m.parameters.materials ) {
+		if ( matJSON.parameters.materials ) {
 
 			var materialArray = [];
 
-			for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
+			for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
 
-				var label = m.parameters.materials[ i ];
+				var label = matJSON.parameters.materials[ i ];
 				materialArray.push( result.materials[ label ] );
 
 			}
 
-			result.materials[ dm ].materials = materialArray;
+			result.materials[ matID ].materials = materialArray;
 
 		}
 
@@ -1134,9 +1151,9 @@ THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
 
 	}
 
-	c = data.defaults.bgcolor;
+	color = data.defaults.bgcolor;
 	result.bgColor = new THREE.Color();
-	result.bgColor.setRGB( c[0], c[1], c[2] );
+	result.bgColor.setRGB( color[0], color[1], color[2] );
 
 	result.bgColorAlpha = data.defaults.bgalpha;
 

+ 4 - 5
src/materials/Material.js

@@ -5,8 +5,6 @@
 
 THREE.Material = function () {
 
-	THREE.MaterialLibrary.push( this );
-
 	this.id = THREE.MaterialIdCount ++;
 
 	this.name = '';
@@ -37,6 +35,8 @@ THREE.Material = function () {
 
 	this.needsUpdate = true;
 
+	THREE.MaterialLibrary[ this.id ] = this;
+
 };
 
 THREE.Material.prototype.setValues = function ( values ) {
@@ -118,10 +118,9 @@ THREE.Material.prototype.clone = function ( material ) {
 
 THREE.Material.prototype.deallocate = function () {
 
-	var index = THREE.MaterialLibrary.indexOf( this );
-	if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
+	delete THREE.MaterialLibrary[ this.id ];
 
 };
 
 THREE.MaterialIdCount = 0;
-THREE.MaterialLibrary = [];
+THREE.MaterialLibrary = {};

+ 270 - 0
src/math/Box2.js

@@ -0,0 +1,270 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+THREE.Box2 = function ( min, max ) {
+
+	if ( min === undefined && max === undefined ) {
+
+		this.min = new THREE.Vector2();
+		this.max = new THREE.Vector2();
+		this.makeEmpty();
+
+	} else {
+		this.min = min.clone();
+		if( max === undefined ) {
+			this.max = new THREE.Vector2().copy( this.min ); // This is done on purpose so you can make a box using a single point and then expand it.
+		}
+		else {
+			this.max = max.clone();
+		}
+	}
+
+};
+
+THREE.Box2.prototype = {
+
+	constructor: THREE.Box2,
+
+	set: function ( min, max ) {
+
+		this.min.copy( min );
+		this.max.copy( max );
+
+		return this;
+	},
+
+	setFromPoints: function ( points ) {
+
+		if ( points.length > 0 ) {
+
+			var p = points[ 0 ];
+
+			this.min.copy( p );
+			this.max.copy( p );
+
+			for ( var i = 1, il = points.length; i < il; i ++ ) {
+
+				p = points[ i ];
+
+				if ( p.x < this.min.x ) {
+
+					this.min.x = p.x;
+
+				} else if ( p.x > this.max.x ) {
+
+					this.max.x = p.x;
+
+				}
+
+				if ( p.y < this.min.y ) {
+
+					this.min.y = p.y;
+
+				} else if ( p.y > this.max.y ) {
+
+					this.max.y = p.y;
+
+				}
+
+			}
+
+		} else {
+
+			this.makeEmpty();
+
+		}
+
+		return this;
+
+	},
+
+	setFromCenterAndSize: function ( center, size ) {
+
+		var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
+		this.min.copy( center ).subSelf( halfSize );
+		this.max.copy( center ).addSelf( halfSize );
+
+		return this;
+
+	},
+
+	copy: function ( box ) {
+
+		this.min.copy( box.min );
+		this.max.copy( box.max );
+
+		return this;
+
+	},
+
+	makeEmpty: function () {
+
+		this.min.x = this.min.y = Infinity;
+		this.max.x = this.max.y = -Infinity;
+
+		return this;
+
+	},
+
+	empty: function () {
+
+		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
+
+		return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
+
+	},
+
+	center: function () {
+
+		return new THREE.Vector2().add( this.min, this.max ).multiplyScalar( 0.5 );
+
+	},
+
+	size: function () {
+
+		return new THREE.Vector2().sub( this.max, this.min );
+
+	},
+
+	expandByPoint: function ( point ) {
+
+		this.min.minSelf( point );
+		this.max.maxSelf( point );
+
+		return this;
+	},
+
+	expandByVector: function ( vector ) {
+
+		this.min.subSelf( vector );
+		this.max.addSelf( vector );
+
+		return this;
+	},
+
+	expandByScalar: function ( scalar ) {
+
+		this.min.addScalar( -scalar );
+		this.max.addScalar( scalar );
+
+		return this;
+	},
+
+	containsPoint: function ( point ) {
+
+		if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
+			 ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
+
+			return true;
+
+		}
+
+		return false;
+
+	},
+
+	containsBox: function ( box ) {
+
+		if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
+			 ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
+
+			return true;
+
+		}
+
+		return false;
+
+	},
+
+	getParameter: function ( point ) {
+
+		// This can potentially have a divide by zero if the box
+		// has a size dimension of 0.
+
+		return new THREE.Vector2(
+			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
+			( point.y - this.min.y ) / ( this.max.y - this.min.y )
+		);
+
+	},
+
+	isIntersection: function ( box ) {
+
+		// using 6 splitting planes to rule out intersections.
+
+		if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
+			 ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ) {
+
+			return false;
+
+		}
+
+		return true;
+
+	},
+
+	clampPoint: function ( point ) {
+
+		return new THREE.Vector2().copy( point ).clampSelf( this.min, this.max );
+
+	},
+
+	distanceToPoint: function ( point ) {
+
+		var clampedPoint = THREE.Box2.__v1.copy( point ).clampSelf( this.min, this.max );
+		return clampedPoint.subSelf( point ).length();
+
+	},
+
+	intersect: function ( box ) {
+
+		this.min.maxSelf( box.min );
+		this.max.minSelf( box.max );
+
+		return this;
+
+	},
+
+	union: function ( box ) {
+
+		this.min.minSelf( box.min );
+		this.max.maxSelf( box.max );
+
+		return this;
+
+	},
+
+	translate: function ( offset ) {
+
+		this.min.addSelf( offset );
+		this.max.addSelf( offset );
+
+		return this;
+
+	},
+
+	scale: function ( factor ) {
+
+		var sizeDeltaHalf = this.size().multiplyScalar( ( factor - 1 )  * 0.5 );
+		this.expandByVector( sizeDeltaHalf );
+
+		return this;
+
+	},
+
+	equals: function ( box ) {
+
+		return box.min.equals( this.min ) && box.max.equals( this.max );
+
+	},
+
+	clone: function () {
+
+		return new THREE.Box2().copy( this );
+
+	}
+
+};
+
+THREE.Box2.__v1 = new THREE.Vector2();

+ 295 - 0
src/math/Box3.js

@@ -0,0 +1,295 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+THREE.Box3 = function ( min, max ) {
+
+	if ( min === undefined && max === undefined ) {
+
+		this.min = new THREE.Vector3();
+		this.max = new THREE.Vector3();
+		this.makeEmpty();
+
+	} else {
+
+		this.min = min.clone();
+
+		if( max === undefined ) {
+
+			this.max = new THREE.Vector3().copy( this.min ); // This is done on purpose so you can make a box using a single point and then expand it.
+
+		} else {
+
+			this.max = max.clone();
+
+		}
+
+	}
+
+};
+
+THREE.Box3.prototype = {
+
+	constructor: THREE.Box3,
+
+	set: function ( min, max ) {
+
+		this.min.copy( min );
+		this.max.copy( max );
+
+		return this;
+
+	},
+
+	setFromPoints: function ( points ) {
+
+		if ( points.length > 0 ) {
+
+			var p = points[ 0 ];
+
+			this.min.copy( p );
+			this.max.copy( p );
+
+			for ( var i = 1, il = points.length; i < il; i ++ ) {
+
+				p = points[ i ];
+
+				if ( p.x < this.min.x ) {
+
+					this.min.x = p.x;
+
+				} else if ( p.x > this.max.x ) {
+
+					this.max.x = p.x;
+
+				}
+
+				if ( p.y < this.min.y ) {
+
+					this.min.y = p.y;
+
+				} else if ( p.y > this.max.y ) {
+
+					this.max.y = p.y;
+
+				}
+
+				if ( p.z < this.min.z ) {
+
+					this.min.z = p.z;
+
+				} else if ( p.z > this.max.z ) {
+
+					this.max.z = p.z;
+
+				}
+
+			}
+
+		} else {
+
+			this.makeEmpty();
+
+		}
+
+		return this;
+
+	},
+
+	setFromCenterAndSize: function ( center, size ) {
+
+		var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
+
+		this.min.copy( center ).subSelf( halfSize );
+		this.max.copy( center ).addSelf( halfSize );
+
+		return this;
+
+	},
+
+	copy: function ( box ) {
+
+		this.min.copy( box.min );
+		this.max.copy( box.max );
+
+		return this;
+
+	},
+
+	makeEmpty: function () {
+
+		this.min.x = this.min.y = this.min.z = Infinity;
+		this.max.x = this.max.y = this.max.z = -Infinity;
+
+		return this;
+
+	},
+
+	empty: function () {
+
+		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
+
+		return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
+
+	},
+
+	center: function () {
+
+		return new THREE.Vector3().add( this.min, this.max ).multiplyScalar( 0.5 );
+
+	},
+
+	size: function () {
+
+		return new THREE.Vector3().sub( this.max, this.min );
+
+	},
+
+	expandByPoint: function ( point ) {
+
+		this.min.minSelf( point );
+		this.max.maxSelf( point );
+
+		return this;
+
+	},
+
+	expandByVector: function ( vector ) {
+
+		this.min.subSelf( vector );
+		this.max.addSelf( vector );
+
+		return this;
+
+	},
+
+	expandByScalar: function ( scalar ) {
+
+		this.min.addScalar( -scalar );
+		this.max.addScalar( scalar );
+
+		return this;
+
+	},
+
+	containsPoint: function ( point ) {
+
+		if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
+			 ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
+			 ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
+
+			return true;
+
+		}
+
+		return false;
+
+	},
+
+	containsBox: function ( box ) {
+
+		if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
+			 ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
+			 ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
+
+			return true;
+
+		}
+
+		return false;
+
+	},
+
+	getParameter: function ( point ) {
+
+		// This can potentially have a divide by zero if the box
+		// has a size dimension of 0.
+
+		return new THREE.Vector3(
+			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
+			( point.y - this.min.y ) / ( this.max.y - this.min.y ),
+			( point.z - this.min.z ) / ( this.max.z - this.min.z )
+		);
+
+	},
+
+	isIntersection: function ( box ) {
+
+		// using 6 splitting planes to rule out intersections.
+
+		if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
+			 ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
+			 ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
+
+			return false;
+
+		}
+
+		return true;
+
+	},
+
+	clampPoint: function ( point ) {
+
+		return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
+
+	},
+
+	distanceToPoint: function ( point ) {
+
+		var clampedPoint = THREE.Box3.__v1.copy( point ).clampSelf( this.min, this.max );
+		return clampedPoint.subSelf( point ).length();
+
+	},
+
+	intersect: function ( box ) {
+
+		this.min.maxSelf( box.min );
+		this.max.minSelf( box.max );
+
+		return this;
+
+	},
+
+	union: function ( box ) {
+
+		this.min.minSelf( box.min );
+		this.max.maxSelf( box.max );
+
+		return this;
+
+	},
+
+	translate: function ( offset ) {
+
+		this.min.addSelf( offset );
+		this.max.addSelf( offset );
+
+		return this;
+
+	},
+
+	scale: function ( factor ) {
+
+		var sizeDeltaHalf = this.size().multiplyScalar( ( factor - 1 )  * 0.5 );
+		this.expandByVector( sizeDeltaHalf );
+
+		return this;
+
+	},
+
+	equals: function ( box ) {
+
+		return box.min.equals( this.min ) && box.max.equals( this.max );
+
+	},
+
+	clone: function () {
+
+		return new THREE.Box3().copy( this );
+
+	}
+
+};
+
+THREE.Box3.__v1 = new THREE.Vector3();

+ 0 - 0
src/core/Clock.js → src/math/Clock.js


+ 0 - 0
src/core/Color.js → src/math/Color.js


+ 19 - 18
src/core/Frustum.js → src/math/Frustum.js

@@ -1,18 +1,19 @@
 /**
  * @author mrdoob / http://mrdoob.com/
  * @author alteredq / http://alteredqualia.com/
+ * @author bhouston / http://exocortex.com
  */
 
 THREE.Frustum = function ( ) {
 
 	this.planes = [
 
-		new THREE.Vector4(),
-		new THREE.Vector4(),
-		new THREE.Vector4(),
-		new THREE.Vector4(),
-		new THREE.Vector4(),
-		new THREE.Vector4()
+		new THREE.Plane(),
+		new THREE.Plane(),
+		new THREE.Plane(),
+		new THREE.Plane(),
+		new THREE.Plane(),
+		new THREE.Plane()
 
 	];
 
@@ -20,7 +21,6 @@ THREE.Frustum = function ( ) {
 
 THREE.Frustum.prototype.setFromMatrix = function ( m ) {
 
-	var plane;
 	var planes = this.planes;
 
 	var me = m.elements;
@@ -29,17 +29,16 @@ THREE.Frustum.prototype.setFromMatrix = function ( m ) {
 	var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
 	var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
 
-	planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
-	planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
-	planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
-	planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
-	planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
-	planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
+	planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
+	planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
+	planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
+	planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
+	planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
+	planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
 
 	for ( var i = 0; i < 6; i ++ ) {
 
-		plane = planes[ i ];
-		plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
+		planes[ i ].normalize();
 
 	}
 
@@ -47,15 +46,17 @@ THREE.Frustum.prototype.setFromMatrix = function ( m ) {
 
 THREE.Frustum.prototype.contains = function ( object ) {
 
-	var distance = 0.0;
 	var planes = this.planes;
+
 	var matrix = object.matrixWorld;
-	var me = matrix.elements;
+	var matrixPosition = matrix.getPosition();
 	var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
 
+	var distance = 0.0;
+
 	for ( var i = 0; i < 6; i ++ ) {
 
-		distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
+		distance = planes[ i ].distanceToPoint( matrixPosition );
 		if ( distance <= radius ) return false;
 
 	}

+ 15 - 0
src/core/Math.js → src/math/Math.js

@@ -65,6 +65,21 @@ THREE.Math = {
 
 		return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
 
+	},
+
+	degreesToRadians: function ( degrees ) {
+
+		return degrees * THREE.Math.__d2r;
+
+	},
+
+	radiansToDegrees: function ( radians ) {
+
+		return radians * THREE.Math.__r2d;
+
 	}
 
 };
+
+THREE.Math.__d2r =  Math.PI / 180;
+THREE.Math.__r2d =  180 / Math.PI;

+ 0 - 0
src/core/Matrix3.js → src/math/Matrix3.js


+ 0 - 0
src/core/Matrix4.js → src/math/Matrix4.js


+ 152 - 0
src/math/Plane.js

@@ -0,0 +1,152 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+THREE.Plane = function ( normal, constant ) {
+
+	if ( normal === undefined && constant === undefined ) {
+
+		this.normal = new THREE.Vector3();
+		this.constant = 0;
+
+	} else {
+
+		this.normal = normal.clone();
+		this.constant = constant || 0;
+
+	}
+
+};
+
+THREE.Plane.prototype = {
+
+	constructor: THREE.Plane,
+
+	set: function ( normal, constant ) {
+
+		this.normal.copy( normal );
+		this.constant = constant;
+
+		return this;
+
+	},
+
+	setComponents: function ( x, y, z, w ) {
+
+		this.normal.set( x, y, z );
+		this.constant = w;
+
+		return this;
+
+	},
+
+	setFromNormalAndCoplanarPoint: function ( normal, point ) {
+
+		this.normal.copy( normal );
+		this.constant = - point.dot( normal );
+
+		return this;
+
+	},
+
+	setFromCoplanarPoints: function ( a, b, c ) {
+
+		var normal = THREE.Plane.__v1.sub( b, a ).cross(
+					 THREE.Plane.__v2.sub( c, a ) );
+
+		// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
+
+		this.setFromNormalAndCoplanarPoint( normal, a );
+
+		return this;
+
+	},
+
+	copy: function ( plane ) {
+
+		this.normal.copy( plane.normal );
+		this.constant = plane.constant;
+
+		return this;
+
+	},
+
+	normalize: function () {
+
+		// Note: will lead to a divide by zero if the plane is invalid.
+
+		var inverseNormalLength = 1.0 / this.normal.length();
+		this.normal.multiplyScalar( inverseNormalLength );
+		this.constant *= inverseNormalLength;
+
+		return this;
+
+	},
+
+	distanceToPoint: function ( point ) {
+
+		return this.normal.dot( point ) + this.constant;
+
+	},
+
+	distanceToSphere: function ( sphere ) {
+
+		return this.distanceToPoint( sphere.center ) - sphere.radius;
+
+	},
+
+	projectPoint: function ( point ) {
+
+		return this.orthoPoint( point ).subSelf( point ).negate();
+
+	},
+
+	orthoPoint: function ( point ) {
+
+		var perpendicularMagnitude = this.distanceToPoint( point );
+
+		return new THREE.Vector3().copy( this.normal ).multiplyScalar( perpendicularMagnitude );
+
+	},
+
+	intersectsLine: function ( startPoint, endPoint ) {
+
+		// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
+
+		var startSign = this.distanceToPoint( startPoint );
+		var endSign = this.distanceToPoint( endPoint );
+
+		return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
+
+	},
+
+	coplanarPoint: function () {
+
+		return new THREE.Vector3().copy( this.normal ).multiplyScalar( - this.constant );
+
+	},
+
+	translate: function ( offset ) {
+
+		this.constant = - offset.dot( this.normal );
+
+		return this;
+
+	},
+
+	equals: function ( plane ) {
+
+		return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
+
+	},
+
+	clone: function () {
+
+		return new THREE.Plane().copy( this );
+
+	}
+
+};
+
+THREE.Plane.__v1 = new THREE.Vector3();
+THREE.Plane.__v2 = new THREE.Vector3();

+ 0 - 0
src/core/Quaternion.js → src/math/Quaternion.js


+ 161 - 0
src/math/Ray.js

@@ -0,0 +1,161 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+THREE.Ray = function ( origin, direction ) {
+
+
+	this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
+	this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
+
+};
+
+THREE.Ray.prototype = {
+
+	constructor: THREE.Ray,
+
+	set: function ( origin, direction ) {
+
+		this.origin.copy( origin );
+		this.direction.copy( direction );
+
+		return this;
+
+	},
+
+	copy: function ( ray ) {
+
+		this.origin.copy( ray.origin );
+		this.direction.copy( ray.direction );
+
+		return this;
+
+	},
+
+	at: function( t, optionalTarget ) {
+
+		if( optionalTarget === undefined ) {
+			optionalTarget = this.direction.clone();
+		}
+		else {
+			optionalTarget.copy( this.direction );
+		}
+		return optionalTarget.multiplyScalar( t ).addSelf( this.origin );
+
+	},
+
+	recastSelf: function ( t ) {
+
+		this.origin = this.at( t );
+
+		return this;
+
+	},
+
+	closestPointToPoint: function ( point ) {
+
+		var result = point.clone().subSelf( this.origin );
+		var directionDistance = result.dot( this.direction );
+
+		return result.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
+
+	},
+
+	distanceToPoint: function ( point ) {
+
+		var directionDistance = THREE.Ray.__v1.sub( point, this.origin ).dot( this.direction );		
+		THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
+
+		return THREE.Ray.__v1.distanceTo( point );
+
+	},
+
+	isIntersectionSphere: function( sphere ) {
+
+		return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
+
+	},
+
+	isIntersectionPlane: function ( plane ) {
+
+		// check if the line and plane are non-perpendicular, if they
+		// eventually they will intersect.
+		var denominator = plane.normal.dot( this.direction );
+		if ( denominator != 0 ) {
+
+			return true;
+
+		}
+
+		// line is coplanar, return origin
+		if( plane.distanceToPoint( this.origin ) == 0 ) {
+
+			return true;
+
+		}
+
+		return false;
+
+	},
+
+	distanceToPlane: function ( plane ) {
+
+		var denominator = plane.normal.dot( this.direction );
+		if ( denominator == 0 ) {
+
+			// line is coplanar, return origin
+			if( plane.distanceToPoint( this.origin ) == 0 ) {
+
+				return 0;
+
+			}
+
+			// Unsure if this is the correct method to handle this case.
+			return undefined;
+
+		}
+
+		var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
+
+		return t;
+
+	},
+
+	intersectPlane: function ( plane ) {
+
+		var t = this.distanceToPlane( plane );
+
+		if( t === undefined ) {
+
+			return undefined;
+		}
+
+		return this.at( t );
+
+	},
+
+	transformSelf: function ( matrix4 ) {
+
+		this.direction = matrix4.multiplyVector3( this.direction.addSelf( this.origin ) );
+		this.origin = matrix4.multiplyVector3( this.origin );
+		this.direction.subSelf( this.origin );
+
+		return this;
+	},
+
+	equals: function ( ray ) {
+
+		return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
+
+	},
+
+	clone: function () {
+
+		return new THREE.Ray().copy( this );
+
+	}
+
+};
+
+THREE.Ray.__v1 = new THREE.Vector3();
+THREE.Ray.__v2 = new THREE.Vector3();

+ 0 - 0
src/core/Rectangle.js → src/math/Rectangle.js


+ 132 - 0
src/math/Sphere.js

@@ -0,0 +1,132 @@
+/**
+ * @author bhouston / http://exocortex.com
+ */
+
+THREE.Sphere = function ( center, radius ) {
+
+	if ( center === undefined && radius === undefined ) {
+
+		this.center = new THREE.Vector3();
+		this.radius = 0;
+
+	} else {
+
+		this.center = center.clone();
+		this.radius = radius || 0;
+
+	}
+
+};
+
+THREE.Sphere.prototype = {
+
+	constructor: THREE.Sphere,
+
+	set: function ( center, radius ) {
+
+		this.center.copy( center );
+		this.radius = radius;
+
+		return this;
+	},
+
+	setFromCenterAndPoints: function ( center, points ) {
+
+		var maxRadiusSq = 0;
+
+		for ( var i = 0, il = points.length; i < il; i ++ ) {
+
+			var radiusSq = center.distanceToSquared( points[ i ] );
+			maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
+
+		}
+
+		this.center = center;
+		this.radius = Math.sqrt( maxRadiusSq );
+
+		return this;
+
+	},
+
+	copy: function ( sphere ) {
+
+		this.center.copy( sphere.center );
+		this.radius = sphere.radius;
+
+		return this;
+
+	},
+
+	empty: function () {
+
+		return ( this.radius <= 0 );
+
+	},
+
+	containsPoint: function ( point ) {
+
+		return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
+
+	},
+
+	distanceToPoint: function ( point ) {
+
+		return ( point.distanceTo( this.center ) - this.radius );
+
+	},
+
+	clampPoint: function ( point ) {
+
+		var deltaLengthSq = this.center.distanceToSquared( point );
+
+		var result = new THREE.Vector3().copy( point );
+
+		if ( deltaLengthSq > ( this.radius * this.radius ) ) {
+
+			result.subSelf( this.center ).normalize();
+			result.multiplyScalar( this.radius ).addSelf( this.center );
+
+		}
+
+		return result;
+
+	},
+
+	bounds: function () {
+
+		var box =  new THREE.Box3( this.center, this.center );
+		box.expandByScalar( this.radius );
+
+		return box;
+
+	},
+
+	translate: function ( offset ) {
+
+		this.center.addSelf( this.offset );
+
+		return this;
+
+	},
+
+	scale: function ( factor ) {
+
+		this.radius *= factor;
+
+		return this;
+
+	},
+
+	equals: function ( sphere ) {
+
+		return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
+
+	},
+
+	clone: function () {
+
+		return new THREE.Sphere3().copy( this );
+
+	}
+
+};

+ 0 - 0
src/core/Spline.js → src/math/Spline.js


+ 10 - 0
src/math/UV.js

@@ -0,0 +1,10 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+THREE.UV = function ( u, v ) {
+
+	console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
+	return new THREE.Vector2( u, v );
+
+};

+ 89 - 0
src/core/Vector2.js → src/math/Vector2.js

@@ -25,6 +25,22 @@ THREE.Vector2.prototype = {
 
 	},
 
+	setX: function ( x ) {
+
+		this.x = x;
+
+		return this;
+
+	},
+
+	setY: function ( y ) {
+
+		this.y = y;
+
+		return this;
+
+	},
+
 	copy: function ( v ) {
 
 		this.x = v.x;
@@ -34,6 +50,15 @@ THREE.Vector2.prototype = {
 
 	},
 
+	addScalar: function ( s ) {
+
+		this.x += s;
+		this.y += s;
+
+		return this;
+
+	},
+
 	add: function ( a, b ) {
 
 		this.x = a.x + b.x;
@@ -96,6 +121,70 @@ THREE.Vector2.prototype = {
 
 	},
 
+	minSelf: function ( v ) {
+
+		if ( this.x > v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y > v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		return this;
+
+	},
+
+	maxSelf: function ( v ) {
+
+		if ( this.x < v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y < v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		return this;
+
+	},
+
+	clampSelf: function ( min, max ) {
+
+		// This function assumes min < max, if this assumption isn't true it will not operate correctly
+
+		if ( this.x < min.x ) {
+
+			this.x = min.x;
+
+		} else if ( this.x > max.x ) {
+
+			this.x = max.x;
+
+		}
+
+		if ( this.y < min.y ) {
+
+			this.y = min.y;
+
+		} else if ( this.y > max.y ) {
+
+			this.y = max.y;
+
+		}
+
+		return this;
+
+	},
+
 	negate: function() {
 
 		return this.multiplyScalar( - 1 );

+ 91 - 2
src/core/Vector3.js → src/math/Vector3.js

@@ -1,6 +1,6 @@
 /**
  * @author mrdoob / http://mrdoob.com/
- * @author kile / http://kile.stravaganza.org/
+ * @author *kile / http://kile.stravaganza.org/
  * @author philogb / http://blog.thejit.org/
  * @author mikael emtinger / http://gomo.se/
  * @author egraether / http://egraether.com/
@@ -174,6 +174,91 @@ THREE.Vector3.prototype = {
 
 	},
 
+	minSelf: function ( v ) {
+
+		if ( this.x > v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y > v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		if ( this.z > v.z ) {
+
+			this.z = v.z;
+
+		}
+
+		return this;
+
+	},
+
+	maxSelf: function ( v ) {
+
+		if ( this.x < v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y < v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		if ( this.z < v.z ) {
+
+			this.z = v.z;
+
+		}
+
+		return this;
+
+	},
+
+	clampSelf: function ( min, max ) {
+
+		// This function assumes min < max, if this assumption isn't true it will not operate correctly
+
+		if ( this.x < min.x ) {
+
+			this.x = min.x;
+
+		} else if ( this.x > max.x ) {
+
+			this.x = max.x;
+
+		}
+
+		if ( this.y < min.y ) {
+
+			this.y = min.y;
+
+		} else if ( this.y > max.y ) {
+
+			this.y = max.y;
+
+		}
+
+		if ( this.z < min.z ) {
+
+			this.z = min.z;
+
+		} else if ( this.z > max.z ) {
+
+			this.z = max.z;
+
+		}
+
+		return this;
+
+	},
 
 	negate: function() {
 
@@ -263,7 +348,11 @@ THREE.Vector3.prototype = {
 
 	distanceToSquared: function ( v ) {
 
-		return new THREE.Vector3().sub( this, v ).lengthSq();
+		var dx = this.x - v.x;
+		var dy = this.y - v.y;
+		var dz = this.z - v.z;
+
+		return dx * dx + dy * dy + dz * dz;
 
 	},
 

+ 157 - 1
src/core/Vector4.js → src/math/Vector4.js

@@ -30,6 +30,38 @@ THREE.Vector4.prototype = {
 
 	},
 
+	setX: function ( x ) {
+
+		this.x = x;
+
+		return this;
+
+	},
+
+	setY: function ( y ) {
+
+		this.y = y;
+
+		return this;
+
+	},
+
+	setZ: function ( z ) {
+
+		this.z = z;
+
+		return this;
+
+	},
+
+	setW: function ( w ) {
+
+		this.w = w;
+
+		return this;
+
+	},
+
 	copy: function ( v ) {
 
 		this.x = v.x;
@@ -41,6 +73,17 @@ THREE.Vector4.prototype = {
 
 	},
 
+	addScalar: function ( s ) {
+
+		this.x += s;
+		this.y += s;
+		this.z += s;
+		this.w += s;
+
+		return this;
+
+	},
+
 	add: function ( a, b ) {
 
 		this.x = a.x + b.x;
@@ -118,6 +161,113 @@ THREE.Vector4.prototype = {
 
 	},
 
+	minSelf: function ( v ) {
+
+		if ( this.x > v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y > v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		if ( this.z > v.z ) {
+
+			this.z = v.z;
+
+		}
+
+		if ( this.w > v.w ) {
+
+			this.w = v.w;
+
+		}
+
+		return this;
+
+	},
+
+	maxSelf: function ( v ) {
+
+		if ( this.x < v.x ) {
+
+			this.x = v.x;
+
+		}
+
+		if ( this.y < v.y ) {
+
+			this.y = v.y;
+
+		}
+
+		if ( this.z < v.z ) {
+
+			this.z = v.z;
+
+		}
+
+		if ( this.w < v.w ) {
+
+			this.w = v.w;
+
+		}
+
+		return this;
+
+	},
+
+	clampSelf: function ( min, max ) {
+
+		// This function assumes min < max, if this assumption isn't true it will not operate correctly
+
+		if ( this.x < min.x ) {
+
+			this.x = min.x;
+
+		} else if ( this.x > max.x ) {
+
+			this.x = max.x;
+
+		}
+
+		if ( this.y < min.y ) {
+
+			this.y = min.y;
+
+		} else if ( this.y > max.y ) {
+
+			this.y = max.y;
+
+		}
+
+		if ( this.z < min.z ) {
+
+			this.z = min.z;
+
+		} else if ( this.z > max.z ) {
+
+			this.z = max.z;
+
+		}
+
+		if ( this.w < min.w ) {
+
+			this.w = min.w;
+
+		} else if ( this.w > max.w ) {
+
+			this.w = max.w;
+
+		}
+
+		return this;
+
+	},
 
 	negate: function() {
 
@@ -172,6 +322,12 @@ THREE.Vector4.prototype = {
 
 	},
 
+	equals: function ( v ) {
+
+		return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
+
+	},
+
 	clone: function () {
 
 		return new THREE.Vector4( this.x, this.y, this.z, this.w );
@@ -316,7 +472,7 @@ THREE.Vector4.prototype = {
 						 + ( m13 - m31 ) * ( m13 - m31 )
 						 + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
 
-		if ( Math.abs( s ) < 0.001 ) s = 1; 
+		if ( Math.abs( s ) < 0.001 ) s = 1;
 
 		// prevent divide by zero, should not happen if matrix is orthogonal and should be
 		// caught by singularity test above, but I've left it in just in case

+ 0 - 0
src/core/Vertex.js → src/math/Vertex.js


+ 2 - 2
src/renderers/WebGLRenderTarget.js

@@ -39,10 +39,10 @@ THREE.WebGLRenderTarget.prototype.clone = function() {
 	tmp.wrapT = this.wrapT;
 
 	tmp.magFilter = this.magFilter;
-	tmp.anisotropy = this.anisotropy;
-
 	tmp.minFilter = this.minFilter;
 
+	tmp.anisotropy = this.anisotropy;
+
 	tmp.offset.copy( this.offset );
 	tmp.repeat.copy( this.repeat );
 

+ 14 - 14
src/renderers/WebGLRenderer.js

@@ -151,7 +151,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 	_projScreenMatrix = new THREE.Matrix4(),
 	_projScreenMatrixPS = new THREE.Matrix4(),
 
-	_vector3 = new THREE.Vector4(),
+	_vector3 = new THREE.Vector3(),
 
 	// light arrays cache
 
@@ -1031,7 +1031,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 			}
 
-			sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
+			sortArray.sort( numericalSort );
 
 			for ( v = 0; v < vl; v ++ ) {
 
@@ -2361,8 +2361,8 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 					uvi = uv[ i ];
 
-					uvArray[ offset_uv ]     = uvi.u;
-					uvArray[ offset_uv + 1 ] = uvi.v;
+					uvArray[ offset_uv ]     = uvi.x;
+					uvArray[ offset_uv + 1 ] = uvi.y;
 
 					offset_uv += 2;
 
@@ -2382,8 +2382,8 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 					uvi = uv[ i ];
 
-					uvArray[ offset_uv ]     = uvi.u;
-					uvArray[ offset_uv + 1 ] = uvi.v;
+					uvArray[ offset_uv ]     = uvi.x;
+					uvArray[ offset_uv + 1 ] = uvi.y;
 
 					offset_uv += 2;
 
@@ -2414,8 +2414,8 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 					uv2i = uv2[ i ];
 
-					uv2Array[ offset_uv2 ]     = uv2i.u;
-					uv2Array[ offset_uv2 + 1 ] = uv2i.v;
+					uv2Array[ offset_uv2 ]     = uv2i.x;
+					uv2Array[ offset_uv2 + 1 ] = uv2i.y;
 
 					offset_uv2 += 2;
 
@@ -2435,8 +2435,8 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 					uv2i = uv2[ i ];
 
-					uv2Array[ offset_uv2 ]     = uv2i.u;
-					uv2Array[ offset_uv2 + 1 ] = uv2i.v;
+					uv2Array[ offset_uv2 ]     = uv2i.x;
+					uv2Array[ offset_uv2 + 1 ] = uv2i.y;
 
 					offset_uv2 += 2;
 
@@ -3798,7 +3798,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 				if ( influence > 0 ) {
 
-					activeInfluenceIndices.push( [ i, influence ] );
+					activeInfluenceIndices.push( [ influence, i ] );
 
 				}
 
@@ -3825,7 +3825,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 				if ( activeInfluenceIndices[ m ] ) {
 
-					influenceIndex = activeInfluenceIndices[ m ][ 0 ];
+					influenceIndex = activeInfluenceIndices[ m ][ 1 ];
 
 					if ( attributes[ "morphTarget" + m ] >= 0 ) {
 
@@ -3896,7 +3896,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 
 	function numericalSort ( a, b ) {
 
-		return b[ 1 ] - a[ 1 ];
+		return b[ 0 ] - a[ 0 ];
 
 	};
 
@@ -6928,7 +6928,7 @@ THREE.WebGLRenderer = function ( parameters ) {
 			}
 
 			_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
-			_gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
+			_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
 
 		}
 

+ 4 - 7
src/renderers/WebGLShaders.js

@@ -268,19 +268,16 @@ THREE.ShaderChunk = {
 
 		"#ifdef USE_MAP",
 
+			"vec4 texelColor = texture2D( map, vUv );",
+
 			"#ifdef GAMMA_INPUT",
 
-				"vec4 texelColor = texture2D( map, vUv );",
 				"texelColor.xyz *= texelColor.xyz;",
 
-				"gl_FragColor = gl_FragColor * texelColor;",
-
-			"#else",
-
-				"gl_FragColor = gl_FragColor * texture2D( map, vUv );",
-
 			"#endif",
 
+			"gl_FragColor = gl_FragColor * texelColor;",
+
 		"#endif"
 
 	].join("\n"),

Some files were not shown because too many files changed in this diff