diff --git a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/plaincanvas3d/glcode.js b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/plaincanvas3d/glcode.js index 690cad8758a20747fd976c0708f3a9c94d682904..154e85b8090f185ff256edb5348d0c8bb25df437 100644 --- a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/plaincanvas3d/glcode.js +++ b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/plaincanvas3d/glcode.js @@ -1,6 +1,5 @@ // -// Draws a cube that has different colors assigned to the vertices. -// Each face of the cube has the linear interpolation of the corner colors. +// Draws a plain green cube. // var gl; @@ -8,10 +7,8 @@ var vertexPositionAttrLoc; var shaderProgram; var cubeVertexPositionBuffer; var cubeVertexIndexBuffer; -var cubeVertexColorBuffer; var vertexShader; var fragmentShader; -var vertexColorAttrLoc; var pMatrixUniformLoc; var mvMatrixUniformLoc; @@ -26,7 +23,6 @@ function initializeGL(canvas) { // Setup the OpenGL state gl.enable(gl.DEPTH_TEST); - gl.enable(gl.DEPTH_WRITE); gl.depthMask(true); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); @@ -35,7 +31,7 @@ function initializeGL(canvas) { // Set viewport gl.viewport(0, 0, canvas.width * canvas.devicePixelRatio, canvas.height * canvas.devicePixelRatio); - // Initialize vertex and color buffers + // Initialize vertex and element array buffers initBuffers(); // Initialize the shader program @@ -78,17 +74,13 @@ function paintGL(canvas) { gl.enableVertexAttribArray(vertexPositionAttrLoc); gl.vertexAttribPointer(vertexPositionAttrLoc, 3, gl.FLOAT, false, 0, 0); - gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); - gl.enableVertexAttribArray(vertexColorAttrLoc); - gl.vertexAttribPointer(vertexColorAttrLoc, 4, gl.FLOAT, false, 0, 0); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0); } function initBuffers() { - // Create a cubeVertexPositionBuffer and put a single clipspace rectangle in - // it (2 triangles) + // Create a buffer for cube vertices. Since we are not using textures, we don't need unique + // vertices for each face. We can define the cube using 8 vertices. cubeVertexPositionBuffer = gl.createBuffer(); cubeVertexPositionBuffer.name = "cubeVertexPositionBuffer"; gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); @@ -107,6 +99,8 @@ function initBuffers() { ]), gl.STATIC_DRAW); + // Create buffer for element array indices. We define six sides, each composed of two + // triangles, using the vertices defined above. cubeVertexIndexBuffer = gl.createBuffer(); cubeVertexIndexBuffer.name = "cubeVertexIndexBuffer"; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer); @@ -131,36 +125,17 @@ function initBuffers() { 6, 2, 1 ]), gl.STATIC_DRAW); - - cubeVertexColorBuffer = gl.createBuffer(); - cubeVertexColorBuffer.name = "cubeVertexColorBuffer"; - gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer); - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([// front - 0.000, 1.000, 0.000, - 1.000, 0.000, 1.000, - 1.000, 1.000, 0.000, - 1.000, 0.000, 0.000, - // back - 0.435, 0.602, 0.223, - 0.310, 0.747, 0.185, - 1.000, 1.000, 1.000, - 0.000, 0.000, 1.000 - ]), gl.STATIC_DRAW); } function initShaders() { vertexShader = getShader(gl, "attribute highp vec3 aVertexPosition; \ - attribute highp vec4 aVertexColor; \ uniform highp mat4 uMVMatrix; \ uniform highp mat4 uPMatrix; \ - varying highp vec4 vColor; \ void main(void) { \ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); \ - vColor = aVertexColor; \ }", gl.VERTEX_SHADER); - fragmentShader = getShader(gl, "varying highp vec4 vColor; \ - void main(void) { \ - gl_FragColor = vColor; \ + fragmentShader = getShader(gl, "void main(void) { \ + gl_FragColor = vec4(0.5, 0.76, 0.26, 1.0); \ }", gl.FRAGMENT_SHADER); shaderProgram = gl.createProgram(); @@ -179,8 +154,6 @@ function initShaders() { // look up where the vertex data needs to go. vertexPositionAttrLoc = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(vertexPositionAttrLoc); - vertexColorAttrLoc = gl.getAttribLocation(shaderProgram, "aVertexColor"); - gl.enableVertexAttribArray(vertexColorAttrLoc); pMatrixUniformLoc = gl.getUniformLocation(shaderProgram, "uPMatrix"); pMatrixUniformLoc.name = "pMatrixUniformLoc"; diff --git a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/3rdparty/three.js b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/3rdparty/three.js index 04823db120c2bce663d60b46218e2867b2860043..be4298c93cfa854671d7f8a5ac9f97335141077d 100644 --- a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/3rdparty/three.js +++ b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/3rdparty/three.js @@ -30,9379 +30,9260 @@ THE SOFTWARE. * @author Pasi keränen / pasi.keranen@theqtcompany.com */ -// File:src/qml/QmlImageElement.js +// File:src/Three.js -var __texImageToImageMap = {}; +/** + * @author mrdoob / http://mrdoob.com/ + */ +function THREE() {}; -function Image () { - this.crossOrigin = undefined; - this._src = undefined; - this._onSuccessCallback = undefined; - this._onProgressCallback = undefined; - this._onErrorCallback = undefined; - this._width = 0; - this._height = 0; - this._texImage = TextureImageFactory.newTexImage(); - __texImageToImageMap[""+this._texImage.id()] = this; +THREE.REVISION = '71' - // Setup mapping between the native QObject image and this image - var _this = this; +// browserify support - this._texImage.imageLoaded.connect(function() { _this.notifySuccess(_this) }); - this._texImage.imageLoadingFailed.connect(function() { _this.notifyError(_this) }); +//if ( typeof module === 'object' ) { - this.__defineGetter__("src", function(){ - return _this._src; - }); +// module.exports = THREE; - this.__defineSetter__("src", function(url){ - if (url && url !== '' && url !== _this._src) { - _this._texImage.src = ""+url; - _this._texImage.name = ""+url; - } - _this._src = url; - }); +//} - this.__defineGetter__("width", function(){ - return (_this._texImage !== undefined)?_this._texImage.width:0; - }); +// polyfills - this.__defineSetter__("width", function(url){ - console.log("TODO: Implement image resize"); - }); +if ( Math.sign === undefined ) { - this.__defineGetter__("height", function(){ - return (_this._texImage !== undefined)?_this._texImage.height:0; - }); + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - this.__defineSetter__("height", function(url){ - console.log("TODO: Implement image resize"); - }); -}; + Math.sign = function ( x ) { -Image.prototype = { - constructor: Image, + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x; - addEventListener: function( eventName, callback, flag ) { - if (eventName === 'load') { - this._onSuccessCallback = callback; - } else if (eventName === 'progress') { - this._onProgressCallback = callback; - } else if (eventName === 'error') { - this._onErrorCallback = callback; - } - }, + }; - notifySuccess: function(image) { - if (this._onSuccessCallback !== undefined) { - this._onSuccessCallback(new Event()); - } - }, +} - notifyProgress: function(image) { - if (this._onProgressCallback !== undefined) { - this._onProgressCallback(new Event()); - } - }, - notifyError: function(image) { - if (this._onErrorCallback !== undefined) { - this._onErrorCallback(new Event()); - } - }, +// set the default log handlers +THREE.log = function() { console.log.apply( console, arguments ); } +THREE.warn = function() { console.warn.apply( console, arguments ); } +THREE.error = function() { console.error.apply( console, arguments ); } - texImage: function() { - return this._texImage; - }, - data: function() { - console.error("Image.data not implemented!"); - } -}; +// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button -// TODO: Support for resizing: -//where.image.width = width; -//where.image.height = height; -//where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height ); +THREE.MOUSE = { LEFT: Qt.LeftButton, MIDDLE: Qt.MiddleButton, RIGHT: Qt.RightButton }; -// File:src/qml/QmlHtmlElements.js +// GL STATE CONSTANTS -// HTML document and Element wrappers/stubs +THREE.CullFaceNone = 0; +THREE.CullFaceBack = 1; +THREE.CullFaceFront = 2; +THREE.CullFaceFrontBack = 3; -function document() { -} +THREE.FrontFaceDirectionCW = 0; +THREE.FrontFaceDirectionCCW = 1; -document.createElement = function(type) { - if (type === "img") { - return new Image(); - } else if (type === 'div') { - return new HtmlDiv(); - } +// SHADOWING TYPES - return new HtmlElement(); -} +THREE.BasicShadowMap = 0; +THREE.PCFShadowMap = 1; +THREE.PCFSoftShadowMap = 2; -document.createTextNode = function(value) { - return new HtmlElement(); -} +// MATERIAL CONSTANTS -function Event() { -} +// side -Event.prototype = { - constructor: Event -} +THREE.FrontSide = 0; +THREE.BackSide = 1; +THREE.DoubleSide = 2; -function HtmlStyle() { - this.position = undefined; - this.right = undefined; - this.top = undefined; - this.fontSize = undefined; - this.textAlign = undefined; - this.background = undefined; - this.color = undefined; - this.width = undefined; - this.width = undefined; - this.padding = undefined; - this.zIndex = undefined; -} +// shading -function HtmlElement() { - this.style = new HtmlStyle(); -} +THREE.NoShading = 0; +THREE.FlatShading = 1; +THREE.SmoothShading = 2; -HtmlElement.prototype = { - constructor: HtmlElement, +// colors - appendChild: function(child) { - } -} +THREE.NoColors = 0; +THREE.FaceColors = 1; +THREE.VertexColors = 2; -function HtmlDiv() { - this.innerHTML = ""; - this.style = new HtmlStyle(); -} +// blending modes +THREE.NoBlending = 0; +THREE.NormalBlending = 1; +THREE.AdditiveBlending = 2; +THREE.SubtractiveBlending = 3; +THREE.MultiplyBlending = 4; +THREE.CustomBlending = 5; +// custom blending equations +// (numbers start from 100 not to clash with other +// mappings to OpenGL constants defined in Texture.js) -// File:src/qml/Canvas3DRenderer.js +THREE.AddEquation = 100; +THREE.SubtractEquation = 101; +THREE.ReverseSubtractEquation = 102; +THREE.MinEquation = 103; +THREE.MaxEquation = 104; -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author pasikeranen / pasi.keranen@theqtcompany.com - */ +// custom blending destination factors -THREE.Canvas3DRenderer = function ( parameters ) { +THREE.ZeroFactor = 200; +THREE.OneFactor = 201; +THREE.SrcColorFactor = 202; +THREE.OneMinusSrcColorFactor = 203; +THREE.SrcAlphaFactor = 204; +THREE.OneMinusSrcAlphaFactor = 205; +THREE.DstAlphaFactor = 206; +THREE.OneMinusDstAlphaFactor = 207; - console.log( 'THREE.Canvas3DRenderer', THREE.REVISION ); +// custom blending source factors - parameters = parameters || {}; +//THREE.ZeroFactor = 200; +//THREE.OneFactor = 201; +//THREE.SrcAlphaFactor = 204; +//THREE.OneMinusSrcAlphaFactor = 205; +//THREE.DstAlphaFactor = 206; +//THREE.OneMinusDstAlphaFactor = 207; +THREE.DstColorFactor = 208; +THREE.OneMinusDstColorFactor = 209; +THREE.SrcAlphaSaturateFactor = 210; - if (parameters.canvas === undefined) { - console.error("parameter.canvas must be set when using THREE.Canvas3DRenderer"); - return; - } - var _canvas = parameters.canvas, - _context = parameters.context !== undefined ? parameters.context : null, +// TEXTURE CONSTANTS - pixelRatio = 1, +THREE.MultiplyOperation = 0; +THREE.MixOperation = 1; +THREE.AddOperation = 2; - _precision = parameters.precision !== undefined ? parameters.precision : 'highp', +// Mapping modes - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, - _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false, +THREE.UVMapping = 300; - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0; +THREE.CubeReflectionMapping = 301; +THREE.CubeRefractionMapping = 302; - var lights = []; +THREE.EquirectangularReflectionMapping = 303; +THREE.EquirectangularRefractionMapping = 304; - var _webglObjects = {}; - var _webglObjectsImmediate = []; +THREE.SphericalReflectionMapping = 305; - var opaqueObjects = []; - var transparentObjects = []; +// Wrapping modes - var sprites = []; - var lensFlares = []; +THREE.RepeatWrapping = 1000; +THREE.ClampToEdgeWrapping = 1001; +THREE.MirroredRepeatWrapping = 1002; - // public properties +// Filters - this.domElement = _canvas; - this.context = null; - pixelRatio = parameters.devicePixelRatio !== undefined - ? parameters.devicePixelRatio - : self.pixelRatio !== undefined - ? self.pixelRatio - : 1; +THREE.NearestFilter = 1003; +THREE.NearestMipMapNearestFilter = 1004; +THREE.NearestMipMapLinearFilter = 1005; +THREE.LinearFilter = 1006; +THREE.LinearMipMapNearestFilter = 1007; +THREE.LinearMipMapLinearFilter = 1008; - // clearing +// Data types - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; +THREE.UnsignedByteType = 1009; +THREE.ByteType = 1010; +THREE.ShortType = 1011; +THREE.UnsignedShortType = 1012; +THREE.IntType = 1013; +THREE.UnsignedIntType = 1014; +THREE.FloatType = 1015; +THREE.HalfFloatType = 1025; - // scene graph +// Pixel types - this.sortObjects = true; +//THREE.UnsignedByteType = 1009; +THREE.UnsignedShort4444Type = 1016; +THREE.UnsignedShort5551Type = 1017; +THREE.UnsignedShort565Type = 1018; - // physically based shading +// Pixel formats - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; +THREE.AlphaFormat = 1019; +THREE.RGBFormat = 1020; +THREE.RGBAFormat = 1021; +THREE.LuminanceFormat = 1022; +THREE.LuminanceAlphaFormat = 1023; +// THREE.RGBEFormat handled as THREE.RGBAFormat in shaders +THREE.RGBEFormat = THREE.RGBAFormat; //1024; - // shadow map +// DDS / ST3C Compressed texture formats - this.shadowMapEnabled = false; - this.shadowMapType = THREE.PCFShadowMap; - this.shadowMapCullFace = THREE.CullFaceFront; - this.shadowMapDebug = false; - this.shadowMapCascade = false; +THREE.RGB_S3TC_DXT1_Format = 2001; +THREE.RGBA_S3TC_DXT1_Format = 2002; +THREE.RGBA_S3TC_DXT3_Format = 2003; +THREE.RGBA_S3TC_DXT5_Format = 2004; - // morphs - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; +// PVRTC compressed texture formats - // flags +THREE.RGB_PVRTC_4BPPV1_Format = 2100; +THREE.RGB_PVRTC_2BPPV1_Format = 2101; +THREE.RGBA_PVRTC_4BPPV1_Format = 2102; +THREE.RGBA_PVRTC_2BPPV1_Format = 2103; - this.autoScaleCubemaps = true; - // info +// DEPRECATED - this.info = { +THREE.Projector = function () { - memory: { + THREE.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); - programs: 0, - geometries: 0, - textures: 0 + this.projectVector = function ( vector, camera ) { - }, + THREE.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); + vector.project( camera ); - render: { + }; - calls: 0, - vertices: 0, - faces: 0, - points: 0 + this.unprojectVector = function ( vector, camera ) { - } + THREE.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); + vector.unproject( camera ); }; - // internal properties + this.pickingRay = function ( vector, camera ) { - var _this = this, + THREE.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); - _programs = [], + }; - // internal state cache +}; - _currentProgram = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, +THREE.CanvasRenderer = function () { - _usedTextureUnits = 0, + THREE.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); - _viewportX = 0, - _viewportY = 0, - _viewportWidth = _canvas.width, - _viewportHeight = _canvas.height, - _currentWidth = 0, - _currentHeight = 0, + this.domElement = document.createElement( 'canvas' ); + this.clear = function () {}; + this.render = function () {}; + this.setClearColor = function () {}; + this.setSize = function () {}; - // frustum +}; - _frustum = new THREE.Frustum(), +// File:src/math/Color.js - // camera matrices cache +/** + * @author mrdoob / http://mrdoob.com/ + */ - _projScreenMatrix = new THREE.Matrix4(), +THREE.Color = function ( color ) { - _vector3 = new THREE.Vector3(), + if ( arguments.length === 3 ) { - // light arrays cache + return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] ); - _direction = new THREE.Vector3(), + } - _lightsNeedUpdate = true, + return this.set( color ) - _lights = { +}; - ambient: [ 0, 0, 0 ], - directional: { length: 0, colors:[], positions: [] }, - point: { length: 0, colors: [], positions: [], distances: [], decays: [] }, - spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] }, - hemi: { length: 0, skyColors: [], groundColors: [], positions: [] } +THREE.Color.prototype = { - }; + constructor: THREE.Color, - // initialize + r: 1, g: 1, b: 1, - var _gl; + set: function ( value ) { - try { + if ( value instanceof THREE.Color ) { - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + this.copy( value ); - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + } else if ( typeof value === 'number' ) { - if ( _gl === null ) { + this.setHex( value ); - if ( _canvas.getContext( 'webgl') !== null ) { + } else if ( typeof value === 'string' ) { - throw 'Error creating WebGL context with your selected attributes.'; + this.setStyle( value ); - } else { + } - throw 'Error creating WebGL context.'; + return this; - } + }, - } + setHex: function ( hex ) { -// _canvas.addEventListener( 'webglcontextlost', function ( event ) { -// -// event.preventDefault(); -// -// resetGLState(); -// setDefaultGLState(); -// -// _webglObjects = {}; -// -// }, false); -// - } catch ( error ) { + hex = Math.floor( hex ); - THREE.error( 'THREE.Canvas3DRenderer: ' + error ); + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - } + return this; - var state = new THREE.WebGLState( _gl, paramThreeToGL ); + }, - if ( _gl.getShaderPrecisionFormat === undefined ) { + setRGB: function ( r, g, b ) { - _gl.getShaderPrecisionFormat = function () { + this.r = r; + this.g = g; + this.b = b; - return { - 'rangeMin': 1, - 'rangeMax': 1, - 'precision': 1 - }; + return this; - } + }, - } + setHSL: function ( h, s, l ) { - var extensions = new THREE.WebGLExtensions( _gl ); + // h,s,l ranges are in 0.0 - 1.0 - extensions.get( 'OES_texture_float' ); - extensions.get( 'OES_texture_float_linear' ); - extensions.get( 'OES_texture_half_float' ); - extensions.get( 'OES_texture_half_float_linear' ); - extensions.get( 'OES_standard_derivatives' ); + if ( s === 0 ) { - if ( _logarithmicDepthBuffer ) { + this.r = this.g = this.b = l; - extensions.get( 'EXT_frag_depth' ); + } else { - } + var hue2rgb = function ( p, q, t ) { - // + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; - var glClearColor = function ( r, g, b, a ) { + }; - if ( _premultipliedAlpha === true ) { + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - r *= a; g *= a; b *= a; + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); } - _gl.clearColor( r, g, b, a ); + return this; - }; + }, - var setDefaultGLState = function () { + setStyle: function ( style ) { - _gl.clearColor( 0, 0, 0, 1 ); - _gl.clearDepth( 1 ); - _gl.clearStencil( 0 ); + // rgb(255,0,0) - _gl.enable( _gl.DEPTH_TEST ); - _gl.depthFunc( _gl.LEQUAL ); + if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) { - _gl.frontFace( _gl.CCW ); - _gl.cullFace( _gl.BACK ); - _gl.enable( _gl.CULL_FACE ); + var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style ); - _gl.enable( _gl.BLEND ); - _gl.blendEquation( _gl.FUNC_ADD ); - _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); + return this; - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + } - }; + // rgb(100%,0%,0%) - var resetGLState = function () { + if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) { - _currentProgram = null; - _currentCamera = null; + var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style ); - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; + this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; + this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - _lightsNeedUpdate = true; + return this; - state.reset(); + } - }; + // #ff0000 - setDefaultGLState(); + if ( /^\#([0-9a-f]{6})$/i.test( style ) ) { - this.context = _gl; - this.state = state; + var color = /^\#([0-9a-f]{6})$/i.exec( style ); - // GPU capabilities + this.setHex( parseInt( color[ 1 ], 16 ) ); - var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); - var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); - var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + return this; - var _supportsVertexTextures = _maxVertexTextures > 0; - var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' ); + } - // + // #f00 - var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); - var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); + if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) { - var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); - var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); + var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style ); - var getCompressedTextureFormats = ( function () { + this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) ); - var array; + return this; - return function () { + } - if ( array !== undefined ) { + // red - return array; + if ( /^(\w+)$/i.test( style ) ) { - } + this.setHex( THREE.ColorKeywords[ style ] ); - array = []; + return this; - if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) { + } - var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ); - for ( var i = 0; i < formats.length; i ++ ) { + }, - array.push( formats[ i ] ); + copy: function ( color ) { - } + this.r = color.r; + this.g = color.g; + this.b = color.b; - } + return this; - return array; + }, - }; + copyGammaToLinear: function ( color, gammaFactor ) { - } )(); + if ( gammaFactor === undefined ) gammaFactor = 2.0; - // clamp precision to maximum available + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; - var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; + return this; - if ( _precision === 'highp' && ! highpAvailable ) { + }, - if ( mediumpAvailable ) { + copyLinearToGamma: function ( color, gammaFactor ) { - _precision = 'mediump'; - THREE.warn( 'THREE.Canvas3DRenderer: highp not supported, using mediump.' ); + if ( gammaFactor === undefined ) gammaFactor = 2.0; - } else { + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - _precision = 'lowp'; - THREE.warn( 'THREE.Canvas3DRenderer: highp and mediump not supported, using lowp.' ); + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - } + return this; - } + }, - if ( _precision === 'mediump' && ! mediumpAvailable ) { + convertGammaToLinear: function () { - _precision = 'lowp'; - THREE.warn( 'THREE.Canvas3DRenderer: mediump not supported, using lowp.' ); + var r = this.r, g = this.g, b = this.b; - } + this.r = r * r; + this.g = g * g; + this.b = b * b; - // Plugins + return this; - var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate ); + }, - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + convertLinearToGamma: function () { - // API + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - this.getContext = function () { + return this; - return _gl; + }, - }; + getHex: function () { - this.forceContextLoss = function () { + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - //extensions.get( 'WEBGL_lose_context' ).loseContext(); + }, - }; + getHexString: function () { - this.supportsVertexTextures = function () { + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - return _supportsVertexTextures; + }, - }; + getHSL: function ( optionalTarget ) { - this.supportsFloatTextures = function () { + // h,s,l ranges are in 0.0 - 1.0 - return extensions.get( 'OES_texture_float' ); + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - }; + var r = this.r, g = this.g, b = this.b; - this.supportsHalfFloatTextures = function () { + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - return extensions.get( 'OES_texture_half_float' ); + var hue, saturation; + var lightness = ( min + max ) / 2.0; - }; + if ( min === max ) { - this.supportsStandardDerivatives = function () { + hue = 0; + saturation = 0; - return extensions.get( 'OES_standard_derivatives' ); + } else { - }; + var delta = max - min; - this.supportsCompressedTextureS3TC = function () { + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - return extensions.get( 'WEBGL_compressed_texture_s3tc' ); + switch ( max ) { - }; + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; - this.supportsCompressedTexturePVRTC = function () { + } - return extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + hue /= 6; - }; + } - this.supportsBlendMinMax = function () { + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - return extensions.get( 'EXT_blend_minmax' ); + return hsl; - }; + }, - this.getMaxAnisotropy = ( function () { + getStyle: function () { - var value; + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - return function () { + }, - if ( value !== undefined ) { + offsetHSL: function ( h, s, l ) { - return value; + var hsl = this.getHSL(); - } + hsl.h += h; hsl.s += s; hsl.l += l; - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + this.setHSL( hsl.h, hsl.s, hsl.l ); - value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; + return this; - return value; + }, - } + add: function ( color ) { - } )(); + this.r += color.r; + this.g += color.g; + this.b += color.b; - this.getPrecision = function () { + return this; - return _precision; + }, - }; + addColors: function ( color1, color2 ) { - this.getPixelRatio = function () { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - return pixelRatio; + return this; - }; + }, - this.setPixelRatio = function ( value ) { + addScalar: function ( s ) { - pixelRatio = value; + this.r += s; + this.g += s; + this.b += s; - }; + return this; - this.setSize = function ( width, height, updateStyle ) { + }, - _canvas.pixelSize = Qt.size(width * pixelRatio, height * pixelRatio) + multiply: function ( color ) { - if ( updateStyle !== false ) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; -// Update styles is ignored in Canvas3D -// _canvas.style.width = width + 'px'; -// _canvas.style.height = height + 'px'; + return this; - } + }, - this.setViewport( 0, 0, width, height ); + multiplyScalar: function ( s ) { - }; + this.r *= s; + this.g *= s; + this.b *= s; - this.setViewport = function ( x, y, width, height ) { + return this; - _viewportX = x * pixelRatio; - _viewportY = y * pixelRatio; + }, - _viewportWidth = width * pixelRatio; - _viewportHeight = height * pixelRatio; + lerp: function ( color, alpha ) { - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - }; + return this; - this.setScissor = function ( x, y, width, height ) { + }, - _gl.scissor( - x * pixelRatio, - y * pixelRatio, - width * pixelRatio, - height * pixelRatio - ); + equals: function ( c ) { - }; + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - this.enableScissorTest = function ( enable ) { + }, - if (enable) - _gl.enable( _gl.SCISSOR_TEST ) - else - _gl.disable( _gl.SCISSOR_TEST ); + fromArray: function ( array ) { - }; + this.r = array[ 0 ]; + this.g = array[ 1 ]; + this.b = array[ 2 ]; - // Clearing + return this; - this.getClearColor = function () { + }, - return _clearColor; + toArray: function ( array, offset ) { - }; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.setClearColor = function ( color, alpha ) { + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - _clearColor.set( color ); + return array; + }, - _clearAlpha = alpha !== undefined ? alpha : 1; + clone: function () { - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + return new THREE.Color().setRGB( this.r, this.g, this.b ); - }; + } - this.getClearAlpha = function () { +}; - return _clearAlpha; +THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, +'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, +'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, +'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, +'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, +'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, +'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, +'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, +'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, +'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, +'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, +'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, +'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, +'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, +'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, +'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, +'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, +'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, +'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, +'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, +'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, +'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, +'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, +'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - }; +// File:src/math/Quaternion.js - this.setClearAlpha = function ( alpha ) { +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://exocortex.com + */ - _clearAlpha = alpha; +THREE.Quaternion = function ( x, y, z, w ) { - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - }; + this.__defineGetter__("x", function(){ + return this._x; + }); + this.__defineSetter__("x", function(value){ + this._x = value; + this.onChangeCallback(); + }); + this.__defineGetter__("y", function(){ + return this._y; + }); + this.__defineSetter__("y", function(value){ + this._y = value; + this.onChangeCallback(); + }); + this.__defineGetter__("z", function(){ + return this._z; + }); + this.__defineSetter__("z", function(value){ + this._z = value; + this.onChangeCallback(); + }); + this.__defineGetter__("w", function(){ + return this._w; + }); + this.__defineSetter__("w", function(value){ + this._w = value; + this.onChangeCallback(); + }); +}; - this.clear = function ( color, depth, stencil ) { +THREE.Quaternion.prototype = { - var bits = 0; + constructor: THREE.Quaternion, - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + _x: 0,_y: 0, _z: 0, _w: 0, - _gl.clear( bits ); + set: function ( x, y, z, w ) { - }; + this._x = x; + this._y = y; + this._z = z; + this._w = w; - this.clearColor = function () { + this.onChangeCallback(); - _gl.clear( _gl.COLOR_BUFFER_BIT ); + return this; - }; + }, - this.clearDepth = function () { + copy: function ( quaternion ) { - _gl.clear( _gl.DEPTH_BUFFER_BIT ); + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - }; + this.onChangeCallback(); - this.clearStencil = function () { + return this; - _gl.clear( _gl.STENCIL_BUFFER_BIT ); + }, - }; + setFromEuler: function ( euler, update ) { - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + if ( euler instanceof THREE.Euler === false ) { - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } - }; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - // Reset + var c1 = Math.cos( euler._x / 2 ); + var c2 = Math.cos( euler._y / 2 ); + var c3 = Math.cos( euler._z / 2 ); + var s1 = Math.sin( euler._x / 2 ); + var s2 = Math.sin( euler._y / 2 ); + var s3 = Math.sin( euler._z / 2 ); - this.resetGLState = resetGLState; + if ( euler.order === 'XYZ' ) { - // Buffer allocation + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - function createParticleBuffers ( geometry ) { + } else if ( euler.order === 'YXZ' ) { - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglVertexBuffer.name = "Particle__webglVertexBuffer"; - geometry.__webglColorBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer.name = "Particle__webglColorBuffer"; + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - _this.info.memory.geometries ++; + } else if ( euler.order === 'ZXY' ) { - }; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - function createLineBuffers ( geometry ) { + } else if ( euler.order === 'ZYX' ) { - geometry.__webglVertexBuffer = _gl.createBuffer(); - geometry.__webglColorBuffer = _gl.createBuffer(); - geometry.__webglLineDistanceBuffer = _gl.createBuffer(); - geometry.__webglVertexBuffer.name = "Line__webglVertexBuffer"; - geometry.__webglColorBuffer.name = "Line__webglColorBuffer"; - geometry.__webglLineDistanceBuffer.name = "Line__webglLineDistanceBuffer"; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - _this.info.memory.geometries ++; + } else if ( euler.order === 'YZX' ) { - }; + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - function createMeshBuffers ( geometryGroup ) { + } else if ( euler.order === 'XZY' ) { - geometryGroup.__webglVertexBuffer = _gl.createBuffer(); - geometryGroup.__webglNormalBuffer = _gl.createBuffer(); - geometryGroup.__webglTangentBuffer = _gl.createBuffer(); - geometryGroup.__webglColorBuffer = _gl.createBuffer(); - geometryGroup.__webglUVBuffer = _gl.createBuffer(); - geometryGroup.__webglUV2Buffer = _gl.createBuffer(); - geometryGroup.__webglVertexBuffer.name = "Mesh__webglVertexBuffer"; - geometryGroup.__webglNormalBuffer.name = "Mesh__webglNormalBuffer"; - geometryGroup.__webglTangentBuffer.name = "Mesh__webglTangentBuffer"; - geometryGroup.__webglColorBuffer.name = "Mesh__webglColorBuffer"; - geometryGroup.__webglUVBuffer.name = "Mesh__webglUVBuffer"; - geometryGroup.__webglUV2Buffer.name = "Mesh__webglUV2Buffer"; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); - geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); - geometryGroup.__webglSkinIndicesBuffer.name = "Mesh__webglSkinIndicesBuffer"; - geometryGroup.__webglSkinWeightsBuffer.name = "Mesh__webglSkinWeightsBuffer"; + } - geometryGroup.__webglFaceBuffer = _gl.createBuffer(); - geometryGroup.__webglLineBuffer = _gl.createBuffer(); - geometryGroup.__webglFaceBuffer.name = "Mesh__webglFaceBuffer"; - geometryGroup.__webglLineBuffer.name = "Mesh__webglLineBuffer"; - - var m, ml; - var numMorphTargets = geometryGroup.numMorphTargets; + if ( update !== false ) this.onChangeCallback(); - if ( numMorphTargets ) { + return this; - geometryGroup.__webglMorphTargetsBuffers = []; + }, - for ( m = 0, ml = numMorphTargets; m < ml; m ++ ) { - var buf = _gl.createBuffer(); - buf.name = "Mesh__MorphTarget_"+m; - geometryGroup.__webglMorphTargetsBuffers.push(buf); + setFromAxisAngle: function ( axis, angle ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - } + // assumes axis is normalized - var numMorphNormals = geometryGroup.numMorphNormals; + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - if ( numMorphNormals ) { + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - geometryGroup.__webglMorphNormalsBuffers = []; + this.onChangeCallback(); - for ( m = 0, ml = numMorphNormals; m < ml; m ++ ) { - var nbuf = _gl.createBuffer(); - nbuf.name = "Mesh__MorphNormal_"+m; - geometryGroup.__webglMorphNormalsBuffers.push( nbuf ); + return this; - } + }, - } + setFromRotationMatrix: function ( m ) { - _this.info.memory.geometries ++; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - }; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - // Events + var te = m.elements, - var onObjectRemoved = function ( event ) { + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - var object = event.target; + trace = m11 + m22 + m33, + s; - object.traverse( function ( child ) { + if ( trace > 0 ) { - child.removeEventListener( 'remove', onObjectRemoved ); + s = 0.5 / Math.sqrt( trace + 1.0 ); - removeObject( child ); + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - } ); + } else if ( m11 > m22 && m11 > m33 ) { - }; + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - var onGeometryDispose = function ( event ) { + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - var geometry = event.target; + } else if ( m22 > m33 ) { - geometry.removeEventListener( 'dispose', onGeometryDispose ); + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - deallocateGeometry( geometry ); + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - }; + } else { - var onTextureDispose = function ( event ) { + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - var texture = event.target; + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - texture.removeEventListener( 'dispose', onTextureDispose ); + } - deallocateTexture( texture ); + this.onChangeCallback(); - _this.info.memory.textures --; + return this; + }, - }; + setFromUnitVectors: function () { - var onRenderTargetDispose = function ( event ) { + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - var renderTarget = event.target; + // assumes direction vectors vFrom and vTo are normalized - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + var v1, r; - deallocateRenderTarget( renderTarget ); + var EPS = 0.000001; - _this.info.memory.textures --; + return function ( vFrom, vTo ) { - }; + if ( v1 === undefined ) v1 = new THREE.Vector3(); - var onMaterialDispose = function ( event ) { + r = vFrom.dot( vTo ) + 1; - var material = event.target; + if ( r < EPS ) { - material.removeEventListener( 'dispose', onMaterialDispose ); + r = 0; - deallocateMaterial( material ); + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - }; + v1.set( - vFrom.y, vFrom.x, 0 ); - // Buffer deallocation + } else { - var deleteBuffers = function ( geometry ) { + v1.set( 0, - vFrom.z, vFrom.y ); - var buffers = [ - '__webglVertexBuffer', - '__webglNormalBuffer', - '__webglTangentBuffer', - '__webglColorBuffer', - '__webglUVBuffer', - '__webglUV2Buffer', + } - '__webglSkinIndicesBuffer', - '__webglSkinWeightsBuffer', + } else { - '__webglFaceBuffer', - '__webglLineBuffer', + v1.crossVectors( vFrom, vTo ); - '__webglLineDistanceBuffer' - ]; + } - for ( var i = 0, l = buffers.length; i < l; i ++ ) { + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - var name = buffers[ i ]; + this.normalize(); - if ( geometry[ name ] !== undefined ) { + return this; - _gl.deleteBuffer( geometry[ name ] ); + } - delete geometry[ name ]; + }(), - } + inverse: function () { - } + this.conjugate().normalize(); - // custom attributes + return this; - if ( geometry.__webglCustomAttributesList !== undefined ) { + }, - for ( var name in geometry.__webglCustomAttributesList ) { + conjugate: function () { - _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer ); + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - } + this.onChangeCallback(); - delete geometry.__webglCustomAttributesList; + return this; - } + }, - _this.info.memory.geometries --; + dot: function ( v ) { - }; + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - var deallocateGeometry = function ( geometry ) { + }, - delete geometry.__webglInit; + lengthSq: function () { - if ( geometry instanceof THREE.BufferGeometry ) { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - for ( var name in geometry.attributes ) { + }, - var attribute = geometry.attributes[ name ]; + length: function () { - if ( attribute.buffer !== undefined ) { + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - _gl.deleteBuffer( attribute.buffer ); + }, - delete attribute.buffer; + normalize: function () { - } + var l = this.length(); - } + if ( l === 0 ) { - _this.info.memory.geometries --; + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; } else { - var geometryGroupsList = geometryGroups[ geometry.id ]; - - if ( geometryGroupsList !== undefined ) { + l = 1 / l; - for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) { + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - var geometryGroup = geometryGroupsList[ i ]; + } - if ( geometryGroup.numMorphTargets !== undefined ) { + this.onChangeCallback(); - for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { + return this; - _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); + }, - } + multiply: function ( q, p ) { - delete geometryGroup.__webglMorphTargetsBuffers; + if ( p !== undefined ) { - } + THREE.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - if ( geometryGroup.numMorphNormals !== undefined ) { + } - for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { + return this.multiplyQuaternions( this, q ); - _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); + }, - } + multiplyQuaternions: function ( a, b ) { - delete geometryGroup.__webglMorphNormalsBuffers; + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - } + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - deleteBuffers( geometryGroup ); + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - } + this.onChangeCallback(); - delete geometryGroups[ geometry.id ]; + return this; - } else { + }, - deleteBuffers( geometry ); + multiplyVector3: function ( vector ) { - } + THREE.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + return vector.applyQuaternion( this ); - } + }, - // TOFIX: Workaround for deleted geometry being currently bound + slerp: function ( qb, t ) { - _currentGeometryProgram = ''; + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - }; + var x = this._x, y = this._y, z = this._z, w = this._w; - var deallocateTexture = function ( texture ) { + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - if ( texture.image && texture.image.__webglTextureCube ) { + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - // cube texture + if ( cosHalfTheta < 0 ) { - _gl.deleteTexture( texture.image.__webglTextureCube ); + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - delete texture.image.__webglTextureCube; + cosHalfTheta = - cosHalfTheta; } else { - // 2D texture + this.copy( qb ); - if ( texture.__webglInit === undefined ) return; + } - _gl.deleteTexture( texture.__webglTexture ); + if ( cosHalfTheta >= 1.0 ) { - delete texture.__webglTexture; - delete texture.__webglInit; + this._w = w; + this._x = x; + this._y = y; + this._z = z; + + return this; } - }; + var halfTheta = Math.acos( cosHalfTheta ); + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - var deallocateRenderTarget = function ( renderTarget ) { + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return; + this._w = 0.5 * ( w + this._w ); + this._x = 0.5 * ( x + this._x ); + this._y = 0.5 * ( y + this._y ); + this._z = 0.5 * ( z + this._z ); - _gl.deleteTexture( renderTarget.__webglTexture ); + return this; - delete renderTarget.__webglTexture; + } - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - for ( var i = 0; i < 6; i ++ ) { + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); + this.onChangeCallback(); - } + return this; - } else { + }, - _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); - _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); + equals: function ( quaternion ) { - } + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - delete renderTarget.__webglFramebuffer; - delete renderTarget.__webglRenderbuffer; + }, - }; + fromArray: function ( array, offset ) { - var deallocateMaterial = function ( material ) { + if ( offset === undefined ) offset = 0; - var program = material.program.program; + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - if ( program === undefined ) return; + this.onChangeCallback(); - material.program = undefined; + return this; - // only deallocate GL program if this was the last use of shared program - // assumed there is only single copy of any program in the _programs list - // (that's how it's constructed) + }, - var i, il, programInfo; - var deleteProgram = false; + toArray: function ( array, offset ) { - for ( i = 0, il = _programs.length; i < il; i ++ ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - programInfo = _programs[ i ]; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - if ( programInfo.program === program ) { + return array; - programInfo.usedTimes --; + }, - if ( programInfo.usedTimes === 0 ) { + onChange: function ( callback ) { - deleteProgram = true; + this.onChangeCallback = callback; - } + return this; - break; + }, - } + onChangeCallback: function () {}, - } + clone: function () { - if ( deleteProgram === true ) { + return new THREE.Quaternion( this._x, this._y, this._z, this._w ); - // avoid using array.splice, this is costlier than creating new array from scratch + } - var newPrograms = []; +}; - for ( i = 0, il = _programs.length; i < il; i ++ ) { +THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { - programInfo = _programs[ i ]; + return qm.copy( qa ).slerp( qb, t ); - if ( programInfo.program !== program ) { +} - newPrograms.push( programInfo ); +// File:src/math/Vector2.js - } +/** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - } +THREE.Vector2 = function ( x, y ) { - _programs = newPrograms; + this.x = x || 0; + this.y = y || 0; - _gl.deleteProgram( program ); +}; - _this.info.memory.programs --; +THREE.Vector2.prototype = { - } + constructor: THREE.Vector2, - }; + set: function ( x, y ) { - // Buffer initialization + this.x = x; + this.y = y; - function initCustomAttributes ( object ) { + return this; - var geometry = object.geometry; - var material = object.material; + }, - var nvertices = geometry.vertices.length; + setX: function ( x ) { - if ( material.attributes ) { + this.x = x; - if ( geometry.__webglCustomAttributesList === undefined ) { + return this; - geometry.__webglCustomAttributesList = []; + }, - } + setY: function ( y ) { - for ( var name in material.attributes ) { + this.y = y; - var attribute = material.attributes[ name ]; + return this; - if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { + }, - attribute.__webglInitialized = true; + setComponent: function ( index, value ) { - var size = 1; // "f" and "i" + switch ( index ) { - if ( attribute.type === 'v2' ) size = 2; - else if ( attribute.type === 'v3' ) size = 3; - else if ( attribute.type === 'v4' ) size = 4; - else if ( attribute.type === 'c' ) size = 3; + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - attribute.size = size; + } - attribute.array = new Float32Array( nvertices * size ); - attribute.array.name = ""+attribute+"attribute.array"; + }, - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = name; + getComponent: function ( index ) { - attribute.needsUpdate = true; + switch ( index ) { - } + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - geometry.__webglCustomAttributesList.push( attribute ); + } - } + }, - } + copy: function ( v ) { - }; + this.x = v.x; + this.y = v.y; - function initParticleBuffers ( geometry, object ) { + return this; - var nvertices = geometry.vertices.length; + }, - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); - geometry.__vertexArray.name = "geometry.__vertexArray"; - geometry.__colorArray.name = "geometry.__colorArray"; + add: function ( v, w ) { - geometry.__webglParticleCount = nvertices; + if ( w !== undefined ) { - initCustomAttributes( object ); + THREE.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - }; + } - function initLineBuffers ( geometry, object ) { + this.x += v.x; + this.y += v.y; - var nvertices = geometry.vertices.length; + return this; - geometry.__vertexArray = new Float32Array( nvertices * 3 ); - geometry.__colorArray = new Float32Array( nvertices * 3 ); - geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); - geometry.__vertexArray.name = "geometry.__vertexArray"; - geometry.__colorArray.name = "geometry.__colorArray"; - geometry.__lineDistanceArray.name = "geometry.__lineDistanceArray"; + }, - geometry.__webglLineCount = nvertices; + addScalar: function ( s ) { - initCustomAttributes( object ); + this.x += s; + this.y += s; - }; + return this; - function initMeshBuffers ( geometryGroup, object ) { + }, - var geometry = object.geometry, - faces3 = geometryGroup.faces3, + addVectors: function ( a, b ) { - nvertices = faces3.length * 3, - ntris = faces3.length * 1, - nlines = faces3.length * 3, + this.x = a.x + b.x; + this.y = a.y + b.y; - material = getBufferMaterial( object, geometryGroup ); + return this; - geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); - geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); - geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); - geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); - geometryGroup.__vertexArray.name = "geometryGroup.__vertexArray"; - geometryGroup.__normalArray.name = "geometryGroup.__normalArray"; - geometryGroup.__colorArray.name = "geometryGroup.__colorArray"; - geometryGroup.__uvArray.name = "geometryGroup.__uvArray"; - - if ( geometry.faceVertexUvs.length > 1 ) { - - geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); - geometryGroup.__uv2Array.name = "geometryGroup.__uv2Array"; + }, - } + sub: function ( v, w ) { - if ( geometry.hasTangents ) { + if ( w !== undefined ) { - geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); - geometryGroup.__tangentArray.name = "geometryGroup.__tangentArray"; + THREE.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); } - if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { - - geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); - geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); - geometryGroup.__skinIndexArray.name = "geometryGroup.__skinIndexArray"; - geometryGroup.__skinWeightArray.name = "geometryGroup.__skinWeightArray"; - } + this.x -= v.x; + this.y -= v.y; - var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 + return this; - geometryGroup.__typeArray = UintArray; - geometryGroup.__faceArray = new UintArray( ntris * 3 ); - geometryGroup.__lineArray = new UintArray( nlines * 2 ); - geometryGroup.__faceArray.name = "geometryGroup.__faceArray"; - geometryGroup.__lineArray.name = "geometryGroup.__lineArray"; + }, - var m, ml; - var numMorphTargets = geometryGroup.numMorphTargets; + subScalar: function ( s ) { - if ( numMorphTargets ) { + this.x -= s; + this.y -= s; - geometryGroup.__morphTargetsArrays = []; + return this; - for ( m = 0, ml = numMorphTargets; m < ml; m ++ ) { - var mta = new Float32Array( nvertices * 3 ); - mta.name = "morphTargetArray_"+m; - geometryGroup.__morphTargetsArrays.push(mta); - } + }, - } + subVectors: function ( a, b ) { - var numMorphNormals = geometryGroup.numMorphNormals; + this.x = a.x - b.x; + this.y = a.y - b.y; - if ( numMorphNormals ) { + return this; - geometryGroup.__morphNormalsArrays = []; + }, - for ( m = 0, ml = numMorphNormals; m < ml; m ++ ) { - var mna = new Float32Array( nvertices * 3 ); - mna.name = "morphNormalsArray_"+m; - geometryGroup.__morphNormalsArrays.push( mna ); - } + multiply: function ( v ) { - } + this.x *= v.x; + this.y *= v.y; - geometryGroup.__webglFaceCount = ntris * 3; - geometryGroup.__webglLineCount = nlines * 2; + return this; + }, - // custom attributes + multiplyScalar: function ( s ) { - if ( material.attributes ) { + this.x *= s; + this.y *= s; - if ( geometryGroup.__webglCustomAttributesList === undefined ) { + return this; - geometryGroup.__webglCustomAttributesList = []; + }, - } + divide: function ( v ) { - for ( var name in material.attributes ) { + this.x /= v.x; + this.y /= v.y; - // Do a shallow copy of the attribute object so different geometryGroup chunks use different - // attribute buffers which are correctly indexed in the setMeshBuffers function + return this; - var originalAttribute = material.attributes[ name ]; + }, - var attribute = {}; + divideScalar: function ( scalar ) { - for ( var property in originalAttribute ) { + if ( scalar !== 0 ) { - attribute[ property ] = originalAttribute[ property ]; + var invScalar = 1 / scalar; - } + this.x *= invScalar; + this.y *= invScalar; - if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { + } else { - attribute.__webglInitialized = true; + this.x = 0; + this.y = 0; - var size = 1; // "f" and "i" + } - if ( attribute.type === 'v2' ) size = 2; - else if ( attribute.type === 'v3' ) size = 3; - else if ( attribute.type === 'v4' ) size = 4; - else if ( attribute.type === 'c' ) size = 3; + return this; - attribute.size = size; + }, - attribute.array = new Float32Array( nvertices * size ); + min: function ( v ) { - attribute.buffer = _gl.createBuffer(); - attribute.buffer.belongsToAttribute = name; + if ( this.x > v.x ) { - originalAttribute.needsUpdate = true; - attribute.__original = originalAttribute; + this.x = v.x; - } + } - geometryGroup.__webglCustomAttributesList.push( attribute ); + if ( this.y > v.y ) { - } + this.y = v.y; } - geometryGroup.__inittedArrays = true; - - }; + return this; - function getBufferMaterial( object, geometryGroup ) { + }, - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ geometryGroup.materialIndex ] - : object.material; + max: function ( v ) { - } + if ( this.x < v.x ) { - function materialNeedsFaceNormals ( material ) { + this.x = v.x; - return material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading; + } - } + if ( this.y < v.y ) { - // Buffer setting + this.y = v.y; - function setParticleBuffers ( geometry, hint, object ) { + } - var v, c, vertex, offset, color, + return this; - vertices = geometry.vertices, - vl = vertices.length, + }, - colors = geometry.colors, - cl = colors.length, + clamp: function ( min, max ) { - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, + // This function assumes min < max, if this assumption isn't true it will not operate correctly - dirtyVertices = geometry.verticesNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, + if ( this.x < min.x ) { - customAttributes = geometry.__webglCustomAttributesList, - i, il, - ca, cal, value, - customAttribute; + this.x = min.x; - if ( dirtyVertices ) { + } else if ( this.x > max.x ) { - for ( v = 0; v < vl; v ++ ) { + this.x = max.x; - vertex = vertices[ v ]; + } - offset = v * 3; + if ( this.y < min.y ) { - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; + this.y = min.y; - } + } else if ( this.y > max.y ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + this.y = max.y; } - if ( dirtyColors ) { - - for ( c = 0; c < cl; c ++ ) { + return this; + }, - color = colors[ c ]; + clampScalar: ( function () { - offset = c * 3; + var min, max; - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; + return function ( minVal, maxVal ) { - } + if ( min === undefined ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + min = new THREE.Vector2(); + max = new THREE.Vector2(); - } + } - if ( customAttributes ) { + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + return this.clamp( min, max ); - customAttribute = customAttributes[ i ]; + }; - if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) { + } )(), - cal = customAttribute.value.length; + floor: function () { - offset = 0; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - if ( customAttribute.size === 1 ) { + return this; - for ( ca = 0; ca < cal; ca ++ ) { + }, - customAttribute.array[ ca ] = customAttribute.value[ ca ]; + ceil: function () { - } + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - } else if ( customAttribute.size === 2 ) { + return this; - for ( ca = 0; ca < cal; ca ++ ) { + }, - value = customAttribute.value[ ca ]; + round: function () { - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - offset += 2; + return this; - } + }, - } else if ( customAttribute.size === 3 ) { + roundToZero: function () { - if ( customAttribute.type === 'c' ) { + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - for ( ca = 0; ca < cal; ca ++ ) { + return this; - value = customAttribute.value[ ca ]; + }, - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; + negate: function () { - offset += 3; + this.x = - this.x; + this.y = - this.y; - } + return this; - } else { + }, - for ( ca = 0; ca < cal; ca ++ ) { + dot: function ( v ) { - value = customAttribute.value[ ca ]; + return this.x * v.x + this.y * v.y; - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; + }, - offset += 3; + lengthSq: function () { - } + return this.x * this.x + this.y * this.y; - } + }, - } else if ( customAttribute.size === 4 ) { + length: function () { - for ( ca = 0; ca < cal; ca ++ ) { + return Math.sqrt( this.x * this.x + this.y * this.y ); - value = customAttribute.value[ ca ]; + }, - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; + normalize: function () { - offset += 4; + return this.divideScalar( this.length() ); - } + }, - } + distanceTo: function ( v ) { - } + return Math.sqrt( this.distanceToSquared( v ) ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + }, - customAttribute.needsUpdate = false; + distanceToSquared: function ( v ) { - } + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - } + }, - } + setLength: function ( l ) { - function setLineBuffers ( geometry, hint ) { + var oldLength = this.length(); - var v, c, d, vertex, offset, color, + if ( oldLength !== 0 && l !== oldLength ) { - vertices = geometry.vertices, - colors = geometry.colors, - lineDistances = geometry.lineDistances, + this.multiplyScalar( l / oldLength ); + } - vl = vertices.length, - cl = colors.length, - dl = lineDistances.length, + return this; - vertexArray = geometry.__vertexArray, - colorArray = geometry.__colorArray, - lineDistanceArray = geometry.__lineDistanceArray, + }, - dirtyVertices = geometry.verticesNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyLineDistances = geometry.lineDistancesNeedUpdate, + lerp: function ( v, alpha ) { - customAttributes = geometry.__webglCustomAttributesList, + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - i, il, - ca, cal, value, - customAttribute; + return this; - if ( dirtyVertices ) { + }, - for ( v = 0; v < vl; v ++ ) { + lerpVectors: function ( v1, v2, alpha ) { - vertex = vertices[ v ]; + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - offset = v * 3; + return this; - vertexArray[ offset ] = vertex.x; - vertexArray[ offset + 1 ] = vertex.y; - vertexArray[ offset + 2 ] = vertex.z; + }, - } + equals: function ( v ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - } + }, - if ( dirtyColors ) { + fromArray: function ( array, offset ) { - for ( c = 0; c < cl; c ++ ) { + if ( offset === undefined ) offset = 0; - color = colors[ c ]; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - offset = c * 3; + return this; - colorArray[ offset ] = color.r; - colorArray[ offset + 1 ] = color.g; - colorArray[ offset + 2 ] = color.b; + }, - } + toArray: function ( array, offset ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - if ( dirtyLineDistances ) { + return array; - for ( d = 0; d < dl; d ++ ) { + }, - lineDistanceArray[ d ] = lineDistances[ d ]; + fromAttribute: function ( attribute, index, offset ) { - } + if ( offset === undefined ) offset = 0; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); + index = index * attribute.itemSize + offset; - } + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - if ( customAttributes ) { + return this; - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + }, - customAttribute = customAttributes[ i ]; + clone: function () { - if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) { + return new THREE.Vector2( this.x, this.y ); - offset = 0; + } - cal = customAttribute.value.length; +}; - if ( customAttribute.size === 1 ) { +// File:src/math/Vector3.js - for ( ca = 0; ca < cal; ca ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author *kile / http://kile.stravaganza.org/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - customAttribute.array[ ca ] = customAttribute.value[ ca ]; +THREE.Vector3 = function ( x, y, z ) { - } + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - } else if ( customAttribute.size === 2 ) { +}; - for ( ca = 0; ca < cal; ca ++ ) { +THREE.Vector3.prototype = { - value = customAttribute.value[ ca ]; + constructor: THREE.Vector3, - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; + set: function ( x, y, z ) { - offset += 2; + this.x = x; + this.y = y; + this.z = z; - } + return this; - } else if ( customAttribute.size === 3 ) { + }, - if ( customAttribute.type === 'c' ) { + setX: function ( x ) { - for ( ca = 0; ca < cal; ca ++ ) { + this.x = x; - value = customAttribute.value[ ca ]; + return this; - customAttribute.array[ offset ] = value.r; - customAttribute.array[ offset + 1 ] = value.g; - customAttribute.array[ offset + 2 ] = value.b; + }, - offset += 3; + setY: function ( y ) { - } + this.y = y; - } else { + return this; - for ( ca = 0; ca < cal; ca ++ ) { + }, - value = customAttribute.value[ ca ]; + setZ: function ( z ) { - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; + this.z = z; - offset += 3; + return this; - } + }, - } + setComponent: function ( index, value ) { - } else if ( customAttribute.size === 4 ) { + switch ( index ) { - for ( ca = 0; ca < cal; ca ++ ) { + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'index is out of range: ' + index ); - value = customAttribute.value[ ca ]; + } - customAttribute.array[ offset ] = value.x; - customAttribute.array[ offset + 1 ] = value.y; - customAttribute.array[ offset + 2 ] = value.z; - customAttribute.array[ offset + 3 ] = value.w; + }, - offset += 4; + getComponent: function ( index ) { - } + switch ( index ) { - } + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + } - customAttribute.needsUpdate = false; + }, - } + copy: function ( v ) { - } + this.x = v.x; + this.y = v.y; + this.z = v.z; - } + return this; - } + }, - function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { + add: function ( v, w ) { - if ( ! geometryGroup.__inittedArrays ) { + if ( w !== undefined ) { - return; + THREE.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); } - var needsFaceNormals = materialNeedsFaceNormals( material ); + this.x += v.x; + this.y += v.y; + this.z += v.z; - var f, fl, fi, face, - vertexNormals, faceNormal, - vertexColors, faceColor, - vertexTangents, - uv, uv2, v1, v2, v3, t1, t2, t3, n1, n2, n3, - c1, c2, c3, - sw1, sw2, sw3, - si1, si2, si3, - i, il, - vn, uvi, uv2i, - vk, vkl, vka, - nka, chf, faceVertexNormals, + return this; - vertexIndex = 0, + }, - offset = 0, - offset_uv = 0, - offset_uv2 = 0, - offset_face = 0, - offset_normal = 0, - offset_tangent = 0, - offset_line = 0, - offset_color = 0, - offset_skin = 0, - offset_morphTarget = 0, - offset_custom = 0, + addScalar: function ( s ) { - value, + this.x += s; + this.y += s; + this.z += s; - vertexArray = geometryGroup.__vertexArray, - uvArray = geometryGroup.__uvArray, - uv2Array = geometryGroup.__uv2Array, - normalArray = geometryGroup.__normalArray, - tangentArray = geometryGroup.__tangentArray, - colorArray = geometryGroup.__colorArray, + return this; - skinIndexArray = geometryGroup.__skinIndexArray, - skinWeightArray = geometryGroup.__skinWeightArray, + }, - morphTargetsArrays = geometryGroup.__morphTargetsArrays, - morphNormalsArrays = geometryGroup.__morphNormalsArrays, + addVectors: function ( a, b ) { - customAttributes = geometryGroup.__webglCustomAttributesList, - customAttribute, + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - faceArray = geometryGroup.__faceArray, - lineArray = geometryGroup.__lineArray, + return this; - geometry = object.geometry, // this is shared for all chunks + }, - dirtyVertices = geometry.verticesNeedUpdate, - dirtyElements = geometry.elementsNeedUpdate, - dirtyUvs = geometry.uvsNeedUpdate, - dirtyNormals = geometry.normalsNeedUpdate, - dirtyTangents = geometry.tangentsNeedUpdate, - dirtyColors = geometry.colorsNeedUpdate, - dirtyMorphTargets = geometry.morphTargetsNeedUpdate, + sub: function ( v, w ) { - vertices = geometry.vertices, - chunk_faces3 = geometryGroup.faces3, - obj_faces = geometry.faces, + if ( w !== undefined ) { - obj_uvs = geometry.faceVertexUvs[ 0 ], - obj_uvs2 = geometry.faceVertexUvs[ 1 ], + THREE.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - obj_skinIndices = geometry.skinIndices, - obj_skinWeights = geometry.skinWeights, + } - morphTargets = geometry.morphTargets, - morphNormals = geometry.morphNormals; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - if ( dirtyVertices ) { + return this; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + }, + + subScalar: function ( s ) { - face = obj_faces[ chunk_faces3[ f ] ]; + this.x -= s; + this.y -= s; + this.z -= s; - v1 = vertices[ face.a ]; - v2 = vertices[ face.b ]; - v3 = vertices[ face.c ]; + return this; - vertexArray[ offset ] = v1.x; - vertexArray[ offset + 1 ] = v1.y; - vertexArray[ offset + 2 ] = v1.z; + }, - vertexArray[ offset + 3 ] = v2.x; - vertexArray[ offset + 4 ] = v2.y; - vertexArray[ offset + 5 ] = v2.z; + subVectors: function ( a, b ) { - vertexArray[ offset + 6 ] = v3.x; - vertexArray[ offset + 7 ] = v3.y; - vertexArray[ offset + 8 ] = v3.z; + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - offset += 9; + return this; - } + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); + multiply: function ( v, w ) { - } + if ( w !== undefined ) { - if ( dirtyMorphTargets ) { + THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { + } - offset_morphTarget = 0; + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + return this; - chf = chunk_faces3[ f ]; - face = obj_faces[ chf ]; + }, - // morph positions + multiplyScalar: function ( scalar ) { - v1 = morphTargets[ vk ].vertices[ face.a ]; - v2 = morphTargets[ vk ].vertices[ face.b ]; - v3 = morphTargets[ vk ].vertices[ face.c ]; + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - vka = morphTargetsArrays[ vk ]; + return this; - vka[ offset_morphTarget ] = v1.x; - vka[ offset_morphTarget + 1 ] = v1.y; - vka[ offset_morphTarget + 2 ] = v1.z; + }, - vka[ offset_morphTarget + 3 ] = v2.x; - vka[ offset_morphTarget + 4 ] = v2.y; - vka[ offset_morphTarget + 5 ] = v2.z; + multiplyVectors: function ( a, b ) { - vka[ offset_morphTarget + 6 ] = v3.x; - vka[ offset_morphTarget + 7 ] = v3.y; - vka[ offset_morphTarget + 8 ] = v3.z; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - // morph normals + return this; - if ( material.morphNormals ) { + }, - if ( needsFaceNormals ) { + applyEuler: function () { - n1 = morphNormals[ vk ].faceNormals[ chf ]; - n2 = n1; - n3 = n1; + var quaternion; - } else { + return function ( euler ) { - faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; + if ( euler instanceof THREE.Euler === false ) { - n1 = faceVertexNormals.a; - n2 = faceVertexNormals.b; - n3 = faceVertexNormals.c; + THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - } + } - nka = morphNormalsArrays[ vk ]; + if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); - nka[ offset_morphTarget ] = n1.x; - nka[ offset_morphTarget + 1 ] = n1.y; - nka[ offset_morphTarget + 2 ] = n1.z; + this.applyQuaternion( quaternion.setFromEuler( euler ) ); - nka[ offset_morphTarget + 3 ] = n2.x; - nka[ offset_morphTarget + 4 ] = n2.y; - nka[ offset_morphTarget + 5 ] = n2.z; + return this; - nka[ offset_morphTarget + 6 ] = n3.x; - nka[ offset_morphTarget + 7 ] = n3.y; - nka[ offset_morphTarget + 8 ] = n3.z; + }; - } + }(), - // + applyAxisAngle: function () { - offset_morphTarget += 9; + var quaternion; - } + return function ( axis, angle ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); + if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); - if ( material.morphNormals ) { + this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); - _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); + return this; - } + }; - } + }(), - } + applyMatrix3: function ( m ) { - if ( obj_skinWeights.length ) { + var x = this.x; + var y = this.y; + var z = this.z; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + var e = m.elements; - face = obj_faces[ chunk_faces3[ f ] ]; + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - // weights + return this; - sw1 = obj_skinWeights[ face.a ]; - sw2 = obj_skinWeights[ face.b ]; - sw3 = obj_skinWeights[ face.c ]; + }, - skinWeightArray[ offset_skin ] = sw1.x; - skinWeightArray[ offset_skin + 1 ] = sw1.y; - skinWeightArray[ offset_skin + 2 ] = sw1.z; - skinWeightArray[ offset_skin + 3 ] = sw1.w; + applyMatrix4: function ( m ) { - skinWeightArray[ offset_skin + 4 ] = sw2.x; - skinWeightArray[ offset_skin + 5 ] = sw2.y; - skinWeightArray[ offset_skin + 6 ] = sw2.z; - skinWeightArray[ offset_skin + 7 ] = sw2.w; + // input: THREE.Matrix4 affine matrix - skinWeightArray[ offset_skin + 8 ] = sw3.x; - skinWeightArray[ offset_skin + 9 ] = sw3.y; - skinWeightArray[ offset_skin + 10 ] = sw3.z; - skinWeightArray[ offset_skin + 11 ] = sw3.w; + var x = this.x, y = this.y, z = this.z; - // indices + var e = m.elements; - si1 = obj_skinIndices[ face.a ]; - si2 = obj_skinIndices[ face.b ]; - si3 = obj_skinIndices[ face.c ]; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; - skinIndexArray[ offset_skin ] = si1.x; - skinIndexArray[ offset_skin + 1 ] = si1.y; - skinIndexArray[ offset_skin + 2 ] = si1.z; - skinIndexArray[ offset_skin + 3 ] = si1.w; + return this; - skinIndexArray[ offset_skin + 4 ] = si2.x; - skinIndexArray[ offset_skin + 5 ] = si2.y; - skinIndexArray[ offset_skin + 6 ] = si2.z; - skinIndexArray[ offset_skin + 7 ] = si2.w; + }, - skinIndexArray[ offset_skin + 8 ] = si3.x; - skinIndexArray[ offset_skin + 9 ] = si3.y; - skinIndexArray[ offset_skin + 10 ] = si3.z; - skinIndexArray[ offset_skin + 11 ] = si3.w; + applyProjection: function ( m ) { - offset_skin += 12; + // input: THREE.Matrix4 projection matrix - } + var x = this.x, y = this.y, z = this.z; - if ( offset_skin > 0 ) { + var e = m.elements; + var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); + return this; - } + }, - } + applyQuaternion: function ( q ) { - if ( dirtyColors ) { + var x = this.x; + var y = this.y; + var z = this.z; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + var qx = q.x; + var qy = q.y; + var qz = q.z; + var qw = q.w; - face = obj_faces[ chunk_faces3[ f ] ]; + // calculate quat * vector - vertexColors = face.vertexColors; - faceColor = face.color; + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = - qx * x - qy * y - qz * z; - if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) { + // calculate result * inverse quat - c1 = vertexColors[ 0 ]; - c2 = vertexColors[ 1 ]; - c3 = vertexColors[ 2 ]; + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - } else { + return this; - c1 = faceColor; - c2 = faceColor; - c3 = faceColor; + }, - } + project: function () { - colorArray[ offset_color ] = c1.r; - colorArray[ offset_color + 1 ] = c1.g; - colorArray[ offset_color + 2 ] = c1.b; + var matrix; - colorArray[ offset_color + 3 ] = c2.r; - colorArray[ offset_color + 4 ] = c2.g; - colorArray[ offset_color + 5 ] = c2.b; + return function ( camera ) { - colorArray[ offset_color + 6 ] = c3.r; - colorArray[ offset_color + 7 ] = c3.g; - colorArray[ offset_color + 8 ] = c3.b; + if ( matrix === undefined ) matrix = new THREE.Matrix4(); - offset_color += 9; + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - } + }; - if ( offset_color > 0 ) { + }(), - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); + unproject: function () { - } + var matrix; - } + return function ( camera ) { - if ( dirtyTangents && geometry.hasTangents ) { + if ( matrix === undefined ) matrix = new THREE.Matrix4(); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - face = obj_faces[ chunk_faces3[ f ] ]; + }; - vertexTangents = face.vertexTangents; + }(), - t1 = vertexTangents[ 0 ]; - t2 = vertexTangents[ 1 ]; - t3 = vertexTangents[ 2 ]; + transformDirection: function ( m ) { - tangentArray[ offset_tangent ] = t1.x; - tangentArray[ offset_tangent + 1 ] = t1.y; - tangentArray[ offset_tangent + 2 ] = t1.z; - tangentArray[ offset_tangent + 3 ] = t1.w; + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - tangentArray[ offset_tangent + 4 ] = t2.x; - tangentArray[ offset_tangent + 5 ] = t2.y; - tangentArray[ offset_tangent + 6 ] = t2.z; - tangentArray[ offset_tangent + 7 ] = t2.w; + var x = this.x, y = this.y, z = this.z; - tangentArray[ offset_tangent + 8 ] = t3.x; - tangentArray[ offset_tangent + 9 ] = t3.y; - tangentArray[ offset_tangent + 10 ] = t3.z; - tangentArray[ offset_tangent + 11 ] = t3.w; + var e = m.elements; - offset_tangent += 12; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - } + this.normalize(); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); + return this; - } + }, - if ( dirtyNormals ) { + divide: function ( v ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - face = obj_faces[ chunk_faces3[ f ] ]; + return this; - vertexNormals = face.vertexNormals; - faceNormal = face.normal; + }, - if ( vertexNormals.length === 3 && needsFaceNormals === false ) { + divideScalar: function ( scalar ) { - for ( i = 0; i < 3; i ++ ) { + if ( scalar !== 0 ) { - vn = vertexNormals[ i ]; + var invScalar = 1 / scalar; - normalArray[ offset_normal ] = vn.x; - normalArray[ offset_normal + 1 ] = vn.y; - normalArray[ offset_normal + 2 ] = vn.z; + this.x *= invScalar; + this.y *= invScalar; + this.z *= invScalar; - offset_normal += 3; + } else { - } + this.x = 0; + this.y = 0; + this.z = 0; - } else { + } - for ( i = 0; i < 3; i ++ ) { + return this; - normalArray[ offset_normal ] = faceNormal.x; - normalArray[ offset_normal + 1 ] = faceNormal.y; - normalArray[ offset_normal + 2 ] = faceNormal.z; + }, - offset_normal += 3; + min: function ( v ) { - } + if ( this.x > v.x ) { - } + this.x = v.x; - } + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); + if ( this.y > v.y ) { + + this.y = v.y; } - if ( dirtyUvs && obj_uvs ) { + if ( this.z > v.z ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + this.z = v.z; - fi = chunk_faces3[ f ]; + } - uv = obj_uvs[ fi ]; + return this; - if ( uv === undefined ) continue; + }, - for ( i = 0; i < 3; i ++ ) { + max: function ( v ) { - uvi = uv[ i ]; + if ( this.x < v.x ) { - uvArray[ offset_uv ] = uvi.x; - uvArray[ offset_uv + 1 ] = uvi.y; + this.x = v.x; - offset_uv += 2; + } - } + if ( this.y < v.y ) { - } + this.y = v.y; - if ( offset_uv > 0 ) { + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); + if ( this.z < v.z ) { - } + this.z = v.z; } - if ( dirtyUvs && obj_uvs2 ) { - - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + return this; - fi = chunk_faces3[ f ]; + }, - uv2 = obj_uvs2[ fi ]; + clamp: function ( min, max ) { - if ( uv2 === undefined ) continue; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - for ( i = 0; i < 3; i ++ ) { + if ( this.x < min.x ) { - uv2i = uv2[ i ]; + this.x = min.x; - uv2Array[ offset_uv2 ] = uv2i.x; - uv2Array[ offset_uv2 + 1 ] = uv2i.y; + } else if ( this.x > max.x ) { - offset_uv2 += 2; + this.x = max.x; - } + } - } + if ( this.y < min.y ) { - if ( offset_uv2 > 0 ) { + this.y = min.y; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); + } else if ( this.y > max.y ) { - } + this.y = max.y; } - if ( dirtyElements ) { + if ( this.z < min.z ) { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + this.z = min.z; - faceArray[ offset_face ] = vertexIndex; - faceArray[ offset_face + 1 ] = vertexIndex + 1; - faceArray[ offset_face + 2 ] = vertexIndex + 2; + } else if ( this.z > max.z ) { - offset_face += 3; + this.z = max.z; - lineArray[ offset_line ] = vertexIndex; - lineArray[ offset_line + 1 ] = vertexIndex + 1; + } - lineArray[ offset_line + 2 ] = vertexIndex; - lineArray[ offset_line + 3 ] = vertexIndex + 2; + return this; - lineArray[ offset_line + 4 ] = vertexIndex + 1; - lineArray[ offset_line + 5 ] = vertexIndex + 2; + }, - offset_line += 6; + clampScalar: ( function () { - vertexIndex += 3; + var min, max; - } + return function ( minVal, maxVal ) { - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); + if ( min === undefined ) { - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); + min = new THREE.Vector3(); + max = new THREE.Vector3(); - } + } - if ( customAttributes ) { + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - for ( i = 0, il = customAttributes.length; i < il; i ++ ) { + return this.clamp( min, max ); - customAttribute = customAttributes[ i ]; + }; - if ( ! customAttribute.__original.needsUpdate ) continue; + } )(), - offset_custom = 0; + floor: function () { - if ( customAttribute.size === 1 ) { + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { + return this; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + }, - face = obj_faces[ chunk_faces3[ f ] ]; + ceil: function () { - customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; - customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; - customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - offset_custom += 3; + return this; - } + }, - } else if ( customAttribute.boundTo === 'faces' ) { + round: function () { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - value = customAttribute.value[ chunk_faces3[ f ] ]; + return this; - customAttribute.array[ offset_custom ] = value; - customAttribute.array[ offset_custom + 1 ] = value; - customAttribute.array[ offset_custom + 2 ] = value; + }, - offset_custom += 3; + roundToZero: function () { - } + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - } + return this; - } else if ( customAttribute.size === 2 ) { + }, - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { + negate: function () { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - face = obj_faces[ chunk_faces3[ f ] ]; + return this; - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; + }, - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; + dot: function ( v ) { - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; + return this.x * v.x + this.y * v.y + this.z * v.z; - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; + }, - offset_custom += 6; + lengthSq: function () { - } + return this.x * this.x + this.y * this.y + this.z * this.z; - } else if ( customAttribute.boundTo === 'faces' ) { + }, - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + length: function () { - value = customAttribute.value[ chunk_faces3[ f ] ]; + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - v1 = value; - v2 = value; - v3 = value; + }, - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; + lengthManhattan: function () { - customAttribute.array[ offset_custom + 2 ] = v2.x; - customAttribute.array[ offset_custom + 3 ] = v2.y; + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - customAttribute.array[ offset_custom + 4 ] = v3.x; - customAttribute.array[ offset_custom + 5 ] = v3.y; + }, - offset_custom += 6; + normalize: function () { - } + return this.divideScalar( this.length() ); - } + }, - } else if ( customAttribute.size === 3 ) { + setLength: function ( l ) { - var pp; + var oldLength = this.length(); - if ( customAttribute.type === 'c' ) { + if ( oldLength !== 0 && l !== oldLength ) { - pp = [ 'r', 'g', 'b' ]; + this.multiplyScalar( l / oldLength ); + } - } else { + return this; - pp = [ 'x', 'y', 'z' ]; + }, - } + lerp: function ( v, alpha ) { - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + return this; - face = obj_faces[ chunk_faces3[ f ] ]; + }, - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; + lerpVectors: function ( v1, v2, alpha ) { - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; + return this; - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; + }, - offset_custom += 9; + cross: function ( v, w ) { - } + if ( w !== undefined ) { - } else if ( customAttribute.boundTo === 'faces' ) { + THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + } - value = customAttribute.value[ chunk_faces3[ f ] ]; + var x = this.x, y = this.y, z = this.z; - v1 = value; - v2 = value; - v3 = value; + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; + return this; - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; + }, - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; + crossVectors: function ( a, b ) { - offset_custom += 9; + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - } + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - } else if ( customAttribute.boundTo === 'faceVertices' ) { + return this; - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + }, - value = customAttribute.value[ chunk_faces3[ f ] ]; + projectOnVector: function () { - v1 = value[ 0 ]; - v2 = value[ 1 ]; - v3 = value[ 2 ]; + var v1, dot; - customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; + return function ( vector ) { - customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; + if ( v1 === undefined ) v1 = new THREE.Vector3(); - customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; - customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; - customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; + v1.copy( vector ).normalize(); - offset_custom += 9; + dot = this.dot( v1 ); - } + return this.copy( v1 ).multiplyScalar( dot ); - } + }; - } else if ( customAttribute.size === 4 ) { + }(), - if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { + projectOnPlane: function () { - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + var v1; - face = obj_faces[ chunk_faces3[ f ] ]; + return function ( planeNormal ) { - v1 = customAttribute.value[ face.a ]; - v2 = customAttribute.value[ face.b ]; - v3 = customAttribute.value[ face.c ]; + if ( v1 === undefined ) v1 = new THREE.Vector3(); - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; + v1.copy( this ).projectOnVector( planeNormal ); - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; + return this.sub( v1 ); - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; + } - offset_custom += 12; + }(), - } + reflect: function () { - } else if ( customAttribute.boundTo === 'faces' ) { + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + var v1; - value = customAttribute.value[ chunk_faces3[ f ] ]; + return function ( normal ) { - v1 = value; - v2 = value; - v3 = value; + if ( v1 === undefined ) v1 = new THREE.Vector3(); - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; + } - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; + }(), - offset_custom += 12; + angleTo: function ( v ) { - } + var theta = this.dot( v ) / ( this.length() * v.length() ); - } else if ( customAttribute.boundTo === 'faceVertices' ) { + // clamp, to handle numerical problems - for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { + return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); - value = customAttribute.value[ chunk_faces3[ f ] ]; + }, - v1 = value[ 0 ]; - v2 = value[ 1 ]; - v3 = value[ 2 ]; + distanceTo: function ( v ) { - customAttribute.array[ offset_custom ] = v1.x; - customAttribute.array[ offset_custom + 1 ] = v1.y; - customAttribute.array[ offset_custom + 2 ] = v1.z; - customAttribute.array[ offset_custom + 3 ] = v1.w; + return Math.sqrt( this.distanceToSquared( v ) ); - customAttribute.array[ offset_custom + 4 ] = v2.x; - customAttribute.array[ offset_custom + 5 ] = v2.y; - customAttribute.array[ offset_custom + 6 ] = v2.z; - customAttribute.array[ offset_custom + 7 ] = v2.w; + }, - customAttribute.array[ offset_custom + 8 ] = v3.x; - customAttribute.array[ offset_custom + 9 ] = v3.y; - customAttribute.array[ offset_custom + 10 ] = v3.z; - customAttribute.array[ offset_custom + 11 ] = v3.w; + distanceToSquared: function ( v ) { - offset_custom += 12; + 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; - } + }, - } + setEulerFromRotationMatrix: function ( m, order ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); - } + }, - } + setEulerFromQuaternion: function ( q, order ) { - if ( dispose ) { + THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); - delete geometryGroup.__inittedArrays; - delete geometryGroup.__colorArray; - delete geometryGroup.__normalArray; - delete geometryGroup.__tangentArray; - delete geometryGroup.__uvArray; - delete geometryGroup.__uv2Array; - delete geometryGroup.__faceArray; - delete geometryGroup.__vertexArray; - delete geometryGroup.__lineArray; - delete geometryGroup.__skinIndexArray; - delete geometryGroup.__skinWeightArray; + }, - } + getPositionFromMatrix: function ( m ) { - }; + THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - // Buffer rendering + return this.setFromMatrixPosition( m ); - this.renderBufferImmediate = function ( object, program, material ) { + }, - state.initAttributes(); + getScaleFromMatrix: function ( m ) { - if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); - if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); - if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); - if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); + THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - if ( object.hasPositions ) { + return this.setFromMatrixScale( m ); + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + getColumnFromMatrix: function ( index, matrix ) { - state.enableAttribute( program.attributes.position ); + THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + return this.setFromMatrixColumn( index, matrix ); - } + }, - if ( object.hasNormals ) { + setFromMatrixPosition: function ( m ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); + this.x = m.elements[ 12 ]; + this.y = m.elements[ 13 ]; + this.z = m.elements[ 14 ]; - if ( material instanceof THREE.MeshPhongMaterial === false && - material.shading === THREE.FlatShading ) { + return this; - var nx, ny, nz, - nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, - normalArray, - i, il = object.count * 3; + }, - for ( i = 0; i < il; i += 9 ) { + setFromMatrixScale: function ( m ) { - normalArray = object.normalArray; + var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); + var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); + var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); - nax = normalArray[ i ]; - nay = normalArray[ i + 1 ]; - naz = normalArray[ i + 2 ]; + this.x = sx; + this.y = sy; + this.z = sz; - nbx = normalArray[ i + 3 ]; - nby = normalArray[ i + 4 ]; - nbz = normalArray[ i + 5 ]; + return this; + }, - ncx = normalArray[ i + 6 ]; - ncy = normalArray[ i + 7 ]; - ncz = normalArray[ i + 8 ]; + setFromMatrixColumn: function ( index, matrix ) { + + var offset = index * 4; - nx = ( nax + nbx + ncx ) / 3; - ny = ( nay + nby + ncy ) / 3; - nz = ( naz + nbz + ncz ) / 3; + var me = matrix.elements; - normalArray[ i ] = nx; - normalArray[ i + 1 ] = ny; - normalArray[ i + 2 ] = nz; + this.x = me[ offset ]; + this.y = me[ offset + 1 ]; + this.z = me[ offset + 2 ]; - normalArray[ i + 3 ] = nx; - normalArray[ i + 4 ] = ny; - normalArray[ i + 5 ] = nz; + return this; - normalArray[ i + 6 ] = nx; - normalArray[ i + 7 ] = ny; - normalArray[ i + 8 ] = nz; + }, - } + equals: function ( v ) { - } + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( program.attributes.normal ); + fromArray: function ( array, offset ) { - _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + if ( offset === undefined ) offset = 0; - } + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - if ( object.hasUvs && material.map ) { + return this; - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( program.attributes.uv ); + toArray: function ( array, offset ) { - _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + return array; - _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( program.attributes.color ); + fromAttribute: function ( attribute, index, offset ) { - _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + if ( offset === undefined ) offset = 0; - } + index = index * attribute.itemSize + offset; - state.disableUnusedAttributes(); + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + return this; - object.count = 0; + }, - }; + clone: function () { - function setupVertexAttributes( material, program, geometry, startIndex ) { + return new THREE.Vector3( this.x, this.y, this.z ); - var geometryAttributes = geometry.attributes; + } - var programAttributes = program.attributes; - var programAttributesKeys = program.attributesKeys; +}; - for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) { +// File:src/math/Vector4.js - var key = programAttributesKeys[ i ]; - var programAttribute = programAttributes[ key ]; +/** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - if ( programAttribute >= 0 ) { +THREE.Vector4 = function ( x, y, z, w ) { - var geometryAttribute = geometryAttributes[ key ]; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - if ( geometryAttribute !== undefined ) { +}; - var size = geometryAttribute.itemSize; +THREE.Vector4.prototype = { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer ); + constructor: THREE.Vector4, - state.enableAttribute( programAttribute ); + set: function ( x, y, z, w ) { - _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32 + this.x = x; + this.y = y; + this.z = z; + this.w = w; - } else if ( material.defaultAttributeValues !== undefined ) { + return this; - if ( material.defaultAttributeValues[ key ].length === 2 ) { + }, - _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] ); + setX: function ( x ) { - } else if ( material.defaultAttributeValues[ key ].length === 3 ) { + this.x = x; - _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] ); + return this; - } + }, - } + setY: function ( y ) { - } + this.y = y; - } + return this; - state.disableUnusedAttributes(); + }, - } + setZ: function ( z ) { - this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { + this.z = z; - if ( material.visible === false ) return; + return this; - updateObject( object ); + }, - var program = setProgram( camera, lights, fog, material, object ); + setW: function ( w ) { - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit; + this.w = w; - if ( geometryProgram !== _currentGeometryProgram ) { + return this; - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + }, - } + setComponent: function ( index, value ) { - if ( updateBuffers ) { + switch ( index ) { - state.initAttributes(); + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); } - // render mesh - - if ( object instanceof THREE.Mesh ) { - - var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES; - - var index = geometry.attributes.index; - - if ( index ) { - - // indexed triangles - - var type, size; + }, - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + getComponent: function ( index ) { - type = _gl.UNSIGNED_INT; - size = 4; + switch ( index ) { - } else { + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); - type = _gl.UNSIGNED_SHORT; - size = 2; + } - } + }, - var offsets = geometry.offsets; + copy: function ( v ) { - if ( offsets.length === 0 ) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - if ( updateBuffers ) { + return this; - setupVertexAttributes( material, program, geometry, 0 ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + }, - } + add: function ( v, w ) { - _gl.drawElements( mode, index.array.length, type, 0 ); + if ( w !== undefined ) { - _this.info.render.calls ++; - _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared - _this.info.render.faces += index.array.length / 3; + THREE.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - } else { + } - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - updateBuffers = true; + return this; - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + }, - var startIndex = offsets[ i ].index; + addScalar: function ( s ) { - if ( updateBuffers ) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; - setupVertexAttributes( material, program, geometry, startIndex ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + return this; - } + }, - // render indexed triangles + addVectors: function ( a, b ) { - _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - _this.info.render.faces += offsets[ i ].count / 3; + return this; - } + }, - } + sub: function ( v, w ) { - } else { + if ( w !== undefined ) { - // non-indexed triangles + THREE.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - if ( updateBuffers ) { + } - setupVertexAttributes( material, program, geometry, 0 ); + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - } + return this; - var position = geometry.attributes[ 'position' ]; + }, - // render non-indexed triangles + subScalar: function ( s ) { - _gl.drawArrays( mode, 0, position.array.length / position.itemSize ); + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - _this.info.render.calls ++; - _this.info.render.vertices += position.array.length / position.itemSize; - _this.info.render.faces += position.array.length / ( 3 * position.itemSize ); + return this; - } + }, - } else if ( object instanceof THREE.PointCloud ) { + subVectors: function ( a, b ) { - // render particles + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - var mode = _gl.POINTS; + return this; - var index = geometry.attributes.index; + }, - if ( index ) { + multiplyScalar: function ( scalar ) { - // indexed points + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - var type, size; + return this; - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + }, - type = _gl.UNSIGNED_INT; - size = 4; + applyMatrix4: function ( m ) { - } else { + var x = this.x; + var y = this.y; + var z = this.z; + var w = this.w; - type = _gl.UNSIGNED_SHORT; - size = 2; + var e = m.elements; - } + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - var offsets = geometry.offsets; + return this; - if ( offsets.length === 0 ) { + }, - if ( updateBuffers ) { + divideScalar: function ( scalar ) { - setupVertexAttributes( material, program, geometry, 0 ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + if ( scalar !== 0 ) { - } + var invScalar = 1 / scalar; - _gl.drawElements( mode, index.array.length, type, 0); + this.x *= invScalar; + this.y *= invScalar; + this.z *= invScalar; + this.w *= invScalar; - _this.info.render.calls ++; - _this.info.render.points += index.array.length; + } else { - } else { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change + } - if ( offsets.length > 1 ) updateBuffers = true; + return this; - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + }, - var startIndex = offsets[ i ].index; + setAxisAngleFromQuaternion: function ( q ) { - if ( updateBuffers ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - setupVertexAttributes( material, program, geometry, startIndex ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + // q is assumed to be normalized - } + this.w = 2 * Math.acos( q.w ); - // render indexed points + var s = Math.sqrt( 1 - q.w * q.w ); - _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); + if ( s < 0.0001 ) { - _this.info.render.calls ++; - _this.info.render.points += offsets[ i ].count; + this.x = 1; + this.y = 0; + this.z = 0; - } + } else { - } + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - } else { + } - // non-indexed points + return this; - if ( updateBuffers ) { + }, - setupVertexAttributes( material, program, geometry, 0 ); + setAxisAngleFromRotationMatrix: function ( m ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - var position = geometry.attributes.position; - var offsets = geometry.offsets; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - if ( offsets.length === 0 ) { + var angle, x, y, z, // variables for result + epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - _gl.drawArrays( mode, 0, position.array.length / 3 ); + te = m.elements, - _this.info.render.calls ++; - _this.info.render.points += position.array.length / 3; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - } else { + if ( ( Math.abs( m12 - m21 ) < epsilon ) + && ( Math.abs( m13 - m31 ) < epsilon ) + && ( Math.abs( m23 - m32 ) < epsilon ) ) { - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count ); + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) + && ( Math.abs( m13 + m31 ) < epsilon2 ) + && ( Math.abs( m23 + m32 ) < epsilon2 ) + && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - _this.info.render.calls ++; - _this.info.render.points += offsets[ i ].count; + // this singularity is identity matrix so angle = 0 - } + this.set( 1, 0, 0, 0 ); - } + return this; // zero angle, arbitrary axis } - } else if ( object instanceof THREE.Line ) { - - var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - - state.setLineWidth( material.linewidth * pixelRatio ); - - var index = geometry.attributes.index; + // otherwise this singularity is angle = 180 - if ( index ) { + angle = Math.PI; - // indexed lines + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - var type, size; + if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term - if ( index.array instanceof Uint32Array ) { + if ( xx < epsilon ) { - type = _gl.UNSIGNED_INT; - size = 4; + x = 0; + y = 0.707106781; + z = 0.707106781; } else { - type = _gl.UNSIGNED_SHORT; - size = 2; + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; } - var offsets = geometry.offsets; - - if ( offsets.length === 0 ) { + } else if ( yy > zz ) { // m22 is the largest diagonal term - if ( updateBuffers ) { + if ( yy < epsilon ) { - setupVertexAttributes( material, program, geometry, 0 ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + x = 0.707106781; + y = 0; + z = 0.707106781; - } + } else { - _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - _this.info.render.calls ++; - _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared + } - } else { + } else { // m33 is the largest diagonal term so base result on this - // if there is more than 1 chunk - // must set attribute pointers to use new offsets for each chunk - // even if geometry and materials didn't change + if ( zz < epsilon ) { - if ( offsets.length > 1 ) updateBuffers = true; + x = 0.707106781; + y = 0.707106781; + z = 0; - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + } else { - var startIndex = offsets[ i ].index; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - if ( updateBuffers ) { + } - setupVertexAttributes( material, program, geometry, startIndex ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); + } - } + this.set( x, y, z, angle ); - // render indexed lines + return this; // return 180 deg rotation - _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array + } - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared + // as we have reached here there are no singularities so we can handle normally - } + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - } + if ( Math.abs( s ) < 0.001 ) s = 1; - } else { + // 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 - // non-indexed lines + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - if ( updateBuffers ) { + return this; - setupVertexAttributes( material, program, geometry, 0 ); + }, - } + min: function ( v ) { - var position = geometry.attributes.position; - var offsets = geometry.offsets; + if ( this.x > v.x ) { - if ( offsets.length === 0 ) { + this.x = v.x; - _gl.drawArrays( mode, 0, position.array.length / 3 ); + } - _this.info.render.calls ++; - _this.info.render.vertices += position.array.length / 3; + if ( this.y > v.y ) { - } else { + this.y = v.y; - for ( var i = 0, il = offsets.length; i < il; i ++ ) { + } - _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count ); + if ( this.z > v.z ) { - _this.info.render.calls ++; - _this.info.render.vertices += offsets[ i ].count; + this.z = v.z; - } + } - } + if ( this.w > v.w ) { - } + this.w = v.w; } - }; - - this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { + return this; - if ( material.visible === false ) return; + }, - updateObject( object ); + max: function ( v ) { - var program = setProgram( camera, lights, fog, material, object ); + if ( this.x < v.x ) { - var attributes = program.attributes; + this.x = v.x; - var updateBuffers = false, - wireframeBit = material.wireframe ? 1 : 0, - geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit; + } - if ( geometryProgram !== _currentGeometryProgram ) { + if ( this.y < v.y ) { - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + this.y = v.y; } - if ( updateBuffers ) { + if ( this.z < v.z ) { - state.initAttributes(); + this.z = v.z; } - // vertices + if ( this.w < v.w ) { - if ( ! material.morphTargets && attributes.position >= 0 ) { + this.w = v.w; - if ( updateBuffers ) { + } - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + return this; - state.enableAttribute( attributes.position ); + }, - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + clamp: function ( min, max ) { - } + // This function assumes min < max, if this assumption isn't true it will not operate correctly - } else { + if ( this.x < min.x ) { - if ( object.morphTargetBase ) { + this.x = min.x; - setupMorphTargets( material, geometryGroup, object ); + } else if ( this.x > max.x ) { - } + this.x = max.x; } + if ( this.y < min.y ) { - if ( updateBuffers ) { + this.y = min.y; - // custom attributes + } else if ( this.y > max.y ) { - // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers + this.y = max.y; - if ( geometryGroup.__webglCustomAttributesList ) { + } - for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { + if ( this.z < min.z ) { - var attribute = geometryGroup.__webglCustomAttributesList[ i ]; + this.z = min.z; - if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { + } else if ( this.z > max.z ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); + this.z = max.z; - state.enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); + } - _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); + if ( this.w < min.w ) { - } + this.w = min.w; - } + } else if ( this.w > max.w ) { - } + this.w = max.w; + } - // colors + return this; - if ( attributes.color >= 0 ) { + }, - if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { + clampScalar: ( function () { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); + var min, max; - state.enableAttribute( attributes.color ); + return function ( minVal, maxVal ) { - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + if ( min === undefined ) { - } else if ( material.defaultAttributeValues !== undefined ) { + min = new THREE.Vector4(); + max = new THREE.Vector4(); + } - _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - } + return this.clamp( min, max ); - } + }; - // normals + } )(), - if ( attributes.normal >= 0 ) { + floor: function () { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - state.enableAttribute( attributes.normal ); + return this; - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + }, - } + ceil: function () { - // tangents + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - if ( attributes.tangent >= 0 ) { + return this; - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); + }, - state.enableAttribute( attributes.tangent ); + round: function () { - _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - } + return this; - // uvs + }, - if ( attributes.uv >= 0 ) { + roundToZero: function () { - if ( object.geometry.faceVertexUvs[ 0 ] ) { + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); + return this; - state.enableAttribute( attributes.uv ); + }, - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + negate: function () { - } else if ( material.defaultAttributeValues !== undefined ) { + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + return this; - _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); + }, - } + dot: function ( v ) { - } + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - if ( attributes.uv2 >= 0 ) { + }, - if ( object.geometry.faceVertexUvs[ 1 ] ) { + lengthSq: function () { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - state.enableAttribute( attributes.uv2 ); + }, - _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); + length: function () { - } else if ( material.defaultAttributeValues !== undefined ) { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + }, - _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); + lengthManhattan: function () { - } + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - } + }, - if ( material.skinning && - attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { + normalize: function () { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); + return this.divideScalar( this.length() ); - state.enableAttribute( attributes.skinIndex ); + }, - _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); + setLength: function ( l ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); + var oldLength = this.length(); - state.enableAttribute( attributes.skinWeight ); + if ( oldLength !== 0 && l !== oldLength ) { - _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); + this.multiplyScalar( l / oldLength ); - } + } - // line distances + return this; - if ( attributes.lineDistance >= 0 ) { + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); + lerp: function ( v, alpha ) { - state.enableAttribute( attributes.lineDistance ); + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; - _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); + return this; - } + }, - } + lerpVectors: function ( v1, v2, alpha ) { - state.disableUnusedAttributes(); + this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - // render mesh + return this; - if ( object instanceof THREE.Mesh ) { + }, - var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; + equals: function ( v ) { - // wireframe + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - if ( material.wireframe ) { + }, - state.setLineWidth( material.wireframeLinewidth * pixelRatio ); + fromArray: function ( array, offset ) { - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); - _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); + if ( offset === undefined ) offset = 0; - // triangles + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - } else { + return this; - if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); - _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); + }, - } + toArray: function ( array, offset ) { - _this.info.render.calls ++; - _this.info.render.vertices += geometryGroup.__webglFaceCount; - _this.info.render.faces += geometryGroup.__webglFaceCount / 3; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - // render lines + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - } else if ( object instanceof THREE.Line ) { + return array; - var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; + }, - state.setLineWidth( material.linewidth * pixelRatio ); + fromAttribute: function ( attribute, index, offset ) { - _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount ); + if ( offset === undefined ) offset = 0; - _this.info.render.calls ++; + index = index * attribute.itemSize + offset; - // render particles + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - } else if ( object instanceof THREE.PointCloud ) { + return this; - _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); + }, - _this.info.render.calls ++; - _this.info.render.points += geometryGroup.__webglParticleCount; + clone: function () { - } + return new THREE.Vector4( this.x, this.y, this.z, this.w ); - }; + } - function setupMorphTargets ( material, geometryGroup, object ) { +}; - // set base +// File:src/math/Euler.js - var attributes = material.program.attributes; +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://exocortex.com + */ - if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) { +THREE.Euler = function ( x, y, z, order ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || THREE.Euler.DefaultOrder; - state.enableAttribute( attributes.position ); + this.__defineGetter__("x", function(){ + return this._x; + }); + this.__defineSetter__("x", function(value){ + this._x = value; + this.onChangeCallback(); + }); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + this.__defineGetter__("y", function(){ + return this._y; + }); + this.__defineSetter__("y", function(value){ + this._y = value; + this.onChangeCallback(); + }); - } else if ( attributes.position >= 0 ) { + this.__defineGetter__("z", function(){ + return this._z; + }); + this.__defineSetter__("z", function(value){ + this._z = value; + this.onChangeCallback(); + }); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + this.__defineGetter__("order", function(){ + return this._order; + }); + this.__defineSetter__("order", function(value){ + this._order = value; + this.onChangeCallback(); + }); +}; - state.enableAttribute( attributes.position ); +THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); +THREE.Euler.DefaultOrder = 'XYZ'; - } +THREE.Euler.prototype = { - if ( object.morphTargetForcedOrder.length ) { + constructor: THREE.Euler, - // set forced order + _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder, - var m = 0; - var order = object.morphTargetForcedOrder; - var influences = object.morphTargetInfluences; + set: function ( x, y, z, order ) { - var attribute; + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - while ( m < material.numSupportedMorphTargets && m < order.length ) { + this.onChangeCallback(); - attribute = attributes[ 'morphTarget' + m ]; + return this; - if ( attribute >= 0 ) { + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); + copy: function ( euler ) { - state.enableAttribute( attribute ); + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); + this.onChangeCallback(); - } + return this; - attribute = attributes[ 'morphNormal' + m ]; + }, - if ( attribute >= 0 && material.morphNormals ) { + setFromRotationMatrix: function ( m, order, update ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); + var clamp = THREE.Math.clamp; - state.enableAttribute( attribute ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); + var te = m.elements; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - } + order = order || this._order; - object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; + if ( order === 'XYZ' ) { - m ++; + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - } + if ( Math.abs( m13 ) < 0.99999 ) { - } else { + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - // find the most influencing + } else { - var activeInfluenceIndices = []; - var influences = object.morphTargetInfluences; - var morphTargets = object.geometry.morphTargets; + this._x = Math.atan2( m32, m22 ); + this._z = 0; - if ( influences.length > morphTargets.length ) { + } - console.warn( 'THREE.Canvas3DRenderer: Influences array is bigger than morphTargets array.' ); - influences.length = morphTargets.length; + } else if ( order === 'YXZ' ) { - } + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - for ( var i = 0, il = influences.length; i < il; i ++ ) { + if ( Math.abs( m23 ) < 0.99999 ) { - var influence = influences[ i ]; + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - activeInfluenceIndices.push( [ influence, i ] ); + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; } - if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { + } else if ( order === 'ZXY' ) { - activeInfluenceIndices.sort( numericalSort ); - activeInfluenceIndices.length = material.numSupportedMorphTargets; + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { + if ( Math.abs( m32 ) < 0.99999 ) { - activeInfluenceIndices.sort( numericalSort ); + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - } else if ( activeInfluenceIndices.length === 0 ) { + } else { - activeInfluenceIndices.push( [ 0, 0 ] ); + this._y = 0; + this._z = Math.atan2( m21, m11 ); } - var attribute; - - for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) { - - if ( activeInfluenceIndices[ m ] ) { + } else if ( order === 'ZYX' ) { - var influenceIndex = activeInfluenceIndices[ m ][ 1 ]; + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - attribute = attributes[ 'morphTarget' + m ]; + if ( Math.abs( m31 ) < 0.99999 ) { - if ( attribute >= 0 ) { + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); + } else { - state.enableAttribute( attribute ); + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); + } - } + } else if ( order === 'YZX' ) { - attribute = attributes[ 'morphNormal' + m ]; + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - if ( attribute >= 0 && material.morphNormals ) { + if ( Math.abs( m21 ) < 0.99999 ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - state.enableAttribute( attribute ); + } else { - _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); + this._x = 0; + this._y = Math.atan2( m13, m33 ); - } + } - object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; + } else if ( order === 'XZY' ) { - } else { + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - /* - _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); + if ( Math.abs( m12 ) < 0.99999 ) { - if ( material.morphNormals ) { + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); + } else { - } - */ + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - object.__webglMorphTargetInfluences[ m ] = 0; + } - } + } else { - } + THREE.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ) } - // load updated influences uniform + this._order = order; - if ( material.program.uniforms.morphTargetInfluences !== null ) { + if ( update !== false ) this.onChangeCallback(); - _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); + return this; - } + }, - } + setFromQuaternion: function () { - // Sorting + var matrix; - function painterSortStable ( a, b ) { + return function ( q, order, update ) { - if ( a.object.renderOrder !== b.object.renderOrder ) { + if ( matrix === undefined ) matrix = new THREE.Matrix4(); + matrix.makeRotationFromQuaternion( q ); + this.setFromRotationMatrix( matrix, order, update ); - return a.object.renderOrder - b.object.renderOrder; + return this; - } else if ( a.material.id !== b.material.id ) { + }; - return a.material.id - b.material.id; + }(), - } else if ( a.z !== b.z ) { + setFromVector3: function ( v, order ) { - return a.z - b.z; + return this.set( v.x, v.y, v.z, order || this._order ); - } else { + }, - return a.id - b.id; + reorder: function () { - } + // WARNING: this discards revolution information -bhouston - } + var q = new THREE.Quaternion(); - function reversePainterSortStable ( a, b ) { + return function ( newOrder ) { - if ( a.object.renderOrder !== b.object.renderOrder ) { + q.setFromEuler( this ); + this.setFromQuaternion( q, newOrder ); - return a.object.renderOrder - b.object.renderOrder; + }; - } if ( a.z !== b.z ) { + }(), - return b.z - a.z; + equals: function ( euler ) { - } else { + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - return a.id - b.id; + }, - } + fromArray: function ( array ) { - } + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - function numericalSort ( a, b ) { + this.onChangeCallback(); - return b[ 0 ] - a[ 0 ]; + return this; - } + }, - // Rendering + toArray: function ( array, offset ) { - this.render = function ( scene, camera, renderTarget, forceClear ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - if ( camera instanceof THREE.Camera === false ) { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - THREE.error( 'THREE.Canvas3DRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + return array; + }, - } + toVector3: function ( optionalResult ) { - var fog = scene.fog; + if ( optionalResult ) { - // reset caching for this frame + return optionalResult.set( this._x, this._y, this._z ); - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; - _lightsNeedUpdate = true; + } else { - // update scene graph + return new THREE.Vector3( this._x, this._y, this._z ); - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + } - // update camera matrices and frustum + }, - if ( camera.parent === undefined ) camera.updateMatrixWorld(); + onChange: function ( callback ) { - // update Skeleton objects + this.onChangeCallback = callback; - scene.traverse( function ( object ) { + return this; - if ( object instanceof THREE.SkinnedMesh ) { + }, - object.skeleton.update(); + onChangeCallback: function () {}, - } + clone: function () { - } ); + return new THREE.Euler( this._x, this._y, this._z, this._order ); - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + } - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); +}; - lights.length = 0; - opaqueObjects.length = 0; - transparentObjects.length = 0; +// File:src/math/Line3.js - sprites.length = 0; - lensFlares.length = 0; +/** + * @author bhouston / http://exocortex.com + */ - projectObject( scene ); +THREE.Line3 = function ( start, end ) { - if ( _this.sortObjects === true ) { + this.start = ( start !== undefined ) ? start : new THREE.Vector3(); + this.end = ( end !== undefined ) ? end : new THREE.Vector3(); - opaqueObjects.sort( painterSortStable ); - transparentObjects.sort( reversePainterSortStable ); +}; - } +THREE.Line3.prototype = { - // custom render plugins (pre pass) + constructor: THREE.Line3, - shadowMapPlugin.render( scene, camera ); + set: function ( start, end ) { - // + this.start.copy( start ); + this.end.copy( end ); - _this.info.render.calls = 0; - _this.info.render.vertices = 0; - _this.info.render.faces = 0; - _this.info.render.points = 0; + return this; - this.setRenderTarget( renderTarget ); + }, - if ( this.autoClear || forceClear ) { + copy: function ( line ) { - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + this.start.copy( line.start ); + this.end.copy( line.end ); - } + return this; - // set matrices for immediate objects + }, - for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) { + center: function ( optionalTarget ) { - var webglObject = _webglObjectsImmediate[ i ]; - var object = webglObject.object; + var result = optionalTarget || new THREE.Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - if ( object.visible ) { + }, - setupMatrices( object, camera ); + delta: function ( optionalTarget ) { - unrollImmediateBufferMaterial( webglObject ); + var result = optionalTarget || new THREE.Vector3(); + return result.subVectors( this.end, this.start ); - } + }, - } + distanceSq: function () { - if ( scene.overrideMaterial ) { + return this.start.distanceToSquared( this.end ); - var overrideMaterial = scene.overrideMaterial; + }, - setMaterial( overrideMaterial ); + distance: function () { - renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial ); - renderObjects( transparentObjects, camera, lights, fog, overrideMaterial ); - renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, overrideMaterial ); + return this.start.distanceTo( this.end ); - } else { + }, - // opaque pass (front-to-back order) + at: function ( t, optionalTarget ) { - state.setBlending( THREE.NoBlending ); + var result = optionalTarget || new THREE.Vector3(); - renderObjects( opaqueObjects, camera, lights, fog, null ); - renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, null ); + return this.delta( result ).multiplyScalar( t ).add( this.start ); - // transparent pass (back-to-front order) + }, - renderObjects( transparentObjects, camera, lights, fog, null ); - renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, null ); + closestPointToPointParameter: function () { - } + var startP = new THREE.Vector3(); + var startEnd = new THREE.Vector3(); - // custom render plugins (post pass) + return function ( point, clampToLine ) { - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight ); + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - // Generate mipmap if we're using any kind of mipmap filtering + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { + var t = startEnd_startP / startEnd2; - updateRenderTargetMipmap( renderTarget ); + if ( clampToLine ) { - } + t = THREE.Math.clamp( t, 0, 1 ); - // Ensure depth buffer writing is enabled so it can be cleared on next render + } - state.setDepthTest( true ); - state.setDepthWrite( true ); - state.setColorWrite( true ); + return t; - // _gl.finish(); + }; - }; + }(), - function projectObject( object ) { + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { - if ( object.visible === false ) return; + var t = this.closestPointToPointParameter( point, clampToLine ); - if ( object instanceof THREE.Scene || object instanceof THREE.Group ) { + var result = optionalTarget || new THREE.Vector3(); - // skip + return this.delta( result ).multiplyScalar( t ).add( this.start ); - } else { + }, - initObject( object ); + applyMatrix4: function ( matrix ) { - if ( object instanceof THREE.Light ) { + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - lights.push( object ); + return this; - } else if ( object instanceof THREE.Sprite ) { + }, - sprites.push( object ); + equals: function ( line ) { - } else if ( object instanceof THREE.LensFlare ) { + return line.start.equals( this.start ) && line.end.equals( this.end ); - lensFlares.push( object ); + }, - } else { + clone: function () { - var webglObjects = _webglObjects[ object.id ]; + return new THREE.Line3().copy( this ); - if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + } - for ( var i = 0, l = webglObjects.length; i < l; i ++ ) { +}; - var webglObject = webglObjects[ i ]; +// File:src/math/Box2.js - unrollBufferMaterial( webglObject ); +/** + * @author bhouston / http://exocortex.com + */ - webglObject.render = true; +THREE.Box2 = function ( min, max ) { - if ( _this.sortObjects === true ) { + this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); + this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); +}; - webglObject.z = _vector3.z; +THREE.Box2.prototype = { - } + constructor: THREE.Box2, - } + set: function ( min, max ) { - } + this.min.copy( min ); + this.max.copy( max ); - } + return this; - } + }, - for ( var i = 0, l = object.children.length; i < l; i ++ ) { + setFromPoints: function ( points ) { - projectObject( object.children[ i ] ); + this.makeEmpty(); - } + for ( var i = 0, il = points.length; i < il; i ++ ) { - } + this.expandByPoint( points[ i ] ) - function renderObjects( renderList, camera, lights, fog, overrideMaterial ) { + } - var material; + return this; - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + }, - var webglObject = renderList[ i ]; + setFromCenterAndSize: function () { - var object = webglObject.object; - var buffer = webglObject.buffer; + var v1 = new THREE.Vector2(); - setupMatrices( object, camera ); + return function ( center, size ) { - if ( overrideMaterial ) { + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - material = overrideMaterial; + return this; - } else { + }; - material = webglObject.material; + }(), - if ( ! material ) continue; + copy: function ( box ) { - setMaterial( material ); + this.min.copy( box.min ); + this.max.copy( box.max ); - } + return this; - _this.setMaterialFaces( material ); + }, - if ( buffer instanceof THREE.BufferGeometry ) { + makeEmpty: function () { - _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = - Infinity; - } else { + return this; - _this.renderBuffer( camera, lights, fog, material, buffer, object ); + }, - } + 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 ); - function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) { + }, - var material; + center: function ( optionalTarget ) { - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + var result = optionalTarget || new THREE.Vector2(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - var webglObject = renderList[ i ]; - var object = webglObject.object; + }, - if ( object.visible ) { + size: function ( optionalTarget ) { - if ( overrideMaterial ) { + var result = optionalTarget || new THREE.Vector2(); + return result.subVectors( this.max, this.min ); - material = overrideMaterial; + }, - } else { + expandByPoint: function ( point ) { - material = webglObject[ materialType ]; + this.min.min( point ); + this.max.max( point ); - if ( ! material ) continue; + return this; + }, - setMaterial( material ); + expandByVector: function ( vector ) { - } + this.min.sub( vector ); + this.max.add( vector ); - _this.renderImmediateObject( camera, lights, fog, material, object ); + return this; + }, - } + expandByScalar: function ( scalar ) { - } + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } + return this; + }, - this.renderImmediateObject = function ( camera, lights, fog, material, object ) { + containsPoint: function ( point ) { - var program = setProgram( camera, lights, fog, material, object ); + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - _currentGeometryProgram = ''; + return false; - _this.setMaterialFaces( material ); + } - if ( object.immediateRenderCallback ) { + return true; - object.immediateRenderCallback( program, _gl, _frustum ); + }, - } else { + containsBox: function ( box ) { - object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } ); + 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; - function unrollImmediateBufferMaterial ( globject ) { + }, - var object = globject.object, - material = object.material; + getParameter: function ( point, optionalTarget ) { - if ( material.transparent ) { + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - globject.transparent = material; - globject.opaque = null; + var result = optionalTarget || new THREE.Vector2(); - } else { + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - globject.opaque = material; - globject.transparent = null; + }, - } + isIntersectionBox: function ( box ) { - } + // using 6 splitting planes to rule out intersections. - function unrollBufferMaterial ( globject ) { + 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 ) { - var object = globject.object; - var buffer = globject.buffer; + return false; - var geometry = object.geometry; - var material = object.material; + } - if ( material instanceof THREE.MeshFaceMaterial ) { + return true; - var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; + }, - material = material.materials[ materialIndex ]; + clampPoint: function ( point, optionalTarget ) { - globject.material = material; + var result = optionalTarget || new THREE.Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - if ( material.transparent ) { + }, - transparentObjects.push( globject ); + distanceToPoint: function () { - } else { + var v1 = new THREE.Vector2(); - opaqueObjects.push( globject ); + return function ( point ) { - } + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - } else if ( material ) { + }; - globject.material = material; + }(), - if ( material.transparent ) { + intersect: function ( box ) { - transparentObjects.push( globject ); + this.min.max( box.min ); + this.max.min( box.max ); - } else { + return this; - opaqueObjects.push( globject ); + }, - } + union: function ( box ) { - } + this.min.min( box.min ); + this.max.max( box.max ); - } + return this; - function initObject( object ) { + }, - if ( object.__webglInit === undefined ) { + translate: function ( offset ) { - object.__webglInit = true; - object._modelViewMatrix = new THREE.Matrix4(); - object._normalMatrix = new THREE.Matrix3(); + this.min.add( offset ); + this.max.add( offset ); - object.addEventListener( 'removed', onObjectRemoved ); + return this; - } + }, - var geometry = object.geometry; + equals: function ( box ) { - if ( geometry === undefined ) { + return box.min.equals( this.min ) && box.max.equals( this.max ); - // ImmediateRenderObject + }, - } else if ( geometry.__webglInit === undefined ) { + clone: function () { - geometry.__webglInit = true; - geometry.addEventListener( 'dispose', onGeometryDispose ); + return new THREE.Box2().copy( this ); - if ( geometry instanceof THREE.BufferGeometry ) { + } - _this.info.memory.geometries ++; +}; - } else if ( object instanceof THREE.Mesh ) { +// File:src/math/Box3.js - initGeometryGroups( object, geometry ); +/** + * @author bhouston / http://exocortex.com + * @author WestLangley / http://github.com/WestLangley + */ - } else if ( object instanceof THREE.Line ) { +THREE.Box3 = function ( min, max ) { - if ( geometry.__webglVertexBuffer === undefined ) { + this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); + this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); - createLineBuffers( geometry ); - initLineBuffers( geometry, object ); +}; - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; - geometry.lineDistancesNeedUpdate = true; +THREE.Box3.prototype = { - } + constructor: THREE.Box3, - } else if ( object instanceof THREE.PointCloud ) { + set: function ( min, max ) { - if ( geometry.__webglVertexBuffer === undefined ) { + this.min.copy( min ); + this.max.copy( max ); - createParticleBuffers( geometry ); - initParticleBuffers( geometry, object ); + return this; - geometry.verticesNeedUpdate = true; - geometry.colorsNeedUpdate = true; + }, - } + setFromPoints: function ( points ) { - } + this.makeEmpty(); - } + for ( var i = 0, il = points.length; i < il; i ++ ) { - if ( object.__webglActive === undefined) { + this.expandByPoint( points[ i ] ) - object.__webglActive = true; + } - if ( object instanceof THREE.Mesh ) { + return this; - if ( geometry instanceof THREE.BufferGeometry ) { + }, - addBuffer( _webglObjects, geometry, object ); + setFromCenterAndSize: function () { - } else if ( geometry instanceof THREE.Geometry ) { + var v1 = new THREE.Vector3(); - var geometryGroupsList = geometryGroups[ geometry.id ]; + return function ( center, size ) { - for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) { + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - addBuffer( _webglObjects, geometryGroupsList[ i ], object ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - } + return this; - } + }; - } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) { + }(), - addBuffer( _webglObjects, geometry, object ); + setFromObject: function () { - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and childrens', world transforms - addBufferImmediate( _webglObjectsImmediate, object ); + var v1 = new THREE.Vector3(); - } + return function ( object ) { - } + var scope = this; - } + object.updateMatrixWorld( true ); - // Geometry splitting + this.makeEmpty(); - var geometryGroups = {}; - var geometryGroupCounter = 0; + object.traverse( function ( node ) { - function makeGroups( geometry, usesFaceMaterial ) { + var geometry = node.geometry; - var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535; + if ( geometry !== undefined ) { - var groupHash, hash_map = {}; + if ( geometry instanceof THREE.Geometry ) { - var numMorphTargets = geometry.morphTargets.length; - var numMorphNormals = geometry.morphNormals.length; + var vertices = geometry.vertices; - var group; - var groups = {}; - var groupsList = []; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { + v1.copy( vertices[ i ] ); - var face = geometry.faces[ f ]; - var materialIndex = usesFaceMaterial ? face.materialIndex : 0; + v1.applyMatrix4( node.matrixWorld ); - if ( ! ( materialIndex in hash_map ) ) { + scope.expandByPoint( v1 ); - hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 }; + } - } + } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) { - groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; + var positions = geometry.attributes[ 'position' ].array; - if ( ! ( groupHash in groups ) ) { + for ( var i = 0, il = positions.length; i < il; i += 3 ) { - group = { - id: geometryGroupCounter ++, - faces3: [], - materialIndex: materialIndex, - vertices: 0, - numMorphTargets: numMorphTargets, - numMorphNormals: numMorphNormals - }; + v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - groups[ groupHash ] = group; - groupsList.push( group ); + v1.applyMatrix4( node.matrixWorld ); - } - - if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) { - - hash_map[ materialIndex ].counter += 1; - groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; - - if ( ! ( groupHash in groups ) ) { + scope.expandByPoint( v1 ); - group = { - id: geometryGroupCounter ++, - faces3: [], - materialIndex: materialIndex, - vertices: 0, - numMorphTargets: numMorphTargets, - numMorphNormals: numMorphNormals - }; + } - groups[ groupHash ] = group; - groupsList.push( group ); + } } - } - - groups[ groupHash ].faces3.push( f ); - groups[ groupHash ].vertices += 3; + } ); - } + return this; - return groupsList; + }; - } + }(), - function initGeometryGroups( object, geometry ) { + copy: function ( box ) { - var material = object.material, addBuffers = false; + this.min.copy( box.min ); + this.max.copy( box.max ); - if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) { + return this; - delete _webglObjects[ object.id ]; + }, - geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial ); + makeEmpty: function () { - geometry.groupsNeedUpdate = false; + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - } + return this; - var geometryGroupsList = geometryGroups[ geometry.id ]; + }, - // create separate VBOs per geometry chunk + empty: function () { - for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) { + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - var geometryGroup = geometryGroupsList[ i ]; + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - // initialise VBO on the first access + }, - if ( geometryGroup.__webglVertexBuffer === undefined ) { + center: function ( optionalTarget ) { - createMeshBuffers( geometryGroup ); - initMeshBuffers( geometryGroup, object ); + var result = optionalTarget || new THREE.Vector3(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - geometry.verticesNeedUpdate = true; - geometry.morphTargetsNeedUpdate = true; - geometry.elementsNeedUpdate = true; - geometry.uvsNeedUpdate = true; - geometry.normalsNeedUpdate = true; - geometry.tangentsNeedUpdate = true; - geometry.colorsNeedUpdate = true; + }, - addBuffers = true; + size: function ( optionalTarget ) { - } else { + var result = optionalTarget || new THREE.Vector3(); + return result.subVectors( this.max, this.min ); - addBuffers = false; + }, - } + expandByPoint: function ( point ) { - if ( addBuffers || object.__webglActive === undefined ) { + this.min.min( point ); + this.max.max( point ); - addBuffer( _webglObjects, geometryGroup, object ); + return this; - } + }, - } + expandByVector: function ( vector ) { - object.__webglActive = true; + this.min.sub( vector ); + this.max.add( vector ); - } + return this; - function addBuffer( objlist, buffer, object ) { + }, - var id = object.id; - objlist[id] = objlist[id] || []; - objlist[id].push( - { - id: id, - buffer: buffer, - object: object, - material: null, - z: 0 - } - ); + expandByScalar: function ( scalar ) { - }; + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - function addBufferImmediate( objlist, object ) { + return this; - objlist.push( - { - id: null, - object: object, - opaque: null, - transparent: null, - z: 0 - } - ); + }, - }; + containsPoint: function ( point ) { - // Objects updates + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ) { - function updateObject( object ) { + return false; - var geometry = object.geometry; + } - if ( geometry instanceof THREE.BufferGeometry ) { + return true; - var attributes = geometry.attributes; - var attributesKeys = geometry.attributesKeys; + }, - for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) { + containsBox: function ( box ) { - var key = attributesKeys[ i ]; - var attribute = attributes[ key ]; - var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; + 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 ) ) { - if ( attribute.buffer === undefined ) { + return true; - attribute.buffer = _gl.createBuffer(); - _gl.bindBuffer( bufferType, attribute.buffer ); - _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW ); + } - attribute.needsUpdate = false; + return false; - } else if ( attribute.needsUpdate === true ) { + }, - _gl.bindBuffer( bufferType, attribute.buffer ); + getParameter: function ( point, optionalTarget ) { - if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - _gl.bufferSubData( bufferType, 0, attribute.array ); + var result = optionalTarget || new THREE.Vector3(); - } else if ( attribute.updateRange.count === 0 ) { + return result.set( + ( 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 ) + ); - console.error( 'THREE.Canvas3DRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' ); + }, - } else { + isIntersectionBox: function ( box ) { - _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT, - attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) ); + // using 6 splitting planes to rule out intersections. - attribute.updateRange.count = 0; // reset range + 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; - attribute.needsUpdate = false; + } - } + return true; - } + }, - } else if ( object instanceof THREE.Mesh ) { + clampPoint: function ( point, optionalTarget ) { - // check all geometry groups + var result = optionalTarget || new THREE.Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - if ( geometry.groupsNeedUpdate === true ) { + }, - initGeometryGroups( object, geometry ); + distanceToPoint: function () { - } + var v1 = new THREE.Vector3(); - var geometryGroupsList = geometryGroups[ geometry.id ]; + return function ( point ) { - for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - var geometryGroup = geometryGroupsList[ i ]; - var material = getBufferMaterial( object, geometryGroup ); + }; - var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + }(), - if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || - geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || - geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { + getBoundingSphere: function () { - setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material ); + var v1 = new THREE.Vector3(); - } + return function ( optionalTarget ) { - } + var result = optionalTarget || new THREE.Sphere(); - geometry.verticesNeedUpdate = false; - geometry.morphTargetsNeedUpdate = false; - geometry.elementsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.tangentsNeedUpdate = false; + result.center = this.center(); + result.radius = this.size( v1 ).length() * 0.5; - if (material.attributes) clearCustomAttributes( material ); + return result; - } else if ( object instanceof THREE.Line ) { + }; - var material = getBufferMaterial( object, geometry ); - var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + }(), - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { + intersect: function ( box ) { - setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); + this.min.max( box.min ); + this.max.min( box.max ); - } + return this; - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.lineDistancesNeedUpdate = false; + }, - if (material.attributes) clearCustomAttributes( material ); + union: function ( box ) { - } else if ( object instanceof THREE.PointCloud ) { + this.min.min( box.min ); + this.max.max( box.max ); - var material = getBufferMaterial( object, geometry ); - var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + return this; - if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) { + }, - setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); + applyMatrix4: function () { - } + var points = [ + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3(), + new THREE.Vector3() + ]; - geometry.verticesNeedUpdate = false; - geometry.colorsNeedUpdate = false; + return function ( matrix ) { - if(material.attributes) clearCustomAttributes( material ); + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - } + this.makeEmpty(); + this.setFromPoints( points ); - } + return this; - // Objects updates - custom attributes check + }; - function areCustomAttributesDirty( material ) { + }(), - for ( var name in material.attributes ) { + translate: function ( offset ) { - if ( material.attributes[ name ].needsUpdate ) return true; + this.min.add( offset ); + this.max.add( offset ); - } + return this; - return false; + }, - } + equals: function ( box ) { - function clearCustomAttributes( material ) { + return box.min.equals( this.min ) && box.max.equals( this.max ); - for ( var name in material.attributes ) { + }, - material.attributes[ name ].needsUpdate = false; + clone: function () { - } + return new THREE.Box3().copy( this ); } - // Objects removal +}; - function removeObject( object ) { +// File:src/math/Matrix3.js - if ( object instanceof THREE.Mesh || - object instanceof THREE.PointCloud || - object instanceof THREE.Line ) { +/** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://exocortex.com + */ - delete _webglObjects[ object.id ]; +THREE.Matrix3 = function () { - } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { + this.elements = new Float32Array( [ - removeInstances( _webglObjectsImmediate, object ); + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - } + ] ); - delete object.__webglInit; - delete object._modelViewMatrix; - delete object._normalMatrix; + if ( arguments.length > 0 ) { - delete object.__webglActive; + THREE.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); } - function removeInstances( objlist, object ) { +}; - for ( var o = objlist.length - 1; o >= 0; o -- ) { +THREE.Matrix3.prototype = { - if ( objlist[ o ].object === object ) { + constructor: THREE.Matrix3, - objlist.splice( o, 1 ); + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - } + var te = this.elements; - } + te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13; + te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23; + te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33; - } + return this; - // Materials + }, - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointCloudMaterial: 'particle_basic' - }; + identity: function () { - function initMaterial( material, lights, fog, object ) { + this.set( - material.addEventListener( 'dispose', onMaterialDispose ); + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - var shaderID = shaderIDs[ material.type ]; + ); - if ( shaderID ) { + return this; - var shader = THREE.ShaderLib[ shaderID ]; + }, - material.__webglShader = { - uniforms: THREE.UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - } + copy: function ( m ) { - } else { + var me = m.elements; - material.__webglShader = { - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - } + this.set( - } + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + ); - var maxLightCount = allocateLights( lights ); - var maxShadows = allocateShadows( lights ); - var maxBones = allocateBones( object ); + return this; - var parameters = { + }, - precision: _precision, - supportsVertexTextures: _supportsVertexTextures, + multiplyVector3: function ( vector ) { - map: !! material.map, - envMap: !! material.envMap, - envMapMode: material.envMap && material.envMap.mapping, - lightMap: !! material.lightMap, - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, + THREE.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); + return vector.applyMatrix3( this ); - combine: material.combine, + }, - vertexColors: material.vertexColors, + multiplyVector3Array: function ( a ) { - fog: fog, - useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, + THREE.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); - flatShading: material.shading === THREE.FlatShading, + }, - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: _logarithmicDepthBuffer, + applyToVector3Array: function () { - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture, + var v1 = new THREE.Vector3(); - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: _this.maxMorphTargets, - maxMorphNormals: _this.maxMorphNormals, + return function ( array, offset, length ) { - maxDirLights: maxLightCount.directional, - maxPointLights: maxLightCount.point, - maxSpotLights: maxLightCount.spot, - maxHemiLights: maxLightCount.hemi, + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - maxShadows: maxShadows, - shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, - shadowMapType: _this.shadowMapType, - shadowMapDebug: _this.shadowMapDebug, - shadowMapCascade: _this.shadowMapCascade, + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - alphaTest: material.alphaTest, - metal: material.metal, - wrapAround: material.wrapAround, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide + v1.x = array[ j ]; + v1.y = array[ j + 1 ]; + v1.z = array[ j + 2 ]; - }; + v1.applyMatrix3( this ); - // Generate code + array[ j ] = v1.x; + array[ j + 1 ] = v1.y; + array[ j + 2 ] = v1.z; - var chunks = []; + } - if ( shaderID ) { + return array; - chunks.push( shaderID ); + }; - } else { + }(), - chunks.push( material.fragmentShader ); - chunks.push( material.vertexShader ); + multiplyScalar: function ( s ) { - } + var te = this.elements; - if ( material.defines !== undefined ) { + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - for ( var name in material.defines ) { + return this; - chunks.push( name ); - chunks.push( material.defines[ name ] ); + }, - } + determinant: function () { - } + var te = this.elements; - for ( var name in parameters ) { + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - chunks.push( name ); - chunks.push( parameters[ name ] ); + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - } + }, - var code = chunks.join(); + getInverse: function ( matrix, throwOnInvertible ) { - var program; + // input: THREE.Matrix4 + // ( based on http://code.google.com/p/webgl-mjs/ ) - // Check if code has been already compiled + var me = matrix.elements; + var te = this.elements; - for ( var p = 0, pl = _programs.length; p < pl; p ++ ) { + te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ]; + te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ]; + te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ]; + te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ]; + te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ]; + te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ]; + te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ]; + te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ]; + te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ]; - var programInfo = _programs[ p ]; + var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; - if ( programInfo.code === code ) { + // no inverse - program = programInfo; - program.usedTimes ++; + if ( det === 0 ) { - break; + var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0"; - } + if ( throwOnInvertible || false ) { - } + throw new Error( msg ); - if ( program === undefined ) { + } else { - program = new THREE.WebGLProgram( _this, code, material, parameters ); - _programs.push( program ); + THREE.warn( msg ); - _this.info.memory.programs = _programs.length; + } + + this.identity(); + + return this; } - material.program = program; + this.multiplyScalar( 1.0 / det ); - var attributes = program.attributes; + return this; - if ( material.morphTargets ) { + }, - material.numSupportedMorphTargets = 0; + transpose: function () { - var id, base = 'morphTarget'; + var tmp, m = this.elements; - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - id = base + i; + return this; - if ( attributes[ id ] >= 0 ) { + }, - material.numSupportedMorphTargets ++; + flattenToArrayOffset: function ( array, offset ) { - } + var te = this.elements; - } + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - } + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - if ( material.morphNormals ) { + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - material.numSupportedMorphNormals = 0; + return array; - var id, base = 'morphNormal'; + }, - for ( i = 0; i < _this.maxMorphNormals; i ++ ) { + getNormalMatrix: function ( m ) { - id = base + i; + // input: THREE.Matrix4 - if ( attributes[ id ] >= 0 ) { + this.getInverse( m ).transpose(); - material.numSupportedMorphNormals ++; + return this; - } + }, - } + transposeIntoArray: function ( r ) { - } + var m = this.elements; - material.uniformsList = []; + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; - for ( var u in material.__webglShader.uniforms ) { + return this; - var location = material.program.uniforms[ u ]; + }, - if ( location ) { - material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] ); - } + fromArray: function ( array ) { - } + this.elements.set( array ); - } + return this; - function setMaterial( material ) { + }, - if ( material.transparent === true ) { + toArray: function () { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha ); + var te = this.elements; - } else { + return [ + te[ 0 ], te[ 1 ], te[ 2 ], + te[ 3 ], te[ 4 ], te[ 5 ], + te[ 6 ], te[ 7 ], te[ 8 ] + ]; - state.setBlending( THREE.NoBlending ); + }, - } + clone: function () { - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); - state.setColorWrite( material.colorWrite ); - state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + return new THREE.Matrix3().fromArray( this.elements ); } - function setProgram( camera, lights, fog, material, object ) { +}; - _usedTextureUnits = 0; +// File:src/math/Matrix4.js - if ( material.needsUpdate ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author jordi_ros / http://plattsoft.com + * @author D1plo1d / http://github.com/D1plo1d + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author timknip / http://www.floorplanner.com/ + * @author bhouston / http://exocortex.com + * @author WestLangley / http://github.com/WestLangley + */ - if ( material.program ) deallocateMaterial( material ); +THREE.Matrix4 = function () { - initMaterial( material, lights, fog, object ); - material.needsUpdate = false; + this.elements = new Float32Array( [ - } + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - if ( material.morphTargets ) { + ] ); - if ( ! object.__webglMorphTargetInfluences ) { + if ( arguments.length > 0 ) { - object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); + THREE.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - } + } - } +}; - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; +THREE.Matrix4.prototype = { - var program = material.program, - p_uniforms = program.uniforms, - m_uniforms = material.__webglShader.uniforms; + constructor: THREE.Matrix4, - if ( program.id !== _currentProgram ) { + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - _gl.useProgram( program.program ); - _currentProgram = program.id; + var te = this.elements; - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - } + return this; - if ( material.id !== _currentMaterialId ) { + }, - if ( _currentMaterialId === -1 ) refreshLights = true; - _currentMaterialId = material.id; + identity: function () { - refreshMaterial = true; + this.set( - } + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - if ( refreshProgram || camera !== _currentCamera ) { + ); - _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + return this; - if ( _logarithmicDepthBuffer ) { + }, - _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + copy: function ( m ) { - } + this.elements.set( m.elements ); + return this; - if ( camera !== _currentCamera ) _currentCamera = camera; + }, - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + extractPosition: function ( m ) { - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material.envMap ) { + THREE.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); + return this.copyPosition( m ); - if ( p_uniforms.cameraPosition !== null ) { + }, - _vector3.setFromMatrixPosition( camera.matrixWorld ); - _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); + copyPosition: function ( m ) { - } + var te = this.elements; + var me = m.elements; - } + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.ShaderMaterial || - material.skinning ) { + return this; - if ( p_uniforms.viewMatrix !== null ) { + }, - _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); + extractBasis: function ( xAxis, yAxis, zAxis ) { + + var te = this.elements; + + xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] ); + yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] ); + zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] ); + + return this; + + }, + + makeBasis: function ( xAxis, yAxis, zAxis ) { - } + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); - } + return this; - } + }, - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + extractRotation: function () { - if ( material.skinning ) { + var v1 = new THREE.Vector3(); - if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) { + return function ( m ) { - _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements ); + var te = this.elements; + var me = m.elements; - } + var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length(); + var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length(); + var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length(); - if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) { + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements ); + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - } + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) { + return this; - if ( p_uniforms.boneTexture !== null ) { + }; - var textureUnit = getTextureUnit(); + }(), - _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); - _this.setTexture( object.skeleton.boneTexture, textureUnit ); + makeRotationFromEuler: function ( euler ) { - } + if ( euler instanceof THREE.Euler === false ) { - if ( p_uniforms.boneTextureWidth !== null ) { + THREE.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth ); + } - } + var te = this.elements; - if ( p_uniforms.boneTextureHeight !== null ) { + var x = euler.x, y = euler.y, z = euler.z; + var a = Math.cos( x ), b = Math.sin( x ); + var c = Math.cos( y ), d = Math.sin( y ); + var e = Math.cos( z ), f = Math.sin( z ); - _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight ); + if ( euler.order === 'XYZ' ) { - } + var ae = a * e, af = a * f, be = b * e, bf = b * f; - } else if ( object.skeleton && object.skeleton.boneMatrices ) { + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - if ( p_uniforms.boneGlobalMatrices !== null ) { + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices ); + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - } + } else if ( euler.order === 'YXZ' ) { - } + var ce = c * e, cf = c * f, de = d * e, df = d * f; - } + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - if ( refreshMaterial ) { + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - // refresh uniforms common to several materials + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - if ( fog && material.fog ) { + } else if ( euler.order === 'ZXY' ) { - refreshUniformsFog( m_uniforms, fog ); + var ce = c * e, cf = c * f, de = d * e, df = d * f; - } + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material.lights ) { + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - if ( _lightsNeedUpdate ) { + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - refreshLights = true; - setupLights( lights ); - _lightsNeedUpdate = false; - } + } else if ( euler.order === 'ZYX' ) { - if ( refreshLights ) { - refreshUniformsLights( m_uniforms, _lights ); - markUniformsLightsNeedsUpdate( m_uniforms, true ); - } else { - markUniformsLightsNeedsUpdate( m_uniforms, false ); - } + var ae = a * e, af = a * f, be = b * e, bf = b * f; - } + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial ) { + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - refreshUniformsCommon( m_uniforms, material ); + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - } + } else if ( euler.order === 'YZX' ) { - // refresh single material specific uniforms + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - if ( material instanceof THREE.LineBasicMaterial ) { + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - refreshUniformsLine( m_uniforms, material ); + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - } else if ( material instanceof THREE.LineDashedMaterial ) { + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + } else if ( euler.order === 'XZY' ) { - } else if ( material instanceof THREE.PointCloudMaterial ) { + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - refreshUniformsParticle( m_uniforms, material ); + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - } else if ( material instanceof THREE.MeshPhongMaterial ) { + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - refreshUniformsPhong( m_uniforms, material ); + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - } else if ( material instanceof THREE.MeshLambertMaterial ) { + } - refreshUniformsLambert( m_uniforms, material ); + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - } else if ( material instanceof THREE.MeshDepthMaterial ) { + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - m_uniforms.mNear.value = camera.near; - m_uniforms.mFar.value = camera.far; - m_uniforms.opacity.value = material.opacity; + return this; - } else if ( material instanceof THREE.MeshNormalMaterial ) { + }, - m_uniforms.opacity.value = material.opacity; + setRotationFromQuaternion: function ( q ) { - } + THREE.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - if ( object.receiveShadow && ! material._shadowPass ) { + return this.makeRotationFromQuaternion( q ); - refreshUniformsShadow( m_uniforms, lights ); + }, - } + makeRotationFromQuaternion: function ( q ) { - // load common uniforms + var te = this.elements; - loadUniformsGeneric( material.uniformsList ); + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x, y2 = y + y, z2 = z + z; + var xx = x * x2, xy = x * y2, xz = x * z2; + var yy = y * y2, yz = y * z2, zz = z * z2; + var wx = w * x2, wy = w * y2, wz = w * z2; - } + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - loadUniformsMatrices( p_uniforms, object ); + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - if ( p_uniforms.modelMatrix !== null ) { + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - } + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - return program; + return this; - } + }, - // Uniforms (refresh uniforms objects) + lookAt: function () { - function refreshUniformsCommon ( uniforms, material ) { + var x = new THREE.Vector3(); + var y = new THREE.Vector3(); + var z = new THREE.Vector3(); - uniforms.opacity.value = material.opacity; + return function ( eye, target, up ) { - uniforms.diffuse.value = material.color; + var te = this.elements; - uniforms.map.value = material.map; - uniforms.lightMap.value = material.lightMap; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + z.subVectors( eye, target ).normalize(); - if ( material.bumpMap ) { + if ( z.length() === 0 ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + z.z = 1; - } + } - if ( material.normalMap ) { + x.crossVectors( up, z ).normalize(); - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - - } - - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map + if ( x.length() === 0 ) { - var uvScaleMap; + z.x += 0.0001; + x.crossVectors( up, z ).normalize(); - if ( material.map ) { + } - uvScaleMap = material.map; + y.crossVectors( z, x ); - } else if ( material.specularMap ) { - uvScaleMap = material.specularMap; + te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; + te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; + te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; - } else if ( material.normalMap ) { + return this; - uvScaleMap = material.normalMap; + }; - } else if ( material.bumpMap ) { + }(), - uvScaleMap = material.bumpMap; + multiply: function ( m, n ) { - } else if ( material.alphaMap ) { + if ( n !== undefined ) { - uvScaleMap = material.alphaMap; + THREE.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); } - if ( uvScaleMap !== undefined ) { + return this.multiplyMatrices( this, m ); - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + }, - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + multiplyMatrices: function ( a, b ) { - } + var ae = a.elements; + var be = b.elements; + var te = this.elements; - uniforms.envMap.value = material.envMap; - uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1; + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - } + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - function refreshUniformsLine ( uniforms, material ) { + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - } + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - function refreshUniformsDash ( uniforms, material ) { + return this; - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + }, - } + multiplyToArray: function ( a, b, r ) { - function refreshUniformsParticle ( uniforms, material ) { + var te = this.elements; - uniforms.psColor.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size; - uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. + this.multiplyMatrices( a, b ); - uniforms.map.value = material.map; + r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; + r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; + r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; + r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; - if ( material.map !== null ) { + return this; - var offset = material.map.offset; - var repeat = material.map.repeat; + }, - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + multiplyScalar: function ( s ) { - } + var te = this.elements; - } + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - function refreshUniformsFog ( uniforms, fog ) { + return this; - uniforms.fogColor.value = fog.color; + }, - if ( fog instanceof THREE.Fog ) { + multiplyVector3: function ( vector ) { - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + THREE.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); + return vector.applyProjection( this ); - } else if ( fog instanceof THREE.FogExp2 ) { + }, - uniforms.fogDensity.value = fog.density; + multiplyVector4: function ( vector ) { - } + THREE.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); - } + }, - function refreshUniformsPhong ( uniforms, material ) { + multiplyVector3Array: function ( a ) { - uniforms.shininess.value = material.shininess; + THREE.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); - uniforms.emissive.value = material.emissive; - uniforms.specular.value = material.specular; + }, - if ( material.wrapAround ) { + applyToVector3Array: function () { - uniforms.wrapRGB.value.copy( material.wrapRGB ); + var v1 = new THREE.Vector3(); - } + return function ( array, offset, length ) { - } + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - function refreshUniformsLambert ( uniforms, material ) { + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - uniforms.emissive.value = material.emissive; + v1.x = array[ j ]; + v1.y = array[ j + 1 ]; + v1.z = array[ j + 2 ]; - if ( material.wrapAround ) { + v1.applyMatrix4( this ); - uniforms.wrapRGB.value.copy( material.wrapRGB ); + array[ j ] = v1.x; + array[ j + 1 ] = v1.y; + array[ j + 2 ] = v1.z; - } + } - } + return array; - function refreshUniformsLights ( uniforms, lights ) { + }; - uniforms.ambientLightColor.value = lights.ambient; + }(), - uniforms.directionalLightColor.value = lights.directional.colors; - uniforms.directionalLightDirection.value = lights.directional.positions; + rotateAxis: function ( v ) { - uniforms.pointLightColor.value = lights.point.colors; - uniforms.pointLightPosition.value = lights.point.positions; - uniforms.pointLightDistance.value = lights.point.distances; - uniforms.pointLightDecay.value = lights.point.decays; + THREE.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - uniforms.spotLightColor.value = lights.spot.colors; - uniforms.spotLightPosition.value = lights.spot.positions; - uniforms.spotLightDistance.value = lights.spot.distances; - uniforms.spotLightDirection.value = lights.spot.directions; - uniforms.spotLightAngleCos.value = lights.spot.anglesCos; - uniforms.spotLightExponent.value = lights.spot.exponents; - uniforms.spotLightDecay.value = lights.spot.decays; + v.transformDirection( this ); - uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; - uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; - uniforms.hemisphereLightDirection.value = lights.hemi.positions; + }, - } + crossVector: function ( vector ) { - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + THREE.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); - function markUniformsLightsNeedsUpdate ( uniforms, value ) { + }, - uniforms.ambientLightColor.needsUpdate = value; + determinant: function () { - uniforms.directionalLightColor.needsUpdate = value; - uniforms.directionalLightDirection.needsUpdate = value; + var te = this.elements; - uniforms.pointLightColor.needsUpdate = value; - uniforms.pointLightPosition.needsUpdate = value; - uniforms.pointLightDistance.needsUpdate = value; - uniforms.pointLightDecay.needsUpdate = value; + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - uniforms.spotLightColor.needsUpdate = value; - uniforms.spotLightPosition.needsUpdate = value; - uniforms.spotLightDistance.needsUpdate = value; - uniforms.spotLightDirection.needsUpdate = value; - uniforms.spotLightAngleCos.needsUpdate = value; - uniforms.spotLightExponent.needsUpdate = value; - uniforms.spotLightDecay.needsUpdate = value; + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - uniforms.hemisphereLightSkyColor.needsUpdate = value; - uniforms.hemisphereLightGroundColor.needsUpdate = value; - uniforms.hemisphereLightDirection.needsUpdate = value; + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) - } + ); - function refreshUniformsShadow ( uniforms, lights ) { + }, - if ( uniforms.shadowMatrix ) { + transpose: function () { - var j = 0; + var te = this.elements; + var tmp; - for ( var i = 0, il = lights.length; i < il; i ++ ) { + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - var light = lights[ i ]; + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - if ( ! light.castShadow ) continue; + return this; - if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { + }, - uniforms.shadowMap.value[ j ] = light.shadowMap; - uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; + flattenToArrayOffset: function ( array, offset ) { - uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; + var te = this.elements; - uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; - uniforms.shadowBias.value[ j ] = light.shadowBias; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - j ++; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - } + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - } + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - } + return array; - } + }, - // Uniforms (load to GPU) + getPosition: function () { - function loadUniformsMatrices ( uniforms, object ) { + var v1 = new THREE.Vector3(); - _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); + return function () { - if ( uniforms.normalMatrix ) { + THREE.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); + var te = this.elements; + return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] ); - } + }; - } + }(), - function getTextureUnit() { + setPosition: function ( v ) { - var textureUnit = _usedTextureUnits; + var te = this.elements; - if ( textureUnit >= _maxTextures ) { + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - THREE.warn( 'Canvas3DRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures ); + return this; - } + }, - _usedTextureUnits += 1; + getInverse: function ( m, throwOnInvertible ) { - return textureUnit; + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements; + var me = m.elements; - } + var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ]; + var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ]; + var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ]; + var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ]; - function loadUniformsGeneric ( uniforms ) { + te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; + te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; + te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; + te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44; + te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44; + te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44; + te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34; + te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44; + te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44; + te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44; + te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34; + te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43; + te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43; + te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43; + te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33; - var texture, textureUnit, offset; + var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; - for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) { + if ( det == 0 ) { - var uniform = uniforms[ j ][ 0 ]; + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - // needsUpdate property is not added to all uniforms. - if ( uniform.needsUpdate === false ) continue; + if ( throwOnInvertible || false ) { - var type = uniform.type; - var value = uniform.value; - var location = uniforms[ j ][ 1 ]; + throw new Error( msg ); - switch ( type ) { + } else { - case '1i': - _gl.uniform1i( location, value ); - break; + THREE.warn( msg ); - case '1f': - _gl.uniform1f( location, value ); - break; + } - case '2f': - _gl.uniform2f( location, value[ 0 ], value[ 1 ] ); - break; + this.identity(); - case '3f': - _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] ); - break; + return this; + } - case '4f': - _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] ); - break; + this.multiplyScalar( 1 / det ); - case '1iv': - _gl.uniform1iv( location, value ); - break; + return this; - case '3iv': - _gl.uniform3iv( location, value ); - break; + }, - case '1fv': - _gl.uniform1fv( location, value ); - break; + translate: function ( v ) { - case '2fv': - _gl.uniform2fv( location, value ); - break; + THREE.error( 'THREE.Matrix4: .translate() has been removed.' ); - case '3fv': - _gl.uniform3fv( location, value ); - break; + }, - case '4fv': - _gl.uniform4fv( location, value ); - break; + rotateX: function ( angle ) { - case 'Matrix3fv': - _gl.uniformMatrix3fv( location, false, value ); - break; + THREE.error( 'THREE.Matrix4: .rotateX() has been removed.' ); - case 'Matrix4fv': - _gl.uniformMatrix4fv( location, false, value ); - break; + }, - // + rotateY: function ( angle ) { - case 'i': + THREE.error( 'THREE.Matrix4: .rotateY() has been removed.' ); - // single integer - _gl.uniform1i( location, value ); + }, - break; + rotateZ: function ( angle ) { - case 'f': + THREE.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); - // single float - _gl.uniform1f( location, value ); + }, - break; + rotateByAxis: function ( axis, angle ) { - case 'v2': + THREE.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); - // single THREE.Vector2 - _gl.uniform2f( location, value.x, value.y ); + }, - break; + scale: function ( v ) { - case 'v3': + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - // single THREE.Vector3 - _gl.uniform3f( location, value.x, value.y, value.z ); + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - break; + return this; - case 'v4': + }, - // single THREE.Vector4 - _gl.uniform4f( location, value.x, value.y, value.z, value.w ); + getMaxScaleOnAxis: function () { - break; + var te = this.elements; - case 'c': + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - // single THREE.Color - _gl.uniform3f( location, value.r, value.g, value.b ); + return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) ); - break; + }, - case 'iv1': + makeTranslation: function ( x, y, z ) { - // flat array of integers (JS or typed array) - _gl.uniform1iv( location, value ); + this.set( - break; + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - case 'iv': + ); - // flat array of integers with 3 x N size (JS or typed array) - _gl.uniform3iv( location, value ); + return this; - break; + }, - case 'fv1': + makeRotationX: function ( theta ) { - // flat array of floats (JS or typed array) - _gl.uniform1fv( location, value ); + var c = Math.cos( theta ), s = Math.sin( theta ); - break; + this.set( - case 'fv': + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - // flat array of floats with 3 x N size (JS or typed array) - _gl.uniform3fv( location, value ); + ); - break; + return this; - case 'v2v': + }, - // array of THREE.Vector2 + makeRotationY: function ( theta ) { - if ( uniform._array === undefined ) { + var c = Math.cos( theta ), s = Math.sin( theta ); - uniform._array = new Float32Array( 2 * value.length ); + this.set( - } + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - for ( var i = 0, il = value.length; i < il; i ++ ) { + ); - offset = i * 2; + return this; - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; + }, - } + makeRotationZ: function ( theta ) { - _gl.uniform2fv( location, uniform._array ); + var c = Math.cos( theta ), s = Math.sin( theta ); - break; + this.set( - case 'v3v': + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - // array of THREE.Vector3 + ); - if ( uniform._array === undefined ) { + return this; - uniform._array = new Float32Array( 3 * value.length ); + }, - } + makeRotationAxis: function ( axis, angle ) { - for ( var i = 0, il = value.length; i < il; i ++ ) { + // Based on http://www.gamedev.net/reference/articles/article1199.asp - offset = i * 3; + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; + this.set( - } + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - _gl.uniform3fv( location, uniform._array ); + ); - break; + return this; - case 'v4v': + }, - // array of THREE.Vector4 + makeScale: function ( x, y, z ) { - if ( uniform._array === undefined ) { + this.set( - uniform._array = new Float32Array( 4 * value.length ); + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - } + ); - for ( var i = 0, il = value.length; i < il; i ++ ) { + return this; - offset = i * 4; + }, - uniform._array[ offset ] = value[ i ].x; - uniform._array[ offset + 1 ] = value[ i ].y; - uniform._array[ offset + 2 ] = value[ i ].z; - uniform._array[ offset + 3 ] = value[ i ].w; + compose: function ( position, quaternion, scale ) { - } + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - _gl.uniform4fv( location, uniform._array ); + return this; - break; + }, - case 'm3': + decompose: function () { - // single THREE.Matrix3 - _gl.uniformMatrix3fv( location, false, value.elements ); + var vector = new THREE.Vector3(); + var matrix = new THREE.Matrix4(); - break; + return function ( position, quaternion, scale ) { - case 'm3v': + var te = this.elements; - // array of THREE.Matrix3 + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - if ( uniform._array === undefined ) { + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) { + sx = - sx; + } - uniform._array = new Float32Array( 9 * value.length ); + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - } + // scale the rotation part - for ( var i = 0, il = value.length; i < il; i ++ ) { + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - value[ i ].flattenToArrayOffset( uniform._array, i * 9 ); + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - } + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - _gl.uniformMatrix3fv( location, false, uniform._array ); + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - break; + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - case 'm4': + quaternion.setFromRotationMatrix( matrix ); - // single THREE.Matrix4 - _gl.uniformMatrix4fv( location, false, value.elements ); + scale.x = sx; + scale.y = sy; + scale.z = sz; - break; + return this; - case 'm4v': + }; - // array of THREE.Matrix4 + }(), - if ( uniform._array === undefined ) { + makeFrustum: function ( left, right, bottom, top, near, far ) { - uniform._array = new Float32Array( 16 * value.length ); + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - } + var a = ( right + left ) / ( right - left ); + var b = ( top + bottom ) / ( top - bottom ); + var c = - ( far + near ) / ( far - near ); + var d = - 2 * far * near / ( far - near ); - for ( var i = 0, il = value.length; i < il; i ++ ) { + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); + return this; - } + }, - _gl.uniformMatrix4fv( location, false, uniform._array ); + makePerspective: function ( fov, aspect, near, far ) { - break; + var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - case 't': + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - // single THREE.Texture (2d or cube) + }, - texture = value; - textureUnit = getTextureUnit(); + makeOrthographic: function ( left, right, top, bottom, near, far ) { - _gl.uniform1i( location, textureUnit ); + var te = this.elements; + var w = right - left; + var h = top - bottom; + var p = far - near; - if ( ! texture ) continue; + var x = ( right + left ) / w; + var y = ( top + bottom ) / h; + var z = ( far + near ) / p; - if ( texture instanceof THREE.CubeTexture || - ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ + te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - setCubeTexture( texture, textureUnit ); + return this; - } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { + }, - setCubeTextureDynamic( texture, textureUnit ); + fromArray: function ( array ) { - } else { + this.elements.set( array ); - _this.setTexture( texture, textureUnit ); + return this; - } + }, - break; + toArray: function () { - case 'tv': + var te = this.elements; - // array of THREE.Texture (2d) + return [ + te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ], + te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ], + te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ], + te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ] + ]; - if ( uniform._array === undefined ) { + }, - uniform._array = []; + clone: function () { - } + return new THREE.Matrix4().fromArray( this.elements ); - for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { + } - uniform._array[ i ] = getTextureUnit(); +}; - } +// File:src/math/Ray.js - _gl.uniform1iv( location, uniform._array ); +/** + * @author bhouston / http://exocortex.com + */ - for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { +THREE.Ray = function ( origin, direction ) { - texture = uniform.value[ i ]; - textureUnit = uniform._array[ i ]; + this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); + this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); - if ( ! texture ) continue; +}; - _this.setTexture( texture, textureUnit ); +THREE.Ray.prototype = { - } + constructor: THREE.Ray, - break; + set: function ( origin, direction ) { - default: + this.origin.copy( origin ); + this.direction.copy( direction ); - THREE.warn( 'THREE.Canvas3DRenderer: Unknown uniform type: ' + type ); + return this; - } + }, - } + copy: function ( ray ) { - } + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - function setupMatrices ( object, camera ) { + return this; - object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); + }, - } + at: function ( t, optionalTarget ) { - function setColorLinear( array, offset, color, intensity ) { + var result = optionalTarget || new THREE.Vector3(); - array[ offset ] = color.r * intensity; - array[ offset + 1 ] = color.g * intensity; - array[ offset + 2 ] = color.b * intensity; + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - } + }, - function setupLights ( lights ) { + recast: function () { - var l, ll, light, - r = 0, g = 0, b = 0, - color, skyColor, groundColor, - intensity, - distance, + var v1 = new THREE.Vector3(); - zlights = _lights, + return function ( t ) { - dirColors = zlights.directional.colors, - dirPositions = zlights.directional.positions, + this.origin.copy( this.at( t, v1 ) ); - pointColors = zlights.point.colors, - pointPositions = zlights.point.positions, - pointDistances = zlights.point.distances, - pointDecays = zlights.point.decays, + return this; - spotColors = zlights.spot.colors, - spotPositions = zlights.spot.positions, - spotDistances = zlights.spot.distances, - spotDirections = zlights.spot.directions, - spotAnglesCos = zlights.spot.anglesCos, - spotExponents = zlights.spot.exponents, - spotDecays = zlights.spot.decays, + }; - hemiSkyColors = zlights.hemi.skyColors, - hemiGroundColors = zlights.hemi.groundColors, - hemiPositions = zlights.hemi.positions, + }(), - dirLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0, + closestPointToPoint: function ( point, optionalTarget ) { - dirCount = 0, - pointCount = 0, - spotCount = 0, - hemiCount = 0, + var result = optionalTarget || new THREE.Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); - dirOffset = 0, - pointOffset = 0, - spotOffset = 0, - hemiOffset = 0; + if ( directionDistance < 0 ) { - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + return result.copy( this.origin ); - light = lights[ l ]; + } - if ( light.onlyShadow ) continue; + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - color = light.color; - intensity = light.intensity; - distance = light.distance; + }, - if ( light instanceof THREE.AmbientLight ) { + distanceToPoint: function () { - if ( ! light.visible ) continue; + var v1 = new THREE.Vector3(); - r += color.r; - g += color.g; - b += color.b; + return function ( point ) { - } else if ( light instanceof THREE.DirectionalLight ) { + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - dirCount += 1; + // point behind the ray - if ( ! light.visible ) continue; + if ( directionDistance < 0 ) { - _direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); + return this.origin.distanceTo( point ); - dirOffset = dirLength * 3; + } - dirPositions[ dirOffset ] = _direction.x; - dirPositions[ dirOffset + 1 ] = _direction.y; - dirPositions[ dirOffset + 2 ] = _direction.z; + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - setColorLinear( dirColors, dirOffset, color, intensity ); + return v1.distanceTo( point ); - dirLength += 1; + }; - } else if ( light instanceof THREE.PointLight ) { + }(), - pointCount += 1; + distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - if ( ! light.visible ) continue; + // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment - pointOffset = pointLength * 3; +// return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - setColorLinear( pointColors, pointOffset, color, intensity ); + var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 ); + var segDir = v1.clone().sub( v0 ).normalize(); + var segExtent = v0.distanceTo( v1 ) * 0.5; + var diff = this.origin.clone().sub( segCenter ); + var a01 = - this.direction.dot( segDir ); + var b0 = diff.dot( this.direction ); + var b1 = - diff.dot( segDir ); + var c = diff.lengthSq(); + var det = Math.abs( 1 - a01 * a01 ); + var s0, s1, sqrDist, extDet; - _vector3.setFromMatrixPosition( light.matrixWorld ); + if ( det >= 0 ) { - pointPositions[ pointOffset ] = _vector3.x; - pointPositions[ pointOffset + 1 ] = _vector3.y; - pointPositions[ pointOffset + 2 ] = _vector3.z; + // The ray and segment are not parallel. - // distance is 0 if decay is 0, because there is no attenuation at all. - pointDistances[ pointLength ] = distance; - pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - pointLength += 1; + if ( s0 >= 0 ) { - } else if ( light instanceof THREE.SpotLight ) { + if ( s1 >= - extDet ) { - spotCount += 1; + if ( s1 <= extDet ) { - if ( ! light.visible ) continue; + // region 0 + // Minimum at interior points of ray and segment. - spotOffset = spotLength * 3; + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - setColorLinear( spotColors, spotOffset, color, intensity ); + } else { - _direction.setFromMatrixPosition( light.matrixWorld ); + // region 1 - spotPositions[ spotOffset ] = _direction.x; - spotPositions[ spotOffset + 1 ] = _direction.y; - spotPositions[ spotOffset + 2 ] = _direction.z; + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - spotDistances[ spotLength ] = distance; + } - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - _direction.sub( _vector3 ); - _direction.normalize(); + } else { - spotDirections[ spotOffset ] = _direction.x; - spotDirections[ spotOffset + 1 ] = _direction.y; - spotDirections[ spotOffset + 2 ] = _direction.z; + // region 5 - spotAnglesCos[ spotLength ] = Math.cos( light.angle ); - spotExponents[ spotLength ] = light.exponent; - spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay; + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - spotLength += 1; + } - } else if ( light instanceof THREE.HemisphereLight ) { + } else { - hemiCount += 1; + if ( s1 <= - extDet ) { - if ( ! light.visible ) continue; + // region 4 - _direction.setFromMatrixPosition( light.matrixWorld ); - _direction.normalize(); + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - hemiOffset = hemiLength * 3; + } else if ( s1 <= extDet ) { - hemiPositions[ hemiOffset ] = _direction.x; - hemiPositions[ hemiOffset + 1 ] = _direction.y; - hemiPositions[ hemiOffset + 2 ] = _direction.z; + // region 3 - skyColor = light.color; - groundColor = light.groundColor; + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); - setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); + } else { - hemiLength += 1; + // region 2 - } + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } + } - // null eventual remains from removed lights - // (this is to avoid if in shader) + } - for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; - for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; - for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; - for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; + } else { - zlights.directional.length = dirLength; - zlights.point.length = pointLength; - zlights.spot.length = spotLength; - zlights.hemi.length = hemiLength; + // Ray and segment are parallel. - zlights.ambient[ 0 ] = r; - zlights.ambient[ 1 ] = g; - zlights.ambient[ 2 ] = b; + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } + } - // GL state setting + if ( optionalPointOnRay ) { - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) ); - if ( cullFace === THREE.CullFaceNone ) { + } - _gl.disable( _gl.CULL_FACE ); + if ( optionalPointOnSegment ) { - } else { + optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) ); - if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { + } - _gl.frontFace( _gl.CW ); + return sqrDist; - } else { - - _gl.frontFace( _gl.CCW ); + }, - } + isIntersectionSphere: function ( sphere ) { - if ( cullFace === THREE.CullFaceBack ) { + return this.distanceToPoint( sphere.center ) <= sphere.radius; - _gl.cullFace( _gl.BACK ); + }, - } else if ( cullFace === THREE.CullFaceFront ) { + intersectSphere: function () { - _gl.cullFace( _gl.FRONT ); + // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/ - } else { + var v1 = new THREE.Vector3(); - _gl.cullFace( _gl.FRONT_AND_BACK ); + return function ( sphere, optionalTarget ) { - } + v1.subVectors( sphere.center, this.origin ); - _gl.enable( _gl.CULL_FACE ); + var tca = v1.dot( this.direction ); - } + var d2 = v1.dot( v1 ) - tca * tca; - }; + var radius2 = sphere.radius * sphere.radius; - this.setMaterialFaces = function ( material ) { + if ( d2 > radius2 ) return null; - state.setDoubleSided( material.side === THREE.DoubleSide ); - state.setFlipSided( material.side === THREE.BackSide ); + var thc = Math.sqrt( radius2 - d2 ); - }; + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - // Textures + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - var extension; + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, optionalTarget ); - if ( isImagePowerOfTwo ) { + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + } - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + }(), - } else { + isIntersectionPlane: function ( plane ) { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + // check if the ray lies on the plane first - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + var distToPoint = plane.distanceToPoint( this.origin ); - THREE.warn( 'THREE.Canvas3DRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' ); + if ( distToPoint === 0 ) { - } + return true; - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + } - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) { + var denominator = plane.normal.dot( this.direction ); - THREE.warn( 'THREE.Canvas3DRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' ); + if ( denominator * distToPoint < 0 ) { - } + return true; } - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - - if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) { - - if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) { - - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) ); - texture.__currentAnisotropy = texture.anisotropy; + // ray origin is behind the plane (and is pointing behind it) - } + return false; - } + }, - } + distanceToPlane: function ( plane ) { - this.uploadTexture = function ( texture ) { + var denominator = plane.normal.dot( this.direction ); + if ( denominator == 0 ) { - if ( texture.__webglInit === undefined ) { + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) == 0 ) { - texture.__webglInit = true; + return 0; - texture.addEventListener( 'dispose', onTextureDispose ); + } - texture.__webglTexture = _gl.createTexture(); + // Null is preferable to undefined since undefined means.... it is undefined - _this.info.memory.textures ++; + return null; } - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + // Return if the ray never intersects the plane - texture.image = clampToMaxSize( texture.image, _maxTextureSize ); + return t >= 0 ? t : null; - var image = texture.image, - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + }, - setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); + intersectPlane: function ( plane, optionalTarget ) { - var mipmap, mipmaps = texture.mipmaps; + var t = this.distanceToPlane( plane ); - if ( texture instanceof THREE.DataTexture ) { + if ( t === null ) { - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + return null; + } - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { + return this.at( t, optionalTarget ); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + }, - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + isIntersectionBox: function () { - } + var v = new THREE.Vector3(); - texture.generateMipmaps = false; + return function ( box ) { - } else { + return this.intersectBox( box, v ) !== null; - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + }; - } + }(), - } else if ( texture instanceof THREE.CompressedTexture ) { + intersectBox: function ( box, optionalTarget ) { - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/ - mipmap = mipmaps[ i ]; + var tmin,tmax,tymin,tymax,tzmin,tzmax; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) { + var origin = this.origin; - _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + if ( invdirx >= 0 ) { - } else { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - THREE.warn( "THREE.Canvas3DRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + } else { - } + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + } - } else { + if ( invdiry >= 0 ) { - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - } + } else { - } + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; + } - } else { // regular Texture (image, video, canvas) + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - if ( mipmaps.length > 0 && isImagePowerOfTwo ) { + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - mipmap = mipmaps[ i ]; - _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + if ( invdirz >= 0 ) { - } + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - texture.generateMipmaps = false; + } else { - } else { + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + } - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image.texImage() ); + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - } + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - } + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + //return point closest to the ray (positive side) - texture.needsUpdate = false; + if ( tmax < 0 ) return null; - if ( texture.onUpdate ) texture.onUpdate(); + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - }; + }, - this.setTexture = function ( texture, slot ) { + intersectTriangle: function () { - _gl.activeTexture( _gl.TEXTURE0 + slot ); + // Compute the offset origin, edges, and normal. + var diff = new THREE.Vector3(); + var edge1 = new THREE.Vector3(); + var edge2 = new THREE.Vector3(); + var normal = new THREE.Vector3(); - if ( texture.needsUpdate ) { + return function ( a, b, c, backfaceCulling, optionalTarget ) { - _this.uploadTexture( texture ); + // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp - } else { + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + var DdN = this.direction.dot( normal ); + var sign; - } + if ( DdN > 0 ) { - }; + if ( backfaceCulling ) return null; + sign = 1; - function clampToMaxSize ( image, maxSize ) { + } else if ( DdN < 0 ) { - if ( image.width > maxSize || image.height > maxSize ) { + sign = - 1; + DdN = - DdN; - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + } else { - var scale = maxSize / Math.max( image.width, image.height ); + return null; - var canvasWidth = Math.floor( image.width * scale ); - var canvasHeight = Math.floor( image.height * scale ); - var canvas = image.resize( canvasWidth, canvasHeight ); + } + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - THREE.warn( 'THREE.Canvas3DRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvasWidth + 'x' + canvasHeight, image ); + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - return canvas; + return null; - } + } - return image; + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - } + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - function setCubeTexture ( texture, slot ) { + return null; - if ( texture.image.length === 6 ) { + } - if ( texture.needsUpdate ) { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - if ( ! texture.image.__webglTextureCube ) { + return null; - texture.addEventListener( 'dispose', onTextureDispose ); + } - texture.image.__webglTextureCube = _gl.createTexture(); + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - _this.info.memory.textures ++; + // t < 0, no intersection + if ( QdN < 0 ) { - } + return null; - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); + } - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - var isCompressed = texture instanceof THREE.CompressedTexture; - var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; + }; - var cubeImage = []; + }(), - for ( var i = 0; i < 6; i ++ ) { + applyMatrix4: function ( matrix4 ) { - if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) { + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); + return this; + }, - } else { + equals: function ( ray ) { - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - } + }, - } + clone: function () { - var image = cubeImage[ 0 ], - isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + return new THREE.Ray().copy( this ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); + } - for ( var i = 0; i < 6; i ++ ) { +}; - if ( ! isCompressed ) { +// File:src/math/Sphere.js - if ( isDataTexture ) { +/** + * @author bhouston / http://exocortex.com + * @author mrdoob / http://mrdoob.com/ + */ - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); +THREE.Sphere = function ( center, radius ) { - } else { + this.center = ( center !== undefined ) ? center : new THREE.Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ].texImage() ); +}; - } +THREE.Sphere.prototype = { - } else { + constructor: THREE.Sphere, - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + set: function ( center, radius ) { - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + this.center.copy( center ); + this.radius = radius; - mipmap = mipmaps[ j ]; + return this; + }, - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + setFromPoints: function () { - if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) { + var box = new THREE.Box3(); - _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + return function ( points, optionalCenter ) { - } else { + var center = this.center; - THREE.warn( "THREE.Canvas3DRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" ); + if ( optionalCenter !== undefined ) { - } + center.copy( optionalCenter ); - } else { + } else { - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + box.setFromPoints( points ).center( center ); - } + } - } + var maxRadiusSq = 0; - } + for ( var i = 0, il = points.length; i < il; i ++ ) { - } + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - if ( texture.generateMipmaps && isImagePowerOfTwo ) { + } - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + this.radius = Math.sqrt( maxRadiusSq ); - } + return this; - texture.needsUpdate = false; + }; - if ( texture.onUpdate ) texture.onUpdate(); + }(), - } else { + copy: function ( sphere ) { - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); + this.center.copy( sphere.center ); + this.radius = sphere.radius; - } + return this; - } + }, - } + empty: function () { - function setCubeTextureDynamic ( texture, slot ) { + return ( this.radius <= 0 ); - _gl.activeTexture( _gl.TEXTURE0 + slot ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); + }, - } + containsPoint: function ( point ) { - // Render targets + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { + }, - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); + distanceToPoint: function ( point ) { - } + return ( point.distanceTo( this.center ) - this.radius ); - function setupRenderBuffer ( renderbuffer, renderTarget ) { + }, - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + intersectsSphere: function ( sphere ) { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + var radiusSum = this.radius + sphere.radius; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - /* For some reason this is not working. Defaulting to RGBA4. - } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + }, - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - */ - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + clampPoint: function ( point, optionalTarget ) { - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + var deltaLengthSq = this.center.distanceToSquared( point ); - } else { + var result = optionalTarget || new THREE.Vector3(); + result.copy( point ); - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); } - } + return result; - this.setRenderTarget = function ( renderTarget ) { + }, - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + getBoundingBox: function ( optionalTarget ) { - if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) { + var box = optionalTarget || new THREE.Box3(); - if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; - if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + return box; - renderTarget.__webglTexture = _gl.createTexture(); + }, - _this.info.memory.textures ++; + applyMatrix4: function ( matrix ) { - // Setup texture, create render and frame buffers + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); - var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), - glFormat = paramThreeToGL( renderTarget.format ), - glType = paramThreeToGL( renderTarget.type ); + return this; - if ( isCube ) { + }, - renderTarget.__webglFramebuffer = []; - renderTarget.__webglRenderbuffer = []; + translate: function ( offset ) { - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); + this.center.add( offset ); - for ( var i = 0; i < 6; i ++ ) { + return this; - renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); + }, - _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + equals: function ( sphere ) { - setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - } + }, - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + clone: function () { - } else { + return new THREE.Sphere().copy( this ); - renderTarget.__webglFramebuffer = _gl.createFramebuffer(); + } - if ( renderTarget.shareDepthFrom ) { +}; - renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; +// File:src/math/Frustum.js - } else { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://exocortex.com + */ - renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); +THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { - } + this.planes = [ - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); + ( p0 !== undefined ) ? p0 : new THREE.Plane(), + ( p1 !== undefined ) ? p1 : new THREE.Plane(), + ( p2 !== undefined ) ? p2 : new THREE.Plane(), + ( p3 !== undefined ) ? p3 : new THREE.Plane(), + ( p4 !== undefined ) ? p4 : new THREE.Plane(), + ( p5 !== undefined ) ? p5 : new THREE.Plane() - _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + ]; - setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); +}; - if ( renderTarget.shareDepthFrom ) { +THREE.Frustum.prototype = { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + constructor: THREE.Frustum, - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); + set: function ( p0, p1, p2, p3, p4, p5 ) { - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + var planes = this.planes; - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - } + return this; - } else { + }, - setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); + copy: function ( frustum ) { - } + var planes = this.planes; - if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + for ( var i = 0; i < 6; i ++ ) { - } + planes[ i ].copy( frustum.planes[ i ] ); - // Release everything + } - if ( isCube ) { + return this; - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + }, - } else { + setFromMatrix: function ( m ) { - _gl.bindTexture( _gl.TEXTURE_2D, null ); - - } + var planes = this.planes; + var me = m.elements; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + 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 ]; - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - } + return this; - var framebuffer, width, height, vx, vy; + }, - if ( renderTarget ) { + intersectsObject: function () { - if ( isCube ) { + var sphere = new THREE.Sphere(); - framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; + return function ( object ) { - } else { + var geometry = object.geometry; - framebuffer = renderTarget.__webglFramebuffer; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - } + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( object.matrixWorld ); - width = renderTarget.width; - height = renderTarget.height; + return this.intersectsSphere( sphere ); - vx = 0; - vy = 0; + }; - } else { + }(), - framebuffer = null; + intersectsSphere: function ( sphere ) { - width = _viewportWidth; - height = _viewportHeight; + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - vx = _viewportX; - vy = _viewportY; + for ( var i = 0; i < 6; i ++ ) { - } + var distance = planes[ i ].distanceToPoint( center ); - if ( framebuffer !== _currentFramebuffer ) { + if ( distance < negRadius ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.viewport( vx, vy, width, height ); + return false; - _currentFramebuffer = framebuffer; + } } - _currentWidth = width; - _currentHeight = height; - - }; + return true; - this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) { + }, - if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) { + intersectsBox: function () { - console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + var p1 = new THREE.Vector3(), + p2 = new THREE.Vector3(); - } + return function ( box ) { - if ( renderTarget.__webglFramebuffer ) { + var planes = this.planes; - if ( renderTarget.format !== THREE.RGBAFormat ) { + for ( var i = 0; i < 6 ; i ++ ) { - console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' ); - return; + var plane = planes[ i ]; - } + p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; + p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; + p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; + p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; + p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; + p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; - var restore = false; + var d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); - if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) { + // if both outside plane, no intersection - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer ); + if ( d1 < 0 && d2 < 0 ) { - restore = true; + return false; + } } - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + return true; + }; - _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer ); + }(), - } else { - console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + containsPoint: function ( point ) { - } + var planes = this.planes; - if ( restore ) { + for ( var i = 0; i < 6; i ++ ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; } } - }; + return true; - function updateRenderTargetMipmap ( renderTarget ) { + }, - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + clone: function () { - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + return new THREE.Frustum().copy( this ); - } else { + } - _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); - _gl.generateMipmap( _gl.TEXTURE_2D ); - _gl.bindTexture( _gl.TEXTURE_2D, null ); +}; - } +// File:src/math/Plane.js - } +/** + * @author bhouston / http://exocortex.com + */ - // Fallback filters for non-power-of-2 textures +THREE.Plane = function ( normal, constant ) { - function filterFallback ( f ) { + this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { +}; - return _gl.NEAREST; +THREE.Plane.prototype = { - } + constructor: THREE.Plane, - return _gl.LINEAR; + set: function ( normal, constant ) { - } + this.normal.copy( normal ); + this.constant = constant; - // Map three.js constants to WebGL constants + return this; - function paramThreeToGL ( p ) { + }, - var extension; + setComponents: function ( x, y, z, w ) { - if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; - if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + this.normal.set( x, y, z ); + this.constant = w; - if ( p === THREE.NearestFilter ) return _gl.NEAREST; - if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + return this; - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + }, - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + setFromNormalAndCoplanarPoint: function ( normal, point ) { - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized - extension = extensions.get( 'OES_texture_half_float' ); + return this; - if ( extension !== null ) { + }, - if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; + setFromCoplanarPoints: function () { - } + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + return function ( a, b, c ) { - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + this.setFromNormalAndCoplanarPoint( normal, a ); - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + return this; - if ( extension !== null ) { + }; - if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + }(), - } - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + copy: function ( plane ) { - if ( extension !== null ) { + this.normal.copy( plane.normal ); + this.constant = plane.constant; - if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + return this; - } + }, - extension = extensions.get( 'EXT_blend_minmax' ); + normalize: function () { - if ( extension !== null ) { + // Note: will lead to a divide by zero if the plane is invalid. - if ( p === THREE.MinEquation ) return extension.MIN_EXT; - if ( p === THREE.MaxEquation ) return extension.MAX_EXT; + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - } + return this; - return 0; + }, - } + negate: function () { - // Allocations + this.constant *= - 1; + this.normal.negate(); - function allocateBones ( object ) { + return this; - if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { + }, - return 1024; + distanceToPoint: function ( point ) { - } else { + return this.normal.dot( point ) + this.constant; - // default for when object is not specified - // ( for example when prebuilding shader - // to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) + }, - var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + distanceToSphere: function ( sphere ) { - var maxBones = nVertexMatrices; + return this.distanceToPoint( sphere.center ) - sphere.radius; - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + }, - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + projectPoint: function ( point, optionalTarget ) { - if ( maxBones < object.skeleton.bones.length ) { + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - THREE.warn( 'Canvas3DRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); + }, - } + orthoPoint: function ( point, optionalTarget ) { - } + var perpendicularMagnitude = this.distanceToPoint( point ); - return maxBones; + var result = optionalTarget || new THREE.Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - } + }, - } + isIntersectionLine: function ( line ) { - function allocateLights( lights ) { + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - var dirLights = 0; - var pointLights = 0; - var spotLights = 0; - var hemiLights = 0; + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - for ( var l = 0, ll = lights.length; l < ll; l ++ ) { + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - var light = lights[ l ]; + }, - if ( light.onlyShadow || light.visible === false ) continue; + intersectLine: function () { - if ( light instanceof THREE.DirectionalLight ) dirLights ++; - if ( light instanceof THREE.PointLight ) pointLights ++; - if ( light instanceof THREE.SpotLight ) spotLights ++; - if ( light instanceof THREE.HemisphereLight ) hemiLights ++; + var v1 = new THREE.Vector3(); - } + return function ( line, optionalTarget ) { - return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights }; + var result = optionalTarget || new THREE.Vector3(); - } + var direction = line.delta( v1 ); - function allocateShadows( lights ) { + var denominator = this.normal.dot( direction ); - var maxShadows = 0; + if ( denominator == 0 ) { - for ( var l = 0, ll = lights.length; l < ll; l ++ ) { + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) == 0 ) { - var light = lights[ l ]; + return result.copy( line.start ); - if ( ! light.castShadow ) continue; + } - if ( light instanceof THREE.SpotLight ) maxShadows ++; - if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; + // Unsure if this is the correct method to handle this case. + return undefined; - } + } - return maxShadows; + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - } + if ( t < 0 || t > 1 ) { - // DEPRECATED + return undefined; - this.initMaterial = function () { + } - THREE.warn( 'THREE.Canvas3DRenderer: .initMaterial() has been removed.' ); + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - }; + }; - this.addPrePlugin = function () { + }(), - THREE.warn( 'THREE.Canvas3DRenderer: .addPrePlugin() has been removed.' ); - }; + coplanarPoint: function ( optionalTarget ) { - this.addPostPlugin = function () { + var result = optionalTarget || new THREE.Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); - THREE.warn( 'THREE.Canvas3DRenderer: .addPostPlugin() has been removed.' ); + }, - }; + applyMatrix4: function () { - this.updateShadowMap = function () { + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); + var m1 = new THREE.Matrix3(); - THREE.warn( 'THREE.Canvas3DRenderer: .updateShadowMap() has been removed.' ); + return function ( matrix, optionalNormalMatrix ) { - }; + // compute new normal based on theory here: + // http://www.songho.ca/opengl/gl_normaltransform.html + var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); + var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); -}; + var newCoplanarPoint = this.coplanarPoint( v2 ); + newCoplanarPoint.applyMatrix4( matrix ); -// File:src/Three.js + this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint ); -/** - * @author mrdoob / http://mrdoob.com/ - */ -function THREE() {}; + return this; -THREE.REVISION = '71' + }; -// browserify support + }(), -//if ( typeof module === 'object' ) { + translate: function ( offset ) { -// module.exports = THREE; + this.constant = this.constant - offset.dot( this.normal ); -//} + return this; -// polyfills + }, -if ( Math.sign === undefined ) { + equals: function ( plane ) { - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + return plane.normal.equals( this.normal ) && ( plane.constant == this.constant ); - Math.sign = function ( x ) { + }, - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x; + clone: function () { - }; + return new THREE.Plane().copy( this ); -} + } +}; -// set the default log handlers -THREE.log = function() { console.log.apply( console, arguments ); } -THREE.warn = function() { console.warn.apply( console, arguments ); } -THREE.error = function() { console.error.apply( console, arguments ); } +// File:src/math/Math.js +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ -// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button +THREE.Math = { -THREE.MOUSE = { LEFT: Qt.LeftButton, MIDDLE: Qt.MiddleButton, RIGHT: Qt.RightButton }; + generateUUID: function () { -// GL STATE CONSTANTS + // http://www.broofa.com/Tools/Math.uuid.htm -THREE.CullFaceNone = 0; -THREE.CullFaceBack = 1; -THREE.CullFaceFront = 2; -THREE.CullFaceFrontBack = 3; + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); + var rnd = 0, r; -THREE.FrontFaceDirectionCW = 0; -THREE.FrontFaceDirectionCCW = 1; + return function () { -// SHADOWING TYPES + for ( var i = 0; i < 36; i ++ ) { -THREE.BasicShadowMap = 0; -THREE.PCFShadowMap = 1; -THREE.PCFSoftShadowMap = 2; + if ( i == 8 || i == 13 || i == 18 || i == 23 ) { -// MATERIAL CONSTANTS + uuid[ i ] = '-'; -// side + } else if ( i == 14 ) { -THREE.FrontSide = 0; -THREE.BackSide = 1; -THREE.DoubleSide = 2; + uuid[ i ] = '4'; -// shading + } else { -THREE.NoShading = 0; -THREE.FlatShading = 1; -THREE.SmoothShading = 2; + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; + r = rnd & 0xf; + rnd = rnd >> 4; + uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ]; -// colors + } + } -THREE.NoColors = 0; -THREE.FaceColors = 1; -THREE.VertexColors = 2; + return uuid.join( '' ); -// blending modes + }; -THREE.NoBlending = 0; -THREE.NormalBlending = 1; -THREE.AdditiveBlending = 2; -THREE.SubtractiveBlending = 3; -THREE.MultiplyBlending = 4; -THREE.CustomBlending = 5; + }(), -// custom blending equations -// (numbers start from 100 not to clash with other -// mappings to OpenGL constants defined in Texture.js) + // Clamp value to range <a, b> -THREE.AddEquation = 100; -THREE.SubtractEquation = 101; -THREE.ReverseSubtractEquation = 102; -THREE.MinEquation = 103; -THREE.MaxEquation = 104; + clamp: function ( x, a, b ) { -// custom blending destination factors + return ( x < a ) ? a : ( ( x > b ) ? b : x ); -THREE.ZeroFactor = 200; -THREE.OneFactor = 201; -THREE.SrcColorFactor = 202; -THREE.OneMinusSrcColorFactor = 203; -THREE.SrcAlphaFactor = 204; -THREE.OneMinusSrcAlphaFactor = 205; -THREE.DstAlphaFactor = 206; -THREE.OneMinusDstAlphaFactor = 207; + }, -// custom blending source factors + // Clamp value to range <a, inf) -//THREE.ZeroFactor = 200; -//THREE.OneFactor = 201; -//THREE.SrcAlphaFactor = 204; -//THREE.OneMinusSrcAlphaFactor = 205; -//THREE.DstAlphaFactor = 206; -//THREE.OneMinusDstAlphaFactor = 207; -THREE.DstColorFactor = 208; -THREE.OneMinusDstColorFactor = 209; -THREE.SrcAlphaSaturateFactor = 210; + clampBottom: function ( x, a ) { + return x < a ? a : x; -// TEXTURE CONSTANTS + }, -THREE.MultiplyOperation = 0; -THREE.MixOperation = 1; -THREE.AddOperation = 2; + // Linear mapping from range <a1, a2> to range <b1, b2> -// Mapping modes + mapLinear: function ( x, a1, a2, b1, b2 ) { -THREE.UVMapping = 300; + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); -THREE.CubeReflectionMapping = 301; -THREE.CubeRefractionMapping = 302; + }, -THREE.EquirectangularReflectionMapping = 303; -THREE.EquirectangularRefractionMapping = 304; + // http://en.wikipedia.org/wiki/Smoothstep -THREE.SphericalReflectionMapping = 305; + smoothstep: function ( x, min, max ) { -// Wrapping modes + if ( x <= min ) return 0; + if ( x >= max ) return 1; -THREE.RepeatWrapping = 1000; -THREE.ClampToEdgeWrapping = 1001; -THREE.MirroredRepeatWrapping = 1002; + x = ( x - min ) / ( max - min ); -// Filters + return x * x * ( 3 - 2 * x ); -THREE.NearestFilter = 1003; -THREE.NearestMipMapNearestFilter = 1004; -THREE.NearestMipMapLinearFilter = 1005; -THREE.LinearFilter = 1006; -THREE.LinearMipMapNearestFilter = 1007; -THREE.LinearMipMapLinearFilter = 1008; + }, -// Data types + smootherstep: function ( x, min, max ) { -THREE.UnsignedByteType = 1009; -THREE.ByteType = 1010; -THREE.ShortType = 1011; -THREE.UnsignedShortType = 1012; -THREE.IntType = 1013; -THREE.UnsignedIntType = 1014; -THREE.FloatType = 1015; -THREE.HalfFloatType = 1025; + if ( x <= min ) return 0; + if ( x >= max ) return 1; -// Pixel types + x = ( x - min ) / ( max - min ); -//THREE.UnsignedByteType = 1009; -THREE.UnsignedShort4444Type = 1016; -THREE.UnsignedShort5551Type = 1017; -THREE.UnsignedShort565Type = 1018; + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); -// Pixel formats + }, -THREE.AlphaFormat = 1019; -THREE.RGBFormat = 1020; -THREE.RGBAFormat = 1021; -THREE.LuminanceFormat = 1022; -THREE.LuminanceAlphaFormat = 1023; -// THREE.RGBEFormat handled as THREE.RGBAFormat in shaders -THREE.RGBEFormat = THREE.RGBAFormat; //1024; + // Random float from <0, 1> with 16 bits of randomness + // (standard Math.random() creates repetitive patterns when applied over larger space) -// DDS / ST3C Compressed texture formats + random16: function () { -THREE.RGB_S3TC_DXT1_Format = 2001; -THREE.RGBA_S3TC_DXT1_Format = 2002; -THREE.RGBA_S3TC_DXT3_Format = 2003; -THREE.RGBA_S3TC_DXT5_Format = 2004; + return ( 65280 * Math.random() + 255 * Math.random() ) / 65535; + }, -// PVRTC compressed texture formats + // Random integer from <low, high> interval -THREE.RGB_PVRTC_4BPPV1_Format = 2100; -THREE.RGB_PVRTC_2BPPV1_Format = 2101; -THREE.RGBA_PVRTC_4BPPV1_Format = 2102; -THREE.RGBA_PVRTC_2BPPV1_Format = 2103; + randInt: function ( low, high ) { + return Math.floor( this.randFloat( low, high ) ); -// DEPRECATED + }, -THREE.Projector = function () { + // Random float from <low, high> interval - THREE.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); + randFloat: function ( low, high ) { - this.projectVector = function ( vector, camera ) { + return low + Math.random() * ( high - low ); - THREE.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); - vector.project( camera ); + }, - }; + // Random float from <-range/2, range/2> interval - this.unprojectVector = function ( vector, camera ) { + randFloatSpread: function ( range ) { - THREE.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); - vector.unproject( camera ); + return range * ( 0.5 - Math.random() ); - }; + }, - this.pickingRay = function ( vector, camera ) { + degToRad: function () { - THREE.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); + var degreeToRadiansFactor = Math.PI / 180; - }; + return function ( degrees ) { -}; + return degrees * degreeToRadiansFactor; -THREE.CanvasRenderer = function () { + }; - THREE.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); + }(), - this.domElement = document.createElement( 'canvas' ); - this.clear = function () {}; - this.render = function () {}; - this.setClearColor = function () {}; - this.setSize = function () {}; + radToDeg: function () { -}; + var radianToDegreesFactor = 180 / Math.PI; -// File:src/math/Color.js + return function ( radians ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return radians * radianToDegreesFactor; -THREE.Color = function ( color ) { + }; - if ( arguments.length === 3 ) { + }(), - return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] ); + isPowerOfTwo: function ( value ) { - } + return ( value & ( value - 1 ) ) === 0 && value !== 0; - return this.set( color ) + }, -}; + nextPowerOfTwo: function ( value ) { -THREE.Color.prototype = { + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - constructor: THREE.Color, + return value; - r: 1, g: 1, b: 1, + } - set: function ( value ) { +}; - if ( value instanceof THREE.Color ) { +// File:src/math/Spline.js - this.copy( value ); +/** + * Spline from Tween.js, slightly optimized (and trashed) + * http://sole.github.com/tween.js/examples/05_spline.html + * + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - } else if ( typeof value === 'number' ) { +THREE.Spline = function ( points ) { - this.setHex( value ); + this.points = points; - } else if ( typeof value === 'string' ) { + var c = [], v3 = { x: 0, y: 0, z: 0 }, + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; - this.setStyle( value ); + this.initFromArray = function ( a ) { - } + this.points = []; - return this; + for ( var i = 0; i < a.length; i ++ ) { - }, + this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; - setHex: function ( hex ) { + } - hex = Math.floor( hex ); + }; - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + this.getPoint = function ( k ) { - return this; + point = ( this.points.length - 1 ) * k; + intPoint = Math.floor( point ); + weight = point - intPoint; - }, + c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; + c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; - setRGB: function ( r, g, b ) { + pa = this.points[ c[ 0 ] ]; + pb = this.points[ c[ 1 ] ]; + pc = this.points[ c[ 2 ] ]; + pd = this.points[ c[ 3 ] ]; - this.r = r; - this.g = g; - this.b = b; + w2 = weight * weight; + w3 = weight * w2; - return this; + v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); + v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); + v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); - }, + return v3; - setHSL: function ( h, s, l ) { + }; - // h,s,l ranges are in 0.0 - 1.0 + this.getControlPointsArray = function () { - if ( s === 0 ) { + var i, p, l = this.points.length, + coords = []; - this.r = this.g = this.b = l; + for ( i = 0; i < l; i ++ ) { - } else { + p = this.points[ i ]; + coords[ i ] = [ p.x, p.y, p.z ]; - var hue2rgb = function ( p, q, t ) { + } - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; + return coords; - }; + }; - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + // approximate length by summing linear segments - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + this.getLength = function ( nSubDivisions ) { - } + var i, index, nSamples, position, + point = 0, intPoint = 0, oldIntPoint = 0, + oldPosition = new THREE.Vector3(), + tmpVec = new THREE.Vector3(), + chunkLengths = [], + totalLength = 0; - return this; + // first point has 0 length - }, + chunkLengths[ 0 ] = 0; - setStyle: function ( style ) { + if ( ! nSubDivisions ) nSubDivisions = 100; - // rgb(255,0,0) + nSamples = this.points.length * nSubDivisions; - if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) { + oldPosition.copy( this.points[ 0 ] ); - var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style ); + for ( i = 1; i < nSamples; i ++ ) { - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; + index = i / nSamples; - return this; + position = this.getPoint( index ); + tmpVec.copy( position ); - } + totalLength += tmpVec.distanceTo( oldPosition ); - // rgb(100%,0%,0%) + oldPosition.copy( position ); - if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) { + point = ( this.points.length - 1 ) * index; + intPoint = Math.floor( point ); - var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style ); + if ( intPoint != oldIntPoint ) { - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + chunkLengths[ intPoint ] = totalLength; + oldIntPoint = intPoint; - return this; + } } - // #ff0000 + // last point ends with total length - if ( /^\#([0-9a-f]{6})$/i.test( style ) ) { + chunkLengths[ chunkLengths.length ] = totalLength; - var color = /^\#([0-9a-f]{6})$/i.exec( style ); + return { chunks: chunkLengths, total: totalLength }; - this.setHex( parseInt( color[ 1 ], 16 ) ); + }; - return this; + this.reparametrizeByArcLength = function ( samplingCoef ) { - } + var i, j, + index, indexCurrent, indexNext, + realDistance, + sampling, position, + newpoints = [], + tmpVec = new THREE.Vector3(), + sl = this.getLength(); - // #f00 + newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) { + for ( i = 1; i < this.points.length; i ++ ) { - var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style ); + //tmpVec.copy( this.points[ i - 1 ] ); + //linearDistance = tmpVec.distanceTo( this.points[ i ] ); - this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) ); + realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; - return this; + sampling = Math.ceil( samplingCoef * realDistance / sl.total ); - } + indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); + indexNext = i / ( this.points.length - 1 ); - // red + for ( j = 1; j < sampling - 1; j ++ ) { - if ( /^(\w+)$/i.test( style ) ) { + index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); - this.setHex( THREE.ColorKeywords[ style ] ); + position = this.getPoint( index ); + newpoints.push( tmpVec.copy( position ).clone() ); - return this; + } + + newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); } + this.points = newpoints; - }, + }; - copy: function ( color ) { + // Catmull-Rom - this.r = color.r; - this.g = color.g; - this.b = color.b; + function interpolate( p0, p1, p2, p3, t, t2, t3 ) { - return this; + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - }, + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - copyGammaToLinear: function ( color, gammaFactor ) { + }; - if ( gammaFactor === undefined ) gammaFactor = 2.0; +}; - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); +// File:src/math/Triangle.js - return this; +/** + * @author bhouston / http://exocortex.com + * @author mrdoob / http://mrdoob.com/ + */ - }, +THREE.Triangle = function ( a, b, c ) { - copyLinearToGamma: function ( color, gammaFactor ) { + this.a = ( a !== undefined ) ? a : new THREE.Vector3(); + this.b = ( b !== undefined ) ? b : new THREE.Vector3(); + this.c = ( c !== undefined ) ? c : new THREE.Vector3(); - if ( gammaFactor === undefined ) gammaFactor = 2.0; +}; - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; +THREE.Triangle.normal = function () { - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + var v0 = new THREE.Vector3(); - return this; + return function ( a, b, c, optionalTarget ) { - }, + var result = optionalTarget || new THREE.Vector3(); - convertGammaToLinear: function () { + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - var r = this.r, g = this.g, b = this.b; + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - this.r = r * r; - this.g = g * g; - this.b = b * b; + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - return this; + } - }, + return result.set( 0, 0, 0 ); - convertLinearToGamma: function () { + }; - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); +}(); - return this; +// static/instance method to calculate barycoordinates +// based on: http://www.blackpawn.com/texts/pointinpoly/default.html +THREE.Triangle.barycoordFromPoint = function () { - }, + var v0 = new THREE.Vector3(); + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); - getHex: function () { + return function ( point, a, b, c, optionalTarget ) { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, 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 ); - getHexString: function () { + var denom = ( dot00 * dot11 - dot01 * dot01 ); - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + var result = optionalTarget || new THREE.Vector3(); - }, + // colinear or singular triangle + if ( denom == 0 ) { + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return result.set( - 2, - 1, - 1 ); + } - getHSL: function ( optionalTarget ) { + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - // h,s,l ranges are in 0.0 - 1.0 + // barycoordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + }; - var r = this.r, g = this.g, b = this.b; +}(); - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); +THREE.Triangle.containsPoint = function () { - var hue, saturation; - var lightness = ( min + max ) / 2.0; + var v1 = new THREE.Vector3(); - if ( min === max ) { + return function ( point, a, b, c ) { - hue = 0; - saturation = 0; + var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); - } else { + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); - var delta = max - min; + }; - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); +}(); - switch ( max ) { +THREE.Triangle.prototype = { - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; + constructor: THREE.Triangle, - } + set: function ( a, b, c ) { - hue /= 6; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - } + return this; - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + }, - return hsl; + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; }, - getStyle: function () { + copy: function ( triangle ) { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; }, - offsetHSL: function ( h, s, l ) { + area: function () { - var hsl = this.getHSL(); + var v0 = new THREE.Vector3(); + var v1 = new THREE.Vector3(); - hsl.h += h; hsl.s += s; hsl.l += l; + return function () { - this.setHSL( hsl.h, hsl.s, hsl.l ); + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - return this; + return v0.cross( v1 ).length() * 0.5; - }, + }; - add: function ( color ) { + }(), - this.r += color.r; - this.g += color.g; - this.b += color.b; + midpoint: function ( optionalTarget ) { - return this; + var result = optionalTarget || new THREE.Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); }, - addColors: function ( color1, color2 ) { - - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + normal: function ( optionalTarget ) { - return this; + return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); }, - addScalar: function ( s ) { - - this.r += s; - this.g += s; - this.b += s; - - return this; - - }, - - multiply: function ( color ) { - - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; - - return this; - - }, - - multiplyScalar: function ( s ) { - - this.r *= s; - this.g *= s; - this.b *= s; - - return this; - - }, - - lerp: function ( color, alpha ) { + plane: function ( optionalTarget ) { - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + var result = optionalTarget || new THREE.Plane(); - return this; + return result.setFromCoplanarPoints( this.a, this.b, this.c ); }, - equals: function ( c ) { + barycoordFromPoint: function ( point, optionalTarget ) { - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); }, - fromArray: function ( array ) { - - this.r = array[ 0 ]; - this.g = array[ 1 ]; - this.b = array[ 2 ]; + containsPoint: function ( point ) { - return this; + return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); }, - toArray: function ( array, offset ) { - - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + equals: function ( triangle ) { - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - return array; }, clone: function () { - return new THREE.Color().setRGB( this.r, this.g, this.b ); + return new THREE.Triangle().copy( this ); } }; -THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, -'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, -'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, -'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, -'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, -'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, -'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, -'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, -'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, -'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, -'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, -'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, -'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, -'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, -'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, -'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, -'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, -'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, -'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, -'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, -'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, -'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, -'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, -'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - -// File:src/math/Quaternion.js +// File:src/core/Clock.js /** - * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com */ -THREE.Quaternion = function ( x, y, z, w ) { - - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; +THREE.Clock = function ( autoStart ) { - this.__defineGetter__("x", function(){ - return this._x; - }); - this.__defineSetter__("x", function(value){ - this._x = value; - this.onChangeCallback(); - }); - this.__defineGetter__("y", function(){ - return this._y; - }); - this.__defineSetter__("y", function(value){ - this._y = value; - this.onChangeCallback(); - }); - this.__defineGetter__("z", function(){ - return this._z; - }); - this.__defineSetter__("z", function(value){ - this._z = value; - this.onChangeCallback(); - }); - this.__defineGetter__("w", function(){ - return this._w; - }); - this.__defineSetter__("w", function(value){ - this._w = value; - this.onChangeCallback(); - }); -}; + this.autoStart = ( autoStart !== undefined ) ? autoStart : true; -THREE.Quaternion.prototype = { + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - constructor: THREE.Quaternion, + this.running = false; - _x: 0,_y: 0, _z: 0, _w: 0, +}; - set: function ( x, y, z, w ) { +THREE.Clock.prototype = { - this._x = x; - this._y = y; - this._z = z; - this._w = w; + constructor: THREE.Clock, - this.onChangeCallback(); + start: function () { - return this; + this.startTime = self.performance !== undefined && self.performance.now !== undefined + ? self.performance.now() + : Date.now(); + this.oldTime = this.startTime; + this.running = true; }, - copy: function ( quaternion ) { - - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; - - this.onChangeCallback(); + stop: function () { - return this; + this.getElapsedTime(); + this.running = false; }, - setFromEuler: function ( euler, update ) { - - if ( euler instanceof THREE.Euler === false ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - } - - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m - - var c1 = Math.cos( euler._x / 2 ); - var c2 = Math.cos( euler._y / 2 ); - var c3 = Math.cos( euler._z / 2 ); - var s1 = Math.sin( euler._x / 2 ); - var s2 = Math.sin( euler._y / 2 ); - var s3 = Math.sin( euler._z / 2 ); - - if ( euler.order === 'XYZ' ) { + getElapsedTime: function () { - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + this.getDelta(); + return this.elapsedTime; - } else if ( euler.order === 'YXZ' ) { + }, - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + getDelta: function () { - } else if ( euler.order === 'ZXY' ) { + var diff = 0; - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + if ( this.autoStart && ! this.running ) { - } else if ( euler.order === 'ZYX' ) { + this.start(); - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + } - } else if ( euler.order === 'YZX' ) { + if ( this.running ) { - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + var newTime = self.performance !== undefined && self.performance.now !== undefined + ? self.performance.now() + : Date.now(); - } else if ( euler.order === 'XZY' ) { + diff = 0.001 * ( newTime - this.oldTime ); + this.oldTime = newTime; - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + this.elapsedTime += diff; } - if ( update !== false ) this.onChangeCallback(); + return diff; - return this; + } - }, +}; - setFromAxisAngle: function ( axis, angle ) { +// File:src/core/EventDispatcher.js - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm +/** + * https://github.com/mrdoob/eventdispatcher.js/ + */ - // assumes axis is normalized +THREE.EventDispatcher = function () {} - var halfAngle = angle / 2, s = Math.sin( halfAngle ); +THREE.EventDispatcher.prototype = { - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + constructor: THREE.EventDispatcher, - this.onChangeCallback(); + apply: function ( object ) { - return this; + object.addEventListener = THREE.EventDispatcher.prototype.addEventListener; + object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener; + object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener; + object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent; }, - setFromRotationMatrix: function ( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - var te = m.elements, + addEventListener: function ( type, listener ) { - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + if ( this._listeners === undefined ) this._listeners = {}; - trace = m11 + m22 + m33, - s; + var listeners = this._listeners; - if ( trace > 0 ) { + if ( listeners[ type ] === undefined ) { - s = 0.5 / Math.sqrt( trace + 1.0 ); + listeners[ type ] = []; - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + } - } else if ( m11 > m22 && m11 > m33 ) { + if ( listeners[ type ].indexOf( listener ) === - 1 ) { - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + listeners[ type ].push( listener ); - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + } - } else if ( m22 > m33 ) { + }, - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + hasEventListener: function ( type, listener ) { - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + if ( this._listeners === undefined ) return false; - } else { + var listeners = this._listeners; - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + return true; } - this.onChangeCallback(); - - return this; + return false; }, - setFromUnitVectors: function () { + removeEventListener: function ( type, listener ) { - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + if ( this._listeners === undefined ) return; - // assumes direction vectors vFrom and vTo are normalized + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - var v1, r; + if ( listenerArray !== undefined ) { - var EPS = 0.000001; + var index = listenerArray.indexOf( listener ); - return function ( vFrom, vTo ) { + if ( index !== - 1 ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + listenerArray.splice( index, 1 ); - r = vFrom.dot( vTo ) + 1; + } - if ( r < EPS ) { + } - r = 0; + }, - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + dispatchEvent: function ( event ) { - v1.set( - vFrom.y, vFrom.x, 0 ); + if ( this._listeners === undefined ) return; - } else { + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; - v1.set( 0, - vFrom.z, vFrom.y ); + if ( listenerArray !== undefined ) { - } + event.target = this; - } else { + var array = []; + var length = listenerArray.length; - v1.crossVectors( vFrom, vTo ); + for ( var i = 0; i < length; i ++ ) { + + array[ i ] = listenerArray[ i ]; } - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + for ( var i = 0; i < length; i ++ ) { - this.normalize(); + array[ i ].call( this, event ); - return this; + } } - }(), + } - inverse: function () { +}; - this.conjugate().normalize(); +// File:src/core/Raycaster.js - return this; +/** + * @author mrdoob / http://mrdoob.com/ + * @author bhouston / http://exocortex.com/ + * @author stephomi / http://stephaneginier.com/ + */ - }, +//( function ( THREE ) { - conjugate: function () { + THREE.Raycaster = function ( origin, direction, near, far ) { - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + this.ray = new THREE.Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - this.onChangeCallback(); + this.near = near || 0; + this.far = far || Infinity; - return this; + this.params = { + Sprite: {}, + Mesh: {}, + PointCloud: { threshold: 1 }, + LOD: {}, + Line: {} + }; - }, + }; - dot: function ( v ) { + var descSort = function ( a, b ) { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + return a.distance - b.distance; - }, + }; - lengthSq: function () { + var intersectObject = function ( object, raycaster, intersects, recursive ) { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + object.raycast( raycaster, intersects ); - }, + if ( recursive === true ) { - length: function () { + var children = object.children; - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - }, + intersectObject( children[ i ], raycaster, intersects, true ); - normalize: function () { + } - var l = this.length(); + } - if ( l === 0 ) { + }; - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + // - } else { + THREE.Raycaster.prototype = { - l = 1 / l; + constructor: THREE.Raycaster, - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + precision: 0.0001, + linePrecision: 1, - } + set: function ( origin, direction ) { - this.onChangeCallback(); + // direction is assumed to be normalized (for accurate distance calculations) - return this; + this.ray.set( origin, direction ); - }, + }, - multiply: function ( q, p ) { + setFromCamera: function ( coords, camera ) { - if ( p !== undefined ) { + // camera is assumed _not_ to be a child of a transformed object - THREE.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + if ( camera instanceof THREE.PerspectiveCamera ) { - } + this.ray.origin.copy( camera.position ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( camera.position ).normalize(); - return this.multiplyQuaternions( this, q ); + } else if ( camera instanceof THREE.OrthographicCamera ) { - }, + this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera ); + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - multiplyQuaternions: function ( a, b ) { + } else { - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + THREE.error( 'THREE.Raycaster: Unsupported camera type.' ); - var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + } - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + }, - this.onChangeCallback(); + intersectObject: function ( object, recursive ) { - return this; + var intersects = []; - }, + intersectObject( object, this, intersects, recursive ); - multiplyVector3: function ( vector ) { + intersects.sort( descSort ); - THREE.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); + return intersects; - }, + }, - slerp: function ( qb, t ) { + intersectObjects: function ( objects, recursive ) { - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + var intersects = []; - var x = this._x, y = this._y, z = this._z, w = this._w; + if ( objects instanceof Array === false ) { - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + THREE.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + } - if ( cosHalfTheta < 0 ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + intersectObject( objects[ i ], this, intersects, recursive ); - cosHalfTheta = - cosHalfTheta; + } - } else { + intersects.sort( descSort ); - this.copy( qb ); + return intersects; } - if ( cosHalfTheta >= 1.0 ) { + }; - this._w = w; - this._x = x; - this._y = y; - this._z = z; +//}( THREE ) ); - return this; +// File:src/core/Object3D.js - } +/** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + */ - var halfTheta = Math.acos( cosHalfTheta ); - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); +THREE.Object3D = function () { - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); - this._w = 0.5 * ( w + this._w ); - this._x = 0.5 * ( x + this._x ); - this._y = 0.5 * ( y + this._y ); - this._z = 0.5 * ( z + this._z ); + this.uuid = THREE.Math.generateUUID(); - return this; + this.name = ''; + this.type = 'Object3D'; - } + this.parent = undefined; + this.children = []; - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + this.up = THREE.Object3D.DefaultUp.clone(); - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); + var position = new THREE.Vector3(); + var rotation = new THREE.Euler(); + var quaternion = new THREE.Quaternion(); + var scale = new THREE.Vector3( 1, 1, 1 ); - this.onChangeCallback(); + var onRotationChange = function () { + quaternion.setFromEuler( rotation, false ); + }; - return this; + var onQuaternionChange = function () { + rotation.setFromQuaternion( quaternion, undefined, false ); + }; - }, + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); - equals: function ( quaternion ) { + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + } + } ); - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + this.rotationAutoUpdate = true; - }, + this.matrix = new THREE.Matrix4(); + this.matrixWorld = new THREE.Matrix4(); - fromArray: function ( array, offset ) { + this.matrixAutoUpdate = true; + this.matrixWorldNeedsUpdate = false; - if ( offset === undefined ) offset = 0; + this.visible = true; - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + this.castShadow = false; + this.receiveShadow = false; - this.onChangeCallback(); + this.frustumCulled = true; + this.renderOrder = 0; - return this; + this.userData = {}; - }, +}; - toArray: function ( array, offset ) { +THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; +THREE.Object3D.prototype = { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + constructor: THREE.Object3D, - return array; + get eulerOrder () { - }, + THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); - onChange: function ( callback ) { + return this.rotation.order; - this.onChangeCallback = callback; + }, - return this; + set eulerOrder ( value ) { - }, + THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); - onChangeCallback: function () {}, + this.rotation.order = value; - clone: function () { + }, - return new THREE.Quaternion( this._x, this._y, this._z, this._w ); + get useQuaternion () { - } + THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); -}; + }, -THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { + set useQuaternion ( value ) { - return qm.copy( qa ).slerp( qb, t ); + THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); -} + }, -// File:src/math/Vector2.js + applyMatrix: function ( matrix ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + this.matrix.multiplyMatrices( matrix, this.matrix ); -THREE.Vector2 = function ( x, y ) { + this.matrix.decompose( this.position, this.quaternion, this.scale ); - this.x = x || 0; - this.y = y || 0; + }, -}; + setRotationFromAxisAngle: function ( axis, angle ) { -THREE.Vector2.prototype = { + // assumes axis is normalized - constructor: THREE.Vector2, + this.quaternion.setFromAxisAngle( axis, angle ); - set: function ( x, y ) { + }, - this.x = x; - this.y = y; + setRotationFromEuler: function ( euler ) { - return this; + this.quaternion.setFromEuler( euler, true ); }, - setX: function ( x ) { + setRotationFromMatrix: function ( m ) { - this.x = x; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this; + this.quaternion.setFromRotationMatrix( m ); }, - setY: function ( y ) { + setRotationFromQuaternion: function ( q ) { - this.y = y; + // assumes q is normalized - return this; + this.quaternion.copy( q ); }, - setComponent: function ( index, value ) { - - switch ( index ) { + rotateOnAxis: function () { - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + // rotate object on axis in object space + // axis is assumed to be normalized - } + var q1 = new THREE.Quaternion(); - }, + return function ( axis, angle ) { - getComponent: function ( index ) { + q1.setFromAxisAngle( axis, angle ); - switch ( index ) { + this.quaternion.multiply( q1 ); - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + return this; } - }, + }(), - copy: function ( v ) { + rotateX: function () { - this.x = v.x; - this.y = v.y; + var v1 = new THREE.Vector3( 1, 0, 0 ); - return this; + return function ( angle ) { - }, + return this.rotateOnAxis( v1, angle ); - add: function ( v, w ) { + }; - if ( w !== undefined ) { + }(), - THREE.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + rotateY: function () { - } + var v1 = new THREE.Vector3( 0, 1, 0 ); - this.x += v.x; - this.y += v.y; + return function ( angle ) { - return this; + return this.rotateOnAxis( v1, angle ); - }, + }; - addScalar: function ( s ) { + }(), - this.x += s; - this.y += s; + rotateZ: function () { - return this; + var v1 = new THREE.Vector3( 0, 0, 1 ); - }, + return function ( angle ) { - addVectors: function ( a, b ) { + return this.rotateOnAxis( v1, angle ); - this.x = a.x + b.x; - this.y = a.y + b.y; + }; - return this; + }(), - }, + translateOnAxis: function () { - sub: function ( v, w ) { + // translate object by distance along axis in object space + // axis is assumed to be normalized - if ( w !== undefined ) { + var v1 = new THREE.Vector3(); - THREE.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + return function ( axis, distance ) { - } + v1.copy( axis ).applyQuaternion( this.quaternion ); - this.x -= v.x; - this.y -= v.y; + this.position.add( v1.multiplyScalar( distance ) ); - return this; + return this; - }, + } - subScalar: function ( s ) { + }(), - this.x -= s; - this.y -= s; + translate: function ( distance, axis ) { - return this; + THREE.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); + return this.translateOnAxis( axis, distance ); }, - subVectors: function ( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; + translateX: function () { - return this; + var v1 = new THREE.Vector3( 1, 0, 0 ); - }, + return function ( distance ) { - multiply: function ( v ) { + return this.translateOnAxis( v1, distance ); - this.x *= v.x; - this.y *= v.y; + }; - return this; + }(), - }, + translateY: function () { - multiplyScalar: function ( s ) { + var v1 = new THREE.Vector3( 0, 1, 0 ); - this.x *= s; - this.y *= s; + return function ( distance ) { - return this; + return this.translateOnAxis( v1, distance ); - }, + }; - divide: function ( v ) { + }(), - this.x /= v.x; - this.y /= v.y; + translateZ: function () { - return this; + var v1 = new THREE.Vector3( 0, 0, 1 ); - }, + return function ( distance ) { - divideScalar: function ( scalar ) { + return this.translateOnAxis( v1, distance ); - if ( scalar !== 0 ) { + }; - var invScalar = 1 / scalar; + }(), - this.x *= invScalar; - this.y *= invScalar; + localToWorld: function ( vector ) { - } else { + return vector.applyMatrix4( this.matrixWorld ); - this.x = 0; - this.y = 0; + }, - } + worldToLocal: function () { - return this; + var m1 = new THREE.Matrix4(); - }, + return function ( vector ) { - min: function ( v ) { + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - if ( this.x > v.x ) { + }; - this.x = v.x; + }(), - } + lookAt: function () { - if ( this.y > v.y ) { + // This routine does not support objects with rotated and/or translated parent(s) - this.y = v.y; + var m1 = new THREE.Matrix4(); - } + return function ( vector ) { - return this; + m1.lookAt( vector, this.position, this.up ); - }, + this.quaternion.setFromRotationMatrix( m1 ); - max: function ( v ) { + }; - if ( this.x < v.x ) { + }(), - this.x = v.x; + add: function ( object ) { - } + if ( arguments.length > 1 ) { - if ( this.y < v.y ) { + for ( var i = 0; i < arguments.length; i ++ ) { - this.y = v.y; + this.add( arguments[ i ] ); - } + } - return this; + return this; - }, + }; - clamp: function ( min, max ) { + if ( object === this ) { - // This function assumes min < max, if this assumption isn't true it will not operate correctly + THREE.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - if ( this.x < min.x ) { + } - this.x = min.x; + if ( object instanceof THREE.Object3D ) { - } else if ( this.x > max.x ) { + if ( object.parent !== undefined ) { - this.x = max.x; + object.parent.remove( object ); - } + } - if ( this.y < min.y ) { + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - this.y = min.y; + this.children.push( object ); - } else if ( this.y > max.y ) { + } else { - this.y = max.y; + THREE.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); } return this; - }, - clampScalar: ( function () { + }, - var min, max; + remove: function ( object ) { - return function ( minVal, maxVal ) { + if ( arguments.length > 1 ) { - if ( min === undefined ) { + for ( var i = 0; i < arguments.length; i ++ ) { - min = new THREE.Vector2(); - max = new THREE.Vector2(); + this.remove( arguments[ i ] ); } - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + }; - return this.clamp( min, max ); + var index = this.children.indexOf( object ); - }; + if ( index !== - 1 ) { - } )(), + object.parent = undefined; - floor: function () { + object.dispatchEvent( { type: 'removed' } ); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + this.children.splice( index, 1 ); - return this; + } }, - ceil: function () { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + getChildByName: function ( name ) { - return this; + THREE.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); + return this.getObjectByName( name ); }, - round: function () { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + getObjectById: function ( id ) { - return this; + return this.getObjectByProperty( 'id', id ); }, - roundToZero: function () { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + getObjectByName: function ( name ) { - return this; + return this.getObjectByProperty( 'name', name ); }, - negate: function () { + getObjectByProperty: function ( name, value ) { - this.x = - this.x; - this.y = - this.y; + if ( this[ name ] === value ) return this; - return this; + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - }, + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - dot: function ( v ) { + if ( object !== undefined ) { - return this.x * v.x + this.y * v.y; + return object; - }, + } - lengthSq: function () { + } - return this.x * this.x + this.y * this.y; + return undefined; }, - length: function () { - - return Math.sqrt( this.x * this.x + this.y * this.y ); + getWorldPosition: function ( optionalTarget ) { - }, + var result = optionalTarget || new THREE.Vector3(); - normalize: function () { + this.updateMatrixWorld( true ); - return this.divideScalar( this.length() ); + return result.setFromMatrixPosition( this.matrixWorld ); }, - distanceTo: function ( v ) { - - return Math.sqrt( this.distanceToSquared( v ) ); - - }, + getWorldQuaternion: function () { - distanceToSquared: function ( v ) { + var position = new THREE.Vector3(); + var scale = new THREE.Vector3(); - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + return function ( optionalTarget ) { - }, + var result = optionalTarget || new THREE.Quaternion(); - setLength: function ( l ) { + this.updateMatrixWorld( true ); - var oldLength = this.length(); + this.matrixWorld.decompose( position, result, scale ); - if ( oldLength !== 0 && l !== oldLength ) { + return result; - this.multiplyScalar( l / oldLength ); } - return this; + }(), - }, + getWorldRotation: function () { - lerp: function ( v, alpha ) { + var quaternion = new THREE.Quaternion(); - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + return function ( optionalTarget ) { - return this; + var result = optionalTarget || new THREE.Euler(); - }, + this.getWorldQuaternion( quaternion ); - lerpVectors: function ( v1, v2, alpha ) { + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + } - return this; + }(), - }, + getWorldScale: function () { - equals: function ( v ) { + var position = new THREE.Vector3(); + var quaternion = new THREE.Quaternion(); - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + return function ( optionalTarget ) { - }, + var result = optionalTarget || new THREE.Vector3(); - fromArray: function ( array, offset ) { + this.updateMatrixWorld( true ); - if ( offset === undefined ) offset = 0; + this.matrixWorld.decompose( position, quaternion, result ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + return result; - return this; + } - }, + }(), - toArray: function ( array, offset ) { + getWorldDirection: function () { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var quaternion = new THREE.Quaternion(); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + return function ( optionalTarget ) { - return array; + var result = optionalTarget || new THREE.Vector3(); - }, + this.getWorldQuaternion( quaternion ); - fromAttribute: function ( attribute, index, offset ) { + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); - if ( offset === undefined ) offset = 0; + } - index = index * attribute.itemSize + offset; + }(), - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + raycast: function () {}, - return this; + traverse: function ( callback ) { - }, + callback( this ); - clone: function () { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - return new THREE.Vector2( this.x, this.y ); + this.children[ i ].traverse( callback ); - } + } -}; + }, -// File:src/math/Vector3.js + traverseVisible: function ( callback ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author *kile / http://kile.stravaganza.org/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + if ( this.visible === false ) return; -THREE.Vector3 = function ( x, y, z ) { + callback( this ); - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + for ( var i = 0, l = this.children.length; i < l; i ++ ) { -}; + this.children[ i ].traverseVisible( callback ); -THREE.Vector3.prototype = { + } - constructor: THREE.Vector3, + }, - set: function ( x, y, z ) { + traverseAncestors: function ( callback ) { - this.x = x; - this.y = y; - this.z = z; + if ( this.parent ) { - return this; + callback( this.parent ); + + this.parent.traverseAncestors( callback ); + + } }, - setX: function ( x ) { + updateMatrix: function () { - this.x = x; + this.matrix.compose( this.position, this.quaternion, this.scale ); - return this; + this.matrixWorldNeedsUpdate = true; }, - setY: function ( y ) { - - this.y = y; + updateMatrixWorld: function ( force ) { - return this; + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - }, + if ( this.matrixWorldNeedsUpdate === true || force === true ) { - setZ: function ( z ) { + if ( this.parent === undefined ) { - this.z = z; + this.matrixWorld.copy( this.matrix ); - return this; + } else { - }, + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - setComponent: function ( index, value ) { + } - switch ( index ) { + this.matrixWorldNeedsUpdate = false; - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); + force = true; } - }, - - getComponent: function ( index ) { + // update children - switch ( index ) { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); + this.children[ i ].updateMatrixWorld( force ); } }, - copy: function ( v ) { + toJSON: function () { - this.x = v.x; - this.y = v.y; - this.z = v.z; + var output = { + metadata: { + version: 4.3, + type: 'Object', + generator: 'ObjectExporter' + } + }; - return this; + // - }, + var geometries = {}; - add: function ( v, w ) { + var parseGeometry = function ( geometry ) { - if ( w !== undefined ) { + if ( output.geometries === undefined ) { - THREE.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + output.geometries = []; - } + } - this.x += v.x; - this.y += v.y; - this.z += v.z; + if ( geometries[ geometry.uuid ] === undefined ) { - return this; + var json = geometry.toJSON(); - }, + delete json.metadata; - addScalar: function ( s ) { + geometries[ geometry.uuid ] = json; - this.x += s; - this.y += s; - this.z += s; + output.geometries.push( json ); - return this; + } - }, + return geometry.uuid; - addVectors: function ( a, b ) { + }; - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + // - return this; + var materials = {}; - }, + var parseMaterial = function ( material ) { - sub: function ( v, w ) { + if ( output.materials === undefined ) { - if ( w !== undefined ) { + output.materials = []; - THREE.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + } - } + if ( materials[ material.uuid ] === undefined ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + var json = material.toJSON(); - return this; + delete json.metadata; - }, - - subScalar: function ( s ) { + materials[ material.uuid ] = json; - this.x -= s; - this.y -= s; - this.z -= s; + output.materials.push( json ); - return this; + } - }, + return material.uuid; - subVectors: function ( a, b ) { + }; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + // - return this; + var parseObject = function ( object ) { - }, + var data = {}; - multiply: function ( v, w ) { + data.uuid = object.uuid; + data.type = object.type; - if ( w !== undefined ) { + if ( object.name !== '' ) data.name = object.name; + if ( JSON.stringify( object.userData ) !== '{}' ) data.userData = object.userData; + if ( object.visible !== true ) data.visible = object.visible; - THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + if ( object instanceof THREE.PerspectiveCamera ) { - } + data.fov = object.fov; + data.aspect = object.aspect; + data.near = object.near; + data.far = object.far; - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + } else if ( object instanceof THREE.OrthographicCamera ) { - return this; + data.left = object.left; + data.right = object.right; + data.top = object.top; + data.bottom = object.bottom; + data.near = object.near; + data.far = object.far; - }, + } else if ( object instanceof THREE.AmbientLight ) { - multiplyScalar: function ( scalar ) { + data.color = object.color.getHex(); - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + } else if ( object instanceof THREE.DirectionalLight ) { - return this; + data.color = object.color.getHex(); + data.intensity = object.intensity; - }, + } else if ( object instanceof THREE.PointLight ) { - multiplyVectors: function ( a, b ) { + data.color = object.color.getHex(); + data.intensity = object.intensity; + data.distance = object.distance; + data.decay = object.decay; - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + } else if ( object instanceof THREE.SpotLight ) { - return this; + data.color = object.color.getHex(); + data.intensity = object.intensity; + data.distance = object.distance; + data.angle = object.angle; + data.exponent = object.exponent; + data.decay = object.decay; - }, + } else if ( object instanceof THREE.HemisphereLight ) { - applyEuler: function () { + data.color = object.color.getHex(); + data.groundColor = object.groundColor.getHex(); - var quaternion; + } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) { - return function ( euler ) { + data.geometry = parseGeometry( object.geometry ); + data.material = parseMaterial( object.material ); - if ( euler instanceof THREE.Euler === false ) { + if ( object instanceof THREE.Line ) data.mode = object.mode; - THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } else if ( object instanceof THREE.Sprite ) { + + data.material = parseMaterial( object.material ); } - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + data.matrix = object.matrix.toArray(); - this.applyQuaternion( quaternion.setFromEuler( euler ) ); + if ( object.children.length > 0 ) { - return this; + data.children = []; - }; + for ( var i = 0; i < object.children.length; i ++ ) { - }(), + data.children.push( parseObject( object.children[ i ] ) ); - applyAxisAngle: function () { + } - var quaternion; + } - return function ( axis, angle ) { + return data; - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + } - this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + output.object = parseObject( this ); - return this; + return output; - }; + }, - }(), + clone: function ( object, recursive ) { - applyMatrix3: function ( m ) { + if ( object === undefined ) object = new THREE.Object3D(); + if ( recursive === undefined ) recursive = true; - var x = this.x; - var y = this.y; - var z = this.z; + object.name = this.name; - var e = m.elements; + object.up.copy( this.up ); - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + object.position.copy( this.position ); + object.quaternion.copy( this.quaternion ); + object.scale.copy( this.scale ); - return this; + object.rotationAutoUpdate = this.rotationAutoUpdate; - }, + object.matrix.copy( this.matrix ); + object.matrixWorld.copy( this.matrixWorld ); - applyMatrix4: function ( m ) { + object.matrixAutoUpdate = this.matrixAutoUpdate; + object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate; - // input: THREE.Matrix4 affine matrix + object.visible = this.visible; - var x = this.x, y = this.y, z = this.z; + object.castShadow = this.castShadow; + object.receiveShadow = this.receiveShadow; - var e = m.elements; + object.frustumCulled = this.frustumCulled; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; + object.userData = JSON.parse( JSON.stringify( this.userData ) ); - return this; + if ( recursive === true ) { - }, + for ( var i = 0; i < this.children.length; i ++ ) { - applyProjection: function ( m ) { + var child = this.children[ i ]; + object.add( child.clone() ); - // input: THREE.Matrix4 projection matrix + } - var x = this.x, y = this.y, z = this.z; + } - var e = m.elements; - var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide + return object; - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; + } - return this; +}; - }, +THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); - applyQuaternion: function ( q ) { +THREE.Object3DIdCount = 0; - var x = this.x; - var y = this.y; - var z = this.z; +// File:src/core/Face3.js - var qx = q.x; - var qy = q.y; - var qz = q.z; - var qw = q.w; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - // calculate quat * vector +THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = - qx * x - qy * y - qz * z; + this.a = a; + this.b = b; + this.c = c; - // calculate result * inverse quat + this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); + this.vertexNormals = normal instanceof Array ? normal : []; - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + this.color = color instanceof THREE.Color ? color : new THREE.Color(); + this.vertexColors = color instanceof Array ? color : []; - return this; + this.vertexTangents = []; - }, + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - project: function () { +}; - var matrix; +THREE.Face3.prototype = { - return function ( camera ) { + constructor: THREE.Face3, - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + clone: function () { - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + var face = new THREE.Face3( this.a, this.b, this.c ); - }; + face.normal.copy( this.normal ); + face.color.copy( this.color ); - }(), + face.materialIndex = this.materialIndex; - unproject: function () { + for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) { - var matrix; + face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); - return function ( camera ) { + } - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) { - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + face.vertexColors[ i ] = this.vertexColors[ i ].clone(); - }; + } - }(), + for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) { - transformDirection: function ( m ) { + face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + } - var x = this.x, y = this.y, z = this.z; + return face; - var e = m.elements; + } - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; +}; - this.normalize(); +// File:src/core/Face4.js - return this; +/** + * @author mrdoob / http://mrdoob.com/ + */ - }, +THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { - divide: function ( v ) { + THREE.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ) + return new THREE.Face3( a, b, c, normal, color, materialIndex ); - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; +}; - return this; +// File:src/core/BufferAttribute.js - }, +/** + * @author mrdoob / http://mrdoob.com/ + */ - divideScalar: function ( scalar ) { +THREE.BufferAttribute = function ( array, itemSize ) { - if ( scalar !== 0 ) { + this.array = array; + this.itemSize = itemSize; - var invScalar = 1 / scalar; + this.needsUpdate = false; - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; +}; - } else { +THREE.BufferAttribute.prototype = { - this.x = 0; - this.y = 0; - this.z = 0; + constructor: THREE.BufferAttribute, - } + get length () { - return this; + return this.array.length; }, - min: function ( v ) { + copyAt: function ( index1, attribute, index2 ) { - if ( this.x > v.x ) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; - this.x = v.x; + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - } + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - if ( this.y > v.y ) { + } - this.y = v.y; + return this; - } + }, - if ( this.z > v.z ) { + set: function ( value, offset ) { - this.z = v.z; + if ( offset === undefined ) offset = 0; - } + this.array.set( value, offset ); return this; }, - max: function ( v ) { + setX: function ( index, x ) { - if ( this.x < v.x ) { + this.array[ index * this.itemSize ] = x; - this.x = v.x; + return this; - } + }, - if ( this.y < v.y ) { + setY: function ( index, y ) { - this.y = v.y; + this.array[ index * this.itemSize + 1 ] = y; - } + return this; - if ( this.z < v.z ) { + }, - this.z = v.z; + setZ: function ( index, z ) { - } + this.array[ index * this.itemSize + 2 ] = z; return this; }, - clamp: function ( min, max ) { + setXY: function ( index, x, y ) { - // This function assumes min < max, if this assumption isn't true it will not operate correctly + index *= this.itemSize; - if ( this.x < min.x ) { + this.array[ index ] = x; + this.array[ index + 1 ] = y; - this.x = min.x; + return this; - } else if ( this.x > max.x ) { + }, - this.x = max.x; + setXYZ: function ( index, x, y, z ) { - } + index *= this.itemSize; - if ( this.y < min.y ) { + this.array[ index ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - this.y = min.y; + return this; - } else if ( this.y > max.y ) { + }, - this.y = max.y; + setXYZW: function ( index, x, y, z, w ) { - } + index *= this.itemSize; - if ( this.z < min.z ) { + this.array[ index ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - this.z = min.z; + return this; - } else if ( this.z > max.z ) { + }, - this.z = max.z; + clone: function () { - } + return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize ); - return this; + } - }, +}; - clampScalar: ( function () { +// - var min, max; +THREE.Int8Attribute = function ( data, itemSize ) { - return function ( minVal, maxVal ) { + THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - if ( min === undefined ) { +}; - min = new THREE.Vector3(); - max = new THREE.Vector3(); +THREE.Uint8Attribute = function ( data, itemSize ) { - } + THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); +}; - return this.clamp( min, max ); +THREE.Uint8ClampedAttribute = function ( data, itemSize ) { - }; + THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - } )(), - floor: function () { +}; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); +THREE.Int16Attribute = function ( data, itemSize ) { - return this; + THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - }, +}; - ceil: function () { +THREE.Uint16Attribute = function ( data, itemSize ) { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - return this; +}; - }, +THREE.Int32Attribute = function ( data, itemSize ) { - round: function () { + THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); +}; - return this; +THREE.Uint32Attribute = function ( data, itemSize ) { - }, + THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - roundToZero: function () { +}; - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); +THREE.Float32Attribute = function ( data, itemSize ) { - return this; + THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - }, +}; - negate: function () { +THREE.Float64Attribute = function ( data, itemSize ) { - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); + return new THREE.BufferAttribute( data, itemSize ); - return this; +}; - }, +// File:src/core/DynamicBufferAttribute.js - dot: function ( v ) { +/** + * @author benaadams / https://twitter.com/ben_a_adams + * @author mrdoob / http://mrdoob.com/ + */ - return this.x * v.x + this.y * v.y + this.z * v.z; +THREE.DynamicBufferAttribute = function ( array, itemSize ) { - }, + THREE.BufferAttribute.call( this, array, itemSize ); - lengthSq: function () { + this.updateRange = { offset: 0, count: -1 }; - return this.x * this.x + this.y * this.y + this.z * this.z; +}; - }, +THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); +THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute; - length: function () { +THREE.DynamicBufferAttribute.prototype.clone = function () { - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize ); - }, +}; - lengthManhattan: function () { +// File:src/core/BufferGeometry.js - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - }, +THREE.BufferGeometry = function () { - normalize: function () { + Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); - return this.divideScalar( this.length() ); + this.uuid = THREE.Math.generateUUID(); - }, + this.name = ''; + this.type = 'BufferGeometry'; - setLength: function ( l ) { + this.attributes = {}; + this.attributesKeys = []; - var oldLength = this.length(); + this.drawcalls = []; + this.offsets = this.drawcalls; // backwards compatibility - if ( oldLength !== 0 && l !== oldLength ) { + this.boundingBox = null; + this.boundingSphere = null; - this.multiplyScalar( l / oldLength ); - } +}; - return this; +THREE.BufferGeometry.prototype = { - }, + constructor: THREE.BufferGeometry, - lerp: function ( v, alpha ) { + addAttribute: function ( name, attribute ) { - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + if ( attribute instanceof THREE.BufferAttribute === false ) { - return this; + THREE.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - }, + this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] }; - lerpVectors: function ( v1, v2, alpha ) { + return; - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + } - return this; + this.attributes[ name ] = attribute; + this.attributesKeys = Object.keys( this.attributes ); }, - cross: function ( v, w ) { + getAttribute: function ( name ) { - if ( w !== undefined ) { + return this.attributes[ name ]; - THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + }, - } + addDrawCall: function ( start, count, indexOffset ) { - var x = this.x, y = this.y, z = this.z; + this.drawcalls.push( { - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + start: start, + count: count, + index: indexOffset !== undefined ? indexOffset : 0 - return this; + } ); }, - crossVectors: function ( a, b ) { + applyMatrix: function ( matrix ) { - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + var position = this.attributes.position; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + if ( position !== undefined ) { - return this; + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - }, + } - projectOnVector: function () { + var normal = this.attributes.normal; - var v1, dot; + if ( normal !== undefined ) { - return function ( vector ) { + var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - if ( v1 === undefined ) v1 = new THREE.Vector3(); + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - v1.copy( vector ).normalize(); + } - dot = this.dot( v1 ); + if ( this.boundingBox !== null ) { - return this.copy( v1 ).multiplyScalar( dot ); + this.computeBoundingBox(); - }; + } - }(), + if ( this.boundingSphere !== null ) { - projectOnPlane: function () { + this.computeBoundingSphere(); - var v1; + } - return function ( planeNormal ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); + center: function () { - v1.copy( this ).projectOnVector( planeNormal ); + this.computeBoundingBox(); - return this.sub( v1 ); + var offset = this.boundingBox.center().negate(); - } + this.applyMatrix( new THREE.Matrix4().setPosition( offset ) ); - }(), + return offset; - reflect: function () { + }, - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + fromGeometry: function ( geometry, settings ) { - var v1; + settings = settings || { 'vertexColors': THREE.NoColors }; - return function ( normal ) { + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs; + var vertexColors = settings.vertexColors; + var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3; - if ( v1 === undefined ) v1 = new THREE.Vector3(); + var positions = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + var normals = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - } + if ( vertexColors !== THREE.NoColors ) { - }(), + var colors = new Float32Array( faces.length * 3 * 3 ); + this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); - angleTo: function ( v ) { + } - var theta = this.dot( v ) / ( this.length() * v.length() ); + if ( hasFaceVertexUv === true ) { - // clamp, to handle numerical problems + var uvs = new Float32Array( faces.length * 3 * 2 ); + this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + } - }, + for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) { - distanceTo: function ( v ) { + var face = faces[ i ]; - return Math.sqrt( this.distanceToSquared( v ) ); + var a = vertices[ face.a ]; + var b = vertices[ face.b ]; + var c = vertices[ face.c ]; - }, + positions[ i3 ] = a.x; + positions[ i3 + 1 ] = a.y; + positions[ i3 + 2 ] = a.z; - distanceToSquared: function ( v ) { + positions[ i3 + 3 ] = b.x; + positions[ i3 + 4 ] = b.y; + positions[ i3 + 5 ] = b.z; - var dx = this.x - v.x; - var dy = this.y - v.y; - var dz = this.z - v.z; + positions[ i3 + 6 ] = c.x; + positions[ i3 + 7 ] = c.y; + positions[ i3 + 8 ] = c.z; - return dx * dx + dy * dy + dz * dz; + if ( hasFaceVertexNormals === true ) { - }, + var na = face.vertexNormals[ 0 ]; + var nb = face.vertexNormals[ 1 ]; + var nc = face.vertexNormals[ 2 ]; - setEulerFromRotationMatrix: function ( m, order ) { + normals[ i3 ] = na.x; + normals[ i3 + 1 ] = na.y; + normals[ i3 + 2 ] = na.z; - THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + normals[ i3 + 3 ] = nb.x; + normals[ i3 + 4 ] = nb.y; + normals[ i3 + 5 ] = nb.z; - }, + normals[ i3 + 6 ] = nc.x; + normals[ i3 + 7 ] = nc.y; + normals[ i3 + 8 ] = nc.z; - setEulerFromQuaternion: function ( q, order ) { + } else { - THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + var n = face.normal; - }, + normals[ i3 ] = n.x; + normals[ i3 + 1 ] = n.y; + normals[ i3 + 2 ] = n.z; - getPositionFromMatrix: function ( m ) { + normals[ i3 + 3 ] = n.x; + normals[ i3 + 4 ] = n.y; + normals[ i3 + 5 ] = n.z; - THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); + normals[ i3 + 6 ] = n.x; + normals[ i3 + 7 ] = n.y; + normals[ i3 + 8 ] = n.z; - return this.setFromMatrixPosition( m ); + } - }, + if ( vertexColors === THREE.FaceColors ) { - getScaleFromMatrix: function ( m ) { + var fc = face.color; - THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); + colors[ i3 ] = fc.r; + colors[ i3 + 1 ] = fc.g; + colors[ i3 + 2 ] = fc.b; - return this.setFromMatrixScale( m ); - }, + colors[ i3 + 3 ] = fc.r; + colors[ i3 + 4 ] = fc.g; + colors[ i3 + 5 ] = fc.b; - getColumnFromMatrix: function ( index, matrix ) { + colors[ i3 + 6 ] = fc.r; + colors[ i3 + 7 ] = fc.g; + colors[ i3 + 8 ] = fc.b; - THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); + } else if ( vertexColors === THREE.VertexColors ) { - return this.setFromMatrixColumn( index, matrix ); + var vca = face.vertexColors[ 0 ]; + var vcb = face.vertexColors[ 1 ]; + var vcc = face.vertexColors[ 2 ]; - }, + colors[ i3 ] = vca.r; + colors[ i3 + 1 ] = vca.g; + colors[ i3 + 2 ] = vca.b; - setFromMatrixPosition: function ( m ) { + colors[ i3 + 3 ] = vcb.r; + colors[ i3 + 4 ] = vcb.g; + colors[ i3 + 5 ] = vcb.b; - this.x = m.elements[ 12 ]; - this.y = m.elements[ 13 ]; - this.z = m.elements[ 14 ]; + colors[ i3 + 6 ] = vcc.r; + colors[ i3 + 7 ] = vcc.g; + colors[ i3 + 8 ] = vcc.b; - return this; + } - }, + if ( hasFaceVertexUv === true ) { - setFromMatrixScale: function ( m ) { + var uva = faceVertexUvs[ 0 ][ i ][ 0 ]; + var uvb = faceVertexUvs[ 0 ][ i ][ 1 ]; + var uvc = faceVertexUvs[ 0 ][ i ][ 2 ]; - var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); - var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); - var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); + uvs[ i2 ] = uva.x; + uvs[ i2 + 1 ] = uva.y; - this.x = sx; - this.y = sy; - this.z = sz; + uvs[ i2 + 2 ] = uvb.x; + uvs[ i2 + 3 ] = uvb.y; - return this; - }, + uvs[ i2 + 4 ] = uvc.x; + uvs[ i2 + 5 ] = uvc.y; - setFromMatrixColumn: function ( index, matrix ) { - - var offset = index * 4; + } - var me = matrix.elements; + } - this.x = me[ offset ]; - this.y = me[ offset + 1 ]; - this.z = me[ offset + 2 ]; + this.computeBoundingSphere() return this; }, - equals: function ( v ) { + computeBoundingBox: function () { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + var vector = new THREE.Vector3(); - }, + return function () { - fromArray: function ( array, offset ) { + if ( this.boundingBox === null ) { - if ( offset === undefined ) offset = 0; + this.boundingBox = new THREE.Box3(); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + } - return this; + var positions = this.attributes.position.array; - }, + if ( positions ) { - toArray: function ( array, offset ) { + var bb = this.boundingBox; + bb.makeEmpty(); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + for ( var i = 0, il = positions.length; i < il; i += 3 ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); + bb.expandByPoint( vector ); - return array; + } - }, + } - fromAttribute: function ( attribute, index, offset ) { + if ( positions === undefined || positions.length === 0 ) { - if ( offset === undefined ) offset = 0; + this.boundingBox.min.set( 0, 0, 0 ); + this.boundingBox.max.set( 0, 0, 0 ); - index = index * attribute.itemSize + offset; + } - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - return this; + THREE.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' ); - }, + } - clone: function () { + } - return new THREE.Vector3( this.x, this.y, this.z ); + }(), - } + computeBoundingSphere: function () { -}; + var box = new THREE.Box3(); + var vector = new THREE.Vector3(); -// File:src/math/Vector4.js + return function () { -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + if ( this.boundingSphere === null ) { -THREE.Vector4 = function ( x, y, z, w ) { + this.boundingSphere = new THREE.Sphere(); - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + } -}; + var positions = this.attributes.position.array; -THREE.Vector4.prototype = { + if ( positions ) { - constructor: THREE.Vector4, + box.makeEmpty(); - set: function ( x, y, z, w ) { + var center = this.boundingSphere.center; - this.x = x; - this.y = y; - this.z = z; - this.w = w; - - return this; - - }, - - setX: function ( x ) { - - this.x = x; - - return this; - - }, - - setY: function ( y ) { - - this.y = y; - - return this; - - }, - - setZ: function ( z ) { - - this.z = z; - - return this; + for ( var i = 0, il = positions.length; i < il; i += 3 ) { - }, + vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); + box.expandByPoint( vector ); - setW: function ( w ) { + } - this.w = w; + box.center( center ); - return this; + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - }, + var maxRadiusSq = 0; - setComponent: function ( index, value ) { + for ( var i = 0, il = positions.length; i < il; i += 3 ) { - switch ( index ) { + vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); + } - } + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - }, + if ( isNaN( this.boundingSphere.radius ) ) { - getComponent: function ( index ) { + THREE.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' ); - switch ( index ) { + } - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); + } } - }, - - copy: function ( v ) { + }(), - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + computeFaceNormals: function () { - return this; + // backwards compatibility }, - add: function ( v, w ) { - - if ( w !== undefined ) { - - THREE.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + computeVertexNormals: function () { - } + var attributes = this.attributes; - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + if ( attributes.position ) { - return this; + var positions = attributes.position.array; - }, + if ( attributes.normal === undefined ) { - addScalar: function ( s ) { + this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); - this.x += s; - this.y += s; - this.z += s; - this.w += s; + } else { - return this; + // reset existing normals to zero - }, + var normals = attributes.normal.array; - addVectors: function ( a, b ) { + for ( var i = 0, il = normals.length; i < il; i ++ ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + normals[ i ] = 0; - return this; + } - }, + } - sub: function ( v, w ) { + var normals = attributes.normal.array; - if ( w !== undefined ) { + var vA, vB, vC, - THREE.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + pA = new THREE.Vector3(), + pB = new THREE.Vector3(), + pC = new THREE.Vector3(), - } + cb = new THREE.Vector3(), + ab = new THREE.Vector3(); - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + // indexed elements - return this; + if ( attributes.index ) { - }, + var indices = attributes.index.array; - subScalar: function ( s ) { + var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] ); - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + for ( var j = 0, jl = offsets.length; j < jl; ++ j ) { - return this; + var start = offsets[ j ].start; + var count = offsets[ j ].count; + var index = offsets[ j ].index; - }, + for ( var i = start, il = start + count; i < il; i += 3 ) { - subVectors: function ( a, b ) { + vA = ( index + indices[ i ] ) * 3; + vB = ( index + indices[ i + 1 ] ) * 3; + vC = ( index + indices[ i + 2 ] ) * 3; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - return this; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - }, + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - multiplyScalar: function ( scalar ) { + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - return this; + } - }, + } - applyMatrix4: function ( m ) { + } else { - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; + // non-indexed elements (unconnected triangle soup) - var e = m.elements; + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - return this; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - }, + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - divideScalar: function ( scalar ) { + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - if ( scalar !== 0 ) { + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - var invScalar = 1 / scalar; + } - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; - this.w *= invScalar; + } - } else { + this.normalizeNormals(); - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 1; + attributes.normal.needsUpdate = true; } - return this; - }, - setAxisAngleFromQuaternion: function ( q ) { + computeTangents: function () { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) - // q is assumed to be normalized + if ( this.attributes.index === undefined || + this.attributes.position === undefined || + this.attributes.normal === undefined || + this.attributes.uv === undefined ) { - this.w = 2 * Math.acos( q.w ); + THREE.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' ); + return; - var s = Math.sqrt( 1 - q.w * q.w ); + } - if ( s < 0.0001 ) { + var indices = this.attributes.index.array; + var positions = this.attributes.position.array; + var normals = this.attributes.normal.array; + var uvs = this.attributes.uv.array; - this.x = 1; - this.y = 0; - this.z = 0; + var nVertices = positions.length / 3; - } else { + if ( this.attributes.tangent === undefined ) { - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); } - return this; - - }, - - setAxisAngleFromRotationMatrix: function ( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + var tangents = this.attributes.tangent.array; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + var tan1 = [], tan2 = []; - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + for ( var k = 0; k < nVertices; k ++ ) { - te = m.elements, + tan1[ k ] = new THREE.Vector3(); + tan2[ k ] = new THREE.Vector3(); - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + } - if ( ( Math.abs( m12 - m21 ) < epsilon ) - && ( Math.abs( m13 - m31 ) < epsilon ) - && ( Math.abs( m23 - m32 ) < epsilon ) ) { + var vA = new THREE.Vector3(), + vB = new THREE.Vector3(), + vC = new THREE.Vector3(), - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + uvA = new THREE.Vector2(), + uvB = new THREE.Vector2(), + uvC = new THREE.Vector2(), - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) - && ( Math.abs( m13 + m31 ) < epsilon2 ) - && ( Math.abs( m23 + m32 ) < epsilon2 ) - && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + x1, x2, y1, y2, z1, z2, + s1, s2, t1, t2, r; - // this singularity is identity matrix so angle = 0 + var sdir = new THREE.Vector3(), tdir = new THREE.Vector3(); - this.set( 1, 0, 0, 0 ); + function handleTriangle( a, b, c ) { - return this; // zero angle, arbitrary axis + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); - } + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); - // otherwise this singularity is angle = 180 + x1 = vB.x - vA.x; + x2 = vC.x - vA.x; - angle = Math.PI; + y1 = vB.y - vA.y; + y2 = vC.y - vA.y; - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; + z1 = vB.z - vA.z; + z2 = vC.z - vA.z; - if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term + s1 = uvB.x - uvA.x; + s2 = uvC.x - uvA.x; - if ( xx < epsilon ) { + t1 = uvB.y - uvA.y; + t2 = uvC.y - uvA.y; - x = 0; - y = 0.707106781; - z = 0.707106781; + r = 1.0 / ( s1 * t2 - s2 * t1 ); - } else { + sdir.set( + ( t2 * x1 - t1 * x2 ) * r, + ( t2 * y1 - t1 * y2 ) * r, + ( t2 * z1 - t1 * z2 ) * r + ); - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + tdir.set( + ( s1 * x2 - s2 * x1 ) * r, + ( s1 * y2 - s2 * y1 ) * r, + ( s1 * z2 - s2 * z1 ) * r + ); - } + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); - } else if ( yy > zz ) { // m22 is the largest diagonal term + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); - if ( yy < epsilon ) { + } - x = 0.707106781; - y = 0; - z = 0.707106781; + var i, il; + var j, jl; + var iA, iB, iC; - } else { + if ( this.drawcalls.length === 0 ) { - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + this.addDrawCall( 0, indices.length, 0 ); - } + } - } else { // m33 is the largest diagonal term so base result on this + var drawcalls = this.drawcalls; - if ( zz < epsilon ) { + for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) { - x = 0.707106781; - y = 0.707106781; - z = 0; + var start = drawcalls[ j ].start; + var count = drawcalls[ j ].count; + var index = drawcalls[ j ].index; - } else { + for ( i = start, il = start + count; i < il; i += 3 ) { - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + iA = index + indices[ i ]; + iB = index + indices[ i + 1 ]; + iC = index + indices[ i + 2 ]; - } + handleTriangle( iA, iB, iC ); } - this.set( x, y, z, angle ); - - return this; // return 180 deg rotation - } - // as we have reached here there are no singularities so we can handle normally - - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) - + ( m13 - m31 ) * ( m13 - m31 ) - + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(); + var n = new THREE.Vector3(), n2 = new THREE.Vector3(); + var w, t, test; - if ( Math.abs( s ) < 0.001 ) s = 1; + function handleVertex( v ) { - // 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 + n.fromArray( normals, v * 3 ); + n2.copy( n ); - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + t = tan1[ v ]; - return this; + // Gram-Schmidt orthogonalize - }, + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); - min: function ( v ) { + // Calculate handedness - if ( this.x > v.x ) { + tmp2.crossVectors( n2, t ); + test = tmp2.dot( tan2[ v ] ); + w = ( test < 0.0 ) ? - 1.0 : 1.0; - this.x = v.x; + tangents[ v * 4 ] = tmp.x; + tangents[ v * 4 + 1 ] = tmp.y; + tangents[ v * 4 + 2 ] = tmp.z; + tangents[ v * 4 + 3 ] = w; } - if ( this.y > v.y ) { - - this.y = v.y; - - } + for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) { - if ( this.z > v.z ) { + var start = drawcalls[ j ].start; + var count = drawcalls[ j ].count; + var index = drawcalls[ j ].index; - this.z = v.z; + for ( i = start, il = start + count; i < il; i += 3 ) { - } + iA = index + indices[ i ]; + iB = index + indices[ i + 1 ]; + iC = index + indices[ i + 2 ]; - if ( this.w > v.w ) { + handleVertex( iA ); + handleVertex( iB ); + handleVertex( iC ); - this.w = v.w; + } } - return this; - }, - max: function ( v ) { - - if ( this.x < v.x ) { - - this.x = v.x; - - } - - if ( this.y < v.y ) { - - this.y = v.y; + /* + Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices. + This method will effectively rewrite the index buffer and remap all attributes to match the new indices. + WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets. + size - Defaults to 65535, but allows for larger or smaller chunks. + */ + computeOffsets: function ( size ) { - } + if ( size === undefined ) size = 65535; // WebGL limits type of index buffer values to 16-bit. - if ( this.z < v.z ) { + var indices = this.attributes.index.array; + var vertices = this.attributes.position.array; - this.z = v.z; + var facesCount = ( indices.length / 3 ); - } + /* + console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length); + console.log("Faces to process: "+(indices.length/3)); + console.log("Reordering "+verticesCount+" vertices."); + */ - if ( this.w < v.w ) { + var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers + var indexPtr = 0; + var vertexPtr = 0; - this.w = v.w; + var offsets = [ { start:0, count:0, index:0 } ]; + var offset = offsets[ 0 ]; - } + var duplicatedVertices = 0; + var newVerticeMaps = 0; + var faceVertices = new Int32Array( 6 ); + var vertexMap = new Int32Array( vertices.length ); + var revVertexMap = new Int32Array( vertices.length ); + for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; } - return this; + /* + Traverse every face and reorder vertices in the proper offsets of 65k. + We can have more than 65k entries in the index buffer per offset, but only reference 65k values. + */ + for ( var findex = 0; findex < facesCount; findex ++ ) { + newVerticeMaps = 0; - }, + for ( var vo = 0; vo < 3; vo ++ ) { + var vid = indices[ findex * 3 + vo ]; + if ( vertexMap[ vid ] == - 1 ) { + //Unmapped vertice + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = - 1; + newVerticeMaps ++; + } else if ( vertexMap[ vid ] < offset.index ) { + //Reused vertices from previous block (duplicate) + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = - 1; + duplicatedVertices ++; + } else { + //Reused vertice in the current block + faceVertices[ vo * 2 ] = vid; + faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ]; + } + } - clamp: function ( min, max ) { + var faceMax = vertexPtr + newVerticeMaps; + if ( faceMax > ( offset.index + size ) ) { + var new_offset = { start:indexPtr, count:0, index:vertexPtr }; + offsets.push( new_offset ); + offset = new_offset; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + //Re-evaluate reused vertices in light of new offset. + for ( var v = 0; v < 6; v += 2 ) { + var new_vid = faceVertices[ v + 1 ]; + if ( new_vid > - 1 && new_vid < offset.index ) + faceVertices[ v + 1 ] = - 1; + } + } - if ( this.x < min.x ) { + //Reindex the face. + for ( var v = 0; v < 6; v += 2 ) { + var vid = faceVertices[ v ]; + var new_vid = faceVertices[ v + 1 ]; - this.x = min.x; + if ( new_vid === - 1 ) + new_vid = vertexPtr ++; - } else if ( this.x > max.x ) { + vertexMap[ vid ] = new_vid; + revVertexMap[ new_vid ] = vid; + sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit + offset.count ++; + } + } - this.x = max.x; + /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */ + this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr ); + this.offsets = offsets; // TODO: Deprecate + this.drawcalls = offsets; - } + /* + var orderTime = Date.now(); + console.log("Reorder time: "+(orderTime-s)+"ms"); + console.log("Duplicated "+duplicatedVertices+" vertices."); + console.log("Compute Buffers time: "+(Date.now()-s)+"ms"); + console.log("Draw offsets: "+offsets.length); + */ - if ( this.y < min.y ) { + return offsets; - this.y = min.y; + }, - } else if ( this.y > max.y ) { + merge: function ( geometry, offset ) { - this.y = max.y; + if ( geometry instanceof THREE.BufferGeometry === false ) { + + THREE.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; } - if ( this.z < min.z ) { + if ( offset === undefined ) offset = 0; - this.z = min.z; + var attributes = this.attributes; - } else if ( this.z > max.z ) { + for ( var key in attributes ) { - this.z = max.z; + if ( geometry.attributes[ key ] === undefined ) continue; - } + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - if ( this.w < min.w ) { + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - this.w = min.w; + var attributeSize = attribute2.itemSize; - } else if ( this.w > max.w ) { + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - this.w = max.w; + attributeArray1[ j ] = attributeArray2[ i ]; + + } } @@ -9410,25893 +9291,26056 @@ THREE.Vector4.prototype = { }, - clampScalar: ( function () { - - var min, max; + normalizeNormals: function () { - return function ( minVal, maxVal ) { + var normals = this.attributes.normal.array; - if ( min === undefined ) { + var x, y, z, n; - min = new THREE.Vector4(); - max = new THREE.Vector4(); + for ( var i = 0, il = normals.length; i < il; i += 3 ) { - } + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - return this.clamp( min, max ); + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; - }; + } - } )(), + }, - floor: function () { + /* + reoderBuffers: + Reorder attributes based on a new indexBuffer and indexMap. + indexBuffer - Uint16Array of the new ordered indices. + indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex. + vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack). + */ + reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + /* Create a copy of all attributes for reordering. */ + var sortedAttributes = {}; + for ( var attr in this.attributes ) { + if ( attr == 'index' ) + continue; + var sourceArray = this.attributes[ attr ].array; + sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount ); + } - return this; + /* Move attribute positions based on the new index map */ + for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) { + var vid = indexMap[ new_vid ]; + for ( var attr in this.attributes ) { + if ( attr == 'index' ) + continue; + var attrArray = this.attributes[ attr ].array; + var attrSize = this.attributes[ attr ].itemSize; + var sortedAttr = sortedAttributes[ attr ]; + for ( var k = 0; k < attrSize; k ++ ) + sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ]; + } + } - }, + /* Carry the new sorted buffers locally */ + this.attributes[ 'index' ].array = indexBuffer; + for ( var attr in this.attributes ) { + if ( attr == 'index' ) + continue; + this.attributes[ attr ].array = sortedAttributes[ attr ]; + this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount; + } + }, - ceil: function () { + toJSON: function () { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + var output = { + metadata: { + version: 4.0, + type: 'BufferGeometry', + generator: 'BufferGeometryExporter' + }, + uuid: this.uuid, + type: this.type, + data: { + attributes: {} + } + }; - return this; + var attributes = this.attributes; + var offsets = this.offsets; + var boundingSphere = this.boundingSphere; - }, + for ( var key in attributes ) { - round: function () { + var attribute = attributes[ key ]; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + var array = Array.prototype.slice.call( attribute.array ); - return this; + output.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array + } - }, + } - roundToZero: function () { + if ( offsets.length > 0 ) { - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + output.data.offsets = JSON.parse( JSON.stringify( offsets ) ); - return this; + } - }, + if ( boundingSphere !== null ) { - negate: function () { + output.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + } - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + } - return this; + return output; }, - dot: function ( v ) { + clone: function () { - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + var geometry = new THREE.BufferGeometry(); - }, + for ( var attr in this.attributes ) { - lengthSq: function () { + var sourceAttr = this.attributes[ attr ]; + geometry.addAttribute( attr, sourceAttr.clone() ); - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } - }, + for ( var i = 0, il = this.offsets.length; i < il; i ++ ) { - length: function () { + var offset = this.offsets[ i ]; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + geometry.offsets.push( { - }, + start: offset.start, + index: offset.index, + count: offset.count - lengthManhattan: function () { + } ); - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + } - }, + return geometry; - normalize: function () { + }, - return this.divideScalar( this.length() ); + dispose: function () { - }, + this.dispatchEvent( { type: 'dispose' } ); - setLength: function ( l ) { + } - var oldLength = this.length(); +}; - if ( oldLength !== 0 && l !== oldLength ) { +THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); - this.multiplyScalar( l / oldLength ); +// File:src/core/Geometry.js - } +/** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author bhouston / http://exocortex.com + */ - return this; +THREE.Geometry = function () { - }, + Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); - lerp: function ( v, alpha ) { + this.uuid = THREE.Math.generateUUID(); - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; + this.name = ''; + this.type = 'Geometry'; - return this; + this.vertices = []; + this.colors = []; // one-to-one vertex colors, used in Points and Line - }, + this.faces = []; - lerpVectors: function ( v1, v2, alpha ) { + this.faceVertexUvs = [ [] ]; - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + this.morphTargets = []; + this.morphColors = []; + this.morphNormals = []; - return this; + this.skinWeights = []; + this.skinIndices = []; - }, + this.lineDistances = []; - equals: function ( v ) { + this.boundingBox = null; + this.boundingSphere = null; - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + this.hasTangents = false; - }, + this.dynamic = true; // the intermediate typed arrays will be deleted when set to false - fromArray: function ( array, offset ) { + // update flags - if ( offset === undefined ) offset = 0; + this.verticesNeedUpdate = false; + this.elementsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.tangentsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + this.groupsNeedUpdate = false; - return this; +}; - }, +THREE.Geometry.prototype = { - toArray: function ( array, offset ) { + constructor: THREE.Geometry, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + applyMatrix: function ( matrix ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - return array; + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - }, + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - fromAttribute: function ( attribute, index, offset ) { + } - if ( offset === undefined ) offset = 0; + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - index = index * attribute.itemSize + offset; + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - return this; + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - }, + } - clone: function () { + } - return new THREE.Vector4( this.x, this.y, this.z, this.w ); + if ( this.boundingBox !== null ) { - } + this.computeBoundingBox(); -}; + } -// File:src/math/Euler.js + if ( this.boundingSphere !== null ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ + this.computeBoundingSphere(); -THREE.Euler = function ( x, y, z, order ) { + } - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - this.__defineGetter__("x", function(){ - return this._x; - }); - this.__defineSetter__("x", function(value){ - this._x = value; - this.onChangeCallback(); - }); + }, - this.__defineGetter__("y", function(){ - return this._y; - }); - this.__defineSetter__("y", function(value){ - this._y = value; - this.onChangeCallback(); - }); + fromBufferGeometry: function ( geometry ) { - this.__defineGetter__("z", function(){ - return this._z; - }); - this.__defineSetter__("z", function(value){ - this._z = value; - this.onChangeCallback(); - }); + var scope = this; - this.__defineGetter__("order", function(){ - return this._order; - }); - this.__defineSetter__("order", function(value){ - this._order = value; - this.onChangeCallback(); - }); -}; + var attributes = geometry.attributes; -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + var vertices = attributes.position.array; + var indices = attributes.index !== undefined ? attributes.index.array : undefined; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; -THREE.Euler.DefaultOrder = 'XYZ'; + var tempNormals = []; + var tempUVs = []; -THREE.Euler.prototype = { + for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) { - constructor: THREE.Euler, + scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder, + if ( normals !== undefined ) { - set: function ( x, y, z, order ) { + tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + } - this.onChangeCallback(); + if ( colors !== undefined ) { - return this; + scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - }, + } - copy: function ( euler ) { + if ( uvs !== undefined ) { - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - this.onChangeCallback(); + } - return this; + } - }, + var addFace = function ( a, b, c ) { - setFromRotationMatrix: function ( m, order, update ) { + var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; + var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; - var clamp = THREE.Math.clamp; + scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) ); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + if ( uvs !== undefined ) { - var te = m.elements; - var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - order = order || this._order; + } - if ( order === 'XYZ' ) { + }; - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + if ( indices !== undefined ) { - if ( Math.abs( m13 ) < 0.99999 ) { + var drawcalls = geometry.drawcalls; - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + if ( drawcalls.length > 0 ) { - } else { + for ( var i = 0; i < drawcalls.length; i ++ ) { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + var drawcall = drawcalls[ i ]; - } + var start = drawcall.start; + var count = drawcall.count; + var index = drawcall.index; - } else if ( order === 'YXZ' ) { + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + addFace( index + indices[ j ], index + indices[ j + 1 ], index + indices[ j + 2 ] ); - if ( Math.abs( m23 ) < 0.99999 ) { + } - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + } } else { - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + for ( var i = 0; i < indices.length; i += 3 ) { - } + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - } else if ( order === 'ZXY' ) { + } - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + } - if ( Math.abs( m32 ) < 0.99999 ) { + } else { - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); - - } else { + for ( var i = 0; i < vertices.length / 3; i += 3 ) { - this._y = 0; - this._z = Math.atan2( m21, m11 ); + addFace( i, i + 1, i + 2 ); } - } else if ( order === 'ZYX' ) { + } - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + this.computeFaceNormals(); - if ( Math.abs( m31 ) < 0.99999 ) { + if ( geometry.boundingBox !== null ) { - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + this.boundingBox = geometry.boundingBox.clone(); - } else { + } - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + if ( geometry.boundingSphere !== null ) { - } + this.boundingSphere = geometry.boundingSphere.clone(); - } else if ( order === 'YZX' ) { + } - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + return this; - if ( Math.abs( m21 ) < 0.99999 ) { + }, - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + center: function () { - } else { + this.computeBoundingBox(); - this._x = 0; - this._y = Math.atan2( m13, m33 ); + var offset = this.boundingBox.center().negate(); - } + this.applyMatrix( new THREE.Matrix4().setPosition( offset ) ); - } else if ( order === 'XZY' ) { + return offset; - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + }, - if ( Math.abs( m12 ) < 0.99999 ) { + computeFaceNormals: function () { - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + var cb = new THREE.Vector3(), ab = new THREE.Vector3(); - } else { + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + var face = this.faces[ f ]; - } + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - } else { + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - THREE.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ) + cb.normalize(); + + face.normal.copy( cb ); } - this._order = order; + }, - if ( update !== false ) this.onChangeCallback(); + computeVertexNormals: function ( areaWeighted ) { - return this; + var v, vl, f, fl, face, vertices; - }, + vertices = new Array( this.vertices.length ); - setFromQuaternion: function () { + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - var matrix; + vertices[ v ] = new THREE.Vector3(); - return function ( q, order, update ) { + } - if ( matrix === undefined ) matrix = new THREE.Matrix4(); - matrix.makeRotationFromQuaternion( q ); - this.setFromRotationMatrix( matrix, order, update ); + if ( areaWeighted ) { - return this; + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - }; + var vA, vB, vC; + var cb = new THREE.Vector3(), ab = new THREE.Vector3(); - }(), + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - setFromVector3: function ( v, order ) { + face = this.faces[ f ]; - return this.set( v.x, v.y, v.z, order || this._order ); + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - }, + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - reorder: function () { + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - // WARNING: this discards revolution information -bhouston + } - var q = new THREE.Quaternion(); + } else { - return function ( newOrder ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - q.setFromEuler( this ); - this.setFromQuaternion( q, newOrder ); + face = this.faces[ f ]; - }; + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - }(), + } - equals: function ( euler ) { + } - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - }, + vertices[ v ].normalize(); - fromArray: function ( array ) { + } - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.onChangeCallback(); + face = this.faces[ f ]; - return this; + face.vertexNormals[ 0 ] = vertices[ face.a ].clone(); + face.vertexNormals[ 1 ] = vertices[ face.b ].clone(); + face.vertexNormals[ 2 ] = vertices[ face.c ].clone(); + + } }, - toArray: function ( array, offset ) { + computeMorphNormals: function () { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var i, il, f, fl, face; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - return array; - }, + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - toVector3: function ( optionalResult ) { + face = this.faces[ f ]; - if ( optionalResult ) { + if ( ! face.__originalFaceNormal ) { - return optionalResult.set( this._x, this._y, this._z ); + face.__originalFaceNormal = face.normal.clone(); - } else { + } else { - return new THREE.Vector3( this._x, this._y, this._z ); + face.__originalFaceNormal.copy( face.normal ); - } + } - }, + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - onChange: function ( callback ) { + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - this.onChangeCallback = callback; + if ( ! face.__originalVertexNormals[ i ] ) { - return this; + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - }, + } else { - onChangeCallback: function () {}, + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - clone: function () { + } - return new THREE.Euler( this._x, this._y, this._z, this._order ); + } - } + } -}; + // use temp geometry to compute face and vertex normals for each morph -// File:src/math/Line3.js + var tmpGeo = new THREE.Geometry(); + tmpGeo.faces = this.faces; -/** - * @author bhouston / http://exocortex.com - */ + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { -THREE.Line3 = function ( start, end ) { + // create on first access - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + if ( ! this.morphNormals[ i ] ) { -}; + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; -THREE.Line3.prototype = { + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - constructor: THREE.Line3, + var faceNormal, vertexNormals; - set: function ( start, end ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.start.copy( start ); - this.end.copy( end ); + faceNormal = new THREE.Vector3(); + vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; - return this; + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - }, + } - copy: function ( line ) { + } - this.start.copy( line.start ); - this.end.copy( line.end ); + var morphNormals = this.morphNormals[ i ]; - return this; + // set vertices to morph target - }, + tmpGeo.vertices = this.morphTargets[ i ].vertices; - center: function ( optionalTarget ) { + // compute morph normals - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - }, + // store morph normals - delta: function ( optionalTarget ) { + var faceNormal, vertexNormals; - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.end, this.start ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + face = this.faces[ f ]; - distanceSq: function () { + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - return this.start.distanceToSquared( this.end ); + faceNormal.copy( face.normal ); - }, + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - distance: function () { + } - return this.start.distanceTo( this.end ); + } - }, + // restore original normals - at: function ( t, optionalTarget ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - var result = optionalTarget || new THREE.Vector3(); + face = this.faces[ f ]; - return this.delta( result ).multiplyScalar( t ).add( this.start ); + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - }, + } - closestPointToPointParameter: function () { + }, - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + computeTangents: function () { - return function ( point, clampToLine ) { + // based on http://www.terathon.com/code/tangent.html + // tangents go to vertices - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + var f, fl, v, vl, i, vertexIndex, + face, uv, vA, vB, vC, uvA, uvB, uvC, + x1, x2, y1, y2, z1, z2, + s1, s2, t1, t2, r, t, test, + tan1 = [], tan2 = [], + sdir = new THREE.Vector3(), tdir = new THREE.Vector3(), + tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), + n = new THREE.Vector3(), w; - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - var t = startEnd_startP / startEnd2; + tan1[ v ] = new THREE.Vector3(); + tan2[ v ] = new THREE.Vector3(); - if ( clampToLine ) { + } - t = THREE.Math.clamp( t, 0, 1 ); + function handleTriangle( context, a, b, c, ua, ub, uc ) { - } + vA = context.vertices[ a ]; + vB = context.vertices[ b ]; + vC = context.vertices[ c ]; - return t; + uvA = uv[ ua ]; + uvB = uv[ ub ]; + uvC = uv[ uc ]; - }; + x1 = vB.x - vA.x; + x2 = vC.x - vA.x; + y1 = vB.y - vA.y; + y2 = vC.y - vA.y; + z1 = vB.z - vA.z; + z2 = vC.z - vA.z; - }(), + s1 = uvB.x - uvA.x; + s2 = uvC.x - uvA.x; + t1 = uvB.y - uvA.y; + t2 = uvC.y - uvA.y; - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + r = 1.0 / ( s1 * t2 - s2 * t1 ); + sdir.set( ( t2 * x1 - t1 * x2 ) * r, + ( t2 * y1 - t1 * y2 ) * r, + ( t2 * z1 - t1 * z2 ) * r ); + tdir.set( ( s1 * x2 - s2 * x1 ) * r, + ( s1 * y2 - s2 * y1 ) * r, + ( s1 * z2 - s2 * z1 ) * r ); - var t = this.closestPointToPointParameter( point, clampToLine ); + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); - var result = optionalTarget || new THREE.Vector3(); + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); - return this.delta( result ).multiplyScalar( t ).add( this.start ); + } - }, + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - applyMatrix4: function ( matrix ) { + face = this.faces[ f ]; + uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 ); - return this; + } - }, + var faceIndex = [ 'a', 'b', 'c', 'd' ]; - equals: function ( line ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - return line.start.equals( this.start ) && line.end.equals( this.end ); + face = this.faces[ f ]; - }, + for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) { - clone: function () { + n.copy( face.vertexNormals[ i ] ); - return new THREE.Line3().copy( this ); + vertexIndex = face[ faceIndex[ i ] ]; - } + t = tan1[ vertexIndex ]; -}; + // Gram-Schmidt orthogonalize -// File:src/math/Box2.js + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); -/** - * @author bhouston / http://exocortex.com - */ + // Calculate handedness -THREE.Box2 = function ( min, max ) { + tmp2.crossVectors( face.vertexNormals[ i ], t ); + test = tmp2.dot( tan2[ vertexIndex ] ); + w = ( test < 0.0 ) ? - 1.0 : 1.0; - this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w ); -}; + } -THREE.Box2.prototype = { + } - constructor: THREE.Box2, + this.hasTangents = true; - set: function ( min, max ) { + }, - this.min.copy( min ); - this.max.copy( max ); + computeLineDistances: function () { - return this; + var d = 0; + var vertices = this.vertices; - }, + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - setFromPoints: function ( points ) { + if ( i > 0 ) { - this.makeEmpty(); + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - for ( var i = 0, il = points.length; i < il; i ++ ) { + } - this.expandByPoint( points[ i ] ) + this.lineDistances[ i ] = d; } - return this; - }, - setFromCenterAndSize: function () { + computeBoundingBox: function () { - var v1 = new THREE.Vector2(); + if ( this.boundingBox === null ) { - return function ( center, size ) { + this.boundingBox = new THREE.Box3(); - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + } - return this; + this.boundingBox.setFromPoints( this.vertices ); - }; + }, - }(), + computeBoundingSphere: function () { - copy: function ( box ) { + if ( this.boundingSphere === null ) { - this.min.copy( box.min ); - this.max.copy( box.max ); + this.boundingSphere = new THREE.Sphere(); - return this; + } + + this.boundingSphere.setFromPoints( this.vertices ); }, - makeEmpty: function () { + merge: function ( geometry, matrix, materialIndexOffset ) { - this.min.x = this.min.y = Infinity; - this.max.x = this.max.y = - Infinity; + if ( geometry instanceof THREE.Geometry === false ) { - return this; + THREE.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - }, + } - empty: function () { + var normalMatrix, + vertexOffset = this.vertices.length, + vertices1 = this.vertices, + vertices2 = geometry.vertices, + faces1 = this.faces, + faces2 = geometry.faces, + uvs1 = this.faceVertexUvs[ 0 ], + uvs2 = geometry.faceVertexUvs[ 0 ]; - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + if ( matrix !== undefined ) { - }, + normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); - center: function ( optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + // vertices - }, + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - size: function ( optionalTarget ) { + var vertex = vertices2[ i ]; - var result = optionalTarget || new THREE.Vector2(); - return result.subVectors( this.max, this.min ); + var vertexCopy = vertex.clone(); - }, + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - expandByPoint: function ( point ) { + vertices1.push( vertexCopy ); - this.min.min( point ); - this.max.max( point ); + } - return this; - }, + // faces - expandByVector: function ( vector ) { + for ( i = 0, il = faces2.length; i < il; i ++ ) { - this.min.sub( vector ); - this.max.add( vector ); + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - return this; - }, + faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - expandByScalar: function ( scalar ) { + if ( normalMatrix !== undefined ) { - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - return this; - }, + } - containsPoint: function ( point ) { + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + normal = faceVertexNormals[ j ].clone(); - return false; + if ( normalMatrix !== undefined ) { - } + normal.applyMatrix3( normalMatrix ).normalize(); - return true; + } - }, + faceCopy.vertexNormals.push( normal ); - 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 ) ) { + faceCopy.color.copy( face.color ); - return true; + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - } + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - return false; + } - }, + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - getParameter: function ( point, optionalTarget ) { + faces1.push( faceCopy ); - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + } - var result = optionalTarget || new THREE.Vector2(); + // uvs - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - }, + var uv = uvs2[ i ], uvCopy = []; - isIntersectionBox: function ( box ) { + if ( uv === undefined ) { - // using 6 splitting planes to rule out intersections. + continue; - 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; + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - } + uvCopy.push( uv[ j ].clone() ); - return true; + } + + uvs1.push( uvCopy ); + + } }, - clampPoint: function ( point, optionalTarget ) { + mergeMesh: function ( mesh ) { - var result = optionalTarget || new THREE.Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + if ( mesh instanceof THREE.Mesh === false ) { - }, + THREE.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - distanceToPoint: function () { + } - var v1 = new THREE.Vector2(); + mesh.matrixAutoUpdate && mesh.updateMatrix(); - return function ( point ) { + this.merge( mesh.geometry, mesh.matrix ); - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + }, - }; + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - }(), + mergeVertices: function () { - intersect: function ( box ) { + var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique) + var unique = [], changes = []; - this.min.max( box.min ); - this.max.min( box.max ); + var v, key; + var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; - return this; + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - }, + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - union: function ( box ) { + if ( verticesMap[ key ] === undefined ) { - this.min.min( box.min ); - this.max.max( box.max ); + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - return this; + } else { - }, + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - translate: function ( offset ) { + } - this.min.add( offset ); - this.max.add( offset ); + }; - return this; - }, + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - equals: function ( box ) { + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + face = this.faces[ i ]; - }, + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - clone: function () { + indices = [ face.a, face.b, face.c ]; - return new THREE.Box2().copy( this ); + var dupIndex = - 1; - } + // if any duplicate vertices are found in a Face3 + // we have to remove the face as nothing can be saved + for ( var n = 0; n < 3; n ++ ) { + if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) { -}; + dupIndex = n; + faceIndicesToRemove.push( i ); + break; -// File:src/math/Box3.js + } + } -/** - * @author bhouston / http://exocortex.com - * @author WestLangley / http://github.com/WestLangley - */ + } -THREE.Box3 = function ( min, max ) { + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + var idx = faceIndicesToRemove[ i ]; - this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + this.faces.splice( idx, 1 ); -}; + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { -THREE.Box3.prototype = { + this.faceVertexUvs[ j ].splice( idx, 1 ); - constructor: THREE.Box3, + } - set: function ( min, max ) { + } - this.min.copy( min ); - this.max.copy( max ); + // Use unique set of vertices - return this; + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; }, - setFromPoints: function ( points ) { + toJSON: function () { - this.makeEmpty(); + var output = { + metadata: { + version: 4.0, + type: 'BufferGeometry', + generator: 'BufferGeometryExporter' + }, + uuid: this.uuid, + type: this.type + }; - for ( var i = 0, il = points.length; i < il; i ++ ) { + if ( this.name !== "" ) output.name = this.name; - this.expandByPoint( points[ i ] ) + if ( this.parameters !== undefined ) { - } + var parameters = this.parameters; - return this; + for ( var key in parameters ) { - }, + if ( parameters[ key ] !== undefined ) output[ key ] = parameters[ key ]; - setFromCenterAndSize: function () { + } - var v1 = new THREE.Vector3(); + return output; - return function ( center, size ) { + } - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + var vertices = []; - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + for ( var i = 0; i < this.vertices.length; i ++ ) { - return this; + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - }; + } - }(), + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - setFromObject: function () { + for ( var i = 0; i < this.faces.length; i ++ ) { - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and childrens', world transforms + var face = this.faces[ i ]; - var v1 = new THREE.Vector3(); + var hasMaterial = false; // face.materialIndex !== undefined; + var hasFaceUv = false; // deprecated + var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; + var hasFaceNormal = face.normal.length() > 0; + var hasFaceVertexNormal = face.vertexNormals.length > 0; + var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; + var hasFaceVertexColor = face.vertexColors.length > 0; - return function ( object ) { + var faceType = 0; - var scope = this; + faceType = setBit( faceType, 0, 0 ); + faceType = setBit( faceType, 1, hasMaterial ); + faceType = setBit( faceType, 2, hasFaceUv ); + faceType = setBit( faceType, 3, hasFaceVertexUv ); + faceType = setBit( faceType, 4, hasFaceNormal ); + faceType = setBit( faceType, 5, hasFaceVertexNormal ); + faceType = setBit( faceType, 6, hasFaceColor ); + faceType = setBit( faceType, 7, hasFaceVertexColor ); - object.updateMatrixWorld( true ); + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); - this.makeEmpty(); - object.traverse( function ( node ) { + /* + if ( hasMaterial ) { - var geometry = node.geometry; + faces.push( face.materialIndex ); - if ( geometry !== undefined ) { + } + */ - if ( geometry instanceof THREE.Geometry ) { + if ( hasFaceVertexUv ) { - var vertices = geometry.vertices; + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - v1.copy( vertices[ i ] ); + } - v1.applyMatrix4( node.matrixWorld ); + if ( hasFaceNormal ) { - scope.expandByPoint( v1 ); + faces.push( getNormalIndex( face.normal ) ); - } + } - } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) { + if ( hasFaceVertexNormal ) { - var positions = geometry.attributes[ 'position' ].array; + var vertexNormals = face.vertexNormals; - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); + } - v1.applyMatrix4( node.matrixWorld ); + if ( hasFaceColor ) { - scope.expandByPoint( v1 ); + faces.push( getColorIndex( face.color ) ); - } + } - } + if ( hasFaceVertexColor ) { - } + var vertexColors = face.vertexColors; - } ); + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - return this; + } - }; + } - }(), + function setBit( value, position, enabled ) { - copy: function ( box ) { + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) ); - this.min.copy( box.min ); - this.max.copy( box.max ); + } - return this; + function getNormalIndex( normal ) { - }, + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - makeEmpty: function () { + if ( normalsHash[ hash ] !== undefined ) { - this.min.x = this.min.y = this.min.z = Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + return normalsHash[ hash ]; - return this; + } - }, + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - empty: function () { + return normalsHash[ hash ]; - // 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 ); + function getColorIndex( color ) { - }, + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - center: function ( optionalTarget ) { + if ( colorsHash[ hash ] !== undefined ) { - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + return colorsHash[ hash ]; - }, + } - size: function ( optionalTarget ) { + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.max, this.min ); + return colorsHash[ hash ]; - }, + } - expandByPoint: function ( point ) { + function getUvIndex( uv ) { - this.min.min( point ); - this.max.max( point ); + var hash = uv.x.toString() + uv.y.toString(); - return this; + if ( uvsHash[ hash ] !== undefined ) { - }, + return uvsHash[ hash ]; - expandByVector: function ( vector ) { + } - this.min.sub( vector ); - this.max.add( vector ); + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - return this; + return uvsHash[ hash ]; - }, + } - expandByScalar: function ( scalar ) { + output.data = {}; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + output.data.vertices = vertices; + output.data.normals = normals; + if ( colors.length > 0 ) output.data.colors = colors; + if ( uvs.length > 0 ) output.data.uvs = [ uvs ]; // temporal backward compatibility + output.data.faces = faces; - return this; + // + + return output; }, - containsPoint: function ( point ) { + clone: function () { - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ) { + var geometry = new THREE.Geometry(); - return false; + var vertices = this.vertices; - } + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - return true; + geometry.vertices.push( vertices[ i ].clone() ); - }, + } - containsBox: function ( box ) { + var faces = this.faces; - 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 ) ) { + for ( var i = 0, il = faces.length; i < il; i ++ ) { - return true; + geometry.faces.push( faces[ i ].clone() ); } - return false; + for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) { - }, + var faceVertexUvs = this.faceVertexUvs[ i ]; - getParameter: function ( point, optionalTarget ) { + if ( geometry.faceVertexUvs[ i ] === undefined ) { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + geometry.faceVertexUvs[ i ] = []; - var result = optionalTarget || new THREE.Vector3(); + } - return result.set( - ( 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 ) - ); + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - }, + var uvs = faceVertexUvs[ j ], uvsCopy = []; - isIntersectionBox: function ( box ) { + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - // using 6 splitting planes to rule out intersections. + var uv = uvs[ k ]; - 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 ) { + uvsCopy.push( uv.clone() ); - return false; + } + + geometry.faceVertexUvs[ i ].push( uvsCopy ); + + } } - return true; + return geometry; }, - clampPoint: function ( point, optionalTarget ) { + dispose: function () { - var result = optionalTarget || new THREE.Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + this.dispatchEvent( { type: 'dispose' } ); - }, + } - distanceToPoint: function () { +}; - var v1 = new THREE.Vector3(); +THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); - return function ( point ) { +THREE.GeometryIdCount = 0; - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); +// File:src/cameras/Camera.js - }; +/** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley +*/ - }(), +THREE.Camera = function () { - getBoundingSphere: function () { + THREE.Object3D.call( this ); - var v1 = new THREE.Vector3(); + this.type = 'Camera'; - return function ( optionalTarget ) { + this.matrixWorldInverse = new THREE.Matrix4(); + this.projectionMatrix = new THREE.Matrix4(); - var result = optionalTarget || new THREE.Sphere(); +}; - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; +THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Camera.prototype.constructor = THREE.Camera; - return result; +THREE.Camera.prototype.getWorldDirection = function () { - }; + var quaternion = new THREE.Quaternion(); - }(), + return function ( optionalTarget ) { - intersect: function ( box ) { + var result = optionalTarget || new THREE.Vector3(); - this.min.max( box.min ); - this.max.min( box.max ); + this.getWorldQuaternion( quaternion ); - return this; + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - }, + } - union: function ( box ) { +}(); - this.min.min( box.min ); - this.max.max( box.max ); +THREE.Camera.prototype.lookAt = function () { - return this; + // This routine does not support cameras with rotated and/or translated parent(s) - }, + var m1 = new THREE.Matrix4(); - applyMatrix4: function () { + return function ( vector ) { - var points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() - ]; + m1.lookAt( this.position, vector, this.up ); - return function ( matrix ) { + this.quaternion.setFromRotationMatrix( m1 ); - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + }; - this.makeEmpty(); - this.setFromPoints( points ); +}(); - return this; +THREE.Camera.prototype.clone = function ( camera ) { - }; + if ( camera === undefined ) camera = new THREE.Camera(); - }(), + THREE.Object3D.prototype.clone.call( this, camera ); - translate: function ( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; - - }, - - equals: function ( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - }, - - clone: function () { - - return new THREE.Box3().copy( this ); - - } + camera.matrixWorldInverse.copy( this.matrixWorldInverse ); + camera.projectionMatrix.copy( this.projectionMatrix ); + return camera; }; -// File:src/math/Matrix3.js +// File:src/cameras/CubeCamera.js /** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com */ -THREE.Matrix3 = function () { +THREE.CubeCamera = function ( near, far, cubeResolution ) { - this.elements = new Float32Array( [ + THREE.Object3D.call( this ); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + this.type = 'CubeCamera'; - ] ); + var fov = 90, aspect = 1; - if ( arguments.length > 0 ) { + var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); - THREE.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); - } + var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); -}; + var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); -THREE.Matrix3.prototype = { + var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - constructor: THREE.Matrix3, + var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); - var te = this.elements; + this.updateCubeMap = function ( renderer, scene ) { - te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13; - te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23; - te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33; + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.generateMipmaps; - return this; + renderTarget.generateMipmaps = false; - }, + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); - identity: function () { + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); - this.set( + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); - ); + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); - return this; + renderTarget.generateMipmaps = generateMipmaps; - }, + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); - copy: function ( m ) { + }; - var me = m.elements; +}; - this.set( +THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); +THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] +// File:src/cameras/OrthographicCamera.js - ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - return this; +THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { - }, + THREE.Camera.call( this ); - multiplyVector3: function ( vector ) { + this.type = 'OrthographicCamera'; - THREE.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); + this.zoom = 1; - }, + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - multiplyVector3Array: function ( a ) { + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - THREE.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); + this.updateProjectionMatrix(); - }, +}; - applyToVector3Array: function () { +THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype ); +THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera; - var v1 = new THREE.Vector3(); +THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () { - return function ( array, offset, length ) { + var dx = ( this.right - this.left ) / ( 2 * this.zoom ); + var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + var cx = ( this.right + this.left ) / 2; + var cy = ( this.top + this.bottom ) / 2; - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far ); - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { +}; - v1.x = array[ j ]; - v1.y = array[ j + 1 ]; - v1.z = array[ j + 2 ]; +THREE.OrthographicCamera.prototype.clone = function () { - v1.applyMatrix3( this ); + var camera = new THREE.OrthographicCamera(); - array[ j ] = v1.x; - array[ j + 1 ] = v1.y; - array[ j + 2 ] = v1.z; + THREE.Camera.prototype.clone.call( this, camera ); - } + camera.zoom = this.zoom; - return array; + camera.left = this.left; + camera.right = this.right; + camera.top = this.top; + camera.bottom = this.bottom; - }; + camera.near = this.near; + camera.far = this.far; - }(), + camera.projectionMatrix.copy( this.projectionMatrix ); - multiplyScalar: function ( s ) { + return camera; +}; - var te = this.elements; +// File:src/cameras/PerspectiveCamera.js - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; +/** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - return this; +THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { - }, + THREE.Camera.call( this ); - determinant: function () { + this.type = 'PerspectiveCamera'; - var te = this.elements; + this.zoom = 1; - var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + this.fov = fov !== undefined ? fov : 50; + this.aspect = aspect !== undefined ? aspect : 1; + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + this.updateProjectionMatrix(); - }, +}; - getInverse: function ( matrix, throwOnInvertible ) { +THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype ); +THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera; - // input: THREE.Matrix4 - // ( based on http://code.google.com/p/webgl-mjs/ ) - var me = matrix.elements; - var te = this.elements; +/** + * Uses Focal Length (in mm) to estimate and set FOV + * 35mm (fullframe) camera is used if frame size is not specified; + * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html + */ - te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ]; - te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ]; - te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ]; - te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ]; - te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ]; - te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ]; - te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ]; - te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ]; - te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ]; +THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) { - var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; + if ( frameHeight === undefined ) frameHeight = 24; - // no inverse + this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); + this.updateProjectionMatrix(); - if ( det === 0 ) { +} - var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0"; - if ( throwOnInvertible || false ) { +/** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * --A-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ - throw new Error( msg ); +THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) { - } else { + this.fullWidth = fullWidth; + this.fullHeight = fullHeight; + this.x = x; + this.y = y; + this.width = width; + this.height = height; - THREE.warn( msg ); + this.updateProjectionMatrix(); - } +}; - this.identity(); - return this; +THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () { - } + var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) ); - this.multiplyScalar( 1.0 / det ); + if ( this.fullWidth ) { - return this; + var aspect = this.fullWidth / this.fullHeight; + var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near; + var bottom = - top; + var left = aspect * bottom; + var right = aspect * top; + var width = Math.abs( right - left ); + var height = Math.abs( top - bottom ); - }, + this.projectionMatrix.makeFrustum( + left + this.x * width / this.fullWidth, + left + ( this.x + this.width ) * width / this.fullWidth, + top - ( this.y + this.height ) * height / this.fullHeight, + top - this.y * height / this.fullHeight, + this.near, + this.far + ); - transpose: function () { + } else { - var tmp, m = this.elements; + this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far ); - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + } - return this; +}; - }, +THREE.PerspectiveCamera.prototype.clone = function () { - flattenToArrayOffset: function ( array, offset ) { + var camera = new THREE.PerspectiveCamera(); - var te = this.elements; + THREE.Camera.prototype.clone.call( this, camera ); - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + camera.zoom = this.zoom; - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + camera.fov = this.fov; + camera.aspect = this.aspect; + camera.near = this.near; + camera.far = this.far; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + camera.projectionMatrix.copy( this.projectionMatrix ); - return array; + return camera; - }, +}; - getNormalMatrix: function ( m ) { +// File:src/lights/Light.js - // input: THREE.Matrix4 +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.getInverse( m ).transpose(); +THREE.Light = function ( color ) { - return this; + THREE.Object3D.call( this ); - }, + this.type = 'Light'; + + this.color = new THREE.Color( color ); - transposeIntoArray: function ( r ) { +}; - var m = this.elements; +THREE.Light.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Light.prototype.constructor = THREE.Light; - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; +THREE.Light.prototype.clone = function ( light ) { - return this; + if ( light === undefined ) light = new THREE.Light(); - }, + THREE.Object3D.prototype.clone.call( this, light ); - fromArray: function ( array ) { + light.color.copy( this.color ); - this.elements.set( array ); + return light; - return this; +}; - }, +// File:src/lights/AmbientLight.js - toArray: function () { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var te = this.elements; +THREE.AmbientLight = function ( color ) { - return [ - te[ 0 ], te[ 1 ], te[ 2 ], - te[ 3 ], te[ 4 ], te[ 5 ], - te[ 6 ], te[ 7 ], te[ 8 ] - ]; + THREE.Light.call( this, color ); - }, + this.type = 'AmbientLight'; - clone: function () { +}; - return new THREE.Matrix3().fromArray( this.elements ); +THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype ); +THREE.AmbientLight.prototype.constructor = THREE.AmbientLight; - } +THREE.AmbientLight.prototype.clone = function () { + + var light = new THREE.AmbientLight(); + + THREE.Light.prototype.clone.call( this, light ); + + return light; }; -// File:src/math/Matrix4.js +// File:src/lights/AreaLight.js /** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d + * @author MPanknin / http://www.redplant.de/ * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://exocortex.com - * @author WestLangley / http://github.com/WestLangley */ -THREE.Matrix4 = function () { +THREE.AreaLight = function ( color, intensity ) { - this.elements = new Float32Array( [ + THREE.Light.call( this, color ); - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + this.type = 'AreaLight'; - ] ); + this.normal = new THREE.Vector3( 0, - 1, 0 ); + this.right = new THREE.Vector3( 1, 0, 0 ); - if ( arguments.length > 0 ) { + this.intensity = ( intensity !== undefined ) ? intensity : 1; - THREE.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + this.width = 1.0; + this.height = 1.0; - } + this.constantAttenuation = 1.5; + this.linearAttenuation = 0.5; + this.quadraticAttenuation = 0.1; }; -THREE.Matrix4.prototype = { +THREE.AreaLight.prototype = Object.create( THREE.Light.prototype ); +THREE.AreaLight.prototype.constructor = THREE.AreaLight; - constructor: THREE.Matrix4, - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { +// File:src/lights/DirectionalLight.js - var te = this.elements; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; +THREE.DirectionalLight = function ( color, intensity ) { - return this; + THREE.Light.call( this, color ); - }, + this.type = 'DirectionalLight'; - identity: function () { + this.position.set( 0, 1, 0 ); + this.target = new THREE.Object3D(); - this.set( + this.intensity = ( intensity !== undefined ) ? intensity : 1; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + this.castShadow = false; + this.onlyShadow = false; - ); + // - return this; + this.shadowCameraNear = 50; + this.shadowCameraFar = 5000; - }, + this.shadowCameraLeft = - 500; + this.shadowCameraRight = 500; + this.shadowCameraTop = 500; + this.shadowCameraBottom = - 500; - copy: function ( m ) { + this.shadowCameraVisible = false; - this.elements.set( m.elements ); + this.shadowBias = 0; + this.shadowDarkness = 0.5; - return this; + this.shadowMapWidth = 512; + this.shadowMapHeight = 512; - }, + // - extractPosition: function ( m ) { + this.shadowCascade = false; - THREE.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); + this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 ); + this.shadowCascadeCount = 2; - }, + this.shadowCascadeBias = [ 0, 0, 0 ]; + this.shadowCascadeWidth = [ 512, 512, 512 ]; + this.shadowCascadeHeight = [ 512, 512, 512 ]; - copyPosition: function ( m ) { + this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ]; + this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ]; - var te = this.elements; - var me = m.elements; + this.shadowCascadeArray = []; - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + // - return this; + this.shadowMap = null; + this.shadowMapSize = null; + this.shadowCamera = null; + this.shadowMatrix = null; - }, +}; - extractBasis: function ( xAxis, yAxis, zAxis ) { - - var te = this.elements; - - xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] ); - yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] ); - zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] ); - - return this; - - }, - - makeBasis: function ( xAxis, yAxis, zAxis ) { +THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype ); +THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight; - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); +THREE.DirectionalLight.prototype.clone = function () { - return this; + var light = new THREE.DirectionalLight(); - }, + THREE.Light.prototype.clone.call( this, light ); - extractRotation: function () { + light.target = this.target.clone(); - var v1 = new THREE.Vector3(); + light.intensity = this.intensity; - return function ( m ) { + light.castShadow = this.castShadow; + light.onlyShadow = this.onlyShadow; - var te = this.elements; - var me = m.elements; + // - var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length(); - var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length(); - var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length(); + light.shadowCameraNear = this.shadowCameraNear; + light.shadowCameraFar = this.shadowCameraFar; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + light.shadowCameraLeft = this.shadowCameraLeft; + light.shadowCameraRight = this.shadowCameraRight; + light.shadowCameraTop = this.shadowCameraTop; + light.shadowCameraBottom = this.shadowCameraBottom; - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + light.shadowCameraVisible = this.shadowCameraVisible; - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + light.shadowBias = this.shadowBias; + light.shadowDarkness = this.shadowDarkness; - return this; + light.shadowMapWidth = this.shadowMapWidth; + light.shadowMapHeight = this.shadowMapHeight; - }; + // - }(), + light.shadowCascade = this.shadowCascade; - makeRotationFromEuler: function ( euler ) { + light.shadowCascadeOffset.copy( this.shadowCascadeOffset ); + light.shadowCascadeCount = this.shadowCascadeCount; - if ( euler instanceof THREE.Euler === false ) { + light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 ); + light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 ); + light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 ); - THREE.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 ); + light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 ); - } + return light; - var te = this.elements; +}; - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); +// File:src/lights/HemisphereLight.js - if ( euler.order === 'XYZ' ) { +/** + * @author alteredq / http://alteredqualia.com/ + */ - var ae = a * e, af = a * f, be = b * e, bf = b * f; +THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + THREE.Light.call( this, skyColor ); - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + this.type = 'HemisphereLight'; - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + this.position.set( 0, 100, 0 ); - } else if ( euler.order === 'YXZ' ) { + this.groundColor = new THREE.Color( groundColor ); + this.intensity = ( intensity !== undefined ) ? intensity : 1; - var ce = c * e, cf = c * f, de = d * e, df = d * f; +}; - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; +THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype ); +THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight; - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; +THREE.HemisphereLight.prototype.clone = function () { - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + var light = new THREE.HemisphereLight(); - } else if ( euler.order === 'ZXY' ) { + THREE.Light.prototype.clone.call( this, light ); - var ce = c * e, cf = c * f, de = d * e, df = d * f; + light.groundColor.copy( this.groundColor ); + light.intensity = this.intensity; - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + return light; - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; +}; - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; +// File:src/lights/PointLight.js - } else if ( euler.order === 'ZYX' ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var ae = a * e, af = a * f, be = b * e, bf = b * f; +THREE.PointLight = function ( color, intensity, distance, decay ) { - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + THREE.Light.call( this, color ); - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + this.type = 'PointLight'; - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + this.intensity = ( intensity !== undefined ) ? intensity : 1; + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - } else if ( euler.order === 'YZX' ) { +}; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; +THREE.PointLight.prototype = Object.create( THREE.Light.prototype ); +THREE.PointLight.prototype.constructor = THREE.PointLight; - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; +THREE.PointLight.prototype.clone = function () { - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + var light = new THREE.PointLight(); - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + THREE.Light.prototype.clone.call( this, light ); - } else if ( euler.order === 'XZY' ) { + light.intensity = this.intensity; + light.distance = this.distance; + light.decay = this.decay; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + return light; - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; +}; - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; +// File:src/lights/SpotLight.js - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; +/** + * @author alteredq / http://alteredqualia.com/ + */ - } +THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) { - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + THREE.Light.call( this, color ); - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + this.type = 'SpotLight'; - return this; + this.position.set( 0, 1, 0 ); + this.target = new THREE.Object3D(); - }, + this.intensity = ( intensity !== undefined ) ? intensity : 1; + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.exponent = ( exponent !== undefined ) ? exponent : 10; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - setRotationFromQuaternion: function ( q ) { + this.castShadow = false; + this.onlyShadow = false; - THREE.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); + // - return this.makeRotationFromQuaternion( q ); + this.shadowCameraNear = 50; + this.shadowCameraFar = 5000; + this.shadowCameraFov = 50; - }, + this.shadowCameraVisible = false; - makeRotationFromQuaternion: function ( q ) { + this.shadowBias = 0; + this.shadowDarkness = 0.5; - var te = this.elements; + this.shadowMapWidth = 512; + this.shadowMapHeight = 512; - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + // - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + this.shadowMap = null; + this.shadowMapSize = null; + this.shadowCamera = null; + this.shadowMatrix = null; - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; +}; - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); +THREE.SpotLight.prototype = Object.create( THREE.Light.prototype ); +THREE.SpotLight.prototype.constructor = THREE.SpotLight; - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; +THREE.SpotLight.prototype.clone = function () { - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + var light = new THREE.SpotLight(); - return this; + THREE.Light.prototype.clone.call( this, light ); - }, + light.target = this.target.clone(); - lookAt: function () { + light.intensity = this.intensity; + light.distance = this.distance; + light.angle = this.angle; + light.exponent = this.exponent; + light.decay = this.decay; - var x = new THREE.Vector3(); - var y = new THREE.Vector3(); - var z = new THREE.Vector3(); + light.castShadow = this.castShadow; + light.onlyShadow = this.onlyShadow; - return function ( eye, target, up ) { + // - var te = this.elements; + light.shadowCameraNear = this.shadowCameraNear; + light.shadowCameraFar = this.shadowCameraFar; + light.shadowCameraFov = this.shadowCameraFov; - z.subVectors( eye, target ).normalize(); + light.shadowCameraVisible = this.shadowCameraVisible; - if ( z.length() === 0 ) { + light.shadowBias = this.shadowBias; + light.shadowDarkness = this.shadowDarkness; - z.z = 1; + light.shadowMapWidth = this.shadowMapWidth; + light.shadowMapHeight = this.shadowMapHeight; - } + return light; - x.crossVectors( up, z ).normalize(); +}; - if ( x.length() === 0 ) { +// File:src/loaders/Cache.js - z.x += 0.0001; - x.crossVectors( up, z ).normalize(); +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +THREE.Cache = { - y.crossVectors( z, x ); + files: {}, + add: function ( key, file ) { - te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; - te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; - te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; + // console.log( 'THREE.Cache', 'Adding key:', key ); - return this; + this.files[ key ] = file; - }; + }, - }(), + get: function ( key ) { - multiply: function ( m, n ) { + // console.log( 'THREE.Cache', 'Checking key:', key ); - if ( n !== undefined ) { + return this.files[ key ]; - THREE.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + }, - } + remove: function ( key ) { - return this.multiplyMatrices( this, m ); + delete this.files[ key ]; }, - multiplyMatrices: function ( a, b ) { + clear: function () { - var ae = a.elements; - var be = b.elements; - var te = this.elements; + this.files = {} - var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + } - var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; +}; - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; +// File:src/loaders/Loader.js - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; +/** + * @author alteredq / http://alteredqualia.com/ + */ - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; +THREE.Loader = function ( showStatus ) { - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + this.showStatus = showStatus; + this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; - return this; + this.imageLoader = new THREE.ImageLoader(); - }, + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; + this.extractUrlBase = function ( url ) { return ""; } - multiplyToArray: function ( a, b, r ) { +}; - var te = this.elements; +THREE.Loader.prototype = { - this.multiplyMatrices( a, b ); + constructor: THREE.Loader, - r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; - r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; - r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; - r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; + crossOrigin: undefined, - return this; + addStatusElement: function () { + + var e = document.createElement( 'div' ); + + e.style.position = 'absolute'; + e.style.right = '0px'; + e.style.top = '0px'; + e.style.fontSize = '0.8em'; + e.style.textAlign = 'left'; + e.style.background = 'rgba(0,0,0,0.25)'; + e.style.color = '#fff'; + e.style.width = '120px'; + e.style.padding = '0.5em 0.5em 0.5em 0.5em'; + e.style.zIndex = 1000; + + e.innerHTML = 'Loading ...'; + + return e; }, - multiplyScalar: function ( s ) { + updateProgress: function ( progress ) { - var te = this.elements; + var message = 'Loaded '; - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + if ( progress.total ) { - return this; + message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%'; - }, - multiplyVector3: function ( vector ) { + } else { - THREE.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); - return vector.applyProjection( this ); + message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB'; + + } + + this.statusDomElement.innerHTML = message; }, - multiplyVector4: function ( vector ) { + extractUrlBase: function ( url ) { - THREE.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + var parts = url.split( '/' ); - }, + if ( parts.length === 1 ) return './'; - multiplyVector3Array: function ( a ) { + parts.pop(); - THREE.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); + return parts.join( '/' ) + '/'; }, - applyToVector3Array: function () { + initMaterials: function ( materials, texturePath ) { - var v1 = new THREE.Vector3(); + var array = []; - return function ( array, offset, length ) { + for ( var i = 0; i < materials.length; ++ i ) { - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + array[ i ] = this.createMaterial( materials[ i ], texturePath ); - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + } - v1.x = array[ j ]; - v1.y = array[ j + 1 ]; - v1.z = array[ j + 2 ]; + return array; - v1.applyMatrix4( this ); + }, - array[ j ] = v1.x; - array[ j + 1 ] = v1.y; - array[ j + 2 ] = v1.z; + needsTangents: function ( materials ) { - } + for ( var i = 0, il = materials.length; i < il; i ++ ) { - return array; + var m = materials[ i ]; - }; + if ( m instanceof THREE.ShaderMaterial ) return true; - }(), + } - rotateAxis: function ( v ) { + return false; - THREE.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + }, - v.transformDirection( this ); + createMaterial: function ( m, texturePath ) { - }, + var scope = this; - crossVector: function ( vector ) { + function nearest_pow2( n ) { - THREE.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + var l = Math.log( n ) / Math.LN2; + return Math.pow( 2, Math.round( l ) ); - }, + } - determinant: function () { + function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { - var te = this.elements; + var fullPath = texturePath + sourceFile; - var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + var texture; - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + var loader = THREE.Loader.Handlers.get( fullPath ); - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) - - ); - - }, - - transpose: function () { - - var te = this.elements; - var tmp; - - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - - return this; - - }, - - flattenToArrayOffset: function ( array, offset ) { - - var te = this.elements; - - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; - - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + if ( loader !== null ) { - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + texture = loader.load( fullPath ); - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + } else { - return array; + texture = new THREE.Texture(); - }, + loader = scope.imageLoader; + loader.crossOrigin = scope.crossOrigin; + loader.load( fullPath, function ( image ) { - getPosition: function () { + if ( THREE.Math.isPowerOfTwo( image.width ) === false || + THREE.Math.isPowerOfTwo( image.height ) === false ) { - var v1 = new THREE.Vector3(); + var width = nearest_pow2( image.width ); + var height = nearest_pow2( image.height ); - return function () { + texture.image = image.resize( width, height ); - THREE.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + } else { - var te = this.elements; - return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] ); + texture.image = image; - }; + } - }(), + texture.needsUpdate = true; - setPosition: function ( v ) { + } ); - var te = this.elements; + } - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + texture.sourceFile = sourceFile; - return this; + if ( repeat ) { - }, + texture.repeat.set( repeat[ 0 ], repeat[ 1 ] ); - getInverse: function ( m, throwOnInvertible ) { + if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements; - var me = m.elements; + } - var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ]; - var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ]; - var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ]; - var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ]; + if ( offset ) { - te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; - te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; - te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; - te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44; - te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44; - te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44; - te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34; - te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44; - te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44; - te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44; - te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34; - te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43; - te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43; - te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43; - te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33; + texture.offset.set( offset[ 0 ], offset[ 1 ] ); - var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; + } - if ( det == 0 ) { + if ( wrap ) { - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + var wrapMap = { + 'repeat': THREE.RepeatWrapping, + 'mirror': THREE.MirroredRepeatWrapping + } - if ( throwOnInvertible || false ) { + if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ]; + if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ]; - throw new Error( msg ); + } - } else { + if ( anisotropy ) { - THREE.warn( msg ); + texture.anisotropy = anisotropy; } - this.identity(); + where[ name ] = texture; - return this; } - this.multiplyScalar( 1 / det ); - - return this; - - }, - - translate: function ( v ) { - - THREE.error( 'THREE.Matrix4: .translate() has been removed.' ); - - }, + function rgb2hex( rgb ) { - rotateX: function ( angle ) { + return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; - THREE.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + } - }, + // defaults - rotateY: function ( angle ) { + var mtype = 'MeshLambertMaterial'; + var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false }; - THREE.error( 'THREE.Matrix4: .rotateY() has been removed.' ); + // parameters from model file - }, + if ( m.shading ) { - rotateZ: function ( angle ) { + var shading = m.shading.toLowerCase(); - THREE.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + if ( shading === 'phong' ) mtype = 'MeshPhongMaterial'; + else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial'; - }, + } - rotateByAxis: function ( axis, angle ) { + if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { - THREE.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + mpars.blending = THREE[ m.blending ]; - }, + } - scale: function ( v ) { + if ( m.transparent !== undefined ) { - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + mpars.transparent = m.transparent; - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + } - return this; + if ( m.opacity !== undefined && m.opacity < 1.0 ) { - }, + mpars.transparent = true; - getMaxScaleOnAxis: function () { + } - var te = this.elements; + if ( m.depthTest !== undefined ) { - var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + mpars.depthTest = m.depthTest; - return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) ); + } - }, + if ( m.depthWrite !== undefined ) { - makeTranslation: function ( x, y, z ) { + mpars.depthWrite = m.depthWrite; - this.set( + } - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + if ( m.visible !== undefined ) { - ); + mpars.visible = m.visible; - return this; + } - }, + if ( m.flipSided !== undefined ) { - makeRotationX: function ( theta ) { + mpars.side = THREE.BackSide; - var c = Math.cos( theta ), s = Math.sin( theta ); + } - this.set( + if ( m.doubleSided !== undefined ) { - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + mpars.side = THREE.DoubleSide; - ); + } - return this; + if ( m.wireframe !== undefined ) { - }, + mpars.wireframe = m.wireframe; - makeRotationY: function ( theta ) { + } - var c = Math.cos( theta ), s = Math.sin( theta ); + if ( m.vertexColors !== undefined ) { - this.set( + if ( m.vertexColors === 'face' ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + mpars.vertexColors = THREE.FaceColors; - ); + } else if ( m.vertexColors ) { - return this; + mpars.vertexColors = THREE.VertexColors; - }, + } - makeRotationZ: function ( theta ) { + } - var c = Math.cos( theta ), s = Math.sin( theta ); + // colors - this.set( + if ( m.colorDiffuse ) { - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + mpars.color = rgb2hex( m.colorDiffuse ); - ); + } else if ( m.DbgColor ) { - return this; + mpars.color = m.DbgColor; - }, + } - makeRotationAxis: function ( axis, angle ) { + if ( m.colorSpecular ) { - // Based on http://www.gamedev.net/reference/articles/article1199.asp + mpars.specular = rgb2hex( m.colorSpecular ); - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; + } - this.set( + if ( m.colorEmissive ) { - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 + mpars.emissive = rgb2hex( m.colorEmissive ); - ); + } - return this; + // modifiers - }, + if ( m.transparency !== undefined ) { - makeScale: function ( x, y, z ) { + console.warn( 'THREE.Loader: transparency has been renamed to opacity' ); + m.opacity = m.transparency; - this.set( + } - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + if ( m.opacity !== undefined ) { - ); + mpars.opacity = m.opacity; - return this; + } - }, + if ( m.specularCoef ) { - compose: function ( position, quaternion, scale ) { + mpars.shininess = m.specularCoef; - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + } - return this; + // textures - }, + if ( m.mapDiffuse && texturePath ) { - decompose: function () { + create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - var vector = new THREE.Vector3(); - var matrix = new THREE.Matrix4(); + } - return function ( position, quaternion, scale ) { + if ( m.mapLight && texturePath ) { - var te = this.elements; + create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + } - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { - sx = - sx; - } + if ( m.mapBump && texturePath ) { - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - // scale the rotation part + } - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + if ( m.mapNormal && texturePath ) { - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + } - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + if ( m.mapSpecular && texturePath ) { - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - quaternion.setFromRotationMatrix( matrix ); + } - scale.x = sx; - scale.y = sy; - scale.z = sz; + if ( m.mapAlpha && texturePath ) { - return this; + create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - }; + } - }(), + // - makeFrustum: function ( left, right, bottom, top, near, far ) { + if ( m.mapBumpScale ) { - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + mpars.bumpScale = m.mapBumpScale; - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); + } - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + if ( m.mapNormalFactor ) { - return this; + mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor ); - }, + } - makePerspective: function ( fov, aspect, near, far ) { + var material = new THREE[ mtype ]( mpars ); - var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + if ( m.DbgName !== undefined ) material.name = m.DbgName; - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + return material; - }, + } - makeOrthographic: function ( left, right, top, bottom, near, far ) { +}; - var te = this.elements; - var w = right - left; - var h = top - bottom; - var p = far - near; +THREE.Loader.Handlers = { - var x = ( right + left ) / w; - var y = ( top + bottom ) / h; - var z = ( far + near ) / p; + handlers: [], - te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + add: function ( regex, loader ) { - return this; + this.handlers.push( regex, loader ); }, - fromArray: function ( array ) { - - this.elements.set( array ); - - return this; + get: function ( file ) { - }, + for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) { - toArray: function () { + var regex = this.handlers[ i ]; + var loader = this.handlers[ i + 1 ]; - var te = this.elements; + if ( regex.test( file ) ) { - return [ - te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ], - te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ], - te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ], - te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ] - ]; + return loader; - }, + } - clone: function () { + } - return new THREE.Matrix4().fromArray( this.elements ); + return null; } }; -// File:src/math/Ray.js +// File:src/loaders/XHRLoader.js /** - * @author bhouston / http://exocortex.com + * @author mrdoob / http://mrdoob.com/ */ -THREE.Ray = function ( origin, direction ) { +THREE.XHRLoader = function ( manager ) { - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; -THREE.Ray.prototype = { - - constructor: THREE.Ray, +THREE.XHRLoader.prototype = { - set: function ( origin, direction ) { + constructor: THREE.XHRLoader, - this.origin.copy( origin ); - this.direction.copy( direction ); + load: function ( url, onLoad, onProgress, onError ) { - return this; + var scope = this; - }, + var cached = THREE.Cache.get( url ); - copy: function ( ray ) { + if ( cached !== undefined ) { - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + if ( onLoad ) onLoad( cached ); + return; - return this; + } - }, + var request = new XMLHttpRequest(); + request.onreadystatechange = function() { + if (request.readyState === XMLHttpRequest.DONE) { +// TODO: Re-visit https://bugreports.qt.io/browse/QTBUG-45581 is solved in Qt + if (request.status == 200 || request.status == 0) { + var response; +// TODO: Remove once https://bugreports.qt.io/browse/QTBUG-45862 is fixed in Qt + if ( scope.responseType == 'arraybuffer' ) + response = request.response; + else + response = request.responseText; - at: function ( t, optionalTarget ) { - - var result = optionalTarget || new THREE.Vector3(); + THREE.Cache.add( url, response ); + if ( onLoad ) onLoad( response ); + scope.manager.itemEnd( url ); + } else { + if ( onError !== undefined ) { + onError(); + } + } + } else if (request.readyState === XMLHttpRequest.HEADERS_RECEIVED) { + if ( onProgress !== undefined ) { + onProgress(); + } + } + }; - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + request.open( 'GET', url, true ); - }, + if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; + if ( this.responseType !== undefined ) request.responseType = this.responseType; - recast: function () { + request.send( null ); - var v1 = new THREE.Vector3(); + scope.manager.itemStart( url ); - return function ( t ) { + }, - this.origin.copy( this.at( t, v1 ) ); + setResponseType: function ( value ) { - return this; + this.responseType = value; - }; + }, - }(), + setCrossOrigin: function ( value ) { - closestPointToPoint: function ( point, optionalTarget ) { + this.crossOrigin = value; - var result = optionalTarget || new THREE.Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + } - if ( directionDistance < 0 ) { +}; - return result.copy( this.origin ); +// File:src/loaders/ImageLoader.js - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); +THREE.ImageLoader = function ( manager ) { - }, + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - distanceToPoint: function () { +}; - var v1 = new THREE.Vector3(); +THREE.ImageLoader.prototype = { - return function ( point ) { + constructor: THREE.ImageLoader, - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + load: function ( url, onLoad, onProgress, onError ) { - // point behind the ray + var scope = this; - if ( directionDistance < 0 ) { + var cached = THREE.Cache.get( url ); - return this.origin.distanceTo( point ); + if ( cached !== undefined ) { - } + onLoad( cached ); + return; - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + } - return v1.distanceTo( point ); + var image = document.createElement( 'img' ); - }; + image.addEventListener( 'load', function ( event ) { - }(), + THREE.Cache.add( url, image ); - distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + if ( onLoad ) onLoad( image ); + + scope.manager.itemEnd( url ); - // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + }, false ); -// return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + if ( onProgress !== undefined ) { - var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 ); - var segDir = v1.clone().sub( v0 ).normalize(); - var segExtent = v0.distanceTo( v1 ) * 0.5; - var diff = this.origin.clone().sub( segCenter ); - var a01 = - this.direction.dot( segDir ); - var b0 = diff.dot( this.direction ); - var b1 = - diff.dot( segDir ); - var c = diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; + image.addEventListener( 'progress', function ( event ) { - if ( det >= 0 ) { + onProgress( event ); - // The ray and segment are not parallel. + }, false ); - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + } - if ( s0 >= 0 ) { + if ( onError !== undefined ) { - if ( s1 >= - extDet ) { + image.addEventListener( 'error', function ( event ) { - if ( s1 <= extDet ) { + onError( event ); - // region 0 - // Minimum at interior points of ray and segment. + }, false ); - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + } - } else { + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - // region 1 + image.src = url; - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + scope.manager.itemStart( url ); - } + return image; - } else { + }, - // region 5 + setCrossOrigin: function ( value ) { - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + this.crossOrigin = value; - } + } - } else { +} - if ( s1 <= - extDet ) { +// File:src/loaders/JSONLoader.js - // region 4 +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; +THREE.JSONLoader = function ( showStatus ) { - } else if ( s1 <= extDet ) { + THREE.Loader.call( this, showStatus ); - // region 3 + this.withCredentials = false; - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; +}; - } else { +THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); +THREE.JSONLoader.prototype.constructor = THREE.JSONLoader; - // region 2 +THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // todo: unify load API to for easier SceneLoader use - } + texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url ); - } + this.onLoadStart(); + this.loadAjaxJSON( this, url, callback, texturePath ); - } else { +}; - // Ray and segment are parallel. +THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) { - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + var xhr = new XMLHttpRequest(); - } + var length = 0; - if ( optionalPointOnRay ) { + xhr.onreadystatechange = function () { - optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) ); + if ( xhr.readyState === xhr.DONE ) { - } + if ( xhr.status === 200 || xhr.status === 0 ) { - if ( optionalPointOnSegment ) { + if ( xhr.responseText ) { - optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) ); + var json = JSON.parse( xhr.responseText ); + var metadata = json.metadata; - } + if ( metadata !== undefined ) { - return sqrDist; + if ( metadata.type === 'object' ) { - }, + THREE.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - isIntersectionSphere: function ( sphere ) { + } - return this.distanceToPoint( sphere.center ) <= sphere.radius; + if ( metadata.type === 'scene' ) { - }, + THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' ); + return; - intersectSphere: function () { + } - // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/ + } - var v1 = new THREE.Vector3(); + var result = context.parse( json, texturePath ); + callback( result.geometry, result.materials ); - return function ( sphere, optionalTarget ) { + } else { - v1.subVectors( sphere.center, this.origin ); + THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' ); - var tca = v1.dot( this.direction ); + } - var d2 = v1.dot( v1 ) - tca * tca; + // in context of more complex asset initialization + // do not block on single failed file + // maybe should go even one more level up - var radius2 = sphere.radius * sphere.radius; + context.onLoadComplete(); - if ( d2 > radius2 ) return null; + } else { - var thc = Math.sqrt( radius2 - d2 ); + THREE.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' ); - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + } - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + } else if ( xhr.readyState === xhr.LOADING ) { - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + if ( callbackProgress ) { - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, optionalTarget ); + if ( length === 0 ) { - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + length = xhr.getResponseHeader( 'Content-Length' ); - } + } - }(), + callbackProgress( { total: length, loaded: xhr.responseText.length } ); - isIntersectionPlane: function ( plane ) { + } - // check if the ray lies on the plane first + } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { - var distToPoint = plane.distanceToPoint( this.origin ); + if ( callbackProgress !== undefined ) { - if ( distToPoint === 0 ) { + length = xhr.getResponseHeader( 'Content-Length' ); - return true; + } } - var denominator = plane.normal.dot( this.direction ); - - if ( denominator * distToPoint < 0 ) { + }; - return true; + xhr.open( 'GET', url, true ); + xhr.withCredentials = this.withCredentials; + xhr.send( null ); - } +}; - // ray origin is behind the plane (and is pointing behind it) +THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { - return false; + var geometry = new THREE.Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - }, + parseModel( scale ); - distanceToPlane: function ( plane ) { + parseSkin(); + parseMorphing( scale ); - var denominator = plane.normal.dot( this.direction ); - if ( denominator == 0 ) { + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) == 0 ) { + function parseModel( scale ) { - return 0; + function isBitSet( value, position ) { - } + return value & ( 1 << position ); - // Null is preferable to undefined since undefined means.... it is undefined + } - return null; + var i, j, fi, - } + offset, zLength, - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + colorIndex, normalIndex, uvIndex, materialIndex, - // Return if the ray never intersects the plane + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - return t >= 0 ? t : null; + vertex, face, faceA, faceB, hex, normal, - }, + uvLayer, uv, u, v, - intersectPlane: function ( plane, optionalTarget ) { + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - var t = this.distanceToPlane( plane ); + nUvLayers = 0; - if ( t === null ) { + if ( json.uvs !== undefined ) { - return null; - } + // disregard empty arrays - return this.at( t, optionalTarget ); + for ( i = 0; i < json.uvs.length; i ++ ) { - }, + if ( json.uvs[ i ].length ) nUvLayers ++; - isIntersectionBox: function () { + } - var v = new THREE.Vector3(); + for ( i = 0; i < nUvLayers; i ++ ) { - return function ( box ) { + geometry.faceVertexUvs[ i ] = []; - return this.intersectBox( box, v ) !== null; + } - }; + } - }(), + offset = 0; + zLength = vertices.length; - intersectBox: function ( box, optionalTarget ) { + while ( offset < zLength ) { - // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/ + vertex = new THREE.Vector3(); - var tmin,tmax,tymin,tymax,tzmin,tzmax; + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + geometry.vertices.push( vertex ); - var origin = this.origin; + } - if ( invdirx >= 0 ) { + offset = 0; + zLength = faces.length; - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + while ( offset < zLength ) { - } else { + type = faces[ offset ++ ]; - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; - } - if ( invdiry >= 0 ) { + isQuad = isBitSet( type, 0 ); + hasMaterial = isBitSet( type, 1 ); + hasFaceVertexUv = isBitSet( type, 3 ); + hasFaceNormal = isBitSet( type, 4 ); + hasFaceVertexNormal = isBitSet( type, 5 ); + hasFaceColor = isBitSet( type, 6 ); + hasFaceVertexColor = isBitSet( type, 7 ); - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - } else { + if ( isQuad ) { - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; - } + faceA = new THREE.Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + faceB = new THREE.Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + offset += 4; - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + if ( hasMaterial ) { - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - if ( invdirz >= 0 ) { + } - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + // to get face <=> uv index correspondence - } else { + fi = geometry.faces.length; - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; - } + if ( hasFaceVertexUv ) { - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + for ( i = 0; i < nUvLayers; i ++ ) { - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + uvLayer = json.uvs[ i ]; - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = [] - //return point closest to the ray (positive side) + for ( j = 0; j < 4; j ++ ) { - if ( tmax < 0 ) return null; + uvIndex = faces[ offset ++ ]; - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - }, + uv = new THREE.Vector2( u, v ); - intersectTriangle: function () { + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - // Compute the offset origin, edges, and normal. - var diff = new THREE.Vector3(); - var edge1 = new THREE.Vector3(); - var edge2 = new THREE.Vector3(); - var normal = new THREE.Vector3(); + } - return function ( a, b, c, backfaceCulling, optionalTarget ) { + } - // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp + } - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + if ( hasFaceNormal ) { - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( normal ); - var sign; + normalIndex = faces[ offset ++ ] * 3; - if ( DdN > 0 ) { + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( backfaceCulling ) return null; - sign = 1; + faceB.normal.copy( faceA.normal ); - } else if ( DdN < 0 ) { + } - sign = - 1; - DdN = - DdN; + if ( hasFaceVertexNormal ) { - } else { + for ( i = 0; i < 4; i ++ ) { - return null; + normalIndex = faces[ offset ++ ] * 3; - } + normal = new THREE.Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - return null; + } - } + } - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + if ( hasFaceColor ) { - return null; + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - } + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + } - return null; - } + if ( hasFaceVertexColor ) { - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + for ( i = 0; i < 4; i ++ ) { - // t < 0, no intersection - if ( QdN < 0 ) { + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - return null; + if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); - } + } - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + } - }; + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - }(), + } else { - applyMatrix4: function ( matrix4 ) { + face = new THREE.Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); + if ( hasMaterial ) { - return this; - }, + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - equals: function ( ray ) { + } - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + // to get face <=> uv index correspondence - }, + fi = geometry.faces.length; - clone: function () { + if ( hasFaceVertexUv ) { - return new THREE.Ray().copy( this ); + for ( i = 0; i < nUvLayers; i ++ ) { - } + uvLayer = json.uvs[ i ]; -}; + geometry.faceVertexUvs[ i ][ fi ] = []; -// File:src/math/Sphere.js + for ( j = 0; j < 3; j ++ ) { -/** - * @author bhouston / http://exocortex.com - * @author mrdoob / http://mrdoob.com/ - */ + uvIndex = faces[ offset ++ ]; -THREE.Sphere = function ( center, radius ) { + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + uv = new THREE.Vector2( u, v ); -}; + geometry.faceVertexUvs[ i ][ fi ].push( uv ); -THREE.Sphere.prototype = { + } - constructor: THREE.Sphere, + } - set: function ( center, radius ) { + } - this.center.copy( center ); - this.radius = radius; + if ( hasFaceNormal ) { - return this; - }, + normalIndex = faces[ offset ++ ] * 3; - setFromPoints: function () { + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - var box = new THREE.Box3(); + } - return function ( points, optionalCenter ) { + if ( hasFaceVertexNormal ) { - var center = this.center; + for ( i = 0; i < 3; i ++ ) { - if ( optionalCenter !== undefined ) { + normalIndex = faces[ offset ++ ] * 3; - center.copy( optionalCenter ); + normal = new THREE.Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - } else { + face.vertexNormals.push( normal ); - box.setFromPoints( points ).center( center ); + } - } + } - var maxRadiusSq = 0; - for ( var i = 0, il = points.length; i < il; i ++ ) { + if ( hasFaceColor ) { - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - } + } - this.radius = Math.sqrt( maxRadiusSq ); - return this; + if ( hasFaceVertexColor ) { - }; + for ( i = 0; i < 3; i ++ ) { - }(), + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); - copy: function ( sphere ) { + } - this.center.copy( sphere.center ); - this.radius = sphere.radius; + } - return this; + geometry.faces.push( face ); - }, + } - empty: function () { + } - return ( this.radius <= 0 ); + }; - }, + function parseSkin() { + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - containsPoint: function ( point ) { + if ( json.skinWeights ) { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - }, + var x = json.skinWeights[ i ]; + var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; + var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; + var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - distanceToPoint: function ( point ) { + geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); - return ( point.distanceTo( this.center ) - this.radius ); + } - }, + } - intersectsSphere: function ( sphere ) { + if ( json.skinIndices ) { - var radiusSum = this.radius + sphere.radius; + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + var a = json.skinIndices[ i ]; + var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; + var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; + var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - }, + geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); - clampPoint: function ( point, optionalTarget ) { + } - var deltaLengthSq = this.center.distanceToSquared( point ); + } - var result = optionalTarget || new THREE.Vector3(); - result.copy( point ); + geometry.bones = json.bones; - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); } - return result; - }, + // could change this to json.animations[0] or remove completely - getBoundingBox: function ( optionalTarget ) { + geometry.animation = json.animation; + geometry.animations = json.animations; - var box = optionalTarget || new THREE.Box3(); + }; - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + function parseMorphing( scale ) { - return box; + if ( json.morphTargets !== undefined ) { - }, + var i, l, v, vl, dstVertices, srcVertices; - applyMatrix4: function ( matrix ) { + for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - return this; + dstVertices = geometry.morphTargets[ i ].vertices; + srcVertices = json.morphTargets [ i ].vertices; - }, + for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - translate: function ( offset ) { + var vertex = new THREE.Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - this.center.add( offset ); + dstVertices.push( vertex ); - return this; + } - }, + } - equals: function ( sphere ) { + } - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + if ( json.morphColors !== undefined ) { - }, + var i, l, c, cl, dstColors, srcColors, color; - clone: function () { + for ( i = 0, l = json.morphColors.length; i < l; i ++ ) { - return new THREE.Sphere().copy( this ); + geometry.morphColors[ i ] = {}; + geometry.morphColors[ i ].name = json.morphColors[ i ].name; + geometry.morphColors[ i ].colors = []; - } + dstColors = geometry.morphColors[ i ].colors; + srcColors = json.morphColors [ i ].colors; -}; + for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { -// File:src/math/Frustum.js + color = new THREE.Color( 0xffaa00 ); + color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); + dstColors.push( color ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://exocortex.com - */ + } -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { + } - this.planes = [ + } - ( p0 !== undefined ) ? p0 : new THREE.Plane(), - ( p1 !== undefined ) ? p1 : new THREE.Plane(), - ( p2 !== undefined ) ? p2 : new THREE.Plane(), - ( p3 !== undefined ) ? p3 : new THREE.Plane(), - ( p4 !== undefined ) ? p4 : new THREE.Plane(), - ( p5 !== undefined ) ? p5 : new THREE.Plane() + }; - ]; + if ( json.materials === undefined || json.materials.length === 0 ) { -}; + return { geometry: geometry }; -THREE.Frustum.prototype = { + } else { - constructor: THREE.Frustum, + var materials = this.initMaterials( json.materials, texturePath ); - set: function ( p0, p1, p2, p3, p4, p5 ) { + if ( this.needsTangents( materials ) ) { - var planes = this.planes; + geometry.computeTangents(); - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + } - return this; + return { geometry: geometry, materials: materials }; - }, + } - copy: function ( frustum ) { +}; - var planes = this.planes; +// File:src/loaders/LoadingManager.js - for ( var i = 0; i < 6; i ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - planes[ i ].copy( frustum.planes[ i ] ); +THREE.LoadingManager = function ( onLoad, onProgress, onError ) { - } + var scope = this; - return this; + var loaded = 0, total = 0; - }, + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - setFromMatrix: function ( m ) { + this.itemStart = function ( url ) { - var planes = this.planes; - var me = m.elements; - var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - 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 ]; + total ++; - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); + }; - return this; + this.itemEnd = function ( url ) { - }, + loaded ++; - intersectsObject: function () { + if ( scope.onProgress !== undefined ) { - var sphere = new THREE.Sphere(); + scope.onProgress( url, loaded, total ); - return function ( object ) { + } - var geometry = object.geometry; + if ( loaded === total && scope.onLoad !== undefined ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + scope.onLoad(); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); + } - return this.intersectsSphere( sphere ); + }; - }; +}; - }(), +THREE.DefaultLoadingManager = new THREE.LoadingManager(); - intersectsSphere: function ( sphere ) { +// File:src/loaders/BufferGeometryLoader.js - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; +/** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var i = 0; i < 6; i ++ ) { +THREE.BufferGeometryLoader = function ( manager ) { - var distance = planes[ i ].distanceToPoint( center ); + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - if ( distance < negRadius ) { +}; - return false; +THREE.BufferGeometryLoader.prototype = { - } + constructor: THREE.BufferGeometryLoader, - } + load: function ( url, onLoad, onProgress, onError ) { - return true; + var scope = this; - }, + var loader = new THREE.XHRLoader( scope.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { - intersectsBox: function () { + onLoad( scope.parse( JSON.parse( text ) ) ); - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + }, onProgress, onError ); - return function ( box ) { + }, - var planes = this.planes; + setCrossOrigin: function ( value ) { - for ( var i = 0; i < 6 ; i ++ ) { + this.crossOrigin = value; - var plane = planes[ i ]; + }, - p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; - p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; - p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; - p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; - p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; - p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; + parse: function ( json ) { - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + var geometry = new THREE.BufferGeometry(); - // if both outside plane, no intersection + var attributes = json.data.attributes; - if ( d1 < 0 && d2 < 0 ) { + for ( var key in attributes ) { - return false; + var attribute = attributes[ key ]; + var typedArray = new self[ attribute.type ]( attribute.array ); - } - } + geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) ); - return true; - }; + } - }(), + var offsets = json.data.offsets; + if ( offsets !== undefined ) { - containsPoint: function ( point ) { + geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); - var planes = this.planes; + } - for ( var i = 0; i < 6; i ++ ) { + var boundingSphere = json.data.boundingSphere; - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + if ( boundingSphere !== undefined ) { - return false; + var center = new THREE.Vector3(); - } + if ( boundingSphere.center !== undefined ) { - } + center.fromArray( boundingSphere.center ); - return true; + } - }, + geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); - clone: function () { + } - return new THREE.Frustum().copy( this ); + return geometry; } }; -// File:src/math/Plane.js +// File:src/loaders/MaterialLoader.js /** - * @author bhouston / http://exocortex.com + * @author mrdoob / http://mrdoob.com/ */ -THREE.Plane = function ( normal, constant ) { +THREE.MaterialLoader = function ( manager ) { - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; -THREE.Plane.prototype = { - - constructor: THREE.Plane, - - set: function ( normal, constant ) { +THREE.MaterialLoader.prototype = { - this.normal.copy( normal ); - this.constant = constant; + constructor: THREE.MaterialLoader, - return this; + load: function ( url, onLoad, onProgress, onError ) { - }, + var scope = this; - setComponents: function ( x, y, z, w ) { + var loader = new THREE.XHRLoader( scope.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { - this.normal.set( x, y, z ); - this.constant = w; + onLoad( scope.parse( JSON.parse( text ) ) ); - return this; + }, onProgress, onError ); }, - setFromNormalAndCoplanarPoint: function ( normal, point ) { - - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + setCrossOrigin: function ( value ) { - return this; + this.crossOrigin = value; }, - setFromCoplanarPoints: function () { + parse: function ( json ) { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var material = new THREE[ json.type ]; - return function ( a, b, c ) { + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; + if ( json.shading !== undefined ) material.shading = json.shading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); + // for PointCloudMaterial + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + if ( json.materials !== undefined ) { - this.setFromNormalAndCoplanarPoint( normal, a ); + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - return this; + material.materials.push( this.parse( json.materials[ i ] ) ); - }; + } - }(), + } + return material; - copy: function ( plane ) { + } - this.normal.copy( plane.normal ); - this.constant = plane.constant; +}; - return this; +// File:src/loaders/ObjectLoader.js - }, +/** + * @author mrdoob / http://mrdoob.com/ + */ - normalize: function () { +THREE.ObjectLoader = function ( manager ) { - // Note: will lead to a divide by zero if the plane is invalid. + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.texturePath = ''; - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; +}; - return this; +THREE.ObjectLoader.prototype = { - }, + constructor: THREE.ObjectLoader, - negate: function () { + load: function ( url, onLoad, onProgress, onError ) { - this.constant *= - 1; - this.normal.negate(); +// if ( this.texturePath === '' ) { - return this; +// this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - }, +// } - distanceToPoint: function ( point ) { + var scope = this; - return this.normal.dot( point ) + this.constant; + var loader = new THREE.XHRLoader( scope.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( text ) { + + scope.parse( JSON.parse( text ), onLoad ); + + }, onProgress, onError ); }, - distanceToSphere: function ( sphere ) { + setTexturePath: function ( value ) { - return this.distanceToPoint( sphere.center ) - sphere.radius; + this.texturePath = value; }, - projectPoint: function ( point, optionalTarget ) { + setCrossOrigin: function ( value ) { - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + this.crossOrigin = value; }, - orthoPoint: function ( point, optionalTarget ) { + parse: function ( json, onLoad ) { - var perpendicularMagnitude = this.distanceToPoint( point ); + var geometries = this.parseGeometries( json.geometries ); - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + var images = this.parseImages( json.images, function () { - }, + if ( onLoad !== undefined ) onLoad( object ); - isIntersectionLine: function ( line ) { + } ); + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); + var object = this.parseObject( json.object, geometries, materials ); - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + if ( json.images === undefined || json.images.length === 0 ) { - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + if ( onLoad !== undefined ) onLoad( object ); - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + } + + return object; }, - intersectLine: function () { + parseGeometries: function ( json ) { - var v1 = new THREE.Vector3(); + var geometries = {}; - return function ( line, optionalTarget ) { + if ( json !== undefined ) { - var result = optionalTarget || new THREE.Vector3(); + var geometryLoader = new THREE.JSONLoader(); + var bufferGeometryLoader = new THREE.BufferGeometryLoader(); - var direction = line.delta( v1 ); + for ( var i = 0, l = json.length; i < l; i ++ ) { - var denominator = this.normal.dot( direction ); + var geometry; + var data = json[ i ]; - if ( denominator == 0 ) { + switch ( data.type ) { - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) == 0 ) { + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - return result.copy( line.start ); + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - } + break; - // Unsure if this is the correct method to handle this case. - return undefined; + case 'BoxGeometry': + case 'CubeGeometry': // backwards compatible - } + geometry = new THREE.BoxGeometry( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + break; - if ( t < 0 || t > 1 ) { + case 'CircleGeometry': - return undefined; + geometry = new THREE.CircleGeometry( + data.radius, + data.segments + ); - } + break; - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + case 'CylinderGeometry': - }; + geometry = new THREE.CylinderGeometry( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded + ); - }(), + break; + case 'SphereGeometry': - coplanarPoint: function ( optionalTarget ) { + geometry = new THREE.SphereGeometry( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + break; - }, + case 'IcosahedronGeometry': - applyMatrix4: function () { + geometry = new THREE.IcosahedronGeometry( + data.radius, + data.detail + ); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + break; - return function ( matrix, optionalNormalMatrix ) { + case 'TorusGeometry': - // compute new normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); + geometry = new THREE.TorusGeometry( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - var newCoplanarPoint = this.coplanarPoint( v2 ); - newCoplanarPoint.applyMatrix4( matrix ); + break; - this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint ); + case 'TorusKnotGeometry': - return this; + geometry = new THREE.TorusKnotGeometry( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.p, + data.q, + data.heightScale + ); - }; + break; - }(), + case 'BufferGeometry': - translate: function ( offset ) { + geometry = bufferGeometryLoader.parse( data ); - this.constant = this.constant - offset.dot( this.normal ); + break; - return this; + case 'Geometry': - }, + geometry = geometryLoader.parse( data.data ).geometry; - equals: function ( plane ) { + break; - return plane.normal.equals( this.normal ) && ( plane.constant == this.constant ); + } - }, + geometry.uuid = data.uuid; - clone: function () { + if ( data.name !== undefined ) geometry.name = data.name; - return new THREE.Plane().copy( this ); + geometries[ data.uuid ] = geometry; - } + } -}; + } -// File:src/math/Math.js + return geometries; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + }, -THREE.Math = { + parseMaterials: function ( json, textures ) { - generateUUID: function () { + var materials = {}; - // http://www.broofa.com/Tools/Math.uuid.htm + if ( json !== undefined ) { - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; + var getTexture = function ( name ) { - return function () { + if ( textures[ name ] === undefined ) { - for ( var i = 0; i < 36; i ++ ) { + THREE.warn( 'THREE.ObjectLoader: Undefined texture', name ); - if ( i == 8 || i == 13 || i == 18 || i == 23 ) { + } - uuid[ i ] = '-'; + return textures[ name ]; - } else if ( i == 14 ) { + }; - uuid[ i ] = '4'; + var loader = new THREE.MaterialLoader(); - } else { + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + var data = json[ i ]; + var material = loader.parse( data ); - } - } + material.uuid = data.uuid; - return uuid.join( '' ); + if ( data.name !== undefined ) material.name = data.name; - }; + if ( data.map !== undefined && data.map !== null ) { - }(), + material.map = getTexture( data.map ); - // Clamp value to range <a, b> + } - clamp: function ( x, a, b ) { + if ( data.bumpMap !== undefined ) { - return ( x < a ) ? a : ( ( x > b ) ? b : x ); + material.bumpMap = getTexture( data.bumpMap ); + if ( data.bumpScale ) { + material.bumpScale = new THREE.Vector2( data.bumpScale, data.bumpScale ); + } - }, + } - // Clamp value to range <a, inf) + if ( data.alphaMap !== undefined ) { - clampBottom: function ( x, a ) { + material.alphaMap = getTexture( data.alphaMap ); - return x < a ? a : x; + } - }, + if ( data.envMap !== undefined ) { - // Linear mapping from range <a1, a2> to range <b1, b2> + material.envMap = getTexture( data.envMap ); - mapLinear: function ( x, a1, a2, b1, b2 ) { + } - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + if ( data.normalMap !== undefined ) { - }, + material.normalMap = getTexture( data.normalMap ); + if ( data.normalScale ) { + material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale ); + } - // http://en.wikipedia.org/wiki/Smoothstep + } - smoothstep: function ( x, min, max ) { + if ( data.lightMap !== undefined ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + material.lightMap = getTexture( data.lightMap ); - x = ( x - min ) / ( max - min ); + } - return x * x * ( 3 - 2 * x ); + if ( data.specularMap !== undefined ) { - }, + material.specularMap = getTexture( data.specularMap ); - smootherstep: function ( x, min, max ) { + } - if ( x <= min ) return 0; - if ( x >= max ) return 1; + materials[ data.uuid ] = material; - x = ( x - min ) / ( max - min ); + } - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + } + + return materials; }, - // Random float from <0, 1> with 16 bits of randomness - // (standard Math.random() creates repetitive patterns when applied over larger space) + parseImages: function ( json, onLoad ) { - random16: function () { + var scope = this; + var images = {}; - return ( 65280 * Math.random() + 255 * Math.random() ) / 65535; + if ( json !== undefined && json.length > 0 ) { - }, + var manager = new THREE.LoadingManager( onLoad ); - // Random integer from <low, high> interval + var loader = new THREE.ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - randInt: function ( low, high ) { + var loadImage = function ( url ) { - return Math.floor( this.randFloat( low, high ) ); + scope.manager.itemStart( url ); - }, + return loader.load( url, function () { - // Random float from <low, high> interval + scope.manager.itemEnd( url ); - randFloat: function ( low, high ) { + } ); - return low + Math.random() * ( high - low ); + }; - }, + for ( var i = 0, l = json.length; i < l; i ++ ) { - // Random float from <-range/2, range/2> interval + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - randFloatSpread: function ( range ) { + images[ image.uuid ] = loadImage( path ); - return range * ( 0.5 - Math.random() ); + } + + } + + return images; }, - degToRad: function () { + parseTextures: function ( json, images ) { - var degreeToRadiansFactor = Math.PI / 180; + var textures = {}; - return function ( degrees ) { + if ( json !== undefined ) { - return degrees * degreeToRadiansFactor; + for ( var i = 0, l = json.length; i < l; i ++ ) { - }; + var data = json[ i ]; - }(), + if ( data.image === undefined ) { - radToDeg: function () { + THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid ); - var radianToDegreesFactor = 180 / Math.PI; + } - return function ( radians ) { + if ( images[ data.image ] === undefined ) { - return radians * radianToDegreesFactor; + THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - }; + } - }(), + var texture = new THREE.Texture( images[ data.image ] ); + texture.needsUpdate = true; - isPowerOfTwo: function ( value ) { + texture.uuid = data.uuid; - return ( value & ( value - 1 ) ) === 0 && value !== 0; + if ( data.name !== undefined ) texture.name = data.name; + if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] ); + if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ]; + if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ]; + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + if ( data.wrap instanceof Array ) { - }, + texture.wrapS = THREE[ data.wrap[ 0 ] ]; + texture.wrapT = THREE[ data.wrap[ 1 ] ]; - nextPowerOfTwo: function ( value ) { + } - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + textures[ data.uuid ] = texture; - return value; + } - } + } -}; + return textures; -// File:src/math/Spline.js + }, -/** - * Spline from Tween.js, slightly optimized (and trashed) - * http://sole.github.com/tween.js/examples/05_spline.html - * - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + parseObject: function () { -THREE.Spline = function ( points ) { + var matrix = new THREE.Matrix4(); - this.points = points; + return function ( data, geometries, materials ) { - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + var object; - this.initFromArray = function ( a ) { + var getGeometry = function ( name ) { - this.points = []; + if ( geometries[ name ] === undefined ) { - for ( var i = 0; i < a.length; i ++ ) { + THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; + } - } + return geometries[ name ]; - }; + }; - this.getPoint = function ( k ) { + var getMaterial = function ( name ) { - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; + if ( materials[ name ] === undefined ) { - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; + THREE.warn( 'THREE.ObjectLoader: Undefined material', name ); - pa = this.points[ c[ 0 ] ]; - pb = this.points[ c[ 1 ] ]; - pc = this.points[ c[ 2 ] ]; - pd = this.points[ c[ 3 ] ]; + } - w2 = weight * weight; - w3 = weight * w2; + return materials[ name ]; - v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); - v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); - v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); + }; - return v3; + switch ( data.type ) { - }; + case 'Scene': - this.getControlPointsArray = function () { + object = new THREE.Scene(); - var i, p, l = this.points.length, - coords = []; + break; - for ( i = 0; i < l; i ++ ) { + case 'PerspectiveCamera': - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; + object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - } + break; - return coords; + case 'OrthographicCamera': - }; + object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - // approximate length by summing linear segments + break; - this.getLength = function ( nSubDivisions ) { + case 'AmbientLight': - var i, index, nSamples, position, - point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), - chunkLengths = [], - totalLength = 0; + object = new THREE.AmbientLight( data.color ); - // first point has 0 length + break; - chunkLengths[ 0 ] = 0; + case 'DirectionalLight': - if ( ! nSubDivisions ) nSubDivisions = 100; + object = new THREE.DirectionalLight( data.color, data.intensity ); - nSamples = this.points.length * nSubDivisions; + break; - oldPosition.copy( this.points[ 0 ] ); + case 'PointLight': - for ( i = 1; i < nSamples; i ++ ) { + object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); - index = i / nSamples; + break; - position = this.getPoint( index ); - tmpVec.copy( position ); + case 'SpotLight': - totalLength += tmpVec.distanceTo( oldPosition ); + object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay ); - oldPosition.copy( position ); + break; - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); + case 'HemisphereLight': - if ( intPoint != oldIntPoint ) { + object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; + break; - } + case 'Mesh': - } + object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) ); - // last point ends with total length + break; - chunkLengths[ chunkLengths.length ] = totalLength; + case 'Line': - return { chunks: chunkLengths, total: totalLength }; + object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - }; + break; - this.reparametrizeByArcLength = function ( samplingCoef ) { + case 'PointCloud': - var i, j, - index, indexCurrent, indexNext, - realDistance, - sampling, position, - newpoints = [], - tmpVec = new THREE.Vector3(), - sl = this.getLength(); + object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) ); - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); + break; - for ( i = 1; i < this.points.length; i ++ ) { + case 'Sprite': - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); + object = new THREE.Sprite( getMaterial( data.material ) ); - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; + break; - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); + case 'Group': - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); + object = new THREE.Group(); - for ( j = 1; j < sampling - 1; j ++ ) { + break; - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); + default: - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); + object = new THREE.Object3D(); } - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); + object.uuid = data.uuid; - } + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - this.points = newpoints; + matrix.fromArray( data.matrix ); + matrix.decompose( object.position, object.quaternion, object.scale ); - }; + } else { - // Catmull-Rom + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { + } - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + if ( data.children !== undefined ) { - }; + for ( var child in data.children ) { + + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + + } + + } + + return object; + + } + + }() }; -// File:src/math/Triangle.js +// File:src/loaders/TextureLoader.js /** - * @author bhouston / http://exocortex.com * @author mrdoob / http://mrdoob.com/ */ -THREE.Triangle = function ( a, b, c ) { +THREE.TextureLoader = function ( manager ) { - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); + this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; -THREE.Triangle.normal = function () { +THREE.TextureLoader.prototype = { - var v0 = new THREE.Vector3(); + constructor: THREE.TextureLoader, - return function ( a, b, c, optionalTarget ) { + load: function ( url, onLoad, onProgress, onError ) { - var result = optionalTarget || new THREE.Vector3(); + var scope = this; - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + var loader = new THREE.ImageLoader( scope.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.load( url, function ( image ) { - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + var texture = new THREE.Texture( image ); + texture.needsUpdate = true; - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + if ( onLoad !== undefined ) { - } + onLoad( texture ); - return result.set( 0, 0, 0 ); + } - }; + }, onProgress, onError ); -}(); + }, -// static/instance method to calculate barycoordinates -// based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { + setCrossOrigin: function ( value ) { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + this.crossOrigin = value; - return function ( point, a, b, c, optionalTarget ) { + } - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, 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 ); +// File:src/loaders/BinaryTextureLoader.js - var denom = ( dot00 * dot11 - dot01 * dot01 ); +/** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + */ - var result = optionalTarget || new THREE.Vector3(); +THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () { - // colinear or singular triangle - if ( denom == 0 ) { - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); - } + // override in sub classes + this._parser = null; - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; +}; - // barycoordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); +THREE.BinaryTextureLoader.prototype = { - }; + constructor: THREE.BinaryTextureLoader, -}(); + load: function ( url, onLoad, onProgress, onError ) { -THREE.Triangle.containsPoint = function () { + var scope = this; - var v1 = new THREE.Vector3(); + var texture = new THREE.DataTexture( ); - return function ( point, a, b, c ) { + var loader = new THREE.XHRLoader(); + loader.setResponseType( 'arraybuffer' ); - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + loader.load( url, function ( buffer ) { - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + var texData = scope._parser( buffer ); - }; + if ( !texData ) return; -}(); + if ( undefined !== texData.image ) { -THREE.Triangle.prototype = { + texture.image = texData.image; - constructor: THREE.Triangle, + } else if ( undefined !== texData.data ) { - set: function ( a, b, c ) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + } - return this; + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; - }, + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + if ( undefined !== texData.format ) { - return this; + texture.format = texData.format; - }, + } + if ( undefined !== texData.type ) { - copy: function ( triangle ) { + texture.type = texData.type; - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + } - return this; + if ( undefined !== texData.mipmaps ) { - }, + texture.mipmaps = texData.mipmaps; - area: function () { + } - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + if ( 1 === texData.mipmapCount ) { - return function () { + texture.minFilter = THREE.LinearFilter; - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + } - return v0.cross( v1 ).length() * 0.5; + texture.needsUpdate = true; - }; + if ( onLoad ) onLoad( texture, texData ); - }(), + }, onProgress, onError ); - midpoint: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + return texture; - }, + } - normal: function ( optionalTarget ) { +}; - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); +// File:src/loaders/CompressedTextureLoader.js - }, +/** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ - plane: function ( optionalTarget ) { +THREE.CompressedTextureLoader = function () { - var result = optionalTarget || new THREE.Plane(); + // override in sub classes + this._parser = null; - return result.setFromCoplanarPoints( this.a, this.b, this.c ); +}; - }, - barycoordFromPoint: function ( point, optionalTarget ) { +THREE.CompressedTextureLoader.prototype = { - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + constructor: THREE.CompressedTextureLoader, - }, + load: function ( url, onLoad, onError ) { - containsPoint: function ( point ) { + var scope = this; - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + var images = []; - }, + var texture = new THREE.CompressedTexture(); + texture.image = images; - equals: function ( triangle ) { + var loader = new THREE.XHRLoader(); + loader.setResponseType( 'arraybuffer' ); - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + if ( url instanceof Array ) { - }, + var loaded = 0; - clone: function () { + var loadTexture = function ( i ) { - return new THREE.Triangle().copy( this ); + loader.load( url[ i ], function ( buffer ) { - } + var texDatas = scope._parser( buffer, true ); -}; + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; -// File:src/core/Clock.js + loaded += 1; -/** - * @author alteredq / http://alteredqualia.com/ - */ + if ( loaded === 6 ) { -THREE.Clock = function ( autoStart ) { + if (texDatas.mipmapCount == 1) + texture.minFilter = THREE.LinearFilter; - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + texture.format = texDatas.format; + texture.needsUpdate = true; - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + if ( onLoad ) onLoad( texture ); - this.running = false; + } -}; + } ); -THREE.Clock.prototype = { + }; - constructor: THREE.Clock, + for ( var i = 0, il = url.length; i < il; ++ i ) { - start: function () { + loadTexture( i ); - this.startTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + } - this.oldTime = this.startTime; - this.running = true; - }, + } else { - stop: function () { + // compressed cubemap texture stored in a single DDS file - this.getElapsedTime(); - this.running = false; + loader.load( url, function ( buffer ) { - }, + var texDatas = scope._parser( buffer, true ); - getElapsedTime: function () { + if ( texDatas.isCubemap ) { - this.getDelta(); - return this.elapsedTime; + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; - }, + for ( var f = 0; f < faces; f ++ ) { - getDelta: function () { + images[ f ] = { mipmaps : [] }; - var diff = 0; + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { - if ( this.autoStart && ! this.running ) { + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; - this.start(); + } - } + } - if ( this.running ) { + } else { - var newTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; - diff = 0.001 * ( newTime - this.oldTime ); - this.oldTime = newTime; + } - this.elapsedTime += diff; + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = THREE.LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } ); } - return diff; + return texture; } }; -// File:src/core/EventDispatcher.js +// File:src/materials/Material.js /** - * https://github.com/mrdoob/eventdispatcher.js/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ */ -THREE.EventDispatcher = function () {} +THREE.Material = function () { -THREE.EventDispatcher.prototype = { + Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); - constructor: THREE.EventDispatcher, + this.uuid = THREE.Math.generateUUID(); - apply: function ( object ) { + this.name = ''; + this.type = 'Material'; - object.addEventListener = THREE.EventDispatcher.prototype.addEventListener; - object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener; - object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener; - object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent; + this.side = THREE.FrontSide; - }, + this.opacity = 1; + this.transparent = false; - addEventListener: function ( type, listener ) { + this.blending = THREE.NormalBlending; - if ( this._listeners === undefined ) this._listeners = {}; + this.blendSrc = THREE.SrcAlphaFactor; + this.blendDst = THREE.OneMinusSrcAlphaFactor; + this.blendEquation = THREE.AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - var listeners = this._listeners; + this.depthTest = true; + this.depthWrite = true; - if ( listeners[ type ] === undefined ) { + this.colorWrite = true; - listeners[ type ] = []; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - } + this.alphaTest = 0; - if ( listeners[ type ].indexOf( listener ) === - 1 ) { + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - listeners[ type ].push( listener ); + this.visible = true; - } + this._needsUpdate = true; - }, +}; - hasEventListener: function ( type, listener ) { +THREE.Material.prototype = { - if ( this._listeners === undefined ) return false; + constructor: THREE.Material, - var listeners = this._listeners; + get needsUpdate () { - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return this._needsUpdate; - return true; + }, - } + set needsUpdate ( value ) { - return false; + if ( value === true ) this.update(); - }, + this._needsUpdate = value; - removeEventListener: function ( type, listener ) { + }, - if ( this._listeners === undefined ) return; + setValues: function ( values ) { - var listeners = this._listeners; - var listenerArray = listeners[ type ]; + if ( values === undefined ) return; - if ( listenerArray !== undefined ) { + for ( var key in values ) { - var index = listenerArray.indexOf( listener ); + var newValue = values[ key ]; - if ( index !== - 1 ) { + if ( newValue === undefined ) { - listenerArray.splice( index, 1 ); + THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; } - } - - }, - - dispatchEvent: function ( event ) { + if ( key in this ) { - if ( this._listeners === undefined ) return; + var currentValue = this[ key ]; - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; + if ( currentValue instanceof THREE.Color ) { - if ( listenerArray !== undefined ) { + currentValue.set( newValue ); - event.target = this; + } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { - var array = []; - var length = listenerArray.length; + currentValue.copy( newValue ); - for ( var i = 0; i < length; i ++ ) { + } else if ( key == 'overdraw' ) { - array[ i ] = listenerArray[ i ]; + // ensure overdraw is backwards-compatable with legacy boolean type + this[ key ] = Number( newValue ); - } + } else { - for ( var i = 0; i < length; i ++ ) { + this[ key ] = newValue; - array[ i ].call( this, event ); + } } } - } + }, -}; + toJSON: function () { -// File:src/core/Raycaster.js + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type + }; -/** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://exocortex.com/ - * @author stephomi / http://stephaneginier.com/ - */ + if ( this.name !== "" ) output.name = this.name; -//( function ( THREE ) { + if ( this instanceof THREE.MeshBasicMaterial ) { - THREE.Raycaster = function ( origin, direction, near, far ) { + output.color = this.color.getHex(); + if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + if ( this.side !== THREE.FrontSide ) output.side = this.side; - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + } else if ( this instanceof THREE.MeshLambertMaterial ) { - this.near = near || 0; - this.far = far || Infinity; + output.color = this.color.getHex(); + output.emissive = this.emissive.getHex(); + if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; + if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading; + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + if ( this.side !== THREE.FrontSide ) output.side = this.side; - this.params = { - Sprite: {}, - Mesh: {}, - PointCloud: { threshold: 1 }, - LOD: {}, - Line: {} - }; + } else if ( this instanceof THREE.MeshPhongMaterial ) { - }; + output.color = this.color.getHex(); + output.emissive = this.emissive.getHex(); + output.specular = this.specular.getHex(); + output.shininess = this.shininess; + if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; + if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading; + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + if ( this.side !== THREE.FrontSide ) output.side = this.side; - var descSort = function ( a, b ) { + } else if ( this instanceof THREE.MeshNormalMaterial ) { - return a.distance - b.distance; + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + if ( this.side !== THREE.FrontSide ) output.side = this.side; - }; + } else if ( this instanceof THREE.MeshDepthMaterial ) { - var intersectObject = function ( object, raycaster, intersects, recursive ) { + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + if ( this.side !== THREE.FrontSide ) output.side = this.side; - object.raycast( raycaster, intersects ); + } else if ( this instanceof THREE.PointCloudMaterial ) { - if ( recursive === true ) { + output.size = this.size; + output.sizeAttenuation = this.sizeAttenuation; + output.color = this.color.getHex(); - var children = object.children; + if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; + if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - for ( var i = 0, l = children.length; i < l; i ++ ) { + } else if ( this instanceof THREE.ShaderMaterial ) { - intersectObject( children[ i ], raycaster, intersects, true ); + output.uniforms = this.uniforms; + output.vertexShader = this.vertexShader; + output.fragmentShader = this.fragmentShader; - } + } else if ( this instanceof THREE.SpriteMaterial ) { + + output.color = this.color.getHex(); } - }; + if ( this.opacity < 1 ) output.opacity = this.opacity; + if ( this.transparent !== false ) output.transparent = this.transparent; + if ( this.wireframe !== false ) output.wireframe = this.wireframe; - // + return output; - THREE.Raycaster.prototype = { + }, - constructor: THREE.Raycaster, + clone: function ( material ) { - precision: 0.0001, - linePrecision: 1, + if ( material === undefined ) material = new THREE.Material(); - set: function ( origin, direction ) { + material.name = this.name; - // direction is assumed to be normalized (for accurate distance calculations) + material.side = this.side; - this.ray.set( origin, direction ); + material.opacity = this.opacity; + material.transparent = this.transparent; - }, + material.blending = this.blending; - setFromCamera: function ( coords, camera ) { + material.blendSrc = this.blendSrc; + material.blendDst = this.blendDst; + material.blendEquation = this.blendEquation; + material.blendSrcAlpha = this.blendSrcAlpha; + material.blendDstAlpha = this.blendDstAlpha; + material.blendEquationAlpha = this.blendEquationAlpha; - // camera is assumed _not_ to be a child of a transformed object + material.depthTest = this.depthTest; + material.depthWrite = this.depthWrite; - if ( camera instanceof THREE.PerspectiveCamera ) { + material.polygonOffset = this.polygonOffset; + material.polygonOffsetFactor = this.polygonOffsetFactor; + material.polygonOffsetUnits = this.polygonOffsetUnits; - this.ray.origin.copy( camera.position ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( camera.position ).normalize(); + material.alphaTest = this.alphaTest; - } else if ( camera instanceof THREE.OrthographicCamera ) { + material.overdraw = this.overdraw; - this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera ); - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + material.visible = this.visible; - } else { + return material; - THREE.error( 'THREE.Raycaster: Unsupported camera type.' ); + }, - } + update: function () { - }, + this.dispatchEvent( { type: 'update' } ); - intersectObject: function ( object, recursive ) { + }, - var intersects = []; + dispose: function () { - intersectObject( object, this, intersects, recursive ); + this.dispatchEvent( { type: 'dispose' } ); - intersects.sort( descSort ); + } - return intersects; +}; - }, +THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); - intersectObjects: function ( objects, recursive ) { +THREE.MaterialIdCount = 0; - var intersects = []; +// File:src/materials/LineBasicMaterial.js - if ( objects instanceof Array === false ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * opacity: <float>, + * + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * linewidth: <float>, + * linecap: "round", + * linejoin: "round", + * + * vertexColors: <bool> + * + * fog: <bool> + * } + */ - THREE.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; +THREE.LineBasicMaterial = function ( parameters ) { - } + THREE.Material.call( this ); - for ( var i = 0, l = objects.length; i < l; i ++ ) { + this.type = 'LineBasicMaterial'; - intersectObject( objects[ i ], this, intersects, recursive ); + this.color = new THREE.Color( 0xffffff ); - } + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - intersects.sort( descSort ); + this.vertexColors = THREE.NoColors; - return intersects; + this.fog = true; - } + this.setValues( parameters ); - }; +}; -//}( THREE ) ); +THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; -// File:src/core/Object3D.js +THREE.LineBasicMaterial.prototype.clone = function () { -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var material = new THREE.LineBasicMaterial(); -THREE.Object3D = function () { + THREE.Material.prototype.clone.call( this, material ); - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + material.color.copy( this.color ); - this.uuid = THREE.Math.generateUUID(); + material.linewidth = this.linewidth; + material.linecap = this.linecap; + material.linejoin = this.linejoin; - this.name = ''; - this.type = 'Object3D'; + material.vertexColors = this.vertexColors; - this.parent = undefined; - this.children = []; + material.fog = this.fog; - this.up = THREE.Object3D.DefaultUp.clone(); + return material; - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); +}; - var onRotationChange = function () { - quaternion.setFromEuler( rotation, false ); - }; +// File:src/materials/LineDashedMaterial.js - var onQuaternionChange = function () { - rotation.setFromQuaternion( quaternion, undefined, false ); - }; +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * opacity: <float>, + * + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * linewidth: <float>, + * + * scale: <float>, + * dashSize: <float>, + * gapSize: <float>, + * + * vertexColors: <bool> + * + * fog: <bool> + * } + */ - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); +THREE.LineDashedMaterial = function ( parameters ) { - Object.defineProperties( this, { - position: { - enumerable: true, - value: position - }, - rotation: { - enumerable: true, - value: rotation - }, - quaternion: { - enumerable: true, - value: quaternion - }, - scale: { - enumerable: true, - value: scale - } - } ); + THREE.Material.call( this ); - this.rotationAutoUpdate = true; + this.type = 'LineDashedMaterial'; - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + this.color = new THREE.Color( 0xffffff ); - this.matrixAutoUpdate = true; - this.matrixWorldNeedsUpdate = false; + this.linewidth = 1; - this.visible = true; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - this.castShadow = false; - this.receiveShadow = false; + this.vertexColors = false; - this.frustumCulled = true; - this.renderOrder = 0; + this.fog = true; - this.userData = {}; + this.setValues( parameters ); }; -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); +THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; -THREE.Object3D.prototype = { +THREE.LineDashedMaterial.prototype.clone = function () { - constructor: THREE.Object3D, + var material = new THREE.LineDashedMaterial(); - get eulerOrder () { + THREE.Material.prototype.clone.call( this, material ); - THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); + material.color.copy( this.color ); - return this.rotation.order; + material.linewidth = this.linewidth; - }, + material.scale = this.scale; + material.dashSize = this.dashSize; + material.gapSize = this.gapSize; - set eulerOrder ( value ) { + material.vertexColors = this.vertexColors; - THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); + material.fog = this.fog; - this.rotation.order = value; + return material; - }, +}; - get useQuaternion () { +// File:src/materials/MeshBasicMaterial.js - THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * opacity: <float>, + * map: new THREE.Texture( <Image> ), + * + * lightMap: new THREE.Texture( <Image> ), + * + * specularMap: new THREE.Texture( <Image> ), + * + * alphaMap: new THREE.Texture( <Image> ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: <float>, + * refractionRatio: <float>, + * + * shading: THREE.SmoothShading, + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float>, + * + * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, + * + * skinning: <bool>, + * morphTargets: <bool>, + * + * fog: <bool> + * } + */ - }, +THREE.MeshBasicMaterial = function ( parameters ) { - set useQuaternion ( value ) { + THREE.Material.call( this ); - THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + this.type = 'MeshBasicMaterial'; - }, + this.color = new THREE.Color( 0xffffff ); // emissive - applyMatrix: function ( matrix ) { + this.map = null; - this.matrix.multiplyMatrices( matrix, this.matrix ); + this.lightMap = null; - this.matrix.decompose( this.position, this.quaternion, this.scale ); + this.specularMap = null; - }, + this.alphaMap = null; - setRotationFromAxisAngle: function ( axis, angle ) { + this.envMap = null; + this.combine = THREE.MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - // assumes axis is normalized + this.fog = true; - this.quaternion.setFromAxisAngle( axis, angle ); + this.shading = THREE.SmoothShading; - }, + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - setRotationFromEuler: function ( euler ) { + this.vertexColors = THREE.NoColors; - this.quaternion.setFromEuler( euler, true ); + this.skinning = false; + this.morphTargets = false; - }, + this.setValues( parameters ); - setRotationFromMatrix: function ( m ) { +}; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) +THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; - this.quaternion.setFromRotationMatrix( m ); +THREE.MeshBasicMaterial.prototype.clone = function () { - }, + var material = new THREE.MeshBasicMaterial(); - setRotationFromQuaternion: function ( q ) { + THREE.Material.prototype.clone.call( this, material ); - // assumes q is normalized + material.color.copy( this.color ); - this.quaternion.copy( q ); + material.map = this.map; - }, + material.lightMap = this.lightMap; - rotateOnAxis: function () { + material.specularMap = this.specularMap; - // rotate object on axis in object space - // axis is assumed to be normalized + material.alphaMap = this.alphaMap; - var q1 = new THREE.Quaternion(); + material.envMap = this.envMap; + material.combine = this.combine; + material.reflectivity = this.reflectivity; + material.refractionRatio = this.refractionRatio; - return function ( axis, angle ) { + material.fog = this.fog; - q1.setFromAxisAngle( axis, angle ); + material.shading = this.shading; - this.quaternion.multiply( q1 ); + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; + material.wireframeLinecap = this.wireframeLinecap; + material.wireframeLinejoin = this.wireframeLinejoin; - return this; + material.vertexColors = this.vertexColors; - } + material.skinning = this.skinning; + material.morphTargets = this.morphTargets; - }(), + return material; - rotateX: function () { +}; - var v1 = new THREE.Vector3( 1, 0, 0 ); +// File:src/materials/MeshLambertMaterial.js - return function ( angle ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * emissive: <hex>, + * opacity: <float>, + * + * map: new THREE.Texture( <Image> ), + * + * lightMap: new THREE.Texture( <Image> ), + * + * specularMap: new THREE.Texture( <Image> ), + * + * alphaMap: new THREE.Texture( <Image> ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: <float>, + * refractionRatio: <float>, + * + * shading: THREE.SmoothShading, + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float>, + * + * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, + * + * skinning: <bool>, + * morphTargets: <bool>, + * morphNormals: <bool>, + * + * fog: <bool> + * } + */ - return this.rotateOnAxis( v1, angle ); +THREE.MeshLambertMaterial = function ( parameters ) { - }; + THREE.Material.call( this ); - }(), + this.type = 'MeshLambertMaterial'; - rotateY: function () { + this.color = new THREE.Color( 0xffffff ); // diffuse + this.emissive = new THREE.Color( 0x000000 ); - var v1 = new THREE.Vector3( 0, 1, 0 ); + this.wrapAround = false; + this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); - return function ( angle ) { + this.map = null; - return this.rotateOnAxis( v1, angle ); + this.lightMap = null; - }; + this.specularMap = null; - }(), + this.alphaMap = null; - rotateZ: function () { + this.envMap = null; + this.combine = THREE.MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - var v1 = new THREE.Vector3( 0, 0, 1 ); + this.fog = true; - return function ( angle ) { + this.shading = THREE.SmoothShading; - return this.rotateOnAxis( v1, angle ); + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - }; + this.vertexColors = THREE.NoColors; - }(), + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - translateOnAxis: function () { + this.setValues( parameters ); - // translate object by distance along axis in object space - // axis is assumed to be normalized +}; - var v1 = new THREE.Vector3(); +THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; - return function ( axis, distance ) { +THREE.MeshLambertMaterial.prototype.clone = function () { - v1.copy( axis ).applyQuaternion( this.quaternion ); + var material = new THREE.MeshLambertMaterial(); - this.position.add( v1.multiplyScalar( distance ) ); + THREE.Material.prototype.clone.call( this, material ); - return this; + material.color.copy( this.color ); + material.emissive.copy( this.emissive ); - } + material.wrapAround = this.wrapAround; + material.wrapRGB.copy( this.wrapRGB ); - }(), + material.map = this.map; - translate: function ( distance, axis ) { + material.lightMap = this.lightMap; - THREE.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); + material.specularMap = this.specularMap; - }, + material.alphaMap = this.alphaMap; - translateX: function () { + material.envMap = this.envMap; + material.combine = this.combine; + material.reflectivity = this.reflectivity; + material.refractionRatio = this.refractionRatio; - var v1 = new THREE.Vector3( 1, 0, 0 ); + material.fog = this.fog; - return function ( distance ) { + material.shading = this.shading; - return this.translateOnAxis( v1, distance ); + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; + material.wireframeLinecap = this.wireframeLinecap; + material.wireframeLinejoin = this.wireframeLinejoin; - }; + material.vertexColors = this.vertexColors; - }(), + material.skinning = this.skinning; + material.morphTargets = this.morphTargets; + material.morphNormals = this.morphNormals; - translateY: function () { + return material; - var v1 = new THREE.Vector3( 0, 1, 0 ); +}; - return function ( distance ) { +// File:src/materials/MeshPhongMaterial.js - return this.translateOnAxis( v1, distance ); +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * emissive: <hex>, + * specular: <hex>, + * shininess: <float>, + * opacity: <float>, + * + * map: new THREE.Texture( <Image> ), + * + * lightMap: new THREE.Texture( <Image> ), + * + * bumpMap: new THREE.Texture( <Image> ), + * bumpScale: <float>, + * + * normalMap: new THREE.Texture( <Image> ), + * normalScale: <Vector2>, + * + * specularMap: new THREE.Texture( <Image> ), + * + * alphaMap: new THREE.Texture( <Image> ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: <float>, + * refractionRatio: <float>, + * + * shading: THREE.SmoothShading, + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float>, + * + * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, + * + * skinning: <bool>, + * morphTargets: <bool>, + * morphNormals: <bool>, + * + * fog: <bool> + * } + */ - }; +THREE.MeshPhongMaterial = function ( parameters ) { - }(), + THREE.Material.call( this ); - translateZ: function () { + this.type = 'MeshPhongMaterial'; - var v1 = new THREE.Vector3( 0, 0, 1 ); + this.color = new THREE.Color( 0xffffff ); // diffuse + this.emissive = new THREE.Color( 0x000000 ); + this.specular = new THREE.Color( 0x111111 ); + this.shininess = 30; - return function ( distance ) { + this.metal = false; - return this.translateOnAxis( v1, distance ); + this.wrapAround = false; + this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); - }; + this.map = null; - }(), + this.lightMap = null; - localToWorld: function ( vector ) { + this.bumpMap = null; + this.bumpScale = 1; - return vector.applyMatrix4( this.matrixWorld ); + this.normalMap = null; + this.normalScale = new THREE.Vector2( 1, 1 ); - }, + this.specularMap = null; - worldToLocal: function () { + this.alphaMap = null; - var m1 = new THREE.Matrix4(); + this.envMap = null; + this.combine = THREE.MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - return function ( vector ) { + this.fog = true; - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + this.shading = THREE.SmoothShading; - }; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - }(), + this.vertexColors = THREE.NoColors; - lookAt: function () { + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - // This routine does not support objects with rotated and/or translated parent(s) + this.setValues( parameters ); - var m1 = new THREE.Matrix4(); +}; - return function ( vector ) { +THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; - m1.lookAt( vector, this.position, this.up ); +THREE.MeshPhongMaterial.prototype.clone = function () { - this.quaternion.setFromRotationMatrix( m1 ); + var material = new THREE.MeshPhongMaterial(); - }; + THREE.Material.prototype.clone.call( this, material ); - }(), + material.color.copy( this.color ); + material.emissive.copy( this.emissive ); + material.specular.copy( this.specular ); + material.shininess = this.shininess; - add: function ( object ) { + material.metal = this.metal; - if ( arguments.length > 1 ) { + material.wrapAround = this.wrapAround; + material.wrapRGB.copy( this.wrapRGB ); - for ( var i = 0; i < arguments.length; i ++ ) { + material.map = this.map; - this.add( arguments[ i ] ); + material.lightMap = this.lightMap; - } + material.bumpMap = this.bumpMap; + material.bumpScale = this.bumpScale; - return this; + material.normalMap = this.normalMap; + material.normalScale.copy( this.normalScale ); - }; + material.specularMap = this.specularMap; - if ( object === this ) { + material.alphaMap = this.alphaMap; - THREE.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + material.envMap = this.envMap; + material.combine = this.combine; + material.reflectivity = this.reflectivity; + material.refractionRatio = this.refractionRatio; - } + material.fog = this.fog; - if ( object instanceof THREE.Object3D ) { + material.shading = this.shading; - if ( object.parent !== undefined ) { + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; + material.wireframeLinecap = this.wireframeLinecap; + material.wireframeLinejoin = this.wireframeLinejoin; - object.parent.remove( object ); + material.vertexColors = this.vertexColors; - } + material.skinning = this.skinning; + material.morphTargets = this.morphTargets; + material.morphNormals = this.morphNormals; - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + return material; - this.children.push( object ); +}; - } else { +// File:src/materials/MeshDepthMaterial.js - THREE.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * opacity: <float>, + * + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float> + * } + */ - } +THREE.MeshDepthMaterial = function ( parameters ) { - return this; + THREE.Material.call( this ); - }, + this.type = 'MeshDepthMaterial'; - remove: function ( object ) { + this.morphTargets = false; + this.wireframe = false; + this.wireframeLinewidth = 1; - if ( arguments.length > 1 ) { + this.setValues( parameters ); - for ( var i = 0; i < arguments.length; i ++ ) { +}; - this.remove( arguments[ i ] ); +THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; - } +THREE.MeshDepthMaterial.prototype.clone = function () { - }; + var material = new THREE.MeshDepthMaterial(); - var index = this.children.indexOf( object ); + THREE.Material.prototype.clone.call( this, material ); - if ( index !== - 1 ) { + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; - object.parent = undefined; + return material; - object.dispatchEvent( { type: 'removed' } ); +}; - this.children.splice( index, 1 ); +// File:src/materials/MeshNormalMaterial.js - } +/** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * opacity: <float>, + * + * shading: THREE.FlatShading, + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float> + * } + */ - }, +THREE.MeshNormalMaterial = function ( parameters ) { - getChildByName: function ( name ) { + THREE.Material.call( this, parameters ); - THREE.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); + this.type = 'MeshNormalMaterial'; - }, + this.wireframe = false; + this.wireframeLinewidth = 1; - getObjectById: function ( id ) { + this.morphTargets = false; - return this.getObjectByProperty( 'id', id ); + this.setValues( parameters ); - }, +}; - getObjectByName: function ( name ) { +THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; - return this.getObjectByProperty( 'name', name ); +THREE.MeshNormalMaterial.prototype.clone = function () { - }, + var material = new THREE.MeshNormalMaterial(); - getObjectByProperty: function ( name, value ) { + THREE.Material.prototype.clone.call( this, material ); - if ( this[ name ] === value ) return this; + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + return material; - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); +}; - if ( object !== undefined ) { +// File:src/materials/MeshFaceMaterial.js - return object; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +THREE.MeshFaceMaterial = function ( materials ) { - } + this.uuid = THREE.Math.generateUUID(); - return undefined; + this.type = 'MeshFaceMaterial'; + + this.materials = materials instanceof Array ? materials : []; - }, +}; - getWorldPosition: function ( optionalTarget ) { +THREE.MeshFaceMaterial.prototype = { - var result = optionalTarget || new THREE.Vector3(); + constructor: THREE.MeshFaceMaterial, - this.updateMatrixWorld( true ); + toJSON: function () { - return result.setFromMatrixPosition( this.matrixWorld ); + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type, + materials: [] + }; - }, + for ( var i = 0, l = this.materials.length; i < l; i ++ ) { - getWorldQuaternion: function () { + output.materials.push( this.materials[ i ].toJSON() ); - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + } - return function ( optionalTarget ) { + return output; - var result = optionalTarget || new THREE.Quaternion(); + }, - this.updateMatrixWorld( true ); + clone: function () { - this.matrixWorld.decompose( position, result, scale ); + var material = new THREE.MeshFaceMaterial(); - return result; + for ( var i = 0; i < this.materials.length; i ++ ) { + + material.materials.push( this.materials[ i ].clone() ); } - }(), + return material; - getWorldRotation: function () { + } - var quaternion = new THREE.Quaternion(); +}; - return function ( optionalTarget ) { +// File:src/materials/PointCloudMaterial.js - var result = optionalTarget || new THREE.Euler(); +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * opacity: <float>, + * map: new THREE.Texture( <Image> ), + * + * size: <float>, + * sizeAttenuation: <bool>, + * + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * vertexColors: <bool>, + * + * fog: <bool> + * } + */ - this.getWorldQuaternion( quaternion ); +THREE.PointCloudMaterial = function ( parameters ) { - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + THREE.Material.call( this ); - } + this.type = 'PointCloudMaterial'; - }(), + this.color = new THREE.Color( 0xffffff ); - getWorldScale: function () { + this.map = null; - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + this.size = 1; + this.sizeAttenuation = true; - return function ( optionalTarget ) { + this.vertexColors = THREE.NoColors; - var result = optionalTarget || new THREE.Vector3(); + this.fog = true; - this.updateMatrixWorld( true ); + this.setValues( parameters ); - this.matrixWorld.decompose( position, quaternion, result ); +}; - return result; +THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial; - } +THREE.PointCloudMaterial.prototype.clone = function () { - }(), + var material = new THREE.PointCloudMaterial(); - getWorldDirection: function () { + THREE.Material.prototype.clone.call( this, material ); - var quaternion = new THREE.Quaternion(); + material.color.copy( this.color ); - return function ( optionalTarget ) { + material.map = this.map; - var result = optionalTarget || new THREE.Vector3(); + material.size = this.size; + material.sizeAttenuation = this.sizeAttenuation; - this.getWorldQuaternion( quaternion ); + material.vertexColors = this.vertexColors; - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + material.fog = this.fog; - } + return material; - }(), +}; - raycast: function () {}, +// backwards compatibility - traverse: function ( callback ) { +THREE.ParticleBasicMaterial = function ( parameters ) { - callback( this ); + THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' ); + return new THREE.PointCloudMaterial( parameters ); - for ( var i = 0, l = this.children.length; i < l; i ++ ) { +}; - this.children[ i ].traverse( callback ); +THREE.ParticleSystemMaterial = function ( parameters ) { - } + THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' ); + return new THREE.PointCloudMaterial( parameters ); - }, +}; - traverseVisible: function ( callback ) { +// File:src/materials/ShaderMaterial.js - if ( this.visible === false ) return; +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, + * + * fragmentShader: <string>, + * vertexShader: <string>, + * + * shading: THREE.SmoothShading, + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * wireframe: <boolean>, + * wireframeLinewidth: <float>, + * + * lights: <bool>, + * + * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, + * + * skinning: <bool>, + * morphTargets: <bool>, + * morphNormals: <bool>, + * + * fog: <bool> + * } + */ - callback( this ); +THREE.ShaderMaterial = function ( parameters ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + THREE.Material.call( this ); - this.children[ i ].traverseVisible( callback ); + this.type = 'ShaderMaterial'; - } + this.defines = {}; + this.uniforms = {}; + this.attributes = null; - }, + this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; + this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; - traverseAncestors: function ( callback ) { + this.shading = THREE.SmoothShading; - if ( this.parent ) { + this.linewidth = 1; - callback( this.parent ); + this.wireframe = false; + this.wireframeLinewidth = 1; - this.parent.traverseAncestors( callback ); + this.fog = false; // set to use scene fog - } + this.lights = false; // set to use scene lights - }, + this.vertexColors = THREE.NoColors; // set to use "color" attribute stream - updateMatrix: function () { + this.skinning = false; // set to use skinning attribute streams - this.matrix.compose( this.position, this.quaternion, this.scale ); + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - this.matrixWorldNeedsUpdate = true; + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] + }; - }, + this.index0AttributeName = undefined; - updateMatrixWorld: function ( force ) { + this.setValues( parameters ); - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); +}; - if ( this.matrixWorldNeedsUpdate === true || force === true ) { +THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; - if ( this.parent === undefined ) { +THREE.ShaderMaterial.prototype.clone = function () { - this.matrixWorld.copy( this.matrix ); + var material = new THREE.ShaderMaterial(); - } else { + THREE.Material.prototype.clone.call( this, material ); - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + material.fragmentShader = this.fragmentShader; + material.vertexShader = this.vertexShader; - } + material.uniforms = THREE.UniformsUtils.clone( this.uniforms ); - this.matrixWorldNeedsUpdate = false; + material.attributes = this.attributes; + material.defines = this.defines; - force = true; + material.shading = this.shading; - } + material.wireframe = this.wireframe; + material.wireframeLinewidth = this.wireframeLinewidth; - // update children + material.fog = this.fog; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + material.lights = this.lights; - this.children[ i ].updateMatrixWorld( force ); + material.vertexColors = this.vertexColors; - } + material.skinning = this.skinning; - }, + material.morphTargets = this.morphTargets; + material.morphNormals = this.morphNormals; - toJSON: function () { + return material; - var output = { - metadata: { - version: 4.3, - type: 'Object', - generator: 'ObjectExporter' - } - }; +}; - // +// File:src/materials/RawShaderMaterial.js - var geometries = {}; +/** + * @author mrdoob / http://mrdoob.com/ + */ - var parseGeometry = function ( geometry ) { +THREE.RawShaderMaterial = function ( parameters ) { - if ( output.geometries === undefined ) { + THREE.ShaderMaterial.call( this, parameters ); - output.geometries = []; + this.type = 'RawShaderMaterial'; - } +}; - if ( geometries[ geometry.uuid ] === undefined ) { +THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); +THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; - var json = geometry.toJSON(); +THREE.RawShaderMaterial.prototype.clone = function () { - delete json.metadata; + var material = new THREE.RawShaderMaterial(); - geometries[ geometry.uuid ] = json; + THREE.ShaderMaterial.prototype.clone.call( this, material ); - output.geometries.push( json ); + return material; - } +}; - return geometry.uuid; +// File:src/materials/SpriteMaterial.js - }; +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: <hex>, + * opacity: <float>, + * map: new THREE.Texture( <Image> ), + * + * blending: THREE.NormalBlending, + * depthTest: <bool>, + * depthWrite: <bool>, + * + * uvOffset: new THREE.Vector2(), + * uvScale: new THREE.Vector2(), + * + * fog: <bool> + * } + */ - // +THREE.SpriteMaterial = function ( parameters ) { - var materials = {}; + THREE.Material.call( this ); - var parseMaterial = function ( material ) { + this.type = 'SpriteMaterial'; - if ( output.materials === undefined ) { + this.color = new THREE.Color( 0xffffff ); + this.map = null; - output.materials = []; + this.rotation = 0; - } + this.fog = false; - if ( materials[ material.uuid ] === undefined ) { + // set parameters - var json = material.toJSON(); + this.setValues( parameters ); - delete json.metadata; +}; - materials[ material.uuid ] = json; +THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); +THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; - output.materials.push( json ); +THREE.SpriteMaterial.prototype.clone = function () { - } + var material = new THREE.SpriteMaterial(); - return material.uuid; + THREE.Material.prototype.clone.call( this, material ); - }; + material.color.copy( this.color ); + material.map = this.map; - // + material.rotation = this.rotation; - var parseObject = function ( object ) { + material.fog = this.fog; - var data = {}; + return material; - data.uuid = object.uuid; - data.type = object.type; +}; - if ( object.name !== '' ) data.name = object.name; - if ( JSON.stringify( object.userData ) !== '{}' ) data.userData = object.userData; - if ( object.visible !== true ) data.visible = object.visible; +// File:src/textures/Texture.js - if ( object instanceof THREE.PerspectiveCamera ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - data.fov = object.fov; - data.aspect = object.aspect; - data.near = object.near; - data.far = object.far; +THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - } else if ( object instanceof THREE.OrthographicCamera ) { + Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); - data.left = object.left; - data.right = object.right; - data.top = object.top; - data.bottom = object.bottom; - data.near = object.near; - data.far = object.far; + this.uuid = THREE.Math.generateUUID(); - } else if ( object instanceof THREE.AmbientLight ) { + this.name = ''; + this.sourceFile = ''; - data.color = object.color.getHex(); + this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; + this.mipmaps = []; - } else if ( object instanceof THREE.DirectionalLight ) { + this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; - data.color = object.color.getHex(); - data.intensity = object.intensity; + this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; - } else if ( object instanceof THREE.PointLight ) { + this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; - data.color = object.color.getHex(); - data.intensity = object.intensity; - data.distance = object.distance; - data.decay = object.decay; + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - } else if ( object instanceof THREE.SpotLight ) { + this.format = format !== undefined ? format : THREE.RGBAFormat; + this.type = type !== undefined ? type : THREE.UnsignedByteType; - data.color = object.color.getHex(); - data.intensity = object.intensity; - data.distance = object.distance; - data.angle = object.angle; - data.exponent = object.exponent; - data.decay = object.decay; + this.offset = new THREE.Vector2( 0, 0 ); + this.repeat = new THREE.Vector2( 1, 1 ); - } else if ( object instanceof THREE.HemisphereLight ) { + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - data.color = object.color.getHex(); - data.groundColor = object.groundColor.getHex(); + this._needsUpdate = false; + this.onUpdate = null; - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) { + var _this = this; + this.__defineGetter__("needsUpdate", function(){ + return _this._needsUpdate; + }); - data.geometry = parseGeometry( object.geometry ); - data.material = parseMaterial( object.material ); + this.__defineSetter__("needsUpdate", function(value){ - if ( object instanceof THREE.Line ) data.mode = object.mode; + if ( value === true ) _this.update(); + _this._needsUpdate = value; + }); +}; - } else if ( object instanceof THREE.Sprite ) { +THREE.Texture.DEFAULT_IMAGE = undefined; +THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; - data.material = parseMaterial( object.material ); +THREE.Texture.prototype = { - } + constructor: THREE.Texture, - data.matrix = object.matrix.toArray(); + clone: function ( texture ) { - if ( object.children.length > 0 ) { + if ( texture === undefined ) texture = new THREE.Texture(); - data.children = []; + texture.image = this.image; + texture.mipmaps = this.mipmaps.slice( 0 ); - for ( var i = 0; i < object.children.length; i ++ ) { + texture.mapping = this.mapping; - data.children.push( parseObject( object.children[ i ] ) ); + texture.wrapS = this.wrapS; + texture.wrapT = this.wrapT; - } + texture.magFilter = this.magFilter; + texture.minFilter = this.minFilter; - } + texture.anisotropy = this.anisotropy; - return data; + texture.format = this.format; + texture.type = this.type; - } + texture.offset.copy( this.offset ); + texture.repeat.copy( this.repeat ); - output.object = parseObject( this ); + texture.generateMipmaps = this.generateMipmaps; + texture.premultiplyAlpha = this.premultiplyAlpha; + texture.flipY = this.flipY; + texture.unpackAlignment = this.unpackAlignment; - return output; + return texture; }, - clone: function ( object, recursive ) { + update: function () { - if ( object === undefined ) object = new THREE.Object3D(); - if ( recursive === undefined ) recursive = true; + this.dispatchEvent( { type: 'update' } ); - object.name = this.name; + }, - object.up.copy( this.up ); + dispose: function () { - object.position.copy( this.position ); - object.quaternion.copy( this.quaternion ); - object.scale.copy( this.scale ); + this.dispatchEvent( { type: 'dispose' } ); - object.rotationAutoUpdate = this.rotationAutoUpdate; + } - object.matrix.copy( this.matrix ); - object.matrixWorld.copy( this.matrixWorld ); +}; - object.matrixAutoUpdate = this.matrixAutoUpdate; - object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate; +THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); - object.visible = this.visible; +THREE.TextureIdCount = 0; - object.castShadow = this.castShadow; - object.receiveShadow = this.receiveShadow; +// File:src/textures/CubeTexture.js - object.frustumCulled = this.frustumCulled; +/** + * @author mrdoob / http://mrdoob.com/ + */ - object.userData = JSON.parse( JSON.stringify( this.userData ) ); +THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - if ( recursive === true ) { + mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + + THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - for ( var i = 0; i < this.children.length; i ++ ) { + this.images = images; - var child = this.children[ i ]; - object.add( child.clone() ); +}; - } +THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); +THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; - } +THREE.CubeTexture.clone = function ( texture ) { - return object; + if ( texture === undefined ) texture = new THREE.CubeTexture(); - } + THREE.Texture.prototype.clone.call( this, texture ); -}; + texture.images = this.images; -THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); + return texture; -THREE.Object3DIdCount = 0; +}; -// File:src/core/Face3.js +// File:src/textures/CompressedTexture.js /** - * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { +THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { - this.a = a; - this.b = b; - this.c = c; + THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = normal instanceof Array ? normal : []; + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - this.color = color instanceof THREE.Color ? color : new THREE.Color(); - this.vertexColors = color instanceof Array ? color : []; + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - this.vertexTangents = []; + this.flipY = false; - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files + + this.generateMipmaps = false; }; -THREE.Face3.prototype = { +THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); +THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; - constructor: THREE.Face3, +THREE.CompressedTexture.prototype.clone = function () { - clone: function () { + var texture = new THREE.CompressedTexture(); - var face = new THREE.Face3( this.a, this.b, this.c ); + THREE.Texture.prototype.clone.call( this, texture ); - face.normal.copy( this.normal ); - face.color.copy( this.color ); + return texture; - face.materialIndex = this.materialIndex; +}; - for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) { +// File:src/textures/DataTexture.js - face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); +/** + * @author alteredq / http://alteredqualia.com/ + */ - } +THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { - for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) { + THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - face.vertexColors[ i ] = this.vertexColors[ i ].clone(); + this.image = { data: data, width: width, height: height }; - } +}; - for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) { +THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); +THREE.DataTexture.prototype.constructor = THREE.DataTexture; - face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); +THREE.DataTexture.prototype.clone = function () { - } + var texture = new THREE.DataTexture(); - return face; + THREE.Texture.prototype.clone.call( this, texture ); - } + return texture; }; -// File:src/core/Face4.js +// File:src/textures/VideoTexture.js /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { +THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - THREE.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ) - return new THREE.Face3( a, b, c, normal, color, materialIndex ); + THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); -}; + this.generateMipmaps = false; -// File:src/core/BufferAttribute.js + var scope = this; -/** - * @author mrdoob / http://mrdoob.com/ - */ + var update = function () { -THREE.BufferAttribute = function ( array, itemSize ) { + requestAnimationFrame( update ); - this.array = array; - this.itemSize = itemSize; + if ( video.readyState === video.HAVE_ENOUGH_DATA ) { - this.needsUpdate = false; + scope.needsUpdate = true; -}; + } -THREE.BufferAttribute.prototype = { + }; - constructor: THREE.BufferAttribute, + update(); - get length () { +}; - return this.array.length; +THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); +THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; - }, +// File:src/objects/Group.js - copyAt: function ( index1, attribute, index2 ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - index1 *= this.itemSize; - index2 *= attribute.itemSize; +THREE.Group = function () { - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + THREE.Object3D.call( this ); - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + this.type = 'Group'; - } +}; - return this; +THREE.Group.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Group.prototype.constructor = THREE.Group; - }, +// File:src/objects/PointCloud.js - set: function ( value, offset ) { +/** + * @author alteredq / http://alteredqualia.com/ + */ - if ( offset === undefined ) offset = 0; +THREE.PointCloud = function ( geometry, material ) { - this.array.set( value, offset ); + THREE.Object3D.call( this ); - return this; + this.type = 'PointCloud'; - }, + this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); + this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } ); - setX: function ( index, x ) { +}; - this.array[ index * this.itemSize ] = x; +THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype ); +THREE.PointCloud.prototype.constructor = THREE.PointCloud; - return this; +THREE.PointCloud.prototype.raycast = ( function () { - }, + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); - setY: function ( index, y ) { + return function ( raycaster, intersects ) { - this.array[ index * this.itemSize + 1 ] = y; + var object = this; + var geometry = object.geometry; + var threshold = raycaster.params.PointCloud.threshold; - return this; + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - }, + if ( geometry.boundingBox !== null ) { - setZ: function ( index, z ) { + if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { - this.array[ index * this.itemSize + 2 ] = z; + return; - return this; + } - }, + } - setXY: function ( index, x, y ) { + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var position = new THREE.Vector3(); - index *= this.itemSize; + var testPoint = function ( point, index ) { - this.array[ index ] = x; - this.array[ index + 1 ] = y; + var rayPointDistance = ray.distanceToPoint( point ); - return this; + if ( rayPointDistance < localThreshold ) { - }, + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( object.matrixWorld ); - setXYZ: function ( index, x, y, z ) { + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - index *= this.itemSize; + intersects.push( { - this.array[ index ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + distance: distance, + distanceToRay: rayPointDistance, + point: intersectPoint.clone(), + index: index, + face: null, + object: object - return this; + } ); - }, + } - setXYZW: function ( index, x, y, z, w ) { + }; - index *= this.itemSize; + if ( geometry instanceof THREE.BufferGeometry ) { - this.array[ index ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + var attributes = geometry.attributes; + var positions = attributes.position.array; - return this; + if ( attributes.index !== undefined ) { - }, + var indices = attributes.index.array; + var offsets = geometry.offsets; - clone: function () { + if ( offsets.length === 0 ) { - return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize ); + var offset = { + start: 0, + count: indices.length, + index: 0 + }; - } + offsets = [ offset ]; -}; + } -// + for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) { -THREE.Int8Attribute = function ( data, itemSize ) { + var start = offsets[ oi ].start; + var count = offsets[ oi ].count; + var index = offsets[ oi ].index; - THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + for ( var i = start, il = start + count; i < il; i ++ ) { -}; + var a = index + indices[ i ]; -THREE.Uint8Attribute = function ( data, itemSize ) { + position.fromArray( positions, a * 3 ); - THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + testPoint( position, a ); -}; + } -THREE.Uint8ClampedAttribute = function ( data, itemSize ) { + } - THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + } else { + var pointCount = positions.length / 3; -}; + for ( var i = 0; i < pointCount; i ++ ) { -THREE.Int16Attribute = function ( data, itemSize ) { + position.set( + positions[ 3 * i ], + positions[ 3 * i + 1 ], + positions[ 3 * i + 2 ] + ); - THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + testPoint( position, i ); -}; + } -THREE.Uint16Attribute = function ( data, itemSize ) { + } - THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + } else { -}; + var vertices = this.geometry.vertices; -THREE.Int32Attribute = function ( data, itemSize ) { + for ( var i = 0; i < vertices.length; i ++ ) { - THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + testPoint( vertices[ i ], i ); -}; + } -THREE.Uint32Attribute = function ( data, itemSize ) { + } - THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + }; -}; +}() ); -THREE.Float32Attribute = function ( data, itemSize ) { +THREE.PointCloud.prototype.clone = function ( object ) { - THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); + if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material ); + + THREE.Object3D.prototype.clone.call( this, object ); + + return object; }; -THREE.Float64Attribute = function ( data, itemSize ) { +// Backwards compatibility - THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' ); - return new THREE.BufferAttribute( data, itemSize ); +THREE.ParticleSystem = function ( geometry, material ) { + + THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' ); + return new THREE.PointCloud( geometry, material ); }; -// File:src/core/DynamicBufferAttribute.js +// File:src/objects/Line.js /** - * @author benaadams / https://twitter.com/ben_a_adams * @author mrdoob / http://mrdoob.com/ */ -THREE.DynamicBufferAttribute = function ( array, itemSize ) { +THREE.Line = function ( geometry, material, mode ) { - THREE.BufferAttribute.call( this, array, itemSize ); + THREE.Object3D.call( this ); - this.updateRange = { offset: 0, count: -1 }; + this.type = 'Line'; -}; + this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); + this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); -THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute; + this.mode = mode !== undefined ? mode : THREE.LineStrip; -THREE.DynamicBufferAttribute.prototype.clone = function () { +}; - return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize ); +THREE.LineStrip = 0; +THREE.LinePieces = 1; -}; +THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Line.prototype.constructor = THREE.Line; -// File:src/core/BufferGeometry.js +THREE.Line.prototype.raycast = ( function () { -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); + var sphere = new THREE.Sphere(); -THREE.BufferGeometry = function () { + return function ( raycaster, intersects ) { - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - this.uuid = THREE.Math.generateUUID(); + var geometry = this.geometry; - this.name = ''; - this.type = 'BufferGeometry'; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - this.attributes = {}; - this.attributesKeys = []; + // Checking boundingSphere distance to ray - this.drawcalls = []; - this.offsets = this.drawcalls; // backwards compatibility + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( this.matrixWorld ); - this.boundingBox = null; - this.boundingSphere = null; + if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { -}; + return; -THREE.BufferGeometry.prototype = { + } - constructor: THREE.BufferGeometry, + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - addAttribute: function ( name, attribute ) { + var vStart = new THREE.Vector3(); + var vEnd = new THREE.Vector3(); + var interSegment = new THREE.Vector3(); + var interRay = new THREE.Vector3(); + var step = this.mode === THREE.LineStrip ? 1 : 2; - if ( attribute instanceof THREE.BufferAttribute === false ) { + if ( geometry instanceof THREE.BufferGeometry ) { - THREE.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + var attributes = geometry.attributes; - this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] }; + if ( attributes.index !== undefined ) { - return; + var indices = attributes.index.array; + var positions = attributes.position.array; + var offsets = geometry.offsets; - } + if ( offsets.length === 0 ) { - this.attributes[ name ] = attribute; - this.attributesKeys = Object.keys( this.attributes ); + offsets = [ { start: 0, count: indices.length, index: 0 } ]; - }, + } - getAttribute: function ( name ) { + for ( var oi = 0; oi < offsets.length; oi ++) { - return this.attributes[ name ]; + var start = offsets[ oi ].start; + var count = offsets[ oi ].count; + var index = offsets[ oi ].index; - }, + for ( var i = start; i < start + count - 1; i += step ) { - addDrawCall: function ( start, count, indexOffset ) { + var a = index + indices[ i ]; + var b = index + indices[ i + 1 ]; - this.drawcalls.push( { + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - start: start, - count: count, - index: indexOffset !== undefined ? indexOffset : 0 + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - } ); + if ( distSq > precisionSq ) continue; - }, + var distance = ray.origin.distanceTo( interRay ); - applyMatrix: function ( matrix ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var position = this.attributes.position; + intersects.push( { - if ( position !== undefined ) { + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + offsetIndex: oi, + face: null, + faceIndex: null, + object: this - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + } ); - } + } - var normal = this.attributes.normal; + } - if ( normal !== undefined ) { + } else { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var positions = attributes.position.array; - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + for ( var i = 0; i < positions.length / 3 - 1; i += step ) { - } + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - if ( this.boundingBox !== null ) { + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - this.computeBoundingBox(); + if ( distSq > precisionSq ) continue; - } + var distance = ray.origin.distanceTo( interRay ); - if ( this.boundingSphere !== null ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - this.computeBoundingSphere(); + intersects.push( { - } + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - }, + } ); - center: function () { + } - this.computeBoundingBox(); + } - var offset = this.boundingBox.center().negate(); + } else if ( geometry instanceof THREE.Geometry ) { - this.applyMatrix( new THREE.Matrix4().setPosition( offset ) ); + var vertices = geometry.vertices; + var nbVertices = vertices.length; - return offset; + for ( var i = 0; i < nbVertices - 1; i += step ) { - }, + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - fromGeometry: function ( geometry, settings ) { + if ( distSq > precisionSq ) continue; - settings = settings || { 'vertexColors': THREE.NoColors }; + var distance = ray.origin.distanceTo( interRay ); - var vertices = geometry.vertices; - var faces = geometry.faces; - var faceVertexUvs = geometry.faceVertexUvs; - var vertexColors = settings.vertexColors; - var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var positions = new Float32Array( faces.length * 3 * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + intersects.push( { - var normals = new Float32Array( faces.length * 3 * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - if ( vertexColors !== THREE.NoColors ) { + } ); - var colors = new Float32Array( faces.length * 3 * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + } } - if ( hasFaceVertexUv === true ) { + }; - var uvs = new Float32Array( faces.length * 3 * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); +}() ); - } +THREE.Line.prototype.clone = function ( object ) { - for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) { + if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode ); - var face = faces[ i ]; + THREE.Object3D.prototype.clone.call( this, object ); - var a = vertices[ face.a ]; - var b = vertices[ face.b ]; - var c = vertices[ face.c ]; + return object; - positions[ i3 ] = a.x; - positions[ i3 + 1 ] = a.y; - positions[ i3 + 2 ] = a.z; +}; - positions[ i3 + 3 ] = b.x; - positions[ i3 + 4 ] = b.y; - positions[ i3 + 5 ] = b.z; +// File:src/objects/Mesh.js - positions[ i3 + 6 ] = c.x; - positions[ i3 + 7 ] = c.y; - positions[ i3 + 8 ] = c.z; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - if ( hasFaceVertexNormals === true ) { +THREE.Mesh = function ( geometry, material ) { - var na = face.vertexNormals[ 0 ]; - var nb = face.vertexNormals[ 1 ]; - var nc = face.vertexNormals[ 2 ]; + THREE.Object3D.call( this ); - normals[ i3 ] = na.x; - normals[ i3 + 1 ] = na.y; - normals[ i3 + 2 ] = na.z; + this.type = 'Mesh'; + + this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); + this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - normals[ i3 + 3 ] = nb.x; - normals[ i3 + 4 ] = nb.y; - normals[ i3 + 5 ] = nb.z; + this.updateMorphTargets(); - normals[ i3 + 6 ] = nc.x; - normals[ i3 + 7 ] = nc.y; - normals[ i3 + 8 ] = nc.z; +}; - } else { +THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Mesh.prototype.constructor = THREE.Mesh; - var n = face.normal; +THREE.Mesh.prototype.updateMorphTargets = function () { - normals[ i3 ] = n.x; - normals[ i3 + 1 ] = n.y; - normals[ i3 + 2 ] = n.z; + if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - normals[ i3 + 3 ] = n.x; - normals[ i3 + 4 ] = n.y; - normals[ i3 + 5 ] = n.z; + this.morphTargetBase = - 1; + this.morphTargetForcedOrder = []; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - normals[ i3 + 6 ] = n.x; - normals[ i3 + 7 ] = n.y; - normals[ i3 + 8 ] = n.z; + for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - if ( vertexColors === THREE.FaceColors ) { + } - var fc = face.color; + } - colors[ i3 ] = fc.r; - colors[ i3 + 1 ] = fc.g; - colors[ i3 + 2 ] = fc.b; +}; - colors[ i3 + 3 ] = fc.r; - colors[ i3 + 4 ] = fc.g; - colors[ i3 + 5 ] = fc.b; +THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) { - colors[ i3 + 6 ] = fc.r; - colors[ i3 + 7 ] = fc.g; - colors[ i3 + 8 ] = fc.b; + if ( this.morphTargetDictionary[ name ] !== undefined ) { - } else if ( vertexColors === THREE.VertexColors ) { + return this.morphTargetDictionary[ name ]; - var vca = face.vertexColors[ 0 ]; - var vcb = face.vertexColors[ 1 ]; - var vcc = face.vertexColors[ 2 ]; + } - colors[ i3 ] = vca.r; - colors[ i3 + 1 ] = vca.g; - colors[ i3 + 2 ] = vca.b; + THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); - colors[ i3 + 3 ] = vcb.r; - colors[ i3 + 4 ] = vcb.g; - colors[ i3 + 5 ] = vcb.b; + return 0; - colors[ i3 + 6 ] = vcc.r; - colors[ i3 + 7 ] = vcc.g; - colors[ i3 + 8 ] = vcc.b; +}; - } - if ( hasFaceVertexUv === true ) { +THREE.Mesh.prototype.raycast = ( function () { - var uva = faceVertexUvs[ 0 ][ i ][ 0 ]; - var uvb = faceVertexUvs[ 0 ][ i ][ 1 ]; - var uvc = faceVertexUvs[ 0 ][ i ][ 2 ]; + var inverseMatrix = new THREE.Matrix4(); + var ray = new THREE.Ray(); + var sphere = new THREE.Sphere(); - uvs[ i2 ] = uva.x; - uvs[ i2 + 1 ] = uva.y; + var vA = new THREE.Vector3(); + var vB = new THREE.Vector3(); + var vC = new THREE.Vector3(); - uvs[ i2 + 2 ] = uvb.x; - uvs[ i2 + 3 ] = uvb.y; + return function ( raycaster, intersects ) { - uvs[ i2 + 4 ] = uvc.x; - uvs[ i2 + 5 ] = uvc.y; + var geometry = this.geometry; - } + // Checking boundingSphere distance to ray - } + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - this.computeBoundingSphere() + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( this.matrixWorld ); - return this; + if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { - }, + return; - computeBoundingBox: function () { + } - var vector = new THREE.Vector3(); + // Check boundingBox before continuing - return function () { + inverseMatrix.getInverse( this.matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - if ( this.boundingBox === null ) { + if ( geometry.boundingBox !== null ) { - this.boundingBox = new THREE.Box3(); + if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + + return; } - var positions = this.attributes.position.array; + } - if ( positions ) { + if ( geometry instanceof THREE.BufferGeometry ) { - var bb = this.boundingBox; - bb.makeEmpty(); + var material = this.material; - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + if ( material === undefined ) return; - vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - bb.expandByPoint( vector ); + var attributes = geometry.attributes; - } + var a, b, c; + var precision = raycaster.precision; - } + if ( attributes.index !== undefined ) { - if ( positions === undefined || positions.length === 0 ) { + var indices = attributes.index.array; + var positions = attributes.position.array; + var offsets = geometry.offsets; - this.boundingBox.min.set( 0, 0, 0 ); - this.boundingBox.max.set( 0, 0, 0 ); + if ( offsets.length === 0 ) { - } + offsets = [ { start: 0, count: indices.length, index: 0 } ]; - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + } - THREE.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' ); + for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) { - } + var start = offsets[ oi ].start; + var count = offsets[ oi ].count; + var index = offsets[ oi ].index; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - }(), + a = index + indices[ i ]; + b = index + indices[ i + 1 ]; + c = index + indices[ i + 2 ]; - computeBoundingSphere: function () { + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + if ( material.side === THREE.BackSide ) { - return function () { + var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); - if ( this.boundingSphere === null ) { + } else { - this.boundingSphere = new THREE.Sphere(); + var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - } + } - var positions = this.attributes.position.array; + if ( intersectionPoint === null ) continue; - if ( positions ) { + intersectionPoint.applyMatrix4( this.matrixWorld ); - box.makeEmpty(); + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - var center = this.boundingSphere.center; + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + intersects.push( { - vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - box.expandByPoint( vector ); + distance: distance, + point: intersectionPoint, + face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), + faceIndex: null, + object: this - } + } ); - box.center( center ); + } - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + } - var maxRadiusSq = 0; + } else { - for ( var i = 0, il = positions.length; i < il; i += 3 ) { - - vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + var positions = attributes.position.array; - } + for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) { - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + a = i; + b = i + 1; + c = i + 2; - if ( isNaN( this.boundingSphere.radius ) ) { + vA.fromArray( positions, j ); + vB.fromArray( positions, j + 3 ); + vC.fromArray( positions, j + 6 ); - THREE.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' ); + if ( material.side === THREE.BackSide ) { - } + var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); - } + } else { - } + var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); - }(), + } - computeFaceNormals: function () { + if ( intersectionPoint === null ) continue; - // backwards compatibility + intersectionPoint.applyMatrix4( this.matrixWorld ); - }, + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - computeVertexNormals: function () { + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - var attributes = this.attributes; + intersects.push( { - if ( attributes.position ) { + distance: distance, + point: intersectionPoint, + face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), + faceIndex: null, + object: this - var positions = attributes.position.array; + } ); - if ( attributes.normal === undefined ) { + } - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + } - } else { + } else if ( geometry instanceof THREE.Geometry ) { - // reset existing normals to zero + var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial; + var objectMaterials = isFaceMaterial === true ? this.material.materials : null; - var normals = attributes.normal.array; + var a, b, c; + var precision = raycaster.precision; - for ( var i = 0, il = normals.length; i < il; i ++ ) { + var vertices = geometry.vertices; - normals[ i ] = 0; + for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - } + var face = geometry.faces[ f ]; - } + var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material; - var normals = attributes.normal.array; + if ( material === undefined ) continue; - var vA, vB, vC, + a = vertices[ face.a ]; + b = vertices[ face.b ]; + c = vertices[ face.c ]; - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + if ( material.morphTargets === true ) { - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; - // indexed elements + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); - if ( attributes.index ) { + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - var indices = attributes.index.array; + var influence = morphInfluences[ t ]; - var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] ); + if ( influence === 0 ) continue; - for ( var j = 0, jl = offsets.length; j < jl; ++ j ) { + var targets = morphTargets[ t ].vertices; - var start = offsets[ j ].start; - var count = offsets[ j ].count; - var index = offsets[ j ].index; + vA.x += ( targets[ face.a ].x - a.x ) * influence; + vA.y += ( targets[ face.a ].y - a.y ) * influence; + vA.z += ( targets[ face.a ].z - a.z ) * influence; - for ( var i = start, il = start + count; i < il; i += 3 ) { + vB.x += ( targets[ face.b ].x - b.x ) * influence; + vB.y += ( targets[ face.b ].y - b.y ) * influence; + vB.z += ( targets[ face.b ].z - b.z ) * influence; - vA = ( index + indices[ i ] ) * 3; - vB = ( index + indices[ i + 1 ] ) * 3; - vC = ( index + indices[ i + 2 ] ) * 3; + vC.x += ( targets[ face.c ].x - c.x ) * influence; + vC.y += ( targets[ face.c ].y - c.y ) * influence; + vC.z += ( targets[ face.c ].z - c.z ) * influence; - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + } - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + vA.add( a ); + vB.add( b ); + vC.add( c ); - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + a = vA; + b = vB; + c = vC; - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + } - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + if ( material.side === THREE.BackSide ) { - } + var intersectionPoint = ray.intersectTriangle( c, b, a, true ); - } + } else { - } else { + var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); - // non-indexed elements (unconnected triangle soup) + } - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + if ( intersectionPoint === null ) continue; - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + intersectionPoint.applyMatrix4( this.matrixWorld ); - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + intersects.push( { - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + distance: distance, + point: intersectionPoint, + face: face, + faceIndex: f, + object: this - } + } ); } - this.normalizeNormals(); - - attributes.normal.needsUpdate = true; - } - }, + }; - computeTangents: function () { +}() ); - // based on http://www.terathon.com/code/tangent.html - // (per vertex tangents) +THREE.Mesh.prototype.clone = function ( object, recursive ) { - if ( this.attributes.index === undefined || - this.attributes.position === undefined || - this.attributes.normal === undefined || - this.attributes.uv === undefined ) { + if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); - THREE.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' ); - return; + THREE.Object3D.prototype.clone.call( this, object, recursive ); - } + return object; - var indices = this.attributes.index.array; - var positions = this.attributes.position.array; - var normals = this.attributes.normal.array; - var uvs = this.attributes.uv.array; +}; - var nVertices = positions.length / 3; +// File:src/objects/Bone.js - if ( this.attributes.tangent === undefined ) { +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); +THREE.Bone = function ( skin ) { - } + THREE.Object3D.call( this ); - var tangents = this.attributes.tangent.array; + this.type = 'Bone'; - var tan1 = [], tan2 = []; + this.skin = skin; - for ( var k = 0; k < nVertices; k ++ ) { +}; - tan1[ k ] = new THREE.Vector3(); - tan2[ k ] = new THREE.Vector3(); +THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Bone.prototype.constructor = THREE.Bone; - } +// File:src/objects/Skeleton.js - var vA = new THREE.Vector3(), - vB = new THREE.Vector3(), - vC = new THREE.Vector3(), +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - uvA = new THREE.Vector2(), - uvB = new THREE.Vector2(), - uvC = new THREE.Vector2(), +THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { - x1, x2, y1, y2, z1, z2, - s1, s2, t1, t2, r; + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - var sdir = new THREE.Vector3(), tdir = new THREE.Vector3(); + this.identityMatrix = new THREE.Matrix4(); - function handleTriangle( a, b, c ) { + // copy the bone array - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + bones = bones || []; - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + this.bones = bones.slice( 0 ); - x1 = vB.x - vA.x; - x2 = vC.x - vA.x; + // create a bone texture or an array of floats - y1 = vB.y - vA.y; - y2 = vC.y - vA.y; + if ( this.useVertexTexture ) { - z1 = vB.z - vA.z; - z2 = vC.z - vA.z; + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones (8 * 8 / 4) + // 16x16 pixel texture max 64 bones (16 * 16 / 4) + // 32x32 pixel texture max 256 bones (32 * 32 / 4) + // 64x64 pixel texture max 1024 bones (64 * 64 / 4) - s1 = uvB.x - uvA.x; - s2 = uvC.x - uvA.x; + var size; - t1 = uvB.y - uvA.y; - t2 = uvC.y - uvA.y; + if ( this.bones.length > 256 ) + size = 64; + else if ( this.bones.length > 64 ) + size = 32; + else if ( this.bones.length > 16 ) + size = 16; + else + size = 8; - r = 1.0 / ( s1 * t2 - s2 * t1 ); + this.boneTextureWidth = size; + this.boneTextureHeight = size; - sdir.set( - ( t2 * x1 - t1 * x2 ) * r, - ( t2 * y1 - t1 * y2 ) * r, - ( t2 * z1 - t1 * z2 ) * r - ); + this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel + this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); + this.boneTexture.minFilter = THREE.NearestFilter; + this.boneTexture.magFilter = THREE.NearestFilter; + this.boneTexture.generateMipmaps = false; + this.boneTexture.flipY = false; - tdir.set( - ( s1 * x2 - s2 * x1 ) * r, - ( s1 * y2 - s2 * y1 ) * r, - ( s1 * z2 - s2 * z1 ) * r - ); + } else { - tan1[ a ].add( sdir ); - tan1[ b ].add( sdir ); - tan1[ c ].add( sdir ); + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - tan2[ a ].add( tdir ); - tan2[ b ].add( tdir ); - tan2[ c ].add( tdir ); + } - } + // use the supplied bone inverses or calculate the inverses - var i, il; - var j, jl; - var iA, iB, iC; + if ( boneInverses === undefined ) { - if ( this.drawcalls.length === 0 ) { + this.calculateInverses(); - this.addDrawCall( 0, indices.length, 0 ); + } else { - } + if ( this.bones.length === boneInverses.length ) { - var drawcalls = this.drawcalls; + this.boneInverses = boneInverses.slice( 0 ); - for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) { + } else { - var start = drawcalls[ j ].start; - var count = drawcalls[ j ].count; - var index = drawcalls[ j ].index; + THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); - for ( i = start, il = start + count; i < il; i += 3 ) { + this.boneInverses = []; - iA = index + indices[ i ]; - iB = index + indices[ i + 1 ]; - iC = index + indices[ i + 2 ]; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - handleTriangle( iA, iB, iC ); + this.boneInverses.push( new THREE.Matrix4() ); } } - var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(); - var n = new THREE.Vector3(), n2 = new THREE.Vector3(); - var w, t, test; - - function handleVertex( v ) { + } - n.fromArray( normals, v * 3 ); - n2.copy( n ); +}; - t = tan1[ v ]; +THREE.Skeleton.prototype.calculateInverses = function () { - // Gram-Schmidt orthogonalize + this.boneInverses = []; - tmp.copy( t ); - tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - // Calculate handedness + var inverse = new THREE.Matrix4(); - tmp2.crossVectors( n2, t ); - test = tmp2.dot( tan2[ v ] ); - w = ( test < 0.0 ) ? - 1.0 : 1.0; + if ( this.bones[ b ] ) { - tangents[ v * 4 ] = tmp.x; - tangents[ v * 4 + 1 ] = tmp.y; - tangents[ v * 4 + 2 ] = tmp.z; - tangents[ v * 4 + 3 ] = w; + inverse.getInverse( this.bones[ b ].matrixWorld ); } - for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) { + this.boneInverses.push( inverse ); - var start = drawcalls[ j ].start; - var count = drawcalls[ j ].count; - var index = drawcalls[ j ].index; + } - for ( i = start, il = start + count; i < il; i += 3 ) { +}; - iA = index + indices[ i ]; - iB = index + indices[ i + 1 ]; - iC = index + indices[ i + 2 ]; +THREE.Skeleton.prototype.pose = function () { - handleVertex( iA ); - handleVertex( iB ); - handleVertex( iC ); + var bone; - } + // recover the bind-time world matrices - } + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - }, + bone = this.bones[ b ]; - /* - Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices. - This method will effectively rewrite the index buffer and remap all attributes to match the new indices. - WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets. - size - Defaults to 65535, but allows for larger or smaller chunks. - */ - computeOffsets: function ( size ) { + if ( bone ) { - if ( size === undefined ) size = 65535; // WebGL limits type of index buffer values to 16-bit. + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); - var indices = this.attributes.index.array; - var vertices = this.attributes.position.array; + } - var facesCount = ( indices.length / 3 ); + } - /* - console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length); - console.log("Faces to process: "+(indices.length/3)); - console.log("Reordering "+verticesCount+" vertices."); - */ + // compute the local matrices, positions, rotations and scales - var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers - var indexPtr = 0; - var vertexPtr = 0; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - var offsets = [ { start:0, count:0, index:0 } ]; - var offset = offsets[ 0 ]; + bone = this.bones[ b ]; - var duplicatedVertices = 0; - var newVerticeMaps = 0; - var faceVertices = new Int32Array( 6 ); - var vertexMap = new Int32Array( vertices.length ); - var revVertexMap = new Int32Array( vertices.length ); - for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; } + if ( bone ) { - /* - Traverse every face and reorder vertices in the proper offsets of 65k. - We can have more than 65k entries in the index buffer per offset, but only reference 65k values. - */ - for ( var findex = 0; findex < facesCount; findex ++ ) { - newVerticeMaps = 0; + if ( bone.parent ) { - for ( var vo = 0; vo < 3; vo ++ ) { - var vid = indices[ findex * 3 + vo ]; - if ( vertexMap[ vid ] == - 1 ) { - //Unmapped vertice - faceVertices[ vo * 2 ] = vid; - faceVertices[ vo * 2 + 1 ] = - 1; - newVerticeMaps ++; - } else if ( vertexMap[ vid ] < offset.index ) { - //Reused vertices from previous block (duplicate) - faceVertices[ vo * 2 ] = vid; - faceVertices[ vo * 2 + 1 ] = - 1; - duplicatedVertices ++; - } else { - //Reused vertice in the current block - faceVertices[ vo * 2 ] = vid; - faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ]; - } - } + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); - var faceMax = vertexPtr + newVerticeMaps; - if ( faceMax > ( offset.index + size ) ) { - var new_offset = { start:indexPtr, count:0, index:vertexPtr }; - offsets.push( new_offset ); - offset = new_offset; + } else { - //Re-evaluate reused vertices in light of new offset. - for ( var v = 0; v < 6; v += 2 ) { - var new_vid = faceVertices[ v + 1 ]; - if ( new_vid > - 1 && new_vid < offset.index ) - faceVertices[ v + 1 ] = - 1; - } - } + bone.matrix.copy( bone.matrixWorld ); - //Reindex the face. - for ( var v = 0; v < 6; v += 2 ) { - var vid = faceVertices[ v ]; - var new_vid = faceVertices[ v + 1 ]; + } - if ( new_vid === - 1 ) - new_vid = vertexPtr ++; + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - vertexMap[ vid ] = new_vid; - revVertexMap[ new_vid ] = vid; - sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit - offset.count ++; - } } - /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */ - this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr ); - this.offsets = offsets; // TODO: Deprecate - this.drawcalls = offsets; + } - /* - var orderTime = Date.now(); - console.log("Reorder time: "+(orderTime-s)+"ms"); - console.log("Duplicated "+duplicatedVertices+" vertices."); - console.log("Compute Buffers time: "+(Date.now()-s)+"ms"); - console.log("Draw offsets: "+offsets.length); - */ +}; - return offsets; +THREE.Skeleton.prototype.update = ( function () { - }, + var offsetMatrix = new THREE.Matrix4(); + + return function () { - merge: function ( geometry, offset ) { + // flatten bone matrices to array - if ( geometry instanceof THREE.BufferGeometry === false ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - THREE.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + // compute the offset between the current and the original transform - } + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - if ( offset === undefined ) offset = 0; + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); - var attributes = this.attributes; + } - for ( var key in attributes ) { + if ( this.useVertexTexture ) { - if ( geometry.attributes[ key ] === undefined ) continue; + this.boneTexture.needsUpdate = true; - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + } + + }; - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; +} )(); - var attributeSize = attribute2.itemSize; - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { +// File:src/objects/SkinnedMesh.js - attributeArray1[ j ] = attributeArray2[ i ]; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - } +THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { - } + THREE.Mesh.call( this, geometry, material ); - return this; + this.type = 'SkinnedMesh'; - }, + this.bindMode = "attached"; + this.bindMatrix = new THREE.Matrix4(); + this.bindMatrixInverse = new THREE.Matrix4(); - normalizeNormals: function () { + // init bones - var normals = this.attributes.normal.array; + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - var x, y, z, n; + var bones = []; - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + if ( this.geometry && this.geometry.bones !== undefined ) { - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; + var bone, gbone, p, q, s; - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; + gbone = this.geometry.bones[ b ]; - } + p = gbone.pos; + q = gbone.rotq; + s = gbone.scl; - }, + bone = new THREE.Bone( this ); + bones.push( bone ); - /* - reoderBuffers: - Reorder attributes based on a new indexBuffer and indexMap. - indexBuffer - Uint16Array of the new ordered indices. - indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex. - vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack). - */ - reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) { + bone.name = gbone.name; + bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] ); + bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] ); - /* Create a copy of all attributes for reordering. */ - var sortedAttributes = {}; - for ( var attr in this.attributes ) { - if ( attr == 'index' ) - continue; - var sourceArray = this.attributes[ attr ].array; - sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount ); - } + if ( s !== undefined ) { + + bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] ); + + } else { + + bone.scale.set( 1, 1, 1 ); - /* Move attribute positions based on the new index map */ - for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) { - var vid = indexMap[ new_vid ]; - for ( var attr in this.attributes ) { - if ( attr == 'index' ) - continue; - var attrArray = this.attributes[ attr ].array; - var attrSize = this.attributes[ attr ].itemSize; - var sortedAttr = sortedAttributes[ attr ]; - for ( var k = 0; k < attrSize; k ++ ) - sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ]; } - } - /* Carry the new sorted buffers locally */ - this.attributes[ 'index' ].array = indexBuffer; - for ( var attr in this.attributes ) { - if ( attr == 'index' ) - continue; - this.attributes[ attr ].array = sortedAttributes[ attr ]; - this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount; } - }, - toJSON: function () { + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - var output = { - metadata: { - version: 4.0, - type: 'BufferGeometry', - generator: 'BufferGeometryExporter' - }, - uuid: this.uuid, - type: this.type, - data: { - attributes: {} - } - }; + gbone = this.geometry.bones[ b ]; - var attributes = this.attributes; - var offsets = this.offsets; - var boundingSphere = this.boundingSphere; + if ( gbone.parent !== - 1 ) { - for ( var key in attributes ) { + bones[ gbone.parent ].add( bones[ b ] ); - var attribute = attributes[ key ]; + } else { - var array = Array.prototype.slice.call( attribute.array ); + this.add( bones[ b ] ); - output.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array } } - if ( offsets.length > 0 ) { + } - output.data.offsets = JSON.parse( JSON.stringify( offsets ) ); + this.normalizeSkinWeights(); - } + this.updateMatrixWorld( true ); + this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) ); - if ( boundingSphere !== null ) { +}; - output.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - } - } +THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); +THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh; - return output; +THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) { - }, + this.skeleton = skeleton; - clone: function () { + if ( bindMatrix === undefined ) { - var geometry = new THREE.BufferGeometry(); + this.updateMatrixWorld( true ); - for ( var attr in this.attributes ) { + bindMatrix = this.matrixWorld; - var sourceAttr = this.attributes[ attr ]; - geometry.addAttribute( attr, sourceAttr.clone() ); + } - } + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - for ( var i = 0, il = this.offsets.length; i < il; i ++ ) { +}; - var offset = this.offsets[ i ]; +THREE.SkinnedMesh.prototype.pose = function () { - geometry.offsets.push( { + this.skeleton.pose(); - start: offset.start, - index: offset.index, - count: offset.count +}; - } ); +THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { - } + if ( this.geometry instanceof THREE.Geometry ) { - return geometry; + for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { - }, + var sw = this.geometry.skinWeights[ i ]; - dispose: function () { + var scale = 1.0 / sw.lengthManhattan(); - this.dispatchEvent( { type: 'dispose' } ); + if ( scale !== Infinity ) { - } + sw.multiplyScalar( scale ); -}; + } else { -THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); + sw.set( 1 ); // this will be normalized by the shader anyway -// File:src/core/Geometry.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @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 () { + } else { - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + // skinning weights assumed to be normalized for THREE.BufferGeometry - this.uuid = THREE.Math.generateUUID(); + } - this.name = ''; - this.type = 'Geometry'; +}; - this.vertices = []; - this.colors = []; // one-to-one vertex colors, used in Points and Line +THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) { - this.faces = []; + THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); - this.faceVertexUvs = [ [] ]; + if ( this.bindMode === "attached" ) { - this.morphTargets = []; - this.morphColors = []; - this.morphNormals = []; + this.bindMatrixInverse.getInverse( this.matrixWorld ); - this.skinWeights = []; - this.skinIndices = []; + } else if ( this.bindMode === "detached" ) { - this.lineDistances = []; + this.bindMatrixInverse.getInverse( this.bindMatrix ); - this.boundingBox = null; - this.boundingSphere = null; + } else { - this.hasTangents = false; + THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode ); - this.dynamic = true; // the intermediate typed arrays will be deleted when set to false + } - // update flags +}; - this.verticesNeedUpdate = false; - this.elementsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.tangentsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; +THREE.SkinnedMesh.prototype.clone = function( object ) { - this.groupsNeedUpdate = false; + if ( object === undefined ) { + + object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture ); + + } + + THREE.Mesh.prototype.clone.call( this, object ); + + return object; }; -THREE.Geometry.prototype = { - constructor: THREE.Geometry, +// File:src/objects/MorphAnimMesh.js - applyMatrix: function ( matrix ) { +/** + * @author alteredq / http://alteredqualia.com/ + */ - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); +THREE.MorphAnimMesh = function ( geometry, material ) { - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + THREE.Mesh.call( this, geometry, material ); - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + this.type = 'MorphAnimMesh'; - } + // API - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + this.duration = 1000; // milliseconds + this.mirroredLoop = false; + this.time = 0; - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + // internals - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + this.lastKeyframe = 0; + this.currentKeyframe = 0; - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + this.direction = 1; + this.directionBackwards = false; - } + this.setFrameRange( 0, this.geometry.morphTargets.length - 1 ); - } +}; - if ( this.boundingBox !== null ) { +THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); +THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh; - this.computeBoundingBox(); +THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { - } + this.startKeyframe = start; + this.endKeyframe = end; - if ( this.boundingSphere !== null ) { + this.length = this.endKeyframe - this.startKeyframe + 1; - this.computeBoundingSphere(); +}; - } +THREE.MorphAnimMesh.prototype.setDirectionForward = function () { - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + this.direction = 1; + this.directionBackwards = false; - }, +}; - fromBufferGeometry: function ( geometry ) { +THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { - var scope = this; + this.direction = - 1; + this.directionBackwards = true; - var attributes = geometry.attributes; +}; - var vertices = attributes.position.array; - var indices = attributes.index !== undefined ? attributes.index.array : undefined; - var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; - var colors = attributes.color !== undefined ? attributes.color.array : undefined; - var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; +THREE.MorphAnimMesh.prototype.parseAnimations = function () { - var tempNormals = []; - var tempUVs = []; + var geometry = this.geometry; - for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) { + if ( ! geometry.animations ) geometry.animations = {}; - scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + var firstAnimation, animations = geometry.animations; - if ( normals !== undefined ) { + var pattern = /([a-z]+)_?(\d+)/; - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - } + var morph = geometry.morphTargets[ i ]; + var parts = morph.name.match( pattern ); - if ( colors !== undefined ) { + if ( parts && parts.length > 1 ) { - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + var label = parts[ 1 ]; - } + if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity }; - if ( uvs !== undefined ) { + var animation = animations[ label ]; - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + if ( i < animation.start ) animation.start = i; + if ( i > animation.end ) animation.end = i; - } + if ( ! firstAnimation ) firstAnimation = label; } - var addFace = function ( a, b, c ) { + } - var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; - var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; + geometry.firstAnimation = firstAnimation; - scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) ); +}; - if ( uvs !== undefined ) { +THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + if ( ! this.geometry.animations ) this.geometry.animations = {}; - } + this.geometry.animations[ label ] = { start: start, end: end }; - }; +}; - if ( indices !== undefined ) { +THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { - var drawcalls = geometry.drawcalls; + var animation = this.geometry.animations[ label ]; - if ( drawcalls.length > 0 ) { + if ( animation ) { - for ( var i = 0; i < drawcalls.length; i ++ ) { + this.setFrameRange( animation.start, animation.end ); + this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); + this.time = 0; - var drawcall = drawcalls[ i ]; + } else { - var start = drawcall.start; - var count = drawcall.count; - var index = drawcall.index; + THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' ); - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + } - addFace( index + indices[ j ], index + indices[ j + 1 ], index + indices[ j + 2 ] ); +}; - } +THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { - } + var frameTime = this.duration / this.length; - } else { + this.time += this.direction * delta; - for ( var i = 0; i < indices.length; i += 3 ) { + if ( this.mirroredLoop ) { - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + if ( this.time > this.duration || this.time < 0 ) { - } + this.direction *= - 1; - } + if ( this.time > this.duration ) { - } else { + this.time = this.duration; + this.directionBackwards = true; - for ( var i = 0; i < vertices.length / 3; i += 3 ) { + } - addFace( i, i + 1, i + 2 ); + if ( this.time < 0 ) { + + this.time = 0; + this.directionBackwards = false; } } - this.computeFaceNormals(); + } else { - if ( geometry.boundingBox !== null ) { + this.time = this.time % this.duration; - this.boundingBox = geometry.boundingBox.clone(); + if ( this.time < 0 ) this.time += this.duration; - } + } - if ( geometry.boundingSphere !== null ) { + var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 ); - this.boundingSphere = geometry.boundingSphere.clone(); + if ( keyframe !== this.currentKeyframe ) { - } + this.morphTargetInfluences[ this.lastKeyframe ] = 0; + this.morphTargetInfluences[ this.currentKeyframe ] = 1; - return this; + this.morphTargetInfluences[ keyframe ] = 0; - }, + this.lastKeyframe = this.currentKeyframe; + this.currentKeyframe = keyframe; - center: function () { + } - this.computeBoundingBox(); + var mix = ( this.time % frameTime ) / frameTime; - var offset = this.boundingBox.center().negate(); + if ( this.directionBackwards ) { - this.applyMatrix( new THREE.Matrix4().setPosition( offset ) ); + mix = 1 - mix; - return offset; + } - }, + this.morphTargetInfluences[ this.currentKeyframe ] = mix; + this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix; - computeFaceNormals: function () { +}; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); +THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + var influences = this.morphTargetInfluences; - var face = this.faces[ f ]; + for ( var i = 0, l = influences.length; i < l; i ++ ) { - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + influences[ i ] = 0; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + } - cb.normalize(); + if ( a > -1 ) influences[ a ] = 1 - t; + if ( b > -1 ) influences[ b ] = t; - face.normal.copy( cb ); +}; - } +THREE.MorphAnimMesh.prototype.clone = function ( object ) { - }, + if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material ); - computeVertexNormals: function ( areaWeighted ) { + object.duration = this.duration; + object.mirroredLoop = this.mirroredLoop; + object.time = this.time; - var v, vl, f, fl, face, vertices; + object.lastKeyframe = this.lastKeyframe; + object.currentKeyframe = this.currentKeyframe; - vertices = new Array( this.vertices.length ); + object.direction = this.direction; + object.directionBackwards = this.directionBackwards; - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + THREE.Mesh.prototype.clone.call( this, object ); - vertices[ v ] = new THREE.Vector3(); + return object; - } +}; - if ( areaWeighted ) { +// File:src/objects/LOD.js - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); +THREE.LOD = function () { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + THREE.Object3D.call( this ); - face = this.faces[ f ]; + this.objects = []; - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; +}; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); +THREE.LOD.prototype = Object.create( THREE.Object3D.prototype ); +THREE.LOD.prototype.constructor = THREE.LOD; - } +THREE.LOD.prototype.addLevel = function ( object, distance ) { - } else { + if ( distance === undefined ) distance = 0; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + distance = Math.abs( distance ); - face = this.faces[ f ]; + for ( var l = 0; l < this.objects.length; l ++ ) { - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + if ( distance < this.objects[ l ].distance ) { - } + break; } - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + } - vertices[ v ].normalize(); + this.objects.splice( l, 0, { distance: distance, object: object } ); + this.add( object ); - } +}; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { +THREE.LOD.prototype.getObjectForDistance = function ( distance ) { - face = this.faces[ f ]; + for ( var i = 1, l = this.objects.length; i < l; i ++ ) { - face.vertexNormals[ 0 ] = vertices[ face.a ].clone(); - face.vertexNormals[ 1 ] = vertices[ face.b ].clone(); - face.vertexNormals[ 2 ] = vertices[ face.c ].clone(); + if ( distance < this.objects[ i ].distance ) { + + break; } - }, + } - computeMorphNormals: function () { + return this.objects[ i - 1 ].object; - var i, il, f, fl, face; +}; - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) +THREE.LOD.prototype.raycast = ( function () { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var matrixPosition = new THREE.Vector3(); - face = this.faces[ f ]; + return function ( raycaster, intersects ) { - if ( ! face.__originalFaceNormal ) { + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - face.__originalFaceNormal = face.normal.clone(); + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - } else { + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - face.__originalFaceNormal.copy( face.normal ); + }; - } +}() ); - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; +THREE.LOD.prototype.update = function () { - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); - if ( ! face.__originalVertexNormals[ i ] ) { + return function ( camera ) { - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + if ( this.objects.length > 1 ) { + + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); + + var distance = v1.distanceTo( v2 ); + + this.objects[ 0 ].object.visible = true; + + for ( var i = 1, l = this.objects.length; i < l; i ++ ) { + + if ( distance >= this.objects[ i ].distance ) { + + this.objects[ i - 1 ].object.visible = false; + this.objects[ i ].object.visible = true; } else { - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + break; } } - } - - // use temp geometry to compute face and vertex normals for each morph + for ( ; i < l; i ++ ) { - var tmpGeo = new THREE.Geometry(); - tmpGeo.faces = this.faces; + this.objects[ i ].object.visible = false; - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + } - // create on first access + } - if ( ! this.morphNormals[ i ] ) { + }; - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; +}(); - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; +THREE.LOD.prototype.clone = function ( object ) { - var faceNormal, vertexNormals; + if ( object === undefined ) object = new THREE.LOD(); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + THREE.Object3D.prototype.clone.call( this, object ); - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + for ( var i = 0, l = this.objects.length; i < l; i ++ ) { + var x = this.objects[ i ].object.clone(); + x.visible = i === 0; + object.addLevel( x, this.objects[ i ].distance ); + } - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + return object; - } +}; - } +// File:src/objects/Sprite.js - var morphNormals = this.morphNormals[ i ]; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - // set vertices to morph target +THREE.Sprite = function (material) { - tmpGeo.vertices = this.morphTargets[ i ].vertices; + var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ); + var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] ); + var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] ); - // compute morph normals + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); +// return function ( material ) { - // store morph normals + THREE.Object3D.call( this ); - var faceNormal, vertexNormals; + this.type = 'Sprite'; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + this.geometry = geometry; + this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); - face = this.faces[ f ]; +// }; - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; +}; - faceNormal.copy( face.normal ); +THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Sprite.prototype.constructor = THREE.Sprite; - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); +THREE.Sprite.prototype.raycast = ( function () { - } + var matrixPosition = new THREE.Vector3(); - } + return function ( raycaster, intersects ) { - // restore original normals + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var distance = raycaster.ray.distanceToPoint( matrixPosition ); - face = this.faces[ f ]; + if ( distance > this.scale.x ) { - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + return; } - }, + intersects.push( { - computeTangents: function () { + distance: distance, + point: this.position, + face: null, + object: this - // based on http://www.terathon.com/code/tangent.html - // tangents go to vertices + } ); - var f, fl, v, vl, i, vertexIndex, - face, uv, vA, vB, vC, uvA, uvB, uvC, - x1, x2, y1, y2, z1, z2, - s1, s2, t1, t2, r, t, test, - tan1 = [], tan2 = [], - sdir = new THREE.Vector3(), tdir = new THREE.Vector3(), - tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), - n = new THREE.Vector3(), w; + }; - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { +}() ); - tan1[ v ] = new THREE.Vector3(); - tan2[ v ] = new THREE.Vector3(); +THREE.Sprite.prototype.clone = function ( object ) { - } + if ( object === undefined ) object = new THREE.Sprite( this.material ); - function handleTriangle( context, a, b, c, ua, ub, uc ) { + THREE.Object3D.prototype.clone.call( this, object ); - vA = context.vertices[ a ]; - vB = context.vertices[ b ]; - vC = context.vertices[ c ]; + return object; - uvA = uv[ ua ]; - uvB = uv[ ub ]; - uvC = uv[ uc ]; +}; - x1 = vB.x - vA.x; - x2 = vC.x - vA.x; - y1 = vB.y - vA.y; - y2 = vC.y - vA.y; - z1 = vB.z - vA.z; - z2 = vC.z - vA.z; +// Backwards compatibility - s1 = uvB.x - uvA.x; - s2 = uvC.x - uvA.x; - t1 = uvB.y - uvA.y; - t2 = uvC.y - uvA.y; +THREE.Particle = THREE.Sprite; - r = 1.0 / ( s1 * t2 - s2 * t1 ); - sdir.set( ( t2 * x1 - t1 * x2 ) * r, - ( t2 * y1 - t1 * y2 ) * r, - ( t2 * z1 - t1 * z2 ) * r ); - tdir.set( ( s1 * x2 - s2 * x1 ) * r, - ( s1 * y2 - s2 * y1 ) * r, - ( s1 * z2 - s2 * z1 ) * r ); +// File:src/objects/LensFlare.js - tan1[ a ].add( sdir ); - tan1[ b ].add( sdir ); - tan1[ c ].add( sdir ); +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - tan2[ a ].add( tdir ); - tan2[ b ].add( tdir ); - tan2[ c ].add( tdir ); +THREE.LensFlare = function ( texture, size, distance, blending, color ) { - } + THREE.Object3D.call( this ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + this.lensFlares = []; - face = this.faces[ f ]; - uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents + this.positionScreen = new THREE.Vector3(); + this.customUpdateCallback = undefined; - handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 ); + if ( texture !== undefined ) { - } + this.add( texture, size, distance, blending, color ); - var faceIndex = [ 'a', 'b', 'c', 'd' ]; + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { +}; - face = this.faces[ f ]; +THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); +THREE.LensFlare.prototype.constructor = THREE.LensFlare; - for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) { - n.copy( face.vertexNormals[ i ] ); +/* + * Add: adds another flare + */ - vertexIndex = face[ faceIndex[ i ] ]; +THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { - t = tan1[ vertexIndex ]; + if ( size === undefined ) size = - 1; + if ( distance === undefined ) distance = 0; + if ( opacity === undefined ) opacity = 1; + if ( color === undefined ) color = new THREE.Color( 0xffffff ); + if ( blending === undefined ) blending = THREE.NormalBlending; - // Gram-Schmidt orthogonalize + distance = Math.min( distance, Math.max( 0, distance ) ); - tmp.copy( t ); - tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + this.lensFlares.push( { + texture: texture, // THREE.Texture + size: size, // size in pixels (-1 = use texture.width) + distance: distance, // distance (0-1) from light source (0=at light source) + x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back + scale: 1, // scale + rotation: 1, // rotation + opacity: opacity, // opacity + color: color, // color + blending: blending // blending + } ); - // Calculate handedness +}; - tmp2.crossVectors( face.vertexNormals[ i ], t ); - test = tmp2.dot( tan2[ vertexIndex ] ); - w = ( test < 0.0 ) ? - 1.0 : 1.0; +/* + * Update lens flares update positions on all flares based on the screen position + * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. + */ - face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w ); +THREE.LensFlare.prototype.updateLensFlares = function () { - } + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; - } + for ( f = 0; f < fl; f ++ ) { - this.hasTangents = true; + flare = this.lensFlares[ f ]; - }, + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; - computeLineDistances: function () { + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - var d = 0; - var vertices = this.vertices; + } - for ( var i = 0, il = vertices.length; i < il; i ++ ) { +}; - if ( i > 0 ) { - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); +// File:src/scenes/Scene.js - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.lineDistances[ i ] = d; +THREE.Scene = function () { - } + THREE.Object3D.call( this ); - }, + this.type = 'Scene'; - computeBoundingBox: function () { + this.fog = null; + this.overrideMaterial = null; - if ( this.boundingBox === null ) { + this.autoUpdate = true; // checked by the renderer - this.boundingBox = new THREE.Box3(); +}; - } +THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Scene.prototype.constructor = THREE.Scene; - this.boundingBox.setFromPoints( this.vertices ); +THREE.Scene.prototype.clone = function ( object ) { - }, + if ( object === undefined ) object = new THREE.Scene(); - computeBoundingSphere: function () { + THREE.Object3D.prototype.clone.call( this, object ); - if ( this.boundingSphere === null ) { + if ( this.fog !== null ) object.fog = this.fog.clone(); + if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone(); - this.boundingSphere = new THREE.Sphere(); + object.autoUpdate = this.autoUpdate; + object.matrixAutoUpdate = this.matrixAutoUpdate; - } + return object; - this.boundingSphere.setFromPoints( this.vertices ); +}; - }, +// File:src/scenes/Fog.js - merge: function ( geometry, matrix, materialIndexOffset ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( geometry instanceof THREE.Geometry === false ) { +THREE.Fog = function ( color, near, far ) { - THREE.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + this.name = ''; - } + this.color = new THREE.Color( color ); - var normalMatrix, - vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - uvs1 = this.faceVertexUvs[ 0 ], - uvs2 = geometry.faceVertexUvs[ 0 ]; + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; +}; - if ( matrix !== undefined ) { +THREE.Fog.prototype.clone = function () { - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + return new THREE.Fog( this.color.getHex(), this.near, this.far ); - } +}; - // vertices +// File:src/scenes/FogExp2.js - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var vertex = vertices2[ i ]; +THREE.FogExp2 = function ( color, density ) { - var vertexCopy = vertex.clone(); + this.name = ''; - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + this.color = new THREE.Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - vertices1.push( vertexCopy ); +}; - } +THREE.FogExp2.prototype.clone = function () { - // faces + return new THREE.FogExp2( this.color.getHex(), this.density ); - for ( i = 0, il = faces2.length; i < il; i ++ ) { +}; - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; +// File:src/renderers/shaders/ShaderChunk.js - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); +THREE.ShaderChunk = {}; - if ( normalMatrix !== undefined ) { +// File:src/renderers/shaders/ShaderChunk/common.glsl - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); +THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\nfloat square( in float a ) { return a*a; }\nvec2 square( in vec2 a ) { return vec2( a.x*a.x, a.y*a.y ); }\nvec3 square( in vec3 a ) { return vec3( a.x*a.x, a.y*a.y, a.z*a.z ); }\nvec4 square( in vec4 a ) { return vec4( a.x*a.x, a.y*a.y, a.z*a.z, a.w*a.w ); }\nfloat saturate( in float a ) { return clamp( a, 0.0, 1.0 ); }\nvec2 saturate( in vec2 a ) { return clamp( a, 0.0, 1.0 ); }\nvec3 saturate( in vec3 a ) { return clamp( a, 0.0, 1.0 ); }\nvec4 saturate( in vec4 a ) { return clamp( a, 0.0, 1.0 ); }\nfloat average( in float a ) { return a; }\nfloat average( in vec2 a ) { return ( a.x + a.y) * 0.5; }\nfloat average( in vec3 a ) { return ( a.x + a.y + a.z) / 3.0; }\nfloat average( in vec4 a ) { return ( a.x + a.y + a.z + a.w) * 0.25; }\nfloat whiteCompliment( in float a ) { return saturate( 1.0 - a ); }\nvec2 whiteCompliment( in vec2 a ) { return saturate( vec2(1.0) - a ); }\nvec3 whiteCompliment( in vec3 a ) { return saturate( vec3(1.0) - a ); }\nvec4 whiteCompliment( in vec4 a ) { return saturate( vec4(1.0) - a ); }\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal) {\n float distance = dot( planeNormal, point-pointOnPlane );\n return point - distance * planeNormal;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return pointOnLine + lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) );\n}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( 1.0 - lightDistance / cutoffDistance ), decayExponent );\n }\n return 1.0;\n}\n\nvec3 inputToLinear( in vec3 a ) {\n#ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\nvec3 linearToOutput( in vec3 a ) {\n#ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\n"; - } +// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { +THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; - normal = faceVertexNormals[ j ].clone(); +// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl - if ( normalMatrix !== undefined ) { +THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * attenuation;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * attenuation;\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * attenuation * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * attenuation * spotEffect;\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n"; - normal.applyMatrix3( normalMatrix ).normalize(); +// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl - } +THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n"; - faceCopy.vertexNormals.push( normal ); +// File:src/renderers/shaders/ShaderChunk/default_vertex.glsl - } +THREE.ShaderChunk[ 'default_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; - faceCopy.color.copy( face.color ); +// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { +THREE.ShaderChunk[ 'map_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif"; - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); +// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl - } +THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n"; - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl - faces1.push( faceCopy ); +THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif"; - } +// File:src/renderers/shaders/ShaderChunk/lightmap_pars_vertex.glsl - // uvs +THREE.ShaderChunk[ 'lightmap_pars_vertex'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif"; - for ( i = 0, il = uvs2.length; i < il; i ++ ) { +// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl - var uv = uvs2[ i ], uvCopy = []; +THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += pointLightColor[ i ] * pointDiffuseWeight * attenuation;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += spotLightColor[ i ] * spotDiffuseWeight * attenuation * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n totalSpecularLight += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) + totalSpecularLight + emissive;\n\n#endif\n"; - if ( uv === undefined ) { +// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl - continue; +THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif"; - } +// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { +THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif"; - uvCopy.push( uv[ j ].clone() ); +// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl - } +THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n"; - uvs1.push( uvCopy ); +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl - } +THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; - }, +// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl - mergeMesh: function ( mesh ) { +THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n"; - if ( mesh instanceof THREE.Mesh === false ) { +// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl - THREE.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; +THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n"; - } +// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl - mesh.matrixAutoUpdate && mesh.updateMatrix(); +THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif"; - this.merge( mesh.geometry, mesh.matrix ); +// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl - }, +THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif"; - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ +// File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl - mergeVertices: function () { +THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif"; - var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique) - var unique = [], changes = []; +// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl - var v, key; - var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; +THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif"; - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { +// File:src/renderers/shaders/ShaderChunk/lightmap_vertex.glsl - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); +THREE.ShaderChunk[ 'lightmap_vertex'] = "#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif"; - if ( verticesMap[ key ] === undefined ) { +// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; +THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n"; - } else { +// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; +THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n"; - } +// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl - }; +THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif"; +// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; +THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n"; - for ( i = 0, il = this.faces.length; i < il; i ++ ) { - - face = this.faces[ i ]; - - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; - - indices = [ face.a, face.b, face.c ]; - - var dupIndex = - 1; +// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { - if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) { +THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n"; - dupIndex = n; - faceIndicesToRemove.push( i ); - break; +// File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl - } - } +THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n"; - } +// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - var idx = faceIndicesToRemove[ i ]; +THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif"; - this.faces.splice( idx, 1 ); +// File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { +THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n"; - this.faceVertexUvs[ j ].splice( idx, 1 ); +// File:src/renderers/shaders/ShaderChunk/map_pars_vertex.glsl - } +THREE.ShaderChunk[ 'map_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n"; - } +// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl - // Use unique set of vertices +THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n"; - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; +// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl - }, +THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif"; - toJSON: function () { +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl - var output = { - metadata: { - version: 4.0, - type: 'BufferGeometry', - generator: 'BufferGeometryExporter' - }, - uuid: this.uuid, - type: this.type - }; +THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif"; - if ( this.name !== "" ) output.name = this.name; +// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl - if ( this.parameters !== undefined ) { +THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif"; - var parameters = this.parameters; +// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl - for ( var key in parameters ) { +THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif"; - if ( parameters[ key ] !== undefined ) output[ key ] = parameters[ key ]; +// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl - } +THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = exp2( - square( fogDensity ) * square( depth ) * LOG2 );\n fogFactor = whiteCompliment( fogFactor );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif"; - return output; +// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl - } +THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n"; - var vertices = []; +// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl - for ( var i = 0; i < this.vertices.length; i ++ ) { +THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); +// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl - } +THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n"; - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; +// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl - for ( var i = 0; i < this.faces.length; i ++ ) { +THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; - var face = this.faces[ i ]; +// File:src/renderers/shaders/ShaderChunk/map_vertex.glsl - var hasMaterial = false; // face.materialIndex !== undefined; - var hasFaceUv = false; // deprecated - var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; - var hasFaceNormal = face.normal.length() > 0; - var hasFaceVertexNormal = face.vertexNormals.length > 0; - var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - var hasFaceVertexColor = face.vertexColors.length > 0; +THREE.ShaderChunk[ 'map_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; - var faceType = 0; +// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl - faceType = setBit( faceType, 0, 0 ); - faceType = setBit( faceType, 1, hasMaterial ); - faceType = setBit( faceType, 2, hasFaceUv ); - faceType = setBit( faceType, 3, hasFaceVertexUv ); - faceType = setBit( faceType, 4, hasFaceNormal ); - faceType = setBit( faceType, 5, hasFaceVertexNormal ); - faceType = setBit( faceType, 6, hasFaceColor ); - faceType = setBit( faceType, 7, hasFaceVertexColor ); +THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n outgoingLight *= diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz;\n\n#endif"; - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); +// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl +THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif"; - /* - if ( hasMaterial ) { +// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl - faces.push( face.materialIndex ); +THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif"; - } - */ +// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl - if ( hasFaceVertexUv ) { +THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif"; - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; +// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); +THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n"; - } +// File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl - if ( hasFaceNormal ) { +THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n // NOTE: I am unsure if this is correct in linear space. -bhouston, Dec 29, 2014\n shadowColor = inputToLinear( shadowColor );\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n"; - faces.push( getNormalIndex( face.normal ) ); +// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl - } +THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n"; - if ( hasFaceVertexNormal ) { +// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl - var vertexNormals = face.vertexNormals; +THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif"; - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); +// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl - } +THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n"; - if ( hasFaceColor ) { +// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl - faces.push( getColorIndex( face.color ) ); +THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif"; - } +// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl - if ( hasFaceVertexColor ) { +THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; - var vertexColors = face.vertexColors; +// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); +THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n"; - } +// File:src/renderers/shaders/UniformsUtils.js - } +/** + * Uniform Utilities + */ - function setBit( value, position, enabled ) { +THREE.UniformsUtils = { - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) ); + merge: function ( uniforms ) { - } + var merged = {}; - function getNormalIndex( normal ) { + for ( var u = 0; u < uniforms.length; u ++ ) { - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + var tmp = this.clone( uniforms[ u ] ); - if ( normalsHash[ hash ] !== undefined ) { + for ( var p in tmp ) { - return normalsHash[ hash ]; + merged[ p ] = tmp[ p ]; } - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); - - return normalsHash[ hash ]; - } - function getColorIndex( color ) { + return merged; - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + }, - if ( colorsHash[ hash ] !== undefined ) { + clone: function ( uniforms_src ) { - return colorsHash[ hash ]; + var uniforms_dst = {}; - } + for ( var u in uniforms_src ) { - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + uniforms_dst[ u ] = {}; - return colorsHash[ hash ]; + for ( var p in uniforms_src[ u ] ) { - } + var parameter_src = uniforms_src[ u ][ p ]; - function getUvIndex( uv ) { + if ( parameter_src instanceof THREE.Color || + parameter_src instanceof THREE.Vector2 || + parameter_src instanceof THREE.Vector3 || + parameter_src instanceof THREE.Vector4 || + parameter_src instanceof THREE.Matrix4 || + parameter_src instanceof THREE.Texture ) { - var hash = uv.x.toString() + uv.y.toString(); + uniforms_dst[ u ][ p ] = parameter_src.clone(); - if ( uvsHash[ hash ] !== undefined ) { + } else if ( parameter_src instanceof Array ) { - return uvsHash[ hash ]; + uniforms_dst[ u ][ p ] = parameter_src.slice(); - } + } else { - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + uniforms_dst[ u ][ p ] = parameter_src; - return uvsHash[ hash ]; + } + + } } - output.data = {}; + return uniforms_dst; - output.data.vertices = vertices; - output.data.normals = normals; - if ( colors.length > 0 ) output.data.colors = colors; - if ( uvs.length > 0 ) output.data.uvs = [ uvs ]; // temporal backward compatibility - output.data.faces = faces; + } - // +}; - return output; +// File:src/renderers/shaders/UniformsLib.js - }, +/** + * Uniforms library for shared webgl shaders + */ - clone: function () { +THREE.UniformsLib = { - var geometry = new THREE.Geometry(); + common: { - var vertices = this.vertices; + "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, + "opacity" : { type: "f", value: 1.0 }, - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + "map" : { type: "t", value: null }, + "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, - geometry.vertices.push( vertices[ i ].clone() ); + "lightMap" : { type: "t", value: null }, + "specularMap" : { type: "t", value: null }, + "alphaMap" : { type: "t", value: null }, - } + "envMap" : { type: "t", value: null }, + "flipEnvMap" : { type: "f", value: - 1 }, + "reflectivity" : { type: "f", value: 1.0 }, + "refractionRatio" : { type: "f", value: 0.98 }, - var faces = this.faces; + "morphTargetInfluences" : { type: "f", value: 0 } - for ( var i = 0, il = faces.length; i < il; i ++ ) { + }, - geometry.faces.push( faces[ i ].clone() ); + bump: { - } + "bumpMap" : { type: "t", value: null }, + "bumpScale" : { type: "f", value: 1 } - for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) { + }, - var faceVertexUvs = this.faceVertexUvs[ i ]; + normalmap: { - if ( geometry.faceVertexUvs[ i ] === undefined ) { + "normalMap" : { type: "t", value: null }, + "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } + }, - geometry.faceVertexUvs[ i ] = []; + fog : { - } + "fogDensity" : { type: "f", value: 0.00025 }, + "fogNear" : { type: "f", value: 1 }, + "fogFar" : { type: "f", value: 2000 }, + "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + }, - var uvs = faceVertexUvs[ j ], uvsCopy = []; + lights: { - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + "ambientLightColor" : { type: "fv", value: [] }, - var uv = uvs[ k ]; + "directionalLightDirection" : { type: "fv", value: [] }, + "directionalLightColor" : { type: "fv", value: [] }, - uvsCopy.push( uv.clone() ); + "hemisphereLightDirection" : { type: "fv", value: [] }, + "hemisphereLightSkyColor" : { type: "fv", value: [] }, + "hemisphereLightGroundColor" : { type: "fv", value: [] }, - } + "pointLightColor" : { type: "fv", value: [] }, + "pointLightPosition" : { type: "fv", value: [] }, + "pointLightDistance" : { type: "fv1", value: [] }, + "pointLightDecay" : { type: "fv1", value: [] }, - geometry.faceVertexUvs[ i ].push( uvsCopy ); + "spotLightColor" : { type: "fv", value: [] }, + "spotLightPosition" : { type: "fv", value: [] }, + "spotLightDirection" : { type: "fv", value: [] }, + "spotLightDistance" : { type: "fv1", value: [] }, + "spotLightAngleCos" : { type: "fv1", value: [] }, + "spotLightExponent" : { type: "fv1", value: [] }, + "spotLightDecay" : { type: "fv1", value: [] } - } + }, - } + particle: { - return geometry; + "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, + "opacity" : { type: "f", value: 1.0 }, + "size" : { type: "f", value: 1.0 }, + "scale" : { type: "f", value: 1.0 }, + "map" : { type: "t", value: null }, + "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + + "fogDensity" : { type: "f", value: 0.00025 }, + "fogNear" : { type: "f", value: 1 }, + "fogFar" : { type: "f", value: 2000 }, + "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } }, - dispose: function () { + shadowmap: { - this.dispatchEvent( { type: 'dispose' } ); + "shadowMap": { type: "tv", value: [] }, + "shadowMapSize": { type: "v2v", value: [] }, - } + "shadowBias" : { type: "fv1", value: [] }, + "shadowDarkness": { type: "fv1", value: [] }, -}; + "shadowMatrix" : { type: "m4v", value: [] } -THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); + } -THREE.GeometryIdCount = 0; +}; -// File:src/cameras/Camera.js +// File:src/renderers/shaders/ShaderLib.js /** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley -*/ + */ -THREE.Camera = function () { - THREE.Object3D.call( this ); +THREE.ShaderLib = { - this.type = 'Camera'; + 'basic': { - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + uniforms: THREE.UniformsUtils.merge( [ -}; + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "shadowmap" ] -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; + ] ), -THREE.Camera.prototype.getWorldDirection = function () { + vertexShader: [ - var quaternion = new THREE.Quaternion(); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - return function ( optionalTarget ) { + "void main() {", - var result = optionalTarget || new THREE.Vector3(); + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], - this.getWorldQuaternion( quaternion ); + " #ifdef USE_ENVMAP", - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], - } + " #endif", -}(); + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], -THREE.Camera.prototype.lookAt = function () { + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - // This routine does not support cameras with rotated and/or translated parent(s) + "}" - var m1 = new THREE.Matrix4(); + ].join("\n"), - return function ( vector ) { + fragmentShader: [ - m1.lookAt( this.position, vector, this.up ); + "uniform vec3 diffuse;", + "uniform float opacity;", - this.quaternion.setFromRotationMatrix( m1 ); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - }; + "void main() {", -}(); + " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does + " vec4 diffuseColor = vec4( diffuse, opacity );", -THREE.Camera.prototype.clone = function ( camera ) { + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], - if ( camera === undefined ) camera = new THREE.Camera(); + " outgoingLight = diffuseColor.rgb;", // simple shader - THREE.Object3D.prototype.clone.call( this, camera ); + THREE.ShaderChunk[ "lightmap_fragment" ], // TODO: Light map on an otherwise unlit surface doesn't make sense. + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense. - camera.matrixWorldInverse.copy( this.matrixWorldInverse ); - camera.projectionMatrix.copy( this.projectionMatrix ); + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - return camera; -}; + THREE.ShaderChunk[ "fog_fragment" ], -// File:src/cameras/CubeCamera.js + " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + "}" -THREE.CubeCamera = function ( near, far, cubeResolution ) { + ].join("\n") - THREE.Object3D.call( this ); + }, - this.type = 'CubeCamera'; + 'lambert': { - var fov = 90, aspect = 1; + uniforms: THREE.UniformsUtils.merge( [ - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "lights" ], + THREE.UniformsLib[ "shadowmap" ], - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + { + "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, + "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } + } - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + ] ), - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + vertexShader: [ - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + "#define LAMBERT", - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); - this.add( cameraNZ ); + "varying vec3 vLightFront;", - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); + "#ifdef DOUBLE_SIDED", - this.updateCubeMap = function ( renderer, scene ) { + " varying vec3 vLightBack;", - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.generateMipmaps; + "#endif", - renderTarget.generateMipmaps = false; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + "void main() {", - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "lights_lambert_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - renderTarget.generateMipmaps = generateMipmaps; + "}" - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + ].join("\n"), - }; + fragmentShader: [ -}; + "uniform vec3 diffuse;", + "uniform vec3 emissive;", + "uniform float opacity;", -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; + "varying vec3 vLightFront;", -// File:src/cameras/OrthographicCamera.js + "#ifdef DOUBLE_SIDED", -/** - * @author alteredq / http://alteredqualia.com/ - */ + " varying vec3 vLightBack;", -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { + "#endif", - THREE.Camera.call( this ); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - this.type = 'OrthographicCamera'; + "void main() {", - this.zoom = 1; + " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does + " vec4 diffuseColor = vec4( diffuse, opacity );", - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + " #ifdef DOUBLE_SIDED", - this.updateProjectionMatrix(); + //"float isFront = float( gl_FrontFacing );", + //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;", -}; + " if ( gl_FrontFacing )", + " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", + " else", + " outgoingLight += diffuseColor.rgb * vLightBack + emissive;", -THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype ); -THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera; + " #else", -THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () { + " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", - var dx = ( this.right - this.left ) / ( 2 * this.zoom ); - var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - var cx = ( this.right + this.left ) / 2; - var cy = ( this.top + this.bottom ) / 2; + " #endif", - this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far ); + THREE.ShaderChunk[ "lightmap_fragment" ], + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], -}; + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], -THREE.OrthographicCamera.prototype.clone = function () { + THREE.ShaderChunk[ "fog_fragment" ], - var camera = new THREE.OrthographicCamera(); + " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects - THREE.Camera.prototype.clone.call( this, camera ); + "}" - camera.zoom = this.zoom; + ].join("\n") - camera.left = this.left; - camera.right = this.right; - camera.top = this.top; - camera.bottom = this.bottom; + }, - camera.near = this.near; - camera.far = this.far; + 'phong': { - camera.projectionMatrix.copy( this.projectionMatrix ); + uniforms: THREE.UniformsUtils.merge( [ - return camera; -}; + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "bump" ], + THREE.UniformsLib[ "normalmap" ], + THREE.UniformsLib[ "fog" ], + THREE.UniformsLib[ "lights" ], + THREE.UniformsLib[ "shadowmap" ], -// File:src/cameras/PerspectiveCamera.js + { + "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, + "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, + "shininess": { type: "f", value: 30 }, + "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + ] ), -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { + vertexShader: [ - THREE.Camera.call( this ); + "#define PHONG", - this.type = 'PerspectiveCamera'; + "varying vec3 vViewPosition;", - this.zoom = 1; + "#ifndef FLAT_SHADED", - this.fov = fov !== undefined ? fov : 50; - this.aspect = aspect !== undefined ? aspect : 1; - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; + " varying vec3 vNormal;", - this.updateProjectionMatrix(); + "#endif", -}; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "map_pars_vertex" ], + THREE.ShaderChunk[ "lightmap_pars_vertex" ], + THREE.ShaderChunk[ "envmap_pars_vertex" ], + THREE.ShaderChunk[ "lights_phong_pars_vertex" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], -THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype ); -THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera; + "void main() {", + THREE.ShaderChunk[ "map_vertex" ], + THREE.ShaderChunk[ "lightmap_vertex" ], + THREE.ShaderChunk[ "color_vertex" ], -/** - * Uses Focal Length (in mm) to estimate and set FOV - * 35mm (fullframe) camera is used if frame size is not specified; - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - */ + THREE.ShaderChunk[ "morphnormal_vertex" ], + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "skinnormal_vertex" ], + THREE.ShaderChunk[ "defaultnormal_vertex" ], -THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) { + "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED - if ( frameHeight === undefined ) frameHeight = 24; + " vNormal = normalize( transformedNormal );", - this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); - this.updateProjectionMatrix(); + "#endif", -} + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], + " vViewPosition = -mvPosition.xyz;", -/** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "envmap_vertex" ], + THREE.ShaderChunk[ "lights_phong_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], -THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) { + "}" - this.fullWidth = fullWidth; - this.fullHeight = fullHeight; - this.x = x; - this.y = y; - this.width = width; - this.height = height; + ].join("\n"), - this.updateProjectionMatrix(); + fragmentShader: [ -}; + "#define PHONG", + "uniform vec3 diffuse;", + "uniform vec3 emissive;", + "uniform vec3 specular;", + "uniform float shininess;", + "uniform float opacity;", -THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () { + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_pars_fragment" ], + THREE.ShaderChunk[ "alphamap_pars_fragment" ], + THREE.ShaderChunk[ "lightmap_pars_fragment" ], + THREE.ShaderChunk[ "envmap_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "lights_phong_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "bumpmap_pars_fragment" ], + THREE.ShaderChunk[ "normalmap_pars_fragment" ], + THREE.ShaderChunk[ "specularmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) ); + "void main() {", - if ( this.fullWidth ) { + " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does + " vec4 diffuseColor = vec4( diffuse, opacity );", - var aspect = this.fullWidth / this.fullHeight; - var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near; - var bottom = - top; - var left = aspect * bottom; - var right = aspect * top; - var width = Math.abs( right - left ); - var height = Math.abs( top - bottom ); + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "alphamap_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], + THREE.ShaderChunk[ "specularmap_fragment" ], - this.projectionMatrix.makeFrustum( - left + this.x * width / this.fullWidth, - left + ( this.x + this.width ) * width / this.fullWidth, - top - ( this.y + this.height ) * height / this.fullHeight, - top - this.y * height / this.fullHeight, - this.near, - this.far - ); + THREE.ShaderChunk[ "lights_phong_fragment" ], - } else { + THREE.ShaderChunk[ "lightmap_fragment" ], + THREE.ShaderChunk[ "envmap_fragment" ], + THREE.ShaderChunk[ "shadowmap_fragment" ], - this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far ); + THREE.ShaderChunk[ "linear_to_gamma_fragment" ], - } + THREE.ShaderChunk[ "fog_fragment" ], -}; + " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects -THREE.PerspectiveCamera.prototype.clone = function () { + "}" - var camera = new THREE.PerspectiveCamera(); + ].join("\n") - THREE.Camera.prototype.clone.call( this, camera ); + }, - camera.zoom = this.zoom; + 'particle_basic': { - camera.fov = this.fov; - camera.aspect = this.aspect; - camera.near = this.near; - camera.far = this.far; + uniforms: THREE.UniformsUtils.merge( [ - camera.projectionMatrix.copy( this.projectionMatrix ); + THREE.UniformsLib[ "particle" ], + THREE.UniformsLib[ "shadowmap" ] - return camera; + ] ), -}; + vertexShader: [ -// File:src/lights/Light.js + "uniform float size;", + "uniform float scale;", -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "shadowmap_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], -THREE.Light = function ( color ) { + "void main() {", - THREE.Object3D.call( this ); + THREE.ShaderChunk[ "color_vertex" ], - this.type = 'Light'; - - this.color = new THREE.Color( color ); + " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", -}; + " #ifdef USE_SIZEATTENUATION", + " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );", + " #else", + " gl_PointSize = size;", + " #endif", -THREE.Light.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Light.prototype.constructor = THREE.Light; + " gl_Position = projectionMatrix * mvPosition;", -THREE.Light.prototype.clone = function ( light ) { + THREE.ShaderChunk[ "logdepthbuf_vertex" ], + THREE.ShaderChunk[ "worldpos_vertex" ], + THREE.ShaderChunk[ "shadowmap_vertex" ], - if ( light === undefined ) light = new THREE.Light(); + "}" - THREE.Object3D.prototype.clone.call( this, light ); + ].join("\n"), - light.color.copy( this.color ); + fragmentShader: [ - return light; + "uniform vec3 psColor;", + "uniform float opacity;", -}; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "map_particle_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "shadowmap_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], -// File:src/lights/AmbientLight.js + "void main() {", -/** - * @author mrdoob / http://mrdoob.com/ - */ + " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does + " vec4 diffuseColor = vec4( psColor, opacity );", -THREE.AmbientLight = function ( color ) { + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "map_particle_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], + THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.Light.call( this, color ); + " outgoingLight = diffuseColor.rgb;", // simple shader - this.type = 'AmbientLight'; + THREE.ShaderChunk[ "shadowmap_fragment" ], + THREE.ShaderChunk[ "fog_fragment" ], -}; + " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects -THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype ); -THREE.AmbientLight.prototype.constructor = THREE.AmbientLight; + "}" -THREE.AmbientLight.prototype.clone = function () { + ].join("\n") - var light = new THREE.AmbientLight(); + }, - THREE.Light.prototype.clone.call( this, light ); + 'dashed': { - return light; + uniforms: THREE.UniformsUtils.merge( [ -}; + THREE.UniformsLib[ "common" ], + THREE.UniformsLib[ "fog" ], -// File:src/lights/AreaLight.js + { + "scale" : { type: "f", value: 1 }, + "dashSize" : { type: "f", value: 1 }, + "totalSize": { type: "f", value: 2 } + } -/** - * @author MPanknin / http://www.redplant.de/ - * @author alteredq / http://alteredqualia.com/ - */ + ] ), -THREE.AreaLight = function ( color, intensity ) { + vertexShader: [ - THREE.Light.call( this, color ); + "uniform float scale;", + "attribute float lineDistance;", - this.type = 'AreaLight'; + "varying float vLineDistance;", - this.normal = new THREE.Vector3( 0, - 1, 0 ); - this.right = new THREE.Vector3( 1, 0, 0 ); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - this.intensity = ( intensity !== undefined ) ? intensity : 1; + "void main() {", - this.width = 1.0; - this.height = 1.0; + THREE.ShaderChunk[ "color_vertex" ], - this.constantAttenuation = 1.5; - this.linearAttenuation = 0.5; - this.quadraticAttenuation = 0.1; + " vLineDistance = scale * lineDistance;", -}; + " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", + " gl_Position = projectionMatrix * mvPosition;", -THREE.AreaLight.prototype = Object.create( THREE.Light.prototype ); -THREE.AreaLight.prototype.constructor = THREE.AreaLight; + THREE.ShaderChunk[ "logdepthbuf_vertex" ], + "}" -// File:src/lights/DirectionalLight.js + ].join("\n"), -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + fragmentShader: [ -THREE.DirectionalLight = function ( color, intensity ) { + "uniform vec3 diffuse;", + "uniform float opacity;", - THREE.Light.call( this, color ); + "uniform float dashSize;", + "uniform float totalSize;", - this.type = 'DirectionalLight'; + "varying float vLineDistance;", - this.position.set( 0, 1, 0 ); - this.target = new THREE.Object3D(); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "color_pars_fragment" ], + THREE.ShaderChunk[ "fog_pars_fragment" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - this.intensity = ( intensity !== undefined ) ? intensity : 1; + "void main() {", - this.castShadow = false; - this.onlyShadow = false; + " if ( mod( vLineDistance, totalSize ) > dashSize ) {", - // + " discard;", - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; + " }", - this.shadowCameraLeft = - 500; - this.shadowCameraRight = 500; - this.shadowCameraTop = 500; - this.shadowCameraBottom = - 500; + " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does + " vec4 diffuseColor = vec4( diffuse, opacity );", - this.shadowCameraVisible = false; + THREE.ShaderChunk[ "logdepthbuf_fragment" ], + THREE.ShaderChunk[ "color_fragment" ], - this.shadowBias = 0; - this.shadowDarkness = 0.5; + " outgoingLight = diffuseColor.rgb;", // simple shader - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; + THREE.ShaderChunk[ "fog_fragment" ], - // + " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects - this.shadowCascade = false; + "}" - this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 ); - this.shadowCascadeCount = 2; + ].join("\n") - this.shadowCascadeBias = [ 0, 0, 0 ]; - this.shadowCascadeWidth = [ 512, 512, 512 ]; - this.shadowCascadeHeight = [ 512, 512, 512 ]; + }, - this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ]; - this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ]; - - this.shadowCascadeArray = []; - - // - - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; + 'depth': { -}; + uniforms: { -THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype ); -THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight; + "mNear": { type: "f", value: 1.0 }, + "mFar" : { type: "f", value: 2000.0 }, + "opacity" : { type: "f", value: 1.0 } -THREE.DirectionalLight.prototype.clone = function () { + }, - var light = new THREE.DirectionalLight(); + vertexShader: [ - THREE.Light.prototype.clone.call( this, light ); + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - light.target = this.target.clone(); + "void main() {", - light.intensity = this.intensity; + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - light.castShadow = this.castShadow; - light.onlyShadow = this.onlyShadow; + "}" - // + ].join("\n"), - light.shadowCameraNear = this.shadowCameraNear; - light.shadowCameraFar = this.shadowCameraFar; + fragmentShader: [ - light.shadowCameraLeft = this.shadowCameraLeft; - light.shadowCameraRight = this.shadowCameraRight; - light.shadowCameraTop = this.shadowCameraTop; - light.shadowCameraBottom = this.shadowCameraBottom; + "uniform float mNear;", + "uniform float mFar;", + "uniform float opacity;", - light.shadowCameraVisible = this.shadowCameraVisible; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - light.shadowBias = this.shadowBias; - light.shadowDarkness = this.shadowDarkness; + "void main() {", - light.shadowMapWidth = this.shadowMapWidth; - light.shadowMapHeight = this.shadowMapHeight; + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - // + " #ifdef USE_LOGDEPTHBUF_EXT", - light.shadowCascade = this.shadowCascade; + " float depth = gl_FragDepthEXT / gl_FragCoord.w;", - light.shadowCascadeOffset.copy( this.shadowCascadeOffset ); - light.shadowCascadeCount = this.shadowCascadeCount; + " #else", - light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 ); - light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 ); - light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 ); + " float depth = gl_FragCoord.z / gl_FragCoord.w;", - light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 ); - light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 ); + " #endif", - return light; + " float color = 1.0 - smoothstep( mNear, mFar, depth );", + " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects -}; + "}" -// File:src/lights/HemisphereLight.js + ].join("\n") -/** - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { + 'normal': { - THREE.Light.call( this, skyColor ); + uniforms: { - this.type = 'HemisphereLight'; + "opacity" : { type: "f", value: 1.0 } - this.position.set( 0, 100, 0 ); + }, - this.groundColor = new THREE.Color( groundColor ); - this.intensity = ( intensity !== undefined ) ? intensity : 1; + vertexShader: [ -}; + "varying vec3 vNormal;", -THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype ); -THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], -THREE.HemisphereLight.prototype.clone = function () { + "void main() {", - var light = new THREE.HemisphereLight(); + " vNormal = normalize( normalMatrix * normal );", - THREE.Light.prototype.clone.call( this, light ); + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - light.groundColor.copy( this.groundColor ); - light.intensity = this.intensity; + "}" - return light; + ].join("\n"), -}; + fragmentShader: [ -// File:src/lights/PointLight.js + "uniform float opacity;", + "varying vec3 vNormal;", -/** - * @author mrdoob / http://mrdoob.com/ - */ + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], -THREE.PointLight = function ( color, intensity, distance, decay ) { + "void main() {", - THREE.Light.call( this, color ); + " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", - this.type = 'PointLight'; + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + "}" -}; + ].join("\n") -THREE.PointLight.prototype = Object.create( THREE.Light.prototype ); -THREE.PointLight.prototype.constructor = THREE.PointLight; + }, -THREE.PointLight.prototype.clone = function () { + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - var light = new THREE.PointLight(); + 'cube': { - THREE.Light.prototype.clone.call( this, light ); + uniforms: { "tCube": { type: "t", value: null }, + "tFlip": { type: "f", value: - 1 } }, - light.intensity = this.intensity; - light.distance = this.distance; - light.decay = this.decay; + vertexShader: [ - return light; + "varying vec3 vWorldPosition;", -}; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], -// File:src/lights/SpotLight.js + "void main() {", -/** - * @author alteredq / http://alteredqualia.com/ - */ + " vWorldPosition = transformDirection( position, modelMatrix );", -THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) { + " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - THREE.Light.call( this, color ); + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - this.type = 'SpotLight'; + "}" - this.position.set( 0, 1, 0 ); - this.target = new THREE.Object3D(); + ].join("\n"), - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.exponent = ( exponent !== undefined ) ? exponent : 10; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + fragmentShader: [ - this.castShadow = false; - this.onlyShadow = false; + "uniform samplerCube tCube;", + "uniform float tFlip;", - // + "varying vec3 vWorldPosition;", - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; - this.shadowCameraFov = 50; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], - this.shadowCameraVisible = false; + "void main() {", - this.shadowBias = 0; - this.shadowDarkness = 0.5; + " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - // + "}" - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; + ].join("\n") -}; + }, -THREE.SpotLight.prototype = Object.create( THREE.Light.prototype ); -THREE.SpotLight.prototype.constructor = THREE.SpotLight; + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ -THREE.SpotLight.prototype.clone = function () { + 'equirect': { - var light = new THREE.SpotLight(); + uniforms: { "tEquirect": { type: "t", value: null }, + "tFlip": { type: "f", value: - 1 } }, - THREE.Light.prototype.clone.call( this, light ); + vertexShader: [ - light.target = this.target.clone(); + "varying vec3 vWorldPosition;", - light.intensity = this.intensity; - light.distance = this.distance; - light.angle = this.angle; - light.exponent = this.exponent; - light.decay = this.decay; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - light.castShadow = this.castShadow; - light.onlyShadow = this.onlyShadow; + "void main() {", - // + " vWorldPosition = transformDirection( position, modelMatrix );", - light.shadowCameraNear = this.shadowCameraNear; - light.shadowCameraFar = this.shadowCameraFar; - light.shadowCameraFov = this.shadowCameraFov; + " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - light.shadowCameraVisible = this.shadowCameraVisible; + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - light.shadowBias = this.shadowBias; - light.shadowDarkness = this.shadowDarkness; + "}" - light.shadowMapWidth = this.shadowMapWidth; - light.shadowMapHeight = this.shadowMapHeight; + ].join("\n"), - return light; + fragmentShader: [ -}; + "uniform sampler2D tEquirect;", + "uniform float tFlip;", -// File:src/loaders/Cache.js + "varying vec3 vWorldPosition;", -/** - * @author mrdoob / http://mrdoob.com/ - */ + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], -THREE.Cache = { + "void main() {", - files: {}, + // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", + "vec3 direction = normalize( vWorldPosition );", + "vec2 sampleUV;", + "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );", + "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", + "gl_FragColor = texture2D( tEquirect, sampleUV );", - add: function ( key, file ) { + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - // console.log( 'THREE.Cache', 'Adding key:', key ); + "}" - this.files[ key ] = file; + ].join("\n") }, - get: function ( key ) { + /* Depth encoding into RGBA texture + * + * based on SpiderGL shadow map example + * http://spidergl.org/example.php?id=6 + * + * originally from + * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD + * + * see also + * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ + */ - // console.log( 'THREE.Cache', 'Checking key:', key ); + 'depthRGBA': { - return this.files[ key ]; + uniforms: {}, - }, + vertexShader: [ - remove: function ( key ) { + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "morphtarget_pars_vertex" ], + THREE.ShaderChunk[ "skinning_pars_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - delete this.files[ key ]; + "void main() {", - }, + THREE.ShaderChunk[ "skinbase_vertex" ], + THREE.ShaderChunk[ "morphtarget_vertex" ], + THREE.ShaderChunk[ "skinning_vertex" ], + THREE.ShaderChunk[ "default_vertex" ], + THREE.ShaderChunk[ "logdepthbuf_vertex" ], - clear: function () { + "}" - this.files = {} + ].join("\n"), - } + fragmentShader: [ -}; + THREE.ShaderChunk[ "common" ], + THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], -// File:src/loaders/Loader.js + "vec4 pack_depth( const in float depth ) {", -/** - * @author alteredq / http://alteredqualia.com/ - */ + " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", + " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", + " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );", + " res -= res.xxyz * bit_mask;", + " return res;", -THREE.Loader = function ( showStatus ) { + "}", - this.showStatus = showStatus; - this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null; + "void main() {", - this.imageLoader = new THREE.ImageLoader(); + THREE.ShaderChunk[ "logdepthbuf_fragment" ], - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; - this.extractUrlBase = function ( url ) { return ""; } + " #ifdef USE_LOGDEPTHBUF_EXT", -}; + " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );", -THREE.Loader.prototype = { + " #else", - constructor: THREE.Loader, + " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", - crossOrigin: undefined, + " #endif", - addStatusElement: function () { + //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", + //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", + //"gl_FragData[ 0 ] = pack_depth( z );", + //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", - var e = document.createElement( 'div' ); + "}" - e.style.position = 'absolute'; - e.style.right = '0px'; - e.style.top = '0px'; - e.style.fontSize = '0.8em'; - e.style.textAlign = 'left'; - e.style.background = 'rgba(0,0,0,0.25)'; - e.style.color = '#fff'; - e.style.width = '120px'; - e.style.padding = '0.5em 0.5em 0.5em 0.5em'; - e.style.zIndex = 1000; + ].join("\n") - e.innerHTML = 'Loading ...'; + } - return e; +}; - }, +// File:src/renderers/WebGLRenderTarget.js - updateProgress: function ( progress ) { +/** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + */ - var message = 'Loaded '; +THREE.WebGLRenderTarget = function ( width, height, options ) { - if ( progress.total ) { + this.width = width; + this.height = height; - message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%'; + options = options || {}; + this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping; + this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping; - } else { + this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter; + this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter; - message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB'; + this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1; - } + this.offset = new THREE.Vector2( 0, 0 ); + this.repeat = new THREE.Vector2( 1, 1 ); - this.statusDomElement.innerHTML = message; + this.format = options.format !== undefined ? options.format : THREE.RGBAFormat; + this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType; - }, + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - extractUrlBase: function ( url ) { + this.generateMipmaps = true; - var parts = url.split( '/' ); + this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null; - if ( parts.length === 1 ) return './'; +}; - parts.pop(); +THREE.WebGLRenderTarget.prototype = { - return parts.join( '/' ) + '/'; + constructor: THREE.WebGLRenderTarget, - }, + setSize: function ( width, height ) { - initMaterials: function ( materials, texturePath ) { + this.width = width; + this.height = height; - var array = []; + }, - for ( var i = 0; i < materials.length; ++ i ) { + clone: function () { - array[ i ] = this.createMaterial( materials[ i ], texturePath ); + var tmp = new THREE.WebGLRenderTarget( this.width, this.height ); - } + tmp.wrapS = this.wrapS; + tmp.wrapT = this.wrapT; - return array; + tmp.magFilter = this.magFilter; + tmp.minFilter = this.minFilter; - }, + tmp.anisotropy = this.anisotropy; - needsTangents: function ( materials ) { + tmp.offset.copy( this.offset ); + tmp.repeat.copy( this.repeat ); - for ( var i = 0, il = materials.length; i < il; i ++ ) { + tmp.format = this.format; + tmp.type = this.type; - var m = materials[ i ]; + tmp.depthBuffer = this.depthBuffer; + tmp.stencilBuffer = this.stencilBuffer; - if ( m instanceof THREE.ShaderMaterial ) return true; + tmp.generateMipmaps = this.generateMipmaps; - } + tmp.shareDepthFrom = this.shareDepthFrom; - return false; + return tmp; }, - createMaterial: function ( m, texturePath ) { + dispose: function () { - var scope = this; + this.dispatchEvent( { type: 'dispose' } ); - function nearest_pow2( n ) { + } - var l = Math.log( n ) / Math.LN2; - return Math.pow( 2, Math.round( l ) ); +}; - } +THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype ); - function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { +// File:src/renderers/WebGLRenderTargetCube.js - var fullPath = texturePath + sourceFile; +/** + * @author alteredq / http://alteredqualia.com + */ - var texture; +THREE.WebGLRenderTargetCube = function ( width, height, options ) { - var loader = THREE.Loader.Handlers.get( fullPath ); + THREE.WebGLRenderTarget.call( this, width, height, options ); - if ( loader !== null ) { + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - texture = loader.load( fullPath ); +}; - } else { +THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); +THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; - texture = new THREE.Texture(); +// File:src/renderers/webgl/WebGLExtensions.js - loader = scope.imageLoader; - loader.crossOrigin = scope.crossOrigin; - loader.load( fullPath, function ( image ) { +/** +* @author mrdoob / http://mrdoob.com/ +*/ - if ( THREE.Math.isPowerOfTwo( image.width ) === false || - THREE.Math.isPowerOfTwo( image.height ) === false ) { +THREE.WebGLExtensions = function ( gl ) { - var width = nearest_pow2( image.width ); - var height = nearest_pow2( image.height ); + var extensions = {}; - texture.image = image.resize( width, height ); + this.get = function ( name ) { - } else { + if ( extensions[ name ] !== undefined ) { - texture.image = image; + return extensions[ name ]; - } + } - texture.needsUpdate = true; + var extension; - } ); + switch ( name ) { - } + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; - texture.sourceFile = sourceFile; + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; - if ( repeat ) { + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - texture.repeat.set( repeat[ 0 ], repeat[ 1 ] ); + default: + extension = gl.getExtension( name ); - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + } - } + if ( extension === null ) { - if ( offset ) { + THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - texture.offset.set( offset[ 0 ], offset[ 1 ] ); + } - } + extensions[ name ] = extension; - if ( wrap ) { + return extension; - var wrapMap = { - 'repeat': THREE.RepeatWrapping, - 'mirror': THREE.MirroredRepeatWrapping - } + }; - if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ]; - if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ]; +}; - } +// File:src/renderers/webgl/WebGLProgram.js - if ( anisotropy ) { +THREE.WebGLProgram = ( function () { - texture.anisotropy = anisotropy; + var programIdCount = 0; - } + var generateDefines = function ( defines ) { - where[ name ] = texture; + var value, chunk, chunks = []; - } + for ( var d in defines ) { - function rgb2hex( rgb ) { + value = defines[ d ]; + if ( value === false ) continue; - return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; + chunk = '#define ' + d + ' ' + value; + chunks.push( chunk ); } - // defaults + return chunks.join( '\n' ); - var mtype = 'MeshLambertMaterial'; - var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false }; + }; - // parameters from model file + var cacheUniformLocations = function ( gl, program, identifiers ) { - if ( m.shading ) { + var uniforms = {}; - var shading = m.shading.toLowerCase(); + for ( var i = 0, l = identifiers.length; i < l; i ++ ) { - if ( shading === 'phong' ) mtype = 'MeshPhongMaterial'; - else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial'; + var id = identifiers[ i ]; + uniforms[ id ] = gl.getUniformLocation( program, id ); } - if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { + return uniforms; - mpars.blending = THREE[ m.blending ]; + }; - } + var cacheAttributeLocations = function ( gl, program, identifiers ) { - if ( m.transparent !== undefined ) { + var attributes = {}; - mpars.transparent = m.transparent; + for ( var i = 0, l = identifiers.length; i < l; i ++ ) { - } + var id = identifiers[ i ]; + attributes[ id ] = gl.getAttribLocation( program, id ); - if ( m.opacity !== undefined && m.opacity < 1.0 ) { + } - mpars.transparent = true; + return attributes; - } + }; - if ( m.depthTest !== undefined ) { + return function ( renderer, code, material, parameters ) { - mpars.depthTest = m.depthTest; + var _this = renderer; + var _gl = _this.context; - } + var defines = material.defines; + var uniforms = material.__webglShader.uniforms; + var attributes = material.attributes; - if ( m.depthWrite !== undefined ) { + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - mpars.depthWrite = m.depthWrite; + var index0AttributeName = material.index0AttributeName; - } + if ( index0AttributeName === undefined && parameters.morphTargets === true ) { - if ( m.visible !== undefined ) { + // programs with morphTargets displace position out of attribute 0 - mpars.visible = m.visible; + index0AttributeName = 'position'; } - if ( m.flipSided !== undefined ) { + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - mpars.side = THREE.BackSide; + if ( parameters.shadowMapType === THREE.PCFShadowMap ) { - } + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - if ( m.doubleSided !== undefined ) { + } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { - mpars.side = THREE.DoubleSide; + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; } - if ( m.wireframe !== undefined ) { + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - mpars.wireframe = m.wireframe; + if ( parameters.envMap ) { - } + switch ( material.envMap.mapping ) { - if ( m.vertexColors !== undefined ) { + case THREE.CubeReflectionMapping: + case THREE.CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - if ( m.vertexColors === 'face' ) { + case THREE.EquirectangularReflectionMapping: + case THREE.EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - mpars.vertexColors = THREE.FaceColors; + case THREE.SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - } else if ( m.vertexColors ) { + } - mpars.vertexColors = THREE.VertexColors; + switch ( material.envMap.mapping ) { - } + case THREE.CubeRefractionMapping: + case THREE.EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - } + } - // colors + switch ( material.combine ) { - if ( m.colorDiffuse ) { + case THREE.MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - mpars.color = rgb2hex( m.colorDiffuse ); + case THREE.MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - } else if ( m.DbgColor ) { + case THREE.AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - mpars.color = m.DbgColor; + } } - if ( m.colorSpecular ) { + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - mpars.specular = rgb2hex( m.colorSpecular ); + // console.log( 'building new program ' ); - } + // - if ( m.colorEmissive ) { + var customDefines = generateDefines( defines ); - mpars.emissive = rgb2hex( m.colorEmissive ); + // - } + var program = _gl.createProgram(); - // modifiers + var prefix_vertex, prefix_fragment; - if ( m.transparency !== undefined ) { + if ( material instanceof THREE.RawShaderMaterial ) { - console.warn( 'THREE.Loader: transparency has been renamed to opacity' ); - m.opacity = m.transparency; + prefix_vertex = ''; + prefix_fragment = ''; - } + } else { - if ( m.opacity !== undefined ) { + prefix_vertex = [ - mpars.opacity = m.opacity; + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - } + customDefines, - if ( m.specularCoef ) { + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - mpars.shininess = m.specularCoef; + _this.gammaInput ? '#define GAMMA_INPUT' : '', + _this.gammaOutput ? '#define GAMMA_OUTPUT' : '', + '#define GAMMA_FACTOR ' + gammaFactorDefine, - } + '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights, + '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights, + '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights, + '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights, - // textures + '#define MAX_SHADOWS ' + parameters.maxShadows, - if ( m.mapDiffuse && texturePath ) { + '#define MAX_BONES ' + parameters.maxBones, - create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - } + parameters.flatShading ? '#define FLAT_SHADED': '', - if ( m.mapLight && texturePath ) { + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals ? '#define USE_MORPHNORMALS' : '', + parameters.wrapAround ? '#define WRAP_AROUND' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - } + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '', + parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '', - if ( m.mapBump && texturePath ) { + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', - } - if ( m.mapNormal && texturePath ) { + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', - create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + 'attribute vec2 uv2;', - } + '#ifdef USE_COLOR', - if ( m.mapSpecular && texturePath ) { + ' attribute vec3 color;', - create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + '#endif', - } + '#ifdef USE_MORPHTARGETS', - if ( m.mapAlpha && texturePath ) { + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + ' #ifdef USE_MORPHNORMALS', - } + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - // + ' #else', - if ( m.mapBumpScale ) { + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - mpars.bumpScale = m.mapBumpScale; + ' #endif', - } + '#endif', - if ( m.mapNormalFactor ) { + '#ifdef USE_SKINNING', - mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor ); + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - } + '#endif', - var material = new THREE[ mtype ]( mpars ); + '' - if ( m.DbgName !== undefined ) material.name = m.DbgName; + ].join( '\n' ); - return material; + prefix_fragment = [ - } + ( parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', -}; + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', -THREE.Loader.Handlers = { + customDefines, - handlers: [], + '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights, + '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights, + '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights, + '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights, - add: function ( regex, loader ) { + '#define MAX_SHADOWS ' + parameters.maxShadows, - this.handlers.push( regex, loader ); + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - }, + _this.gammaInput ? '#define GAMMA_INPUT' : '', + _this.gammaOutput ? '#define GAMMA_OUTPUT' : '', + '#define GAMMA_FACTOR ' + gammaFactorDefine, - get: function ( file ) { + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) { + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - var regex = this.handlers[ i ]; - var loader = this.handlers[ i + 1 ]; + parameters.flatShading ? '#define FLAT_SHADED': '', - if ( regex.test( file ) ) { + parameters.metal ? '#define METAL' : '', + parameters.wrapAround ? '#define WRAP_AROUND' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - return loader; + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '', + parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '', - } + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', - } + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + '' - return null; + ].join( '\n' ); - } + } -}; + var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader ); + var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader ); -// File:src/loaders/XHRLoader.js + _gl.attachShader( program, glVertexShader ); + _gl.attachShader( program, glFragmentShader ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( index0AttributeName !== undefined ) { -THREE.XHRLoader = function ( manager ) { + // Force a particular attribute to index 0. + // because potentially expensive emulation is done by browser if attribute 0 is disabled. + // And, color, for example is often automatically bound to index 0 so disabling it - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + _gl.bindAttribLocation( program, 0, index0AttributeName ); -}; + } -THREE.XHRLoader.prototype = { + _gl.linkProgram( program ); - constructor: THREE.XHRLoader, + var programLogInfo = _gl.getProgramInfoLog( program ); - load: function ( url, onLoad, onProgress, onError ) { + if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { - var scope = this; + THREE.error( 'THREE.WebGLProgram: shader error: ' + _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getPRogramInfoLog', programLogInfo ); - var cached = THREE.Cache.get( url ); + } - if ( cached !== undefined ) { + if ( programLogInfo !== '' ) { - if ( onLoad ) onLoad( cached ); - return; + THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()' + programLogInfo ); + // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); } - var request = new XMLHttpRequest(); - request.onreadystatechange = function() { - if (request.readyState === XMLHttpRequest.DONE) { -// TODO: Re-visit https://bugreports.qt.io/browse/QTBUG-45581 is solved in Qt - if (request.status == 200 || request.status == 0) { - var response; -// TODO: Remove once https://bugreports.qt.io/browse/QTBUG-45862 is fixed in Qt - if ( scope.responseType == 'arraybuffer' ) - response = request.response; - else - response = request.responseText; - - THREE.Cache.add( url, response ); - if ( onLoad ) onLoad( response ); - scope.manager.itemEnd( url ); - } else { - if ( onError !== undefined ) { - onError(); - } - } - } else if (request.readyState === XMLHttpRequest.HEADERS_RECEIVED) { - if ( onProgress !== undefined ) { - onProgress(); - } - } - }; + // clean up - request.open( 'GET', url, true ); + _gl.deleteShader( glVertexShader ); + _gl.deleteShader( glFragmentShader ); - if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; - if ( this.responseType !== undefined ) request.responseType = this.responseType; + // cache uniform locations - request.send( null ); + var identifiers = [ - scope.manager.itemStart( url ); + 'viewMatrix', + 'modelViewMatrix', + 'projectionMatrix', + 'normalMatrix', + 'modelMatrix', + 'cameraPosition', + 'morphTargetInfluences', + 'bindMatrix', + 'bindMatrixInverse' - }, + ]; - setResponseType: function ( value ) { + if ( parameters.useVertexTexture ) { - this.responseType = value; + identifiers.push( 'boneTexture' ); + identifiers.push( 'boneTextureWidth' ); + identifiers.push( 'boneTextureHeight' ); - }, + } else { - setCrossOrigin: function ( value ) { + identifiers.push( 'boneGlobalMatrices' ); - this.crossOrigin = value; + } - } + if ( parameters.logarithmicDepthBuffer ) { -}; + identifiers.push('logDepthBufFC'); -// File:src/loaders/ImageLoader.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ -THREE.ImageLoader = function ( manager ) { + for ( var u in uniforms ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + identifiers.push( u ); -}; + } -THREE.ImageLoader.prototype = { + this.uniforms = cacheUniformLocations( _gl, program, identifiers ); - constructor: THREE.ImageLoader, + // cache attributes locations - load: function ( url, onLoad, onProgress, onError ) { + identifiers = [ - var scope = this; + 'position', + 'normal', + 'uv', + 'uv2', + 'tangent', + 'color', + 'skinIndex', + 'skinWeight', + 'lineDistance' - var cached = THREE.Cache.get( url ); + ]; - if ( cached !== undefined ) { + for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) { - onLoad( cached ); - return; + identifiers.push( 'morphTarget' + i ); } - var image = document.createElement( 'img' ); + for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) { - image.addEventListener( 'load', function ( event ) { + identifiers.push( 'morphNormal' + i ); - THREE.Cache.add( url, image ); + } - if ( onLoad ) onLoad( image ); - - scope.manager.itemEnd( url ); + for ( var a in attributes ) { - }, false ); + identifiers.push( a ); - if ( onProgress !== undefined ) { + } - image.addEventListener( 'progress', function ( event ) { + this.attributes = cacheAttributeLocations( _gl, program, identifiers ); + this.attributesKeys = Object.keys( this.attributes ); - onProgress( event ); + // - }, false ); + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - } + return this; - if ( onError !== undefined ) { + }; - image.addEventListener( 'error', function ( event ) { +} )(); - onError( event ); +// File:src/renderers/webgl/WebGLShader.js - }, false ); +THREE.WebGLShader = ( function () { - } + var addLineNumbers = function ( string ) { - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + var lines = string.split( '\n' ); - image.src = url; + for ( var i = 0; i < lines.length; i ++ ) { - scope.manager.itemStart( url ); + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - return image; - - }, + } - setCrossOrigin: function ( value ) { + return lines.join( '\n' ); - this.crossOrigin = value; + }; - } + return function ( gl, type, string ) { -} + var shader = gl.createShader( type ); -// File:src/loaders/JSONLoader.js + gl.shaderSource( shader, string ); + gl.compileShader( shader ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { -THREE.JSONLoader = function ( showStatus ) { + THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - THREE.Loader.call( this, showStatus ); + } - this.withCredentials = false; + if ( gl.getShaderInfoLog( shader ) !== '' ) { -}; + THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); -THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype ); -THREE.JSONLoader.prototype.constructor = THREE.JSONLoader; + } -THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) { + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - // todo: unify load API to for easier SceneLoader use + return shader; - texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url ); + }; - this.onLoadStart(); - this.loadAjaxJSON( this, url, callback, texturePath ); +} )(); -}; +// File:src/renderers/webgl/WebGLState.js -THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) { +/** +* @author mrdoob / http://mrdoob.com/ +*/ - var xhr = new XMLHttpRequest(); +THREE.WebGLState = function ( gl, paramThreeToGL ) { - var length = 0; + var newAttributes = new Uint8Array( 16 ); + var enabledAttributes = new Uint8Array( 16 ); - xhr.onreadystatechange = function () { + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; - if ( xhr.readyState === xhr.DONE ) { + var currentDepthTest = null; + var currentDepthWrite = null; - if ( xhr.status === 200 || xhr.status === 0 ) { + var currentColorWrite = null; - if ( xhr.responseText ) { + var currentDoubleSided = null; + var currentFlipSided = null; - var json = JSON.parse( xhr.responseText ); - var metadata = json.metadata; + var currentLineWidth = null; - if ( metadata !== undefined ) { + var currentPolygonOffset = null; + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - if ( metadata.type === 'object' ) { + this.initAttributes = function () { - THREE.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { - } + newAttributes[ i ] = 0; - if ( metadata.type === 'scene' ) { + } - THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' ); - return; + }; - } + this.enableAttribute = function ( attribute ) { - } + newAttributes[ attribute ] = 1; - var result = context.parse( json, texturePath ); - callback( result.geometry, result.materials ); + if ( enabledAttributes[ attribute ] === 0 ) { - } else { + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' ); + } - } + }; - // in context of more complex asset initialization - // do not block on single failed file - // maybe should go even one more level up + this.disableUnusedAttributes = function () { - context.onLoadComplete(); + for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) { - } else { + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - THREE.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' ); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; } - } else if ( xhr.readyState === xhr.LOADING ) { + } - if ( callbackProgress ) { + }; - if ( length === 0 ) { + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) { - length = xhr.getResponseHeader( 'Content-Length' ); + if ( blending !== currentBlending ) { - } + if ( blending === THREE.NoBlending ) { - callbackProgress( { total: length, loaded: xhr.responseText.length } ); + gl.disable( gl.BLEND ); - } + } else if ( blending === THREE.AdditiveBlending ) { - } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { + gl.enable( gl.BLEND ); + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - if ( callbackProgress !== undefined ) { + } else if ( blending === THREE.SubtractiveBlending ) { - length = xhr.getResponseHeader( 'Content-Length' ); + // TODO: Find blendFuncSeparate() combination + gl.enable( gl.BLEND ); + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - } + } else if ( blending === THREE.MultiplyBlending ) { - } + // TODO: Find blendFuncSeparate() combination + gl.enable( gl.BLEND ); + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - }; + } else if ( blending === THREE.CustomBlending ) { - xhr.open( 'GET', url, true ); - xhr.withCredentials = this.withCredentials; - xhr.send( null ); + gl.enable( gl.BLEND ); -}; + } else { -THREE.JSONLoader.prototype.parse = function ( json, texturePath ) { + gl.enable( gl.BLEND ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - var geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + } - parseModel( scale ); + currentBlending = blending; - parseSkin(); - parseMorphing( scale ); + } - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + if ( blending === THREE.CustomBlending ) { - function parseModel( scale ) { + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - function isBitSet( value, position ) { + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - return value & ( 1 << position ); + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); - } + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - var i, j, fi, + } - offset, zLength, + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - colorIndex, normalIndex, uvIndex, materialIndex, + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - vertex, face, faceA, faceB, hex, normal, + } - uvLayer, uv, u, v, + } else { - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - nUvLayers = 0; + } - if ( json.uvs !== undefined ) { + }; - // disregard empty arrays + this.setDepthTest = function ( depthTest ) { - for ( i = 0; i < json.uvs.length; i ++ ) { + if ( currentDepthTest !== depthTest ) { - if ( json.uvs[ i ].length ) nUvLayers ++; + if ( depthTest ) { - } + gl.enable( gl.DEPTH_TEST ); - for ( i = 0; i < nUvLayers; i ++ ) { + } else { - geometry.faceVertexUvs[ i ] = []; + gl.disable( gl.DEPTH_TEST ); } - } + currentDepthTest = depthTest; - offset = 0; - zLength = vertices.length; + } - while ( offset < zLength ) { + }; - vertex = new THREE.Vector3(); + this.setDepthWrite = function ( depthWrite ) { - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + if ( currentDepthWrite !== depthWrite ) { - geometry.vertices.push( vertex ); + gl.depthMask( depthWrite ); + currentDepthWrite = depthWrite; } - offset = 0; - zLength = faces.length; + }; - while ( offset < zLength ) { + this.setColorWrite = function ( colorWrite ) { - type = faces[ offset ++ ]; + if ( currentColorWrite !== colorWrite ) { + gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite ); + currentColorWrite = colorWrite; - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); + } - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + }; - if ( isQuad ) { + this.setDoubleSided = function ( doubleSided ) { - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + if ( currentDoubleSided !== doubleSided ) { - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + if ( doubleSided ) { - offset += 4; + gl.disable( gl.CULL_FACE ); - if ( hasMaterial ) { + } else { - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + gl.enable( gl.CULL_FACE ); - } + } - // to get face <=> uv index correspondence + currentDoubleSided = doubleSided; - fi = geometry.faces.length; + } - if ( hasFaceVertexUv ) { + }; - for ( i = 0; i < nUvLayers; i ++ ) { + this.setFlipSided = function ( flipSided ) { - uvLayer = json.uvs[ i ]; + if ( currentFlipSided !== flipSided ) { - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = [] + if ( flipSided ) { - for ( j = 0; j < 4; j ++ ) { + gl.frontFace( gl.CW ); - uvIndex = faces[ offset ++ ]; + } else { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + gl.frontFace( gl.CCW ); - uv = new THREE.Vector2( u, v ); + } - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + currentFlipSided = flipSided; - } + } - } + }; - } + this.setLineWidth = function ( width ) { - if ( hasFaceNormal ) { + if ( width !== currentLineWidth ) { - normalIndex = faces[ offset ++ ] * 3; + gl.lineWidth( width ); - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + currentLineWidth = width; - faceB.normal.copy( faceA.normal ); + } - } + }; - if ( hasFaceVertexNormal ) { + this.setPolygonOffset = function ( polygonoffset, factor, units ) { - for ( i = 0; i < 4; i ++ ) { + if ( currentPolygonOffset !== polygonoffset ) { - normalIndex = faces[ offset ++ ] * 3; + if ( polygonoffset ) { - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + gl.enable( gl.POLYGON_OFFSET_FILL ); + } else { - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + gl.disable( gl.POLYGON_OFFSET_FILL ); - } + } - } + currentPolygonOffset = polygonoffset; + } - if ( hasFaceColor ) { + if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) { - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + gl.polygonOffset( factor, units ); - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - } + } + }; - if ( hasFaceVertexColor ) { + this.reset = function () { - for ( i = 0; i < 4; i ++ ) { + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + enabledAttributes[ i ] = 0; - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + } - } + currentBlending = null; + currentDepthTest = null; + currentDepthWrite = null; + currentColorWrite = null; + currentDoubleSided = null; + currentFlipSided = null; - } + }; - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); +}; - } else { +// File:src/renderers/webgl/plugins/LensFlarePlugin.js - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( hasMaterial ) { +THREE.LensFlarePlugin = function ( renderer, flares ) { - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + var gl = renderer.context; - } + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; + var hasVertexTexture; - // to get face <=> uv index correspondence + var tempTexture, occlusionTexture; - fi = geometry.faces.length; + var init = function () { - if ( hasFaceVertexUv ) { + var vertices = new Float32Array( [ + -1, -1, 0, 0, + 1, -1, 1, 0, + 1, 1, 1, 1, + -1, 1, 0, 1 + ] ); - for ( i = 0; i < nUvLayers; i ++ ) { + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - uvLayer = json.uvs[ i ]; + // buffers - geometry.faceVertexUvs[ i ][ fi ] = []; + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - for ( j = 0; j < 3; j ++ ) { + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - uvIndex = faces[ offset ++ ]; + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + // textures - uv = new THREE.Vector2( u, v ); + tempTexture = gl.createTexture(); + occlusionTexture = gl.createTexture(); - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + gl.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - } + gl.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - } + hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0; - } + var shader; - if ( hasFaceNormal ) { + if ( hasVertexTexture ) { - normalIndex = faces[ offset ++ ] * 3; + shader = { - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + vertexShader: [ - } + "uniform lowp int renderType;", - if ( hasFaceVertexNormal ) { + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - for ( i = 0; i < 3; i ++ ) { + "uniform sampler2D occlusionMap;", - normalIndex = faces[ offset ++ ] * 3; + "attribute vec2 position;", + "attribute vec2 uv;", - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + "varying vec2 vUV;", + "varying float vVisibility;", - face.vertexNormals.push( normal ); + "void main() {", - } + "vUV = uv;", - } + "vec2 pos = position;", + "if( renderType == 2 ) {", - if ( hasFaceColor ) { + "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - } + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + "}", - if ( hasFaceVertexColor ) { + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - for ( i = 0; i < 3; i ++ ) { + "}" - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); - - } - - } + ].join( "\n" ), - geometry.faces.push( face ); + fragmentShader: [ - } + "uniform lowp int renderType;", - } + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - }; + "varying vec2 vUV;", + "varying float vVisibility;", - function parseSkin() { - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + "void main() {", - if ( json.skinWeights ) { + // pink square - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + "if( renderType == 0 ) {", - var x = json.skinWeights[ i ]; - var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; - var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; - var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); + // restore - } + "} else if( renderType == 1 ) {", - } + "gl_FragColor = texture2D( map, vUV );", - if ( json.skinIndices ) { + // flare - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + "} else {", - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); + "}", - } + "}" - } + ].join( "\n" ) - geometry.bones = json.bones; + }; - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + } else { - THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + shader = { - } + vertexShader: [ + "uniform lowp int renderType;", - // could change this to json.animations[0] or remove completely + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - geometry.animation = json.animation; - geometry.animations = json.animations; + "attribute vec2 position;", + "attribute vec2 uv;", - }; + "varying vec2 vUV;", - function parseMorphing( scale ) { + "void main() {", - if ( json.morphTargets !== undefined ) { + "vUV = uv;", - var i, l, v, vl, dstVertices, srcVertices; + "vec2 pos = position;", - for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { + "if( renderType == 2 ) {", - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - dstVertices = geometry.morphTargets[ i ].vertices; - srcVertices = json.morphTargets [ i ].vertices; + "}", - for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + "}" - dstVertices.push( vertex ); + ].join( "\n" ), - } + fragmentShader: [ - } + "precision mediump float;", - } + "uniform lowp int renderType;", - if ( json.morphColors !== undefined ) { + "uniform sampler2D map;", + "uniform sampler2D occlusionMap;", + "uniform float opacity;", + "uniform vec3 color;", - var i, l, c, cl, dstColors, srcColors, color; + "varying vec2 vUV;", - for ( i = 0, l = json.morphColors.length; i < l; i ++ ) { + "void main() {", - geometry.morphColors[ i ] = {}; - geometry.morphColors[ i ].name = json.morphColors[ i ].name; - geometry.morphColors[ i ].colors = []; + // pink square - dstColors = geometry.morphColors[ i ].colors; - srcColors = json.morphColors [ i ].colors; + "if( renderType == 0 ) {", - for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { + "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );", - color = new THREE.Color( 0xffaa00 ); - color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); - dstColors.push( color ); + // restore - } + "} else if( renderType == 1 ) {", - } + "gl_FragColor = texture2D( map, vUV );", - } + // flare - }; + "} else {", - if ( json.materials === undefined || json.materials.length === 0 ) { + "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;", + "visibility = ( 1.0 - visibility / 4.0 );", - return { geometry: geometry }; + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * visibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - } else { + "}", - var materials = this.initMaterials( json.materials, texturePath ); + "}" - if ( this.needsTangents( materials ) ) { + ].join( "\n" ) - geometry.computeTangents(); + }; } - return { geometry: geometry, materials: materials }; - - } - -}; - -// File:src/loaders/LoadingManager.js + program = createProgram( shader ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + } -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { + uniforms = { + renderType: gl.getUniformLocation( program, "renderType" ), + map: gl.getUniformLocation( program, "map" ), + occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), + opacity: gl.getUniformLocation( program, "opacity" ), + color: gl.getUniformLocation( program, "color" ), + scale: gl.getUniformLocation( program, "scale" ), + rotation: gl.getUniformLocation( program, "rotation" ), + screenPosition: gl.getUniformLocation( program, "screenPosition" ) + }; - var scope = this; + }; - var loaded = 0, total = 0; + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - this.itemStart = function ( url ) { + if ( flares.length === 0 ) return; - total ++; + var tempPosition = new THREE.Vector3(); - }; + var invAspect = viewportHeight / viewportWidth, + halfViewportWidth = viewportWidth * 0.5, + halfViewportHeight = viewportHeight * 0.5; - this.itemEnd = function ( url ) { + var size = 16 / viewportHeight, + scale = new THREE.Vector2( size * invAspect, size ); - loaded ++; + var screenPosition = new THREE.Vector3( 1, 1, 0 ), + screenPositionPixels = new THREE.Vector2( 1, 1 ); - if ( scope.onProgress !== undefined ) { + if ( program === undefined ) { - scope.onProgress( url, loaded, total ); + init(); } - if ( loaded === total && scope.onLoad !== undefined ) { - - scope.onLoad(); + gl.useProgram( program ); - } + gl.enableVertexAttribArray( attributes.vertex ); + gl.enableVertexAttribArray( attributes.uv ); - }; + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/unforms -}; + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); -THREE.DefaultLoadingManager = new THREE.LoadingManager(); + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); -// File:src/loaders/BufferGeometryLoader.js + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + gl.disable( gl.CULL_FACE ); + gl.depthMask( false ); -THREE.BufferGeometryLoader = function ( manager ) { + for ( var i = 0, l = flares.length; i < l; i ++ ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + size = 16 / viewportHeight; + scale.set( size * invAspect, size ); -}; + // calc object screen position -THREE.BufferGeometryLoader.prototype = { + var flare = flares[ i ]; - constructor: THREE.BufferGeometryLoader, + tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] ); - load: function ( url, onLoad, onProgress, onError ) { + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - var scope = this; + // setup arrays for gl programs - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + screenPosition.copy( tempPosition ) - onLoad( scope.parse( JSON.parse( text ) ) ); + screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth; + screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight; - }, onProgress, onError ); + // screen cull - }, + if ( hasVertexTexture || ( + screenPositionPixels.x > 0 && + screenPositionPixels.x < viewportWidth && + screenPositionPixels.y > 0 && + screenPositionPixels.y < viewportHeight ) ) { - setCrossOrigin: function ( value ) { + // save current RGB to temp texture - this.crossOrigin = value; + gl.activeTexture( gl.TEXTURE1 ); + gl.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); - }, - parse: function ( json ) { + // render pink quad - var geometry = new THREE.BufferGeometry(); + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - var attributes = json.data.attributes; + gl.disable( gl.BLEND ); + gl.enable( gl.DEPTH_TEST ); - for ( var key in attributes ) { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - var attribute = attributes[ key ]; - var typedArray = new self[ attribute.type ]( attribute.array ); - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) ); + // copy result to occlusionMap - } + gl.activeTexture( gl.TEXTURE0 ); + gl.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); - var offsets = json.data.offsets; - if ( offsets !== undefined ) { + // restore graphics - geometry.offsets = JSON.parse( JSON.stringify( offsets ) ); + gl.uniform1i( uniforms.renderType, 1 ); + gl.disable( gl.DEPTH_TEST ); - } + gl.activeTexture( gl.TEXTURE1 ); + gl.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - var boundingSphere = json.data.boundingSphere; - if ( boundingSphere !== undefined ) { + // update object positions - var center = new THREE.Vector3(); + flare.positionScreen.copy( screenPosition ) - if ( boundingSphere.center !== undefined ) { + if ( flare.customUpdateCallback ) { - center.fromArray( boundingSphere.center ); + flare.customUpdateCallback( flare ); - } + } else { - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + flare.updateLensFlares(); - } + } - return geometry; + // render flares - } + gl.uniform1i( uniforms.renderType, 2 ); + gl.enable( gl.BLEND ); -}; + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { -// File:src/loaders/MaterialLoader.js + var sprite = flare.lensFlares[ j ]; -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { -THREE.MaterialLoader = function ( manager ) { + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + size = sprite.size * sprite.scale / viewportHeight; -}; + scale.x = size * invAspect; + scale.y = size; -THREE.MaterialLoader.prototype = { + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform1f( uniforms.rotation, sprite.rotation ); - constructor: THREE.MaterialLoader, + gl.uniform1f( uniforms.opacity, sprite.opacity ); + gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - load: function ( url, onLoad, onProgress, onError ) { + renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); + renderer.setTexture( sprite.texture, 1 ); - var scope = this; + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + } - onLoad( scope.parse( JSON.parse( text ) ) ); + } - }, onProgress, onError ); + } - }, + } - setCrossOrigin: function ( value ) { + // restore gl - this.crossOrigin = value; + gl.enable( gl.CULL_FACE ); + gl.enable( gl.DEPTH_TEST ); + gl.depthMask( true ); - }, + renderer.resetGLState(); - parse: function ( json ) { + }; - var material = new THREE[ json.type ]; + function createProgram ( shader ) { - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.shading !== undefined ) material.shading = json.shading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + var program = gl.createProgram(); - // for PointCloudMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - if ( json.materials !== undefined ) { + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - material.materials.push( this.parse( json.materials[ i ] ) ); + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - } + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - } + gl.linkProgram( program ); - return material; + return program; } }; -// File:src/loaders/ObjectLoader.js +// File:src/renderers/webgl/plugins/ShadowMapPlugin.js /** - * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ */ -THREE.ObjectLoader = function ( manager ) { +THREE.ShadowMapPlugin = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.texturePath = ''; + var _gl = _renderer.context; -}; + var _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, -THREE.ObjectLoader.prototype = { + _frustum = new THREE.Frustum(), + _projScreenMatrix = new THREE.Matrix4(), - constructor: THREE.ObjectLoader, + _min = new THREE.Vector3(), + _max = new THREE.Vector3(), - load: function ( url, onLoad, onProgress, onError ) { + _matrixPosition = new THREE.Vector3(), -// if ( this.texturePath === '' ) { + _renderList = []; -// this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + // init -// } + var depthShader = THREE.ShaderLib[ "depthRGBA" ]; + var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); - var scope = this; + _depthMaterial = new THREE.ShaderMaterial( { + uniforms: depthUniforms, + vertexShader: depthShader.vertexShader, + fragmentShader: depthShader.fragmentShader + } ); - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + _depthMaterialMorph = new THREE.ShaderMaterial( { + uniforms: depthUniforms, + vertexShader: depthShader.vertexShader, + fragmentShader: depthShader.fragmentShader, + morphTargets: true + } ); - scope.parse( JSON.parse( text ), onLoad ); + _depthMaterialSkin = new THREE.ShaderMaterial( { + uniforms: depthUniforms, + vertexShader: depthShader.vertexShader, + fragmentShader: depthShader.fragmentShader, + skinning: true + } ); - }, onProgress, onError ); + _depthMaterialMorphSkin = new THREE.ShaderMaterial( { + uniforms: depthUniforms, + vertexShader: depthShader.vertexShader, + fragmentShader: depthShader.fragmentShader, + morphTargets: true, + skinning: true + } ); - }, + _depthMaterial._shadowPass = true; + _depthMaterialMorph._shadowPass = true; + _depthMaterialSkin._shadowPass = true; + _depthMaterialMorphSkin._shadowPass = true; - setTexturePath: function ( value ) { + this.render = function ( scene, camera ) { - this.texturePath = value; + if ( _renderer.shadowMapEnabled === false ) return; - }, + var i, il, j, jl, n, - setCrossOrigin: function ( value ) { + shadowMap, shadowMatrix, shadowCamera, + buffer, material, + webglObject, object, light, - this.crossOrigin = value; + lights = [], + k = 0, - }, + fog = null; - parse: function ( json, onLoad ) { + // set GL state for depth map - var geometries = this.parseGeometries( json.geometries ); + _gl.clearColor( 1, 1, 1, 1 ); + _gl.disable( _gl.BLEND ); - var images = this.parseImages( json.images, function () { + _gl.enable( _gl.CULL_FACE ); + _gl.frontFace( _gl.CCW ); - if ( onLoad !== undefined ) onLoad( object ); + if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { - } ); - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); - var object = this.parseObject( json.object, geometries, materials ); + _gl.cullFace( _gl.FRONT ); - if ( json.images === undefined || json.images.length === 0 ) { + } else { - if ( onLoad !== undefined ) onLoad( object ); + _gl.cullFace( _gl.BACK ); } - return object; + _renderer.state.setDepthTest( true ); - }, + // preprocess lights + // - skip lights that are not casting shadows + // - create virtual lights for cascaded shadow maps - parseGeometries: function ( json ) { + for ( i = 0, il = _lights.length; i < il; i ++ ) { - var geometries = {}; + light = _lights[ i ]; - if ( json !== undefined ) { + if ( ! light.castShadow ) continue; - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + for ( n = 0; n < light.shadowCascadeCount; n ++ ) { - var geometry; - var data = json[ i ]; + var virtualLight; - switch ( data.type ) { + if ( ! light.shadowCascadeArray[ n ] ) { - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + virtualLight = createVirtualLight( light, n ); + virtualLight.originalCamera = camera; - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + var gyro = new THREE.Gyroscope(); + gyro.position.copy( light.shadowCascadeOffset ); - break; + gyro.add( virtualLight ); + gyro.add( virtualLight.target ); - case 'BoxGeometry': - case 'CubeGeometry': // backwards compatible + camera.add( gyro ); - geometry = new THREE.BoxGeometry( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + light.shadowCascadeArray[ n ] = virtualLight; - break; + //console.log( "Created virtualLight", virtualLight ); - case 'CircleGeometry': + } else { - geometry = new THREE.CircleGeometry( - data.radius, - data.segments - ); + virtualLight = light.shadowCascadeArray[ n ]; - break; + } - case 'CylinderGeometry': + updateVirtualLight( light, n ); - geometry = new THREE.CylinderGeometry( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded - ); + lights[ k ] = virtualLight; + k ++; - break; + } - case 'SphereGeometry': + } else { - geometry = new THREE.SphereGeometry( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + lights[ k ] = light; + k ++; - break; + } - case 'IcosahedronGeometry': + } - geometry = new THREE.IcosahedronGeometry( - data.radius, - data.detail - ); + // render depth map - break; + for ( i = 0, il = lights.length; i < il; i ++ ) { - case 'TorusGeometry': + light = lights[ i ]; - geometry = new THREE.TorusGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + if ( ! light.shadowMap ) { - break; + var shadowFilter = THREE.LinearFilter; - case 'TorusKnotGeometry': + if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) { - geometry = new THREE.TorusKnotGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.p, - data.q, - data.heightScale - ); + shadowFilter = THREE.NearestFilter; - break; + } - case 'BufferGeometry': + var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat }; - geometry = bufferGeometryLoader.parse( data ); + light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars ); + light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight ); - break; + light.shadowMatrix = new THREE.Matrix4(); - case 'Geometry': + } - geometry = geometryLoader.parse( data.data ).geometry; + if ( ! light.shadowCamera ) { - break; + if ( light instanceof THREE.SpotLight ) { - } + light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar ); - geometry.uuid = data.uuid; + } else if ( light instanceof THREE.DirectionalLight ) { - if ( data.name !== undefined ) geometry.name = data.name; + light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar ); - geometries[ data.uuid ] = geometry; + } else { - } + THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light ); + continue; - } + } - return geometries; + scene.add( light.shadowCamera ); - }, + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - parseMaterials: function ( json, textures ) { + } - var materials = {}; + if ( light.shadowCameraVisible && ! light.cameraHelper ) { - if ( json !== undefined ) { + light.cameraHelper = new THREE.CameraHelper( light.shadowCamera ); + scene.add( light.cameraHelper ); - var getTexture = function ( name ) { + } - if ( textures[ name ] === undefined ) { + if ( light.isVirtual && virtualLight.originalCamera == camera ) { - THREE.warn( 'THREE.ObjectLoader: Undefined texture', name ); + updateShadowCamera( camera, light ); - } + } - return textures[ name ]; + shadowMap = light.shadowMap; + shadowMatrix = light.shadowMatrix; + shadowCamera = light.shadowCamera; - }; + // - var loader = new THREE.MaterialLoader(); + shadowCamera.position.setFromMatrixPosition( light.matrixWorld ); + _matrixPosition.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _matrixPosition ); + shadowCamera.updateMatrixWorld(); - for ( var i = 0, l = json.length; i < l; i ++ ) { + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - var data = json[ i ]; - var material = loader.parse( data ); + // - material.uuid = data.uuid; + if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible; + if ( light.shadowCameraVisible ) light.cameraHelper.update(); - if ( data.name !== undefined ) material.name = data.name; + // compute shadow matrix - if ( data.map !== undefined && data.map !== null ) { + shadowMatrix.set( + 0.5, 0.0, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); - material.map = getTexture( data.map ); + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - } + // update camera matrices and frustum - if ( data.bumpMap !== undefined ) { + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - material.bumpMap = getTexture( data.bumpMap ); - if ( data.bumpScale ) { - material.bumpScale = new THREE.Vector2( data.bumpScale, data.bumpScale ); - } + // render shadow map - } + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - if ( data.alphaMap !== undefined ) { + // set object matrices & frustum culling - material.alphaMap = getTexture( data.alphaMap ); + _renderList.length = 0; - } + projectObject( scene, scene, shadowCamera ); - if ( data.envMap !== undefined ) { - material.envMap = getTexture( data.envMap ); + // render regular objects - } + var objectMaterial, useMorphing, useSkinning; - if ( data.normalMap !== undefined ) { + for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { - material.normalMap = getTexture( data.normalMap ); - if ( data.normalScale ) { - material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale ); - } + webglObject = _renderList[ j ]; - } + object = webglObject.object; + buffer = webglObject.buffer; - if ( data.lightMap !== undefined ) { + // culling is overriden globally for all objects + // while rendering depth map - material.lightMap = getTexture( data.lightMap ); + // need to deal with MeshFaceMaterial somehow + // in that case just use the first of material.materials for now + // (proper solution would require to break objects by materials + // similarly to regular rendering and then set corresponding + // depth materials per each chunk instead of just once per object) - } + objectMaterial = getObjectMaterial( object ); - if ( data.specularMap !== undefined ) { + useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; + useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; - material.specularMap = getTexture( data.specularMap ); + if ( object.customDepthMaterial ) { - } + material = object.customDepthMaterial; - materials[ data.uuid ] = material; + } else if ( useSkinning ) { - } + material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; - } + } else if ( useMorphing ) { - return materials; + material = _depthMaterialMorph; - }, + } else { - parseImages: function ( json, onLoad ) { + material = _depthMaterial; - var scope = this; - var images = {}; + } - if ( json !== undefined && json.length > 0 ) { + _renderer.setMaterialFaces( objectMaterial ); - var manager = new THREE.LoadingManager( onLoad ); + if ( buffer instanceof THREE.BufferGeometry ) { - var loader = new THREE.ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object ); - var loadImage = function ( url ) { + } else { - scope.manager.itemStart( url ); + _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object ); - return loader.load( url, function () { + } - scope.manager.itemEnd( url ); + } - } ); + // set matrices and render immediate objects - }; + for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + webglObject = _webglObjectsImmediate[ j ]; + object = webglObject.object; - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + if ( object.visible && object.castShadow ) { - images[ image.uuid ] = loadImage( path ); + object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object ); + + } } } - return images; + // restore GL state - }, + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); - parseTextures: function ( json, images ) { + _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); + _gl.enable( _gl.BLEND ); - var textures = {}; + if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { - if ( json !== undefined ) { + _gl.cullFace( _gl.BACK ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var data = json[ i ]; + _renderer.resetGLState(); - if ( data.image === undefined ) { + }; - THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid ); + function projectObject( scene, object, shadowCamera ) { - } + if ( object.visible ) { - if ( images[ data.image ] === undefined ) { + var webglObjects = _webglObjects[ object.id ]; - THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { - } + for ( var i = 0, l = webglObjects.length; i < l; i ++ ) { - var texture = new THREE.Texture( images[ data.image ] ); - texture.needsUpdate = true; + var webglObject = webglObjects[ i ]; - texture.uuid = data.uuid; + object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( webglObject ); - if ( data.name !== undefined ) texture.name = data.name; - if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] ); - if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ]; - if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ]; - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; - if ( data.wrap instanceof Array ) { + } - texture.wrapS = THREE[ data.wrap[ 0 ] ]; - texture.wrapT = THREE[ data.wrap[ 1 ] ]; + } - } + for ( var i = 0, l = object.children.length; i < l; i ++ ) { - textures[ data.uuid ] = texture; + projectObject( scene, object.children[ i ], shadowCamera ); } } - return textures; + } - }, + function createVirtualLight( light, cascade ) { - parseObject: function () { + var virtualLight = new THREE.DirectionalLight(); - var matrix = new THREE.Matrix4(); + virtualLight.isVirtual = true; - return function ( data, geometries, materials ) { + virtualLight.onlyShadow = true; + virtualLight.castShadow = true; - var object; + virtualLight.shadowCameraNear = light.shadowCameraNear; + virtualLight.shadowCameraFar = light.shadowCameraFar; - var getGeometry = function ( name ) { + virtualLight.shadowCameraLeft = light.shadowCameraLeft; + virtualLight.shadowCameraRight = light.shadowCameraRight; + virtualLight.shadowCameraBottom = light.shadowCameraBottom; + virtualLight.shadowCameraTop = light.shadowCameraTop; - if ( geometries[ name ] === undefined ) { + virtualLight.shadowCameraVisible = light.shadowCameraVisible; - THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + virtualLight.shadowDarkness = light.shadowDarkness; - } + virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; + virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ]; + virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ]; - return geometries[ name ]; + virtualLight.pointsWorld = []; + virtualLight.pointsFrustum = []; - }; + var pointsWorld = virtualLight.pointsWorld, + pointsFrustum = virtualLight.pointsFrustum; - var getMaterial = function ( name ) { + for ( var i = 0; i < 8; i ++ ) { - if ( materials[ name ] === undefined ) { + pointsWorld[ i ] = new THREE.Vector3(); + pointsFrustum[ i ] = new THREE.Vector3(); - THREE.warn( 'THREE.ObjectLoader: Undefined material', name ); + } - } + var nearZ = light.shadowCascadeNearZ[ cascade ]; + var farZ = light.shadowCascadeFarZ[ cascade ]; - return materials[ name ]; + pointsFrustum[ 0 ].set( - 1, - 1, nearZ ); + pointsFrustum[ 1 ].set( 1, - 1, nearZ ); + pointsFrustum[ 2 ].set( - 1, 1, nearZ ); + pointsFrustum[ 3 ].set( 1, 1, nearZ ); - }; + pointsFrustum[ 4 ].set( - 1, - 1, farZ ); + pointsFrustum[ 5 ].set( 1, - 1, farZ ); + pointsFrustum[ 6 ].set( - 1, 1, farZ ); + pointsFrustum[ 7 ].set( 1, 1, farZ ); - switch ( data.type ) { + return virtualLight; - case 'Scene': + } - object = new THREE.Scene(); + // Synchronize virtual light with the original light - break; + function updateVirtualLight( light, cascade ) { - case 'PerspectiveCamera': + var virtualLight = light.shadowCascadeArray[ cascade ]; - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + virtualLight.position.copy( light.position ); + virtualLight.target.position.copy( light.target.position ); + virtualLight.lookAt( virtualLight.target ); - break; + virtualLight.shadowCameraVisible = light.shadowCameraVisible; + virtualLight.shadowDarkness = light.shadowDarkness; - case 'OrthographicCamera': + virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + var nearZ = light.shadowCascadeNearZ[ cascade ]; + var farZ = light.shadowCascadeFarZ[ cascade ]; - break; + var pointsFrustum = virtualLight.pointsFrustum; - case 'AmbientLight': + pointsFrustum[ 0 ].z = nearZ; + pointsFrustum[ 1 ].z = nearZ; + pointsFrustum[ 2 ].z = nearZ; + pointsFrustum[ 3 ].z = nearZ; - object = new THREE.AmbientLight( data.color ); + pointsFrustum[ 4 ].z = farZ; + pointsFrustum[ 5 ].z = farZ; + pointsFrustum[ 6 ].z = farZ; + pointsFrustum[ 7 ].z = farZ; - break; + } - case 'DirectionalLight': + // Fit shadow camera's ortho frustum to camera frustum - object = new THREE.DirectionalLight( data.color, data.intensity ); + function updateShadowCamera( camera, light ) { - break; + var shadowCamera = light.shadowCamera, + pointsFrustum = light.pointsFrustum, + pointsWorld = light.pointsWorld; - case 'PointLight': + _min.set( Infinity, Infinity, Infinity ); + _max.set( - Infinity, - Infinity, - Infinity ); - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + for ( var i = 0; i < 8; i ++ ) { - break; + var p = pointsWorld[ i ]; - case 'SpotLight': + p.copy( pointsFrustum[ i ] ); + p.unproject( camera ); - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay ); + p.applyMatrix4( shadowCamera.matrixWorldInverse ); - break; + if ( p.x < _min.x ) _min.x = p.x; + if ( p.x > _max.x ) _max.x = p.x; - case 'HemisphereLight': + if ( p.y < _min.y ) _min.y = p.y; + if ( p.y > _max.y ) _max.y = p.y; - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + if ( p.z < _min.z ) _min.z = p.z; + if ( p.z > _max.z ) _max.z = p.z; - break; + } - case 'Mesh': + shadowCamera.left = _min.x; + shadowCamera.right = _max.x; + shadowCamera.top = _max.y; + shadowCamera.bottom = _min.y; - object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) ); + // can't really fit near/far + //shadowCamera.near = _min.z; + //shadowCamera.far = _max.z; - break; + shadowCamera.updateProjectionMatrix(); - case 'Line': + } - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + // For the moment just ignore objects that have multiple materials with different animation methods + // Only the first material will be taken into account for deciding which depth material to use for shadow maps - break; + function getObjectMaterial( object ) { - case 'PointCloud': + return object.material instanceof THREE.MeshFaceMaterial + ? object.material.materials[ 0 ] + : object.material; - object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) ); + }; - break; +}; - case 'Sprite': +// File:src/renderers/webgl/plugins/SpritePlugin.js - object = new THREE.Sprite( getMaterial( data.material ) ); +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - break; +THREE.SpritePlugin = function ( renderer, sprites ) { - case 'Group': + var gl = renderer.context; - object = new THREE.Group(); + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; - break; + var texture; - default: + // decompose matrixWorld - object = new THREE.Object3D(); + var spritePosition = new THREE.Vector3(); + var spriteRotation = new THREE.Quaternion(); + var spriteScale = new THREE.Vector3(); - } + var init = function () { - object.uuid = data.uuid; + var vertices = new Float32Array( [ + - 0.5, - 0.5, 0, 0, + 0.5, - 0.5, 1, 0, + 0.5, 0.5, 1, 1, + - 0.5, 0.5, 0, 1 + ] ); - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - } else { + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - } + program = createProgram(); - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - if ( data.children !== undefined ) { + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - for ( var child in data.children ) { + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - } + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - } + fogType: gl.getUniformLocation( program, 'fogType' ), + fogDensity: gl.getUniformLocation( program, 'fogDensity' ), + fogNear: gl.getUniformLocation( program, 'fogNear' ), + fogFar: gl.getUniformLocation( program, 'fogFar' ), + fogColor: gl.getUniformLocation( program, 'fogColor' ), - return object; + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - } + var canvas = document.createElement( 'canvas' ); + canvas.width = 8; + canvas.height = 8; - }() + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); -}; + texture = new THREE.Texture( canvas ); + texture.needsUpdate = true; -// File:src/loaders/TextureLoader.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.render = function ( scene, camera ) { -THREE.TextureLoader = function ( manager ) { + if ( sprites.length === 0 ) return; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + // setup gl -}; + if ( program === undefined ) { -THREE.TextureLoader.prototype = { + init(); - constructor: THREE.TextureLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + gl.useProgram( program ); - var scope = this; + gl.enableVertexAttribArray( attributes.position ); + gl.enableVertexAttribArray( attributes.uv ); - var loader = new THREE.ImageLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( image ) { + gl.disable( gl.CULL_FACE ); + gl.enable( gl.BLEND ); - var texture = new THREE.Texture( image ); - texture.needsUpdate = true; + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - if ( onLoad !== undefined ) { + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - onLoad( texture ); + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - } + gl.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - }, onProgress, onError ); + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - }, + if ( fog ) { - setCrossOrigin: function ( value ) { + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - this.crossOrigin = value; + if ( fog instanceof THREE.Fog ) { - } + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); -}; + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; -// File:src/loaders/BinaryTextureLoader.js + } else if ( fog instanceof THREE.FogExp2 ) { -/** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + gl.uniform1f( uniforms.fogDensity, fog.density ); -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () { + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - // override in sub classes - this._parser = null; + } -}; + } else { -THREE.BinaryTextureLoader.prototype = { + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - constructor: THREE.BinaryTextureLoader, + } - load: function ( url, onLoad, onProgress, onError ) { - var scope = this; + // update positions and sort - var texture = new THREE.DataTexture( ); + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - var loader = new THREE.XHRLoader(); - loader.setResponseType( 'arraybuffer' ); + var sprite = sprites[ i ]; - loader.load( url, function ( buffer ) { + sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite._modelViewMatrix.elements[ 14 ]; - var texData = scope._parser( buffer ); + } - if ( !texData ) return; + sprites.sort( painterSortStable ); - if ( undefined !== texData.image ) { + // render all sprites - texture.image = texData.image; + var scale = []; - } else if ( undefined !== texData.data ) { + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + var sprite = sprites[ i ]; + var material = sprite.material; - } + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements ); - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + var fogType = 0; - if ( undefined !== texData.format ) { + if ( scene.fog && material.fog ) { - texture.format = texData.format; + fogType = sceneFogType; } - if ( undefined !== texData.type ) { - texture.type = texData.type; + if ( oldFogType !== fogType ) { + + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; } - if ( undefined !== texData.mipmaps ) { + if ( material.map !== null ) { - texture.mipmaps = texData.mipmaps; + gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); + gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + + } else { + + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); } - if ( 1 === texData.mipmapCount ) { + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - texture.minFilter = THREE.LinearFilter; + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - } + renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + renderer.state.setDepthTest( material.depthTest ); + renderer.state.setDepthWrite( material.depthWrite ); - texture.needsUpdate = true; + if ( material.map && material.map.image && material.map.image.width ) { - if ( onLoad ) onLoad( texture, texData ); + renderer.setTexture( material.map, 0 ); - }, onProgress, onError ); + } else { + renderer.setTexture( texture, 0 ); - return texture; + } - } + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); -}; + } -// File:src/loaders/CompressedTextureLoader.js + // restore gl -/** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + gl.enable( gl.CULL_FACE ); -THREE.CompressedTextureLoader = function () { + renderer.resetGLState(); - // override in sub classes - this._parser = null; + }; -}; + function createProgram () { + var program = gl.createProgram(); -THREE.CompressedTextureLoader.prototype = { + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - constructor: THREE.CompressedTextureLoader, + gl.shaderSource( vertexShader, [ - load: function ( url, onLoad, onError ) { + 'precision ' + renderer.getPrecision() + ' float;', - var scope = this; + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - var images = []; + 'attribute vec2 position;', + 'attribute vec2 uv;', - var texture = new THREE.CompressedTexture(); - texture.image = images; + 'varying vec2 vUV;', - var loader = new THREE.XHRLoader(); - loader.setResponseType( 'arraybuffer' ); + 'void main() {', - if ( url instanceof Array ) { + 'vUV = uvOffset + uv * uvScale;', - var loaded = 0; + 'vec2 alignedPosition = position * scale;', - var loadTexture = function ( i ) { + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', - loader.load( url[ i ], function ( buffer ) { + 'vec4 finalPosition;', - var texDatas = scope._parser( buffer, true ); + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + 'gl_Position = finalPosition;', - loaded += 1; + '}' - if ( loaded === 6 ) { + ].join( '\n' ) ); - if (texDatas.mipmapCount == 1) - texture.minFilter = THREE.LinearFilter; + gl.shaderSource( fragmentShader, [ - texture.format = texDatas.format; - texture.needsUpdate = true; + 'precision ' + renderer.getPrecision() + ' float;', - if ( onLoad ) onLoad( texture ); + 'uniform vec3 color;', + 'uniform sampler2D map;', + 'uniform float opacity;', - } + 'uniform int fogType;', + 'uniform vec3 fogColor;', + 'uniform float fogDensity;', + 'uniform float fogNear;', + 'uniform float fogFar;', + 'uniform float alphaTest;', - } ); + 'varying vec2 vUV;', - }; + 'void main() {', - for ( var i = 0, il = url.length; i < il; ++ i ) { + 'vec4 texture = texture2D( map, vUV );', - loadTexture( i ); + 'if ( texture.a < alphaTest ) discard;', - } + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - } else { + 'if ( fogType > 0 ) {', - // compressed cubemap texture stored in a single DDS file + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - loader.load( url, function ( buffer ) { + 'if ( fogType == 1 ) {', - var texDatas = scope._parser( buffer, true ); + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - if ( texDatas.isCubemap ) { + '} else {', - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + 'const float LOG2 = 1.442695;', + 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - for ( var f = 0; f < faces; f ++ ) { + '}', - images[ f ] = { mipmaps : [] }; + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + '}', - images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); - images[ f ].format = texDatas.format; - images[ f ].width = texDatas.width; - images[ f ].height = texDatas.height; + '}' - } + ].join( '\n' ) ); - } + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - } else { + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + gl.linkProgram( program ); - } + return program; - if ( texDatas.mipmapCount === 1 ) { + }; - texture.minFilter = THREE.LinearFilter; + function painterSortStable ( a, b ) { - } + if ( a.z !== b.z ) { - texture.format = texDatas.format; - texture.needsUpdate = true; + return b.z - a.z; - if ( onLoad ) onLoad( texture ); + } else { - } ); + return b.id - a.id; } - return texture; - - } + }; }; -// File:src/materials/Material.js +// File:src/extras/GeometryUtils.js /** * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ */ -THREE.Material = function () { +THREE.GeometryUtils = { - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + merge: function ( geometry1, geometry2, materialIndexOffset ) { - this.uuid = THREE.Math.generateUUID(); + THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - this.name = ''; - this.type = 'Material'; + var matrix; - this.side = THREE.FrontSide; + if ( geometry2 instanceof THREE.Mesh ) { - this.opacity = 1; - this.transparent = false; + geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - this.blending = THREE.NormalBlending; + matrix = geometry2.matrix; + geometry2 = geometry2.geometry; - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + } - this.depthTest = true; - this.depthWrite = true; + geometry1.merge( geometry2, matrix, materialIndexOffset ); - this.colorWrite = true; + }, - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + center: function ( geometry ) { - this.alphaTest = 0; + THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); + return geometry.center(); - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + } - this.visible = true; +}; - this._needsUpdate = true; +// File:src/extras/ImageUtils.js -}; +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author Daosheng Mu / https://github.com/DaoshengMu/ + */ -THREE.Material.prototype = { +THREE.ImageUtils = { - constructor: THREE.Material, + crossOrigin: undefined, - get needsUpdate () { + loadTexture: function ( url, mapping, onLoad, onError ) { - return this._needsUpdate; + var loader = new THREE.ImageLoader(); + loader.crossOrigin = this.crossOrigin; - }, + var texture = new THREE.Texture( undefined, mapping ); - set needsUpdate ( value ) { + loader.load( url, function ( image ) { - if ( value === true ) this.update(); + texture.image = image; + texture.needsUpdate = true; - this._needsUpdate = value; + if ( onLoad ) onLoad( texture ); - }, + }, undefined, function ( event ) { - setValues: function ( values ) { + if ( onError ) onError( event ); - if ( values === undefined ) return; + } ); - for ( var key in values ) { + texture.sourceFile = url; - var newValue = values[ key ]; + return texture; - if ( newValue === undefined ) { + }, - THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + loadTextureCube: function ( array, mapping, onLoad, onError ) { - } + var images = []; - if ( key in this ) { + var loader = new THREE.ImageLoader(); + loader.crossOrigin = this.crossOrigin; - var currentValue = this[ key ]; + var texture = new THREE.CubeTexture( images, mapping ); - if ( currentValue instanceof THREE.Color ) { + // no flipping needed for cube textures - currentValue.set( newValue ); + texture.flipY = false; - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + var loaded = 0; - currentValue.copy( newValue ); + var loadTexture = function ( i ) { - } else if ( key == 'overdraw' ) { + loader.load( array[ i ], function ( image ) { - // ensure overdraw is backwards-compatable with legacy boolean type - this[ key ] = Number( newValue ); + texture.images[ i ] = image; - } else { + loaded += 1; - this[ key ] = newValue; + if ( loaded === 6 ) { + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); } - } + }, undefined, onError ); } - }, + for ( var i = 0, il = array.length; i < il; ++ i ) { - toJSON: function () { + loadTexture( i ); - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type - }; + } - if ( this.name !== "" ) output.name = this.name; + return texture; - if ( this instanceof THREE.MeshBasicMaterial ) { + }, - output.color = this.color.getHex(); - if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - if ( this.side !== THREE.FrontSide ) output.side = this.side; + loadCompressedTexture: function () { - } else if ( this instanceof THREE.MeshLambertMaterial ) { + THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ) - output.color = this.color.getHex(); - output.emissive = this.emissive.getHex(); - if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; - if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading; - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - if ( this.side !== THREE.FrontSide ) output.side = this.side; + }, - } else if ( this instanceof THREE.MeshPhongMaterial ) { + loadCompressedTextureCube: function () { - output.color = this.color.getHex(); - output.emissive = this.emissive.getHex(); - output.specular = this.specular.getHex(); - output.shininess = this.shininess; - if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; - if ( this.shading !== THREE.SmoothShading ) output.shading = this.shading; - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - if ( this.side !== THREE.FrontSide ) output.side = this.side; + THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ) - } else if ( this instanceof THREE.MeshNormalMaterial ) { + }, - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - if ( this.side !== THREE.FrontSide ) output.side = this.side; + getNormalMap: function ( image, depth ) { - } else if ( this instanceof THREE.MeshDepthMaterial ) { + // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/ - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; - if ( this.side !== THREE.FrontSide ) output.side = this.side; + var cross = function ( a, b ) { - } else if ( this instanceof THREE.PointCloudMaterial ) { + return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ]; - output.size = this.size; - output.sizeAttenuation = this.sizeAttenuation; - output.color = this.color.getHex(); + } - if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors; - if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending; + var subtract = function ( a, b ) { - } else if ( this instanceof THREE.ShaderMaterial ) { + return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ]; - output.uniforms = this.uniforms; - output.vertexShader = this.vertexShader; - output.fragmentShader = this.fragmentShader; + } - } else if ( this instanceof THREE.SpriteMaterial ) { + var normalize = function ( a ) { - output.color = this.color.getHex(); + var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] ); + return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ]; } - if ( this.opacity < 1 ) output.opacity = this.opacity; - if ( this.transparent !== false ) output.transparent = this.transparent; - if ( this.wireframe !== false ) output.wireframe = this.wireframe; + depth = depth | 1; - return output; + var width = image.width; + var height = image.height; - }, + // TODO: Make this work in Qt Quick - clone: function ( material ) { + var canvas = document.createElement( 'canvas' ); + canvas.width = width; + canvas.height = height; - if ( material === undefined ) material = new THREE.Material(); + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0 ); - material.name = this.name; + var data = context.getImageData( 0, 0, width, height ).data; + var imageData = context.createImageData( width, height ); + var output = imageData.data; - material.side = this.side; + for ( var x = 0; x < width; x ++ ) { - material.opacity = this.opacity; - material.transparent = this.transparent; + for ( var y = 0; y < height; y ++ ) { - material.blending = this.blending; + var ly = y - 1 < 0 ? 0 : y - 1; + var uy = y + 1 > height - 1 ? height - 1 : y + 1; + var lx = x - 1 < 0 ? 0 : x - 1; + var ux = x + 1 > width - 1 ? width - 1 : x + 1; - material.blendSrc = this.blendSrc; - material.blendDst = this.blendDst; - material.blendEquation = this.blendEquation; - material.blendSrcAlpha = this.blendSrcAlpha; - material.blendDstAlpha = this.blendDstAlpha; - material.blendEquationAlpha = this.blendEquationAlpha; + var points = []; + var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ]; + points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] ); + points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] ); + points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] ); + points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] ); + points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] ); + points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] ); - material.depthTest = this.depthTest; - material.depthWrite = this.depthWrite; + var normals = []; + var num_points = points.length; - material.polygonOffset = this.polygonOffset; - material.polygonOffsetFactor = this.polygonOffsetFactor; - material.polygonOffsetUnits = this.polygonOffsetUnits; + for ( var i = 0; i < num_points; i ++ ) { - material.alphaTest = this.alphaTest; + var v1 = points[ i ]; + var v2 = points[ ( i + 1 ) % num_points ]; + v1 = subtract( v1, origin ); + v2 = subtract( v2, origin ); + normals.push( normalize( cross( v1, v2 ) ) ); - material.overdraw = this.overdraw; + } - material.visible = this.visible; + var normal = [ 0, 0, 0 ]; - return material; + for ( var i = 0; i < normals.length; i ++ ) { - }, + normal[ 0 ] += normals[ i ][ 0 ]; + normal[ 1 ] += normals[ i ][ 1 ]; + normal[ 2 ] += normals[ i ][ 2 ]; - update: function () { + } - this.dispatchEvent( { type: 'update' } ); + normal[ 0 ] /= normals.length; + normal[ 1 ] /= normals.length; + normal[ 2 ] /= normals.length; + + var idx = ( y * width + x ) * 4; + + output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0; + output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0; + output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0; + output[ idx + 3 ] = 255; + + } + + } + + context.putImageData( imageData, 0, 0 ); + + return canvas; }, - dispose: function () { + generateDataTexture: function ( width, height, color ) { - this.dispatchEvent( { type: 'dispose' } ); + var size = width * height; + var data = new Uint8Array( 3 * size ); - } + var r = Math.floor( color.r * 255 ); + var g = Math.floor( color.g * 255 ); + var b = Math.floor( color.b * 255 ); -}; + for ( var i = 0; i < size; i ++ ) { -THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); + data[ i * 3 ] = r; + data[ i * 3 + 1 ] = g; + data[ i * 3 + 2 ] = b; -THREE.MaterialIdCount = 0; + } -// File:src/materials/LineBasicMaterial.js + var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat ); + texture.needsUpdate = true; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * opacity: <float>, - * - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * linewidth: <float>, - * linecap: "round", - * linejoin: "round", - * - * vertexColors: <bool> - * - * fog: <bool> - * } - */ + return texture; -THREE.LineBasicMaterial = function ( parameters ) { + } - THREE.Material.call( this ); +}; - this.type = 'LineBasicMaterial'; +// File:src/extras/SceneUtils.js - this.color = new THREE.Color( 0xffffff ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; +THREE.SceneUtils = { - this.vertexColors = THREE.NoColors; + createMultiMaterialObject: function ( geometry, materials ) { - this.fog = true; + var group = new THREE.Object3D(); - this.setValues( parameters ); + for ( var i = 0, l = materials.length; i < l; i ++ ) { -}; + group.add( new THREE.Mesh( geometry, materials[ i ] ) ); -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; + } -THREE.LineBasicMaterial.prototype.clone = function () { + return group; - var material = new THREE.LineBasicMaterial(); + }, - THREE.Material.prototype.clone.call( this, material ); + detach: function ( child, parent, scene ) { - material.color.copy( this.color ); + child.applyMatrix( parent.matrixWorld ); + parent.remove( child ); + scene.add( child ); - material.linewidth = this.linewidth; - material.linecap = this.linecap; - material.linejoin = this.linejoin; + }, - material.vertexColors = this.vertexColors; + attach: function ( child, scene, parent ) { - material.fog = this.fog; + var matrixWorldInverse = new THREE.Matrix4(); + matrixWorldInverse.getInverse( parent.matrixWorld ); + child.applyMatrix( matrixWorldInverse ); - return material; + scene.remove( child ); + parent.add( child ); + + } }; -// File:src/materials/LineDashedMaterial.js +// File:src/extras/FontUtils.js /** + * @author zz85 / http://www.lab4games.net/zz85/blog * @author alteredq / http://alteredqualia.com/ * - * parameters = { - * color: <hex>, - * opacity: <float>, + * For Text operations in three.js (See TextGeometry) * - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, + * It uses techniques used in: * - * linewidth: <float>, + * typeface.js and canvastext + * For converting fonts and rendering with javascript + * http://typeface.neocracy.org * - * scale: <float>, - * dashSize: <float>, - * gapSize: <float>, + * Triangulation ported from AS3 + * Simple Polygon Triangulation + * http://actionsnippet.com/?p=1462 * - * vertexColors: <bool> + * A Method to triangulate shapes with holes + * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/ * - * fog: <bool> - * } */ -THREE.LineDashedMaterial = function ( parameters ) { +THREE.FontUtils = { - THREE.Material.call( this ); + faces: {}, - this.type = 'LineDashedMaterial'; + // Just for now. face[weight][style] - this.color = new THREE.Color( 0xffffff ); + face: 'helvetiker', + weight: 'normal', + style: 'normal', + size: 150, + divisions: 10, - this.linewidth = 1; + getFace: function () { - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + try { - this.vertexColors = false; + return this.faces[ this.face ][ this.weight ][ this.style ]; - this.fog = true; + } catch (e) { - this.setValues( parameters ); + throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing." -}; + }; -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; + }, -THREE.LineDashedMaterial.prototype.clone = function () { + loadFace: function ( data ) { - var material = new THREE.LineDashedMaterial(); + var family = data.familyName.toLowerCase(); - THREE.Material.prototype.clone.call( this, material ); + var ThreeFont = this; - material.color.copy( this.color ); + ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {}; - material.linewidth = this.linewidth; + ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {}; + ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - material.scale = this.scale; - material.dashSize = this.dashSize; - material.gapSize = this.gapSize; + ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; - material.vertexColors = this.vertexColors; + return data; - material.fog = this.fog; + }, - return material; + drawText: function ( text ) { -}; + // RenderText -// File:src/materials/MeshBasicMaterial.js + var i, + face = this.getFace(), + scale = this.size / face.resolution, + offset = 0, + chars = String( text ).split( '' ), + length = chars.length; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * opacity: <float>, - * map: new THREE.Texture( <Image> ), - * - * lightMap: new THREE.Texture( <Image> ), - * - * specularMap: new THREE.Texture( <Image> ), - * - * alphaMap: new THREE.Texture( <Image> ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: <float>, - * refractionRatio: <float>, - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float>, - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: <bool>, - * morphTargets: <bool>, - * - * fog: <bool> - * } - */ + var fontPaths = []; -THREE.MeshBasicMaterial = function ( parameters ) { + for ( i = 0; i < length; i ++ ) { - THREE.Material.call( this ); + var path = new THREE.Path(); - this.type = 'MeshBasicMaterial'; + var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path ); + offset += ret.offset; - this.color = new THREE.Color( 0xffffff ); // emissive + fontPaths.push( ret.path ); - this.map = null; + } - this.lightMap = null; + // get the width - this.specularMap = null; + var width = offset / 2; + // + // for ( p = 0; p < allPts.length; p++ ) { + // + // allPts[ p ].x -= width; + // + // } - this.alphaMap = null; + //var extract = this.extractPoints( allPts, characterPts ); + //extract.contour = allPts; - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + //extract.paths = fontPaths; + //extract.offset = width; - this.fog = true; + return { paths: fontPaths, offset: width }; - this.shading = THREE.SmoothShading; + }, - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - this.vertexColors = THREE.NoColors; - this.skinning = false; - this.morphTargets = false; - this.setValues( parameters ); + extractGlyphPoints: function ( c, face, scale, offset, path ) { -}; + var pts = []; -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; + var i, i2, divisions, + outline, action, length, + scaleX, scaleY, + x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, + laste, + glyph = face.glyphs[ c ] || face.glyphs[ '?' ]; -THREE.MeshBasicMaterial.prototype.clone = function () { + if ( ! glyph ) return; - var material = new THREE.MeshBasicMaterial(); + if ( glyph.o ) { - THREE.Material.prototype.clone.call( this, material ); + outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + length = outline.length; - material.color.copy( this.color ); + scaleX = scale; + scaleY = scale; - material.map = this.map; + for ( i = 0; i < length; ) { - material.lightMap = this.lightMap; + action = outline[ i ++ ]; - material.specularMap = this.specularMap; + //console.log( action ); - material.alphaMap = this.alphaMap; + switch ( action ) { - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; + case 'm': - material.fog = this.fog; + // Move To - material.shading = this.shading; + x = outline[ i ++ ] * scaleX + offset; + y = outline[ i ++ ] * scaleY; - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; + path.moveTo( x, y ); + break; - material.vertexColors = this.vertexColors; + case 'l': - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; + // Line To - return material; + x = outline[ i ++ ] * scaleX + offset; + y = outline[ i ++ ] * scaleY; + path.lineTo( x, y ); + break; -}; + case 'q': -// File:src/materials/MeshLambertMaterial.js + // QuadraticCurveTo -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * emissive: <hex>, - * opacity: <float>, - * - * map: new THREE.Texture( <Image> ), - * - * lightMap: new THREE.Texture( <Image> ), - * - * specularMap: new THREE.Texture( <Image> ), - * - * alphaMap: new THREE.Texture( <Image> ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: <float>, - * refractionRatio: <float>, - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float>, - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: <bool>, - * morphTargets: <bool>, - * morphNormals: <bool>, - * - * fog: <bool> - * } - */ + cpx = outline[ i ++ ] * scaleX + offset; + cpy = outline[ i ++ ] * scaleY; + cpx1 = outline[ i ++ ] * scaleX + offset; + cpy1 = outline[ i ++ ] * scaleY; -THREE.MeshLambertMaterial = function ( parameters ) { + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - THREE.Material.call( this ); + laste = pts[ pts.length - 1 ]; - this.type = 'MeshLambertMaterial'; + if ( laste ) { - this.color = new THREE.Color( 0xffffff ); // diffuse - this.emissive = new THREE.Color( 0x000000 ); + cpx0 = laste.x; + cpy0 = laste.y; - this.wrapAround = false; - this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); + for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { - this.map = null; + var t = i2 / divisions; + THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); + THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); + } - this.lightMap = null; + } - this.specularMap = null; + break; - this.alphaMap = null; + case 'b': - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + // Cubic Bezier Curve - this.fog = true; + cpx = outline[ i ++ ] * scaleX + offset; + cpy = outline[ i ++ ] * scaleY; + cpx1 = outline[ i ++ ] * scaleX + offset; + cpy1 = outline[ i ++ ] * scaleY; + cpx2 = outline[ i ++ ] * scaleX + offset; + cpy2 = outline[ i ++ ] * scaleY; - this.shading = THREE.SmoothShading; + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + laste = pts[ pts.length - 1 ]; - this.vertexColors = THREE.NoColors; + if ( laste ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + cpx0 = laste.x; + cpy0 = laste.y; - this.setValues( parameters ); + for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { -}; + var t = i2 / divisions; + THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); + THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; + } -THREE.MeshLambertMaterial.prototype.clone = function () { + } - var material = new THREE.MeshLambertMaterial(); + break; - THREE.Material.prototype.clone.call( this, material ); + } - material.color.copy( this.color ); - material.emissive.copy( this.emissive ); + } + } - material.wrapAround = this.wrapAround; - material.wrapRGB.copy( this.wrapRGB ); - material.map = this.map; - material.lightMap = this.lightMap; + return { offset: glyph.ha * scale, path:path }; + } - material.specularMap = this.specularMap; +}; - material.alphaMap = this.alphaMap; - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; +THREE.FontUtils.generateShapes = function ( text, parameters ) { - material.fog = this.fog; + // Parameters - material.shading = this.shading; + parameters = parameters || {}; - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; + var size = parameters.size !== undefined ? parameters.size : 100; + var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4; - material.vertexColors = this.vertexColors; + var font = parameters.font !== undefined ? parameters.font : 'helvetiker'; + var weight = parameters.weight !== undefined ? parameters.weight : 'normal'; + var style = parameters.style !== undefined ? parameters.style : 'normal'; - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; + THREE.FontUtils.size = size; + THREE.FontUtils.divisions = curveSegments; - return material; + THREE.FontUtils.face = font; + THREE.FontUtils.weight = weight; + THREE.FontUtils.style = style; + + // Get a Font data json object + + var data = THREE.FontUtils.drawText( text ); + + var paths = data.paths; + var shapes = []; + + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + + } + + return shapes; }; -// File:src/materials/MeshPhongMaterial.js /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * emissive: <hex>, - * specular: <hex>, - * shininess: <float>, - * opacity: <float>, - * - * map: new THREE.Texture( <Image> ), - * - * lightMap: new THREE.Texture( <Image> ), - * - * bumpMap: new THREE.Texture( <Image> ), - * bumpScale: <float>, - * - * normalMap: new THREE.Texture( <Image> ), - * normalScale: <Vector2>, - * - * specularMap: new THREE.Texture( <Image> ), - * - * alphaMap: new THREE.Texture( <Image> ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: <float>, - * refractionRatio: <float>, - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float>, + * This code is a quick port of code written in C++ which was submitted to + * flipcode.com by John W. Ratcliff // July 22, 2000 + * See original code and more information here: + * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, + * ported to actionscript by Zevan Rosser + * www.actionsnippet.com * - * skinning: <bool>, - * morphTargets: <bool>, - * morphNormals: <bool>, + * ported to javascript by Joshua Koo + * http://www.lab4games.net/zz85/blog * - * fog: <bool> - * } */ -THREE.MeshPhongMaterial = function ( parameters ) { - THREE.Material.call( this ); +//( function ( namespace ) { - this.type = 'MeshPhongMaterial'; + var EPSILON = 0.0000000001; - this.color = new THREE.Color( 0xffffff ); // diffuse - this.emissive = new THREE.Color( 0x000000 ); - this.specular = new THREE.Color( 0x111111 ); - this.shininess = 30; + // takes in an contour array and returns - this.metal = false; +THREE.FontUtils.process = function ( contour, indices ) { - this.wrapAround = false; - this.wrapRGB = new THREE.Vector3( 1, 1, 1 ); + var n = contour.length; - this.map = null; + if ( n < 3 ) return null; - this.lightMap = null; + var result = [], + verts = [], + vertIndices = []; - this.bumpMap = null; - this.bumpScale = 1; + /* we want a counter-clockwise polygon in verts */ - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + var u, v, w; - this.specularMap = null; + if ( THREE.FontUtils.area( contour ) > 0.0 ) { - this.alphaMap = null; + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + } else { - this.fog = true; + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - this.shading = THREE.SmoothShading; + } - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + var nv = n; - this.vertexColors = THREE.NoColors; + /* remove nv - 2 vertices, creating 1 triangle every time */ - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + var count = 2 * nv; /* error detection */ - this.setValues( parameters ); + for ( v = nv - 1; nv > 2; ) { -}; + /* if we loop, it is probably a non-simple polygon */ -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; + if ( ( count -- ) <= 0 ) { -THREE.MeshPhongMaterial.prototype.clone = function () { + //** Triangulate: ERROR - probable bad polygon! - var material = new THREE.MeshPhongMaterial(); + //throw ( "Warning, unable to triangulate polygon!" ); + //return null; + // Sometimes warning is fine, especially polygons are triangulated in reverse. + THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' ); - THREE.Material.prototype.clone.call( this, material ); + if ( indices ) return vertIndices; + return result; - material.color.copy( this.color ); - material.emissive.copy( this.emissive ); - material.specular.copy( this.specular ); - material.shininess = this.shininess; + } - material.metal = this.metal; + /* three consecutive vertices in current polygon, <u,v,w> */ - material.wrapAround = this.wrapAround; - material.wrapRGB.copy( this.wrapRGB ); + u = v; if ( nv <= u ) u = 0; /* previous */ + v = u + 1; if ( nv <= v ) v = 0; /* new v */ + w = v + 1; if ( nv <= w ) w = 0; /* next */ - material.map = this.map; + if ( THREE.FontUtils.snip( contour, u, v, w, nv, verts ) ) { - material.lightMap = this.lightMap; + var a, b, c, s, t; - material.bumpMap = this.bumpMap; - material.bumpScale = this.bumpScale; + /* true names of the vertices */ - material.normalMap = this.normalMap; - material.normalScale.copy( this.normalScale ); + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - material.specularMap = this.specularMap; + /* output Triangle */ - material.alphaMap = this.alphaMap; + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); - material.envMap = this.envMap; - material.combine = this.combine; - material.reflectivity = this.reflectivity; - material.refractionRatio = this.refractionRatio; - material.fog = this.fog; + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - material.shading = this.shading; + /* remove v from the remaining polygon */ - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; - material.wireframeLinecap = this.wireframeLinecap; - material.wireframeLinejoin = this.wireframeLinejoin; + for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - material.vertexColors = this.vertexColors; + verts[ s ] = verts[ t ]; - material.skinning = this.skinning; - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; + } - return material; + nv --; -}; + /* reset error detection counter */ -// File:src/materials/MeshDepthMaterial.js + count = 2 * nv; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * opacity: <float>, - * - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float> - * } - */ + } -THREE.MeshDepthMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + if ( indices ) return vertIndices; + return result; - this.type = 'MeshDepthMaterial'; + }; - this.morphTargets = false; - this.wireframe = false; - this.wireframeLinewidth = 1; + // calculate area of the contour polygon - this.setValues( parameters ); +THREE.FontUtils.area = function ( contour ) { -}; + var n = contour.length; + var a = 0.0; -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { -THREE.MeshDepthMaterial.prototype.clone = function () { + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - var material = new THREE.MeshDepthMaterial(); + } - THREE.Material.prototype.clone.call( this, material ); + return a * 0.5; - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; + }; - return material; +THREE.FontUtils.snip = function ( contour, u, v, w, n, verts ) { -}; + var p; + var ax, ay, bx, by; + var cx, cy, px, py; -// File:src/materials/MeshNormalMaterial.js + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: <float>, - * - * shading: THREE.FlatShading, - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float> - * } - */ + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; -THREE.MeshNormalMaterial = function ( parameters ) { + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - THREE.Material.call( this, parameters ); + if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - this.type = 'MeshNormalMaterial'; + var aX, aY, bX, bY, cX, cY; + var apx, apy, bpx, bpy, cpx, cpy; + var cCROSSap, bCROSScp, aCROSSbp; - this.wireframe = false; - this.wireframeLinewidth = 1; + aX = cx - bx; aY = cy - by; + bX = ax - cx; bY = ay - cy; + cX = bx - ax; cY = by - ay; - this.morphTargets = false; + for ( p = 0; p < n; p ++ ) { - this.setValues( parameters ); + px = contour[ verts[ p ] ].x + py = contour[ verts[ p ] ].y -}; + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; -THREE.MeshNormalMaterial.prototype.clone = function () { + // see if p is inside triangle abc - var material = new THREE.MeshNormalMaterial(); + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - THREE.Material.prototype.clone.call( this, material ); + if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false; - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; + } - return material; + return true; -}; + }; -// File:src/materials/MeshFaceMaterial.js + +THREE.FontUtils.Triangulate = THREE.FontUtils.process; +THREE.FontUtils.Triangulate.area = THREE.FontUtils.area; + +//return namespace; + +//} )( THREE.FontUtils ); + +// To use the typeface.js face files, hook up the API +var _typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace }; +THREE.typeface_js = _typeface_js; + +// File:src/extras/audio/Audio.js /** * @author mrdoob / http://mrdoob.com/ */ -THREE.MeshFaceMaterial = function ( materials ) { - - this.uuid = THREE.Math.generateUUID(); +THREE.Audio = function ( listener ) { - this.type = 'MeshFaceMaterial'; - - this.materials = materials instanceof Array ? materials : []; + THREE.Object3D.call( this ); -}; + this.type = 'Audio'; -THREE.MeshFaceMaterial.prototype = { + this.context = listener.context; + this.source = this.context.createBufferSource(); + this.source.onended = this.onEnded.bind(this); - constructor: THREE.MeshFaceMaterial, + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - toJSON: function () { + this.panner = this.context.createPanner(); + this.panner.connect( this.gain ); - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + this.autoplay = false; - for ( var i = 0, l = this.materials.length; i < l; i ++ ) { + this.startTime = 0; + this.isPlaying = false; - output.materials.push( this.materials[ i ].toJSON() ); +}; - } +THREE.Audio.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Audio.prototype.constructor = THREE.Audio; - return output; +THREE.Audio.prototype.load = function ( file ) { - }, + var scope = this; - clone: function () { + var request = new XMLHttpRequest(); + request.open( 'GET', file, true ); + request.responseType = 'arraybuffer'; + request.onload = function ( e ) { - var material = new THREE.MeshFaceMaterial(); + scope.context.decodeAudioData( this.response, function ( buffer ) { - for ( var i = 0; i < this.materials.length; i ++ ) { + scope.source.buffer = buffer; - material.materials.push( this.materials[ i ].clone() ); + if( scope.autoplay ) scope.play(); - } + } ); - return material; + }; + request.send(); - } + return this; }; -// File:src/materials/PointCloudMaterial.js +THREE.Audio.prototype.play = function () { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * opacity: <float>, - * map: new THREE.Texture( <Image> ), - * - * size: <float>, - * sizeAttenuation: <bool>, - * - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * vertexColors: <bool>, - * - * fog: <bool> - * } - */ + if ( this.isPlaying === true ) { -THREE.PointCloudMaterial = function ( parameters ) { + THREE.warn( 'THREE.Audio: Audio is already playing.' ); + return; - THREE.Material.call( this ); + } - this.type = 'PointCloudMaterial'; + var source = this.context.createBufferSource(); - this.color = new THREE.Color( 0xffffff ); + source.buffer = this.source.buffer; + source.loop = this.source.loop; + source.onended = this.source.onended; + source.connect( this.panner ); + source.start( 0, this.startTime ); - this.map = null; + this.isPlaying = true; - this.size = 1; - this.sizeAttenuation = true; + this.source = source; - this.vertexColors = THREE.NoColors; +}; - this.fog = true; +THREE.Audio.prototype.pause = function () { - this.setValues( parameters ); + this.source.stop(); + this.startTime = this.context.currentTime; }; -THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial; - -THREE.PointCloudMaterial.prototype.clone = function () { - - var material = new THREE.PointCloudMaterial(); +THREE.Audio.prototype.stop = function () { - THREE.Material.prototype.clone.call( this, material ); + this.source.stop(); + this.startTime = 0; - material.color.copy( this.color ); +}; - material.map = this.map; +THREE.Audio.prototype.onEnded = function() { - material.size = this.size; - material.sizeAttenuation = this.sizeAttenuation; + this.isPlaying = false; - material.vertexColors = this.vertexColors; +}; - material.fog = this.fog; +THREE.Audio.prototype.setLoop = function ( value ) { - return material; + this.source.loop = value; }; -// backwards compatibility - -THREE.ParticleBasicMaterial = function ( parameters ) { +THREE.Audio.prototype.setRefDistance = function ( value ) { - THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' ); - return new THREE.PointCloudMaterial( parameters ); + this.panner.refDistance = value; }; -THREE.ParticleSystemMaterial = function ( parameters ) { +THREE.Audio.prototype.setRolloffFactor = function ( value ) { - THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' ); - return new THREE.PointCloudMaterial( parameters ); + this.panner.rolloffFactor = value; }; -// File:src/materials/ShaderMaterial.js - -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, - * - * fragmentShader: <string>, - * vertexShader: <string>, - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * wireframe: <boolean>, - * wireframeLinewidth: <float>, - * - * lights: <bool>, - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: <bool>, - * morphTargets: <bool>, - * morphNormals: <bool>, - * - * fog: <bool> - * } - */ +THREE.Audio.prototype.setVolume = function ( value ) { -THREE.ShaderMaterial = function ( parameters ) { + this.gain.gain.value = value; - THREE.Material.call( this ); +}; - this.type = 'ShaderMaterial'; +THREE.Audio.prototype.updateMatrixWorld = ( function () { - this.defines = {}; - this.uniforms = {}; - this.attributes = null; + var position = new THREE.Vector3(); - this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; - this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + return function ( force ) { - this.shading = THREE.SmoothShading; + THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); - this.linewidth = 1; + position.setFromMatrixPosition( this.matrixWorld ); - this.wireframe = false; - this.wireframeLinewidth = 1; + this.panner.setPosition( position.x, position.y, position.z ); - this.fog = false; // set to use scene fog + }; - this.lights = false; // set to use scene lights +} )(); - this.vertexColors = THREE.NoColors; // set to use "color" attribute stream +// File:src/extras/audio/AudioListener.js - this.skinning = false; // set to use skinning attribute streams +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals +THREE.AudioListener = function () { - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + THREE.Object3D.call( this ); - this.index0AttributeName = undefined; + this.type = 'AudioListener'; - this.setValues( parameters ); + this.context = new ( window.AudioContext || window.webkitAudioContext )(); }; -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; - -THREE.ShaderMaterial.prototype.clone = function () { - - var material = new THREE.ShaderMaterial(); +THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype ); +THREE.AudioListener.prototype.constructor = THREE.AudioListener; - THREE.Material.prototype.clone.call( this, material ); +THREE.AudioListener.prototype.updateMatrixWorld = ( function () { - material.fragmentShader = this.fragmentShader; - material.vertexShader = this.vertexShader; + var position = new THREE.Vector3(); + var quaternion = new THREE.Quaternion(); + var scale = new THREE.Vector3(); - material.uniforms = THREE.UniformsUtils.clone( this.uniforms ); + var orientation = new THREE.Vector3(); + var velocity = new THREE.Vector3(); - material.attributes = this.attributes; - material.defines = this.defines; + var positionPrev = new THREE.Vector3(); - material.shading = this.shading; + return function ( force ) { - material.wireframe = this.wireframe; - material.wireframeLinewidth = this.wireframeLinewidth; + THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); - material.fog = this.fog; + var listener = this.context.listener; + var up = this.up; - material.lights = this.lights; + this.matrixWorld.decompose( position, quaternion, scale ); - material.vertexColors = this.vertexColors; + orientation.set( 0, 0, -1 ).applyQuaternion( quaternion ); + velocity.subVectors( position, positionPrev ); - material.skinning = this.skinning; + listener.setPosition( position.x, position.y, position.z ); + listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); + listener.setVelocity( velocity.x, velocity.y, velocity.z ); - material.morphTargets = this.morphTargets; - material.morphNormals = this.morphNormals; + positionPrev.copy( position ); - return material; + }; -}; +} )(); -// File:src/materials/RawShaderMaterial.js +// File:src/extras/core/Curve.js /** - * @author mrdoob / http://mrdoob.com/ - */ - -THREE.RawShaderMaterial = function ( parameters ) { + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object + * + * Some common of Curve methods + * .getPoint(t), getTangent(t) + * .getPointAt(u), getTagentAt(u) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following classes subclasses THREE.Curve: + * + * -- 2d classes -- + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.CubicBezierCurve + * THREE.SplineCurve + * THREE.ArcCurve + * THREE.EllipseCurve + * + * -- 3d classes -- + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * THREE.CubicBezierCurve3 + * THREE.SplineCurve3 + * THREE.ClosedSplineCurve3 + * + * A series of curves can be represented as a THREE.CurvePath + * + **/ - THREE.ShaderMaterial.call( this, parameters ); +/************************************************************** + * Abstract Curve base class + **************************************************************/ - this.type = 'RawShaderMaterial'; +THREE.Curve = function () { }; -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; +// Virtual base class method to overwrite and implement in subclasses +// - t [0 .. 1] -THREE.RawShaderMaterial.prototype.clone = function () { +THREE.Curve.prototype.getPoint = function ( t ) { - var material = new THREE.RawShaderMaterial(); + THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); + return null; - THREE.ShaderMaterial.prototype.clone.call( this, material ); +}; - return material; +// Get point at relative position in curve according to arc length +// - u [0 .. 1] -}; +THREE.Curve.prototype.getPointAt = function ( u ) { -// File:src/materials/SpriteMaterial.js + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: <hex>, - * opacity: <float>, - * map: new THREE.Texture( <Image> ), - * - * blending: THREE.NormalBlending, - * depthTest: <bool>, - * depthWrite: <bool>, - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2(), - * - * fog: <bool> - * } - */ +}; -THREE.SpriteMaterial = function ( parameters ) { +// Get sequence of points using getPoint( t ) - THREE.Material.call( this ); +THREE.Curve.prototype.getPoints = function ( divisions ) { - this.type = 'SpriteMaterial'; + if ( ! divisions ) divisions = 5; - this.color = new THREE.Color( 0xffffff ); - this.map = null; + var d, pts = []; - this.rotation = 0; + for ( d = 0; d <= divisions; d ++ ) { - this.fog = false; + pts.push( this.getPoint( d / divisions ) ); - // set parameters + } - this.setValues( parameters ); + return pts; }; -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; +// Get sequence of points using getPointAt( u ) -THREE.SpriteMaterial.prototype.clone = function () { +THREE.Curve.prototype.getSpacedPoints = function ( divisions ) { - var material = new THREE.SpriteMaterial(); + if ( ! divisions ) divisions = 5; - THREE.Material.prototype.clone.call( this, material ); + var d, pts = []; - material.color.copy( this.color ); - material.map = this.map; + for ( d = 0; d <= divisions; d ++ ) { - material.rotation = this.rotation; + pts.push( this.getPointAt( d / divisions ) ); - material.fog = this.fog; + } - return material; + return pts; }; -// File:src/textures/Texture.js +// Get total curve arc length -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ +THREE.Curve.prototype.getLength = function () { -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); +}; - this.uuid = THREE.Math.generateUUID(); +// Get list of cumulative segment lengths - this.name = ''; - this.sourceFile = ''; +THREE.Curve.prototype.getLengths = function ( divisions ) { - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; - this.mipmaps = []; + if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200; - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length == divisions + 1 ) + && ! this.needsUpdate) { - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + } - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + this.needsUpdate = false; - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + cache.push( 0 ); - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + for ( p = 1; p <= divisions; p ++ ) { - this._needsUpdate = false; - this.onUpdate = null; + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - var _this = this; - this.__defineGetter__("needsUpdate", function(){ - return _this._needsUpdate; - }); + } - this.__defineSetter__("needsUpdate", function(value){ + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - if ( value === true ) _this.update(); - _this._needsUpdate = value; - }); }; -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; -THREE.Texture.prototype = { +THREE.Curve.prototype.updateArcLengths = function() { + this.needsUpdate = true; + this.getLengths(); +}; - constructor: THREE.Texture, +// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance - clone: function ( texture ) { +THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { - if ( texture === undefined ) texture = new THREE.Texture(); + var arcLengths = this.getLengths(); - texture.image = this.image; - texture.mipmaps = this.mipmaps.slice( 0 ); + var i = 0, il = arcLengths.length; - texture.mapping = this.mapping; + var targetArcLength; // The targeted u distance value to get - texture.wrapS = this.wrapS; - texture.wrapT = this.wrapT; + if ( distance ) { - texture.magFilter = this.magFilter; - texture.minFilter = this.minFilter; + targetArcLength = distance; - texture.anisotropy = this.anisotropy; + } else { - texture.format = this.format; - texture.type = this.type; + targetArcLength = u * arcLengths[ il - 1 ]; - texture.offset.copy( this.offset ); - texture.repeat.copy( this.repeat ); + } - texture.generateMipmaps = this.generateMipmaps; - texture.premultiplyAlpha = this.premultiplyAlpha; - texture.flipY = this.flipY; - texture.unpackAlignment = this.unpackAlignment; + //var time = Date.now(); - return texture; + // binary search for the index with largest value smaller than target u distance - }, + var low = 0, high = il - 1, comparison; - update: function () { + while ( low <= high ) { - this.dispatchEvent( { type: 'update' } ); + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - }, + comparison = arcLengths[ i ] - targetArcLength; - dispose: function () { + if ( comparison < 0 ) { - this.dispatchEvent( { type: 'dispose' } ); + low = i + 1; - } + } else if ( comparison > 0 ) { -}; + high = i - 1; -THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); + } else { -THREE.TextureIdCount = 0; + high = i; + break; -// File:src/textures/CubeTexture.js + // DONE -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + } - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; - - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + i = high; - this.images = images; + //console.log('b' , i, low, high, Date.now()- time); -}; + if ( arcLengths[ i ] == targetArcLength ) { -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; + var t = i / ( il - 1 ); + return t; -THREE.CubeTexture.clone = function ( texture ) { + } - if ( texture === undefined ) texture = new THREE.CubeTexture(); + // we could get finer grain at lengths, or use simple interpolatation between two points - THREE.Texture.prototype.clone.call( this, texture ); + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - texture.images = this.images; + var segmentLength = lengthAfter - lengthBefore; - return texture; + // determine where we are between the 'before' and 'after' points -}; + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; -// File:src/textures/CompressedTexture.js + // add that fractional amount to t -/** - * @author alteredq / http://alteredqualia.com/ - */ + var t = ( i + segmentFraction ) / ( il - 1 ); -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + return t; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); +}; - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; +// Returns a unit vector tangent at t +// 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 - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) +THREE.Curve.prototype.getTangent = function( t ) { - this.flipY = false; + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + // Capping in case of danger - this.generateMipmaps = false; + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; -}; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; + var vec = pt2.clone().sub(pt1); + return vec.normalize(); -THREE.CompressedTexture.prototype.clone = function () { +}; - var texture = new THREE.CompressedTexture(); - THREE.Texture.prototype.clone.call( this, texture ); +THREE.Curve.prototype.getTangentAt = function ( u ) { - return texture; + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); }; -// File:src/textures/DataTexture.js - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.image = { data: data, width: width, height: height }; -}; -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; +/************************************************************** + * Utils + **************************************************************/ -THREE.DataTexture.prototype.clone = function () { +THREE.Curve.Utils = { - var texture = new THREE.DataTexture(); + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - THREE.Texture.prototype.clone.call( this, texture ); + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - return texture; + }, -}; + // Puay Bing, thanks for helping with this derivative! -// File:src/textures/VideoTexture.js + tangentCubicBezier: function (t, p0, p1, p2, p3 ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return - 3 * p0 * (1 - t) * (1 - t) + + 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) + + 6 * t * p2 * (1 - t) - 3 * t * t * p2 + + 3 * t * t * p3; -THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + }, - THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + tangentSpline: function ( t, p0, p1, p2, p3 ) { - this.generateMipmaps = false; + // To check if my formulas are correct - var scope = this; - - var update = function () { + var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 + var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t + var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 + var h11 = 3 * t * t - 2 * t; // t3 − t2 - requestAnimationFrame( update ); + return h00 + h10 + h01 + h11; - if ( video.readyState === video.HAVE_ENOUGH_DATA ) { + }, - scope.needsUpdate = true; + // Catmull-Rom - } + interpolate: function( p0, p1, p2, p3, t ) { - }; + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - update(); + } }; -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; -// File:src/objects/Group.js +// TODO: Transformation for Curves? -/** - * @author mrdoob / http://mrdoob.com/ - */ +/************************************************************** + * 3D Curves + **************************************************************/ -THREE.Group = function () { +// A Factory method for creating new curve subclasses - THREE.Object3D.call( this ); +THREE.Curve.create = function ( constructor, getPointFunc ) { - this.type = 'Group'; + constructor.prototype = Object.create( THREE.Curve.prototype ); + constructor.prototype.constructor = constructor; + constructor.prototype.getPoint = getPointFunc; -}; + return constructor; -THREE.Group.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Group.prototype.constructor = THREE.Group; +}; -// File:src/objects/PointCloud.js +// File:src/extras/core/CurvePath.js /** - * @author alteredq / http://alteredqualia.com/ - */ + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ -THREE.PointCloud = function ( geometry, material ) { +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - THREE.Object3D.call( this ); +THREE.CurvePath = function () { - this.type = 'PointCloud'; + this.curves = []; + this.bends = []; + + this.autoClose = false; // Automatically closes the path +}; - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } ); +THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype ); +THREE.CurvePath.prototype.constructor = THREE.CurvePath; + +THREE.CurvePath.prototype.add = function ( curve ) { + + this.curves.push( curve ); }; -THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype ); -THREE.PointCloud.prototype.constructor = THREE.PointCloud; +THREE.CurvePath.prototype.checkConnection = function() { + // TODO + // If the ending of curve is not connected to the starting + // or the next curve, then, this is not a real path +}; -THREE.PointCloud.prototype.raycast = ( function () { +THREE.CurvePath.prototype.closePath = function() { + // TODO Test + // and verify for vector3 (needs to implement equals) + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[0].getPoint(0); + var endPoint = this.curves[this.curves.length - 1].getPoint(1); + + if (! startPoint.equals(endPoint)) { + this.curves.push( new THREE.LineCurve(endPoint, startPoint) ); + } + +}; - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); +// To get accurate point with reference to +// entire path distance at time t, +// following has to be done: - return function ( raycaster, intersects ) { +// 1. Length of each sub path have to be known +// 2. Locate and identify type of curve +// 3. Get t for the curve +// 4. Return curve.getPointAt(t') - var object = this; - var geometry = object.geometry; - var threshold = raycaster.params.PointCloud.threshold; +THREE.CurvePath.prototype.getPoint = function( t ) { - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0, diff, curve; - if ( geometry.boundingBox !== null ) { + // To think about boundaries points. - if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + while ( i < curveLengths.length ) { - return; + if ( curveLengths[ i ] >= d ) { - } + diff = curveLengths[ i ] - d; + curve = this.curves[ i ]; + + var u = 1 - diff / curve.getLength(); + + return curve.getPointAt( u ); } - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var position = new THREE.Vector3(); + i ++; - var testPoint = function ( point, index ) { + } - var rayPointDistance = ray.distanceToPoint( point ); + return null; - if ( rayPointDistance < localThreshold ) { + // loop where sum != 0, sum > d , sum+1 <d - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( object.matrixWorld ); +}; - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); +/* +THREE.CurvePath.prototype.getTangent = function( t ) { +};*/ - intersects.push( { - distance: distance, - distanceToRay: rayPointDistance, - point: intersectPoint.clone(), - index: index, - face: null, - object: object +// We cannot use the default THREE.Curve getPoint() with getLength() because in +// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath +// getPoint() depends on getLength - } ); +THREE.CurvePath.prototype.getLength = function() { - } + var lens = this.getCurveLengths(); + return lens[ lens.length - 1 ]; - }; +}; - if ( geometry instanceof THREE.BufferGeometry ) { +// Compute lengths and cache them +// We cannot overwrite getLengths() because UtoT mapping uses it. - var attributes = geometry.attributes; - var positions = attributes.position.array; +THREE.CurvePath.prototype.getCurveLengths = function() { - if ( attributes.index !== undefined ) { + // We use cache values if curves and cache array are same length - var indices = attributes.index.array; - var offsets = geometry.offsets; + if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) { - if ( offsets.length === 0 ) { + return this.cacheLengths; - var offset = { - start: 0, - count: indices.length, - index: 0 - }; + }; - offsets = [ offset ]; + // Get length of subsurve + // Push sums into cached array - } + var lengths = [], sums = 0; + var i, il = this.curves.length; - for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) { + for ( i = 0; i < il; i ++ ) { - var start = offsets[ oi ].start; - var count = offsets[ oi ].count; - var index = offsets[ oi ].index; + sums += this.curves[ i ].getLength(); + lengths.push( sums ); - for ( var i = start, il = start + count; i < il; i ++ ) { + } - var a = index + indices[ i ]; + this.cacheLengths = lengths; - position.fromArray( positions, a * 3 ); + return lengths; - testPoint( position, a ); +}; - } - } - } else { +// Returns min and max coordinates - var pointCount = positions.length / 3; +THREE.CurvePath.prototype.getBoundingBox = function () { - for ( var i = 0; i < pointCount; i ++ ) { + var points = this.getPoints(); - position.set( - positions[ 3 * i ], - positions[ 3 * i + 1 ], - positions[ 3 * i + 2 ] - ); + var maxX, maxY, maxZ; + var minX, minY, minZ; - testPoint( position, i ); + maxX = maxY = Number.NEGATIVE_INFINITY; + minX = minY = Number.POSITIVE_INFINITY; - } + var p, i, il, sum; - } + var v3 = points[0] instanceof THREE.Vector3; - } else { + sum = v3 ? new THREE.Vector3() : new THREE.Vector2(); - var vertices = this.geometry.vertices; + for ( i = 0, il = points.length; i < il; i ++ ) { - for ( var i = 0; i < vertices.length; i ++ ) { + p = points[ i ]; - testPoint( vertices[ i ], i ); + if ( p.x > maxX ) maxX = p.x; + else if ( p.x < minX ) minX = p.x; - } + if ( p.y > maxY ) maxY = p.y; + else if ( p.y < minY ) minY = p.y; - } + if ( v3 ) { - }; + if ( p.z > maxZ ) maxZ = p.z; + else if ( p.z < minZ ) minZ = p.z; -}() ); + } -THREE.PointCloud.prototype.clone = function ( object ) { + sum.add( p ); - if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material ); + } - THREE.Object3D.prototype.clone.call( this, object ); + var ret = { - return object; + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY -}; + }; -// Backwards compatibility + if ( v3 ) { -THREE.ParticleSystem = function ( geometry, material ) { + ret.maxZ = maxZ; + ret.minZ = minZ; - THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' ); - return new THREE.PointCloud( geometry, material ); + } + + return ret; }; -// File:src/objects/Line.js +/************************************************************** + * Create Geometries Helpers + **************************************************************/ -/** - * @author mrdoob / http://mrdoob.com/ - */ +/// Generate geometry from path points (for Line or Points objects) -THREE.Line = function ( geometry, material, mode ) { +THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) { - THREE.Object3D.call( this ); + var pts = this.getPoints( divisions, true ); + return this.createGeometry( pts ); - this.type = 'Line'; +}; - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); +// Generate geometry from equidistance sampling along the path - this.mode = mode !== undefined ? mode : THREE.LineStrip; +THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) { + + var pts = this.getSpacedPoints( divisions, true ); + return this.createGeometry( pts ); }; -THREE.LineStrip = 0; -THREE.LinePieces = 1; +THREE.CurvePath.prototype.createGeometry = function( points ) { -THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Line.prototype.constructor = THREE.Line; + var geometry = new THREE.Geometry(); -THREE.Line.prototype.raycast = ( function () { + for ( var i = 0; i < points.length; i ++ ) { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) ); - return function ( raycaster, intersects ) { + } - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + return geometry; - var geometry = this.geometry; +}; - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - // Checking boundingSphere distance to ray +/************************************************************** + * Bend / Wrap Helper Methods + **************************************************************/ - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( this.matrixWorld ); +// Wrap path / Bend modifiers? - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { +THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) { - return; + this.bends.push( bendpath ); - } +}; - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); +THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) { - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this.mode === THREE.LineStrip ? 1 : 2; + var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints + var i, il; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( ! bends ) { - var attributes = geometry.attributes; + bends = this.bends; - if ( attributes.index !== undefined ) { + } - var indices = attributes.index.array; - var positions = attributes.position.array; - var offsets = geometry.offsets; + for ( i = 0, il = bends.length; i < il; i ++ ) { - if ( offsets.length === 0 ) { + oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - offsets = [ { start: 0, count: indices.length, index: 0 } ]; + } - } + return oldPts; - for ( var oi = 0; oi < offsets.length; oi ++) { +}; - var start = offsets[ oi ].start; - var count = offsets[ oi ].count; - var index = offsets[ oi ].index; +THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) { - for ( var i = start; i < start + count - 1; i += step ) { + var oldPts = this.getSpacedPoints( segments ); - var a = index + indices[ i ]; - var b = index + indices[ i + 1 ]; + var i, il; - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + if ( ! bends ) { - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + bends = this.bends; - if ( distSq > precisionSq ) continue; + } - var distance = ray.origin.distanceTo( interRay ); + for ( i = 0, il = bends.length; i < il; i ++ ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + oldPts = this.getWrapPoints( oldPts, bends[ i ] ); - intersects.push( { + } - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - offsetIndex: oi, - face: null, - faceIndex: null, - object: this + return oldPts; - } ); +}; - } +// This returns getPoints() bend/wrapped around the contour of a path. +// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html - } +THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) { - } else { + var bounds = this.getBoundingBox(); - var positions = attributes.position.array; + var i, il, p, oldX, oldY, xNorm; - for ( var i = 0; i < positions.length / 3 - 1; i += step ) { + for ( i = 0, il = oldPts.length; i < il; i ++ ) { - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + p = oldPts[ i ]; - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + oldX = p.x; + oldY = p.y; - if ( distSq > precisionSq ) continue; + xNorm = oldX / bounds.maxX; - var distance = ray.origin.distanceTo( interRay ); + // If using actual distance, for length > path, requires line extrusions + //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance - if ( distance < raycaster.near || distance > raycaster.far ) continue; + xNorm = path.getUtoTmapping( xNorm, oldX ); - intersects.push( { + // check for out of bounds? - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + var pathPt = path.getPoint( xNorm ); + var normal = path.getTangent( xNorm ); + normal.set( - normal.y, normal.x ).multiplyScalar( oldY ); - } ); + p.x = pathPt.x + normal.x; + p.y = pathPt.y + normal.y; - } + } - } + return oldPts; - } else if ( geometry instanceof THREE.Geometry ) { +}; - var vertices = geometry.vertices; - var nbVertices = vertices.length; - for ( var i = 0; i < nbVertices - 1; i += step ) { +// File:src/extras/core/Gyroscope.js - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - if ( distSq > precisionSq ) continue; +THREE.Gyroscope = function () { - var distance = ray.origin.distanceTo( interRay ); + THREE.Object3D.call( this ); - if ( distance < raycaster.near || distance > raycaster.far ) continue; +}; - intersects.push( { +THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); +THREE.Gyroscope.prototype.constructor = THREE.Gyroscope; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this +THREE.Gyroscope.prototype.updateMatrixWorld = function () { - } ); + var translationObject = new THREE.Vector3(); + var quaternionObject = new THREE.Quaternion(); + var scaleObject = new THREE.Vector3(); - } + var translationWorld = new THREE.Vector3(); + var quaternionWorld = new THREE.Quaternion(); + var scaleWorld = new THREE.Vector3(); - } + return function ( force ) { - }; + this.matrixAutoUpdate && this.updateMatrix(); -}() ); + // update matrixWorld -THREE.Line.prototype.clone = function ( object ) { + if ( this.matrixWorldNeedsUpdate || force ) { - if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode ); + if ( this.parent ) { - THREE.Object3D.prototype.clone.call( this, object ); + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - return object; + this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld ); + this.matrix.decompose( translationObject, quaternionObject, scaleObject ); -}; + this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld ); -// File:src/objects/Mesh.js -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + } else { -THREE.Mesh = function ( geometry, material ) { + this.matrixWorld.copy( this.matrix ); - THREE.Object3D.call( this ); + } - this.type = 'Mesh'; - - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - this.updateMorphTargets(); + this.matrixWorldNeedsUpdate = false; -}; + force = true; -THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Mesh.prototype.constructor = THREE.Mesh; + } -THREE.Mesh.prototype.updateMorphTargets = function () { + // update children - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - this.morphTargetBase = - 1; - this.morphTargetForcedOrder = []; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + this.children[ i ].updateMatrixWorld( force ); - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + } - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + }; + +}(); - } +// File:src/extras/core/Path.js - } +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ -}; +THREE.Path = function ( points ) { -THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) { + THREE.CurvePath.call(this); - if ( this.morphTargetDictionary[ name ] !== undefined ) { + this.actions = []; - return this.morphTargetDictionary[ name ]; + if ( points ) { + + this.fromPoints( points ); } - THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); +}; - return 0; +THREE.Path.prototype = Object.create( THREE.CurvePath.prototype ); +THREE.Path.prototype.constructor = THREE.Path; +THREE.PathActions = { + + MOVE_TO: 'moveTo', + LINE_TO: 'lineTo', + QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve + BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve + CSPLINE_THRU: 'splineThru', // Catmull-rom spline + ARC: 'arc', // Circle + ELLIPSE: 'ellipse' }; +// TODO Clean up PATH API -THREE.Mesh.prototype.raycast = ( function () { +// Create path using straight lines to connect all points +// - vectors: array of Vector2 - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); +THREE.Path.prototype.fromPoints = function ( vectors ) { - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - return function ( raycaster, intersects ) { + for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { - var geometry = this.geometry; + this.lineTo( vectors[ v ].x, vectors[ v ].y ); - // Checking boundingSphere distance to ray + }; - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); +}; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( this.matrixWorld ); +// startPath() endPath()? - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { +THREE.Path.prototype.moveTo = function ( x, y ) { - return; + var args = Array.prototype.slice.call( arguments ); + this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } ); - } +}; - // Check boundingBox before continuing +THREE.Path.prototype.lineTo = function ( x, y ) { - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + var args = Array.prototype.slice.call( arguments ); - if ( geometry.boundingBox !== null ) { + var lastargs = this.actions[ this.actions.length - 1 ].args; - if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - return; + var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) ); + this.curves.push( curve ); - } + this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } ); - } +}; - if ( geometry instanceof THREE.BufferGeometry ) { +THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { - var material = this.material; + var args = Array.prototype.slice.call( arguments ); - if ( material === undefined ) return; + var lastargs = this.actions[ this.actions.length - 1 ].args; - var attributes = geometry.attributes; + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - var a, b, c; - var precision = raycaster.precision; + var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), + new THREE.Vector2( aCPx, aCPy ), + new THREE.Vector2( aX, aY ) ); + this.curves.push( curve ); - if ( attributes.index !== undefined ) { + this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); - var indices = attributes.index.array; - var positions = attributes.position.array; - var offsets = geometry.offsets; +}; - if ( offsets.length === 0 ) { +THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, + aCP2x, aCP2y, + aX, aY ) { - offsets = [ { start: 0, count: indices.length, index: 0 } ]; + var args = Array.prototype.slice.call( arguments ); - } + var lastargs = this.actions[ this.actions.length - 1 ].args; - for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) { + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - var start = offsets[ oi ].start; - var count = offsets[ oi ].count; - var index = offsets[ oi ].index; + var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ), + new THREE.Vector2( aCP1x, aCP1y ), + new THREE.Vector2( aCP2x, aCP2y ), + new THREE.Vector2( aX, aY ) ); + this.curves.push( curve ); - for ( var i = start, il = start + count; i < il; i += 3 ) { + this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } ); - a = index + indices[ i ]; - b = index + indices[ i + 1 ]; - c = index + indices[ i + 2 ]; +}; - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); +THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { - if ( material.side === THREE.BackSide ) { + var args = Array.prototype.slice.call( arguments ); + var lastargs = this.actions[ this.actions.length - 1 ].args; - var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; +//--- + var npts = [ new THREE.Vector2( x0, y0 ) ]; + Array.prototype.push.apply( npts, pts ); - } else { + var curve = new THREE.SplineCurve( npts ); + this.curves.push( curve ); - var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); + this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } ); - } +}; - if ( intersectionPoint === null ) continue; +// FUTURE: Change the API or follow canvas API? - intersectionPoint.applyMatrix4( this.matrixWorld ); +THREE.Path.prototype.arc = function ( aX, aY, aRadius, + aStartAngle, aEndAngle, aClockwise ) { - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); + var lastargs = this.actions[ this.actions.length - 1].args; + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; + this.absarc(aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - intersects.push( { + }; - distance: distance, - point: intersectionPoint, - face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), - faceIndex: null, - object: this + THREE.Path.prototype.absarc = function ( aX, aY, aRadius, + aStartAngle, aEndAngle, aClockwise ) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + }; - } ); +THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ) { - } + var lastargs = this.actions[ this.actions.length - 1].args; + var x0 = lastargs[ lastargs.length - 2 ]; + var y0 = lastargs[ lastargs.length - 1 ]; - } + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ); - } else { + }; - var positions = attributes.position.array; - for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) { +THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ) { - a = i; - b = i + 1; - c = i + 2; + var args = Array.prototype.slice.call( arguments ); + var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, + aStartAngle, aEndAngle, aClockwise ); + this.curves.push( curve ); - vA.fromArray( positions, j ); - vB.fromArray( positions, j + 3 ); - vC.fromArray( positions, j + 6 ); + var lastPoint = curve.getPoint(1); + args.push(lastPoint.x); + args.push(lastPoint.y); - if ( material.side === THREE.BackSide ) { + this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } ); - var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true ); + }; - } else { +THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { - var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide ); + if ( ! divisions ) divisions = 40; - } + var points = []; - if ( intersectionPoint === null ) continue; + for ( var i = 0; i < divisions; i ++ ) { - intersectionPoint.applyMatrix4( this.matrixWorld ); + points.push( this.getPoint( i / divisions ) ); - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); + //if( !this.getPoint( i / divisions ) ) throw "DIE"; - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; + } - intersects.push( { + // if ( closedPath ) { + // + // points.push( points[ 0 ] ); + // + // } - distance: distance, - point: intersectionPoint, - face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), - faceIndex: null, - object: this + return points; - } ); +}; - } +/* Return an array of vectors based on contour of the path */ - } +THREE.Path.prototype.getPoints = function( divisions, closedPath ) { - } else if ( geometry instanceof THREE.Geometry ) { + if (this.useSpacedPoints) { + console.log('tata'); + return this.getSpacedPoints( divisions, closedPath ); + } - var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial; - var objectMaterials = isFaceMaterial === true ? this.material.materials : null; + divisions = divisions || 12; - var a, b, c; - var precision = raycaster.precision; + var points = []; - var vertices = geometry.vertices; + var i, il, item, action, args; + var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0, + laste, j, + t, tx, ty; - for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { + for ( i = 0, il = this.actions.length; i < il; i ++ ) { - var face = geometry.faces[ f ]; + item = this.actions[ i ]; - var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material; + action = item.action; + args = item.args; - if ( material === undefined ) continue; + switch ( action ) { - a = vertices[ face.a ]; - b = vertices[ face.b ]; - c = vertices[ face.c ]; + case THREE.PathActions.MOVE_TO: - if ( material.morphTargets === true ) { + points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + break; - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + case THREE.PathActions.LINE_TO: - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); - var influence = morphInfluences[ t ]; + break; - if ( influence === 0 ) continue; + case THREE.PathActions.QUADRATIC_CURVE_TO: - var targets = morphTargets[ t ].vertices; + cpx = args[ 2 ]; + cpy = args[ 3 ]; - vA.x += ( targets[ face.a ].x - a.x ) * influence; - vA.y += ( targets[ face.a ].y - a.y ) * influence; - vA.z += ( targets[ face.a ].z - a.z ) * influence; + cpx1 = args[ 0 ]; + cpy1 = args[ 1 ]; - vB.x += ( targets[ face.b ].x - b.x ) * influence; - vB.y += ( targets[ face.b ].y - b.y ) * influence; - vB.z += ( targets[ face.b ].z - b.z ) * influence; + if ( points.length > 0 ) { - vC.x += ( targets[ face.c ].x - c.x ) * influence; - vC.y += ( targets[ face.c ].y - c.y ) * influence; - vC.z += ( targets[ face.c ].z - c.z ) * influence; + laste = points[ points.length - 1 ]; - } + cpx0 = laste.x; + cpy0 = laste.y; - vA.add( a ); - vB.add( b ); - vC.add( c ); + } else { - a = vA; - b = vB; - c = vC; + laste = this.actions[ i - 1 ].args; - } + cpx0 = laste[ laste.length - 2 ]; + cpy0 = laste[ laste.length - 1 ]; - if ( material.side === THREE.BackSide ) { + } - var intersectionPoint = ray.intersectTriangle( c, b, a, true ); + for ( j = 1; j <= divisions; j ++ ) { - } else { + t = j / divisions; - var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide ); + tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); + ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - } + points.push( new THREE.Vector2( tx, ty ) ); - if ( intersectionPoint === null ) continue; + } - intersectionPoint.applyMatrix4( this.matrixWorld ); + break; - var distance = raycaster.ray.origin.distanceTo( intersectionPoint ); + case THREE.PathActions.BEZIER_CURVE_TO: - if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue; + cpx = args[ 4 ]; + cpy = args[ 5 ]; - intersects.push( { + cpx1 = args[ 0 ]; + cpy1 = args[ 1 ]; - distance: distance, - point: intersectionPoint, - face: face, - faceIndex: f, - object: this + cpx2 = args[ 2 ]; + cpy2 = args[ 3 ]; - } ); + if ( points.length > 0 ) { - } + laste = points[ points.length - 1 ]; - } + cpx0 = laste.x; + cpy0 = laste.y; - }; + } else { -}() ); + laste = this.actions[ i - 1 ].args; -THREE.Mesh.prototype.clone = function ( object, recursive ) { + cpx0 = laste[ laste.length - 2 ]; + cpy0 = laste[ laste.length - 1 ]; - if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material ); + } - THREE.Object3D.prototype.clone.call( this, object, recursive ); - return object; + for ( j = 1; j <= divisions; j ++ ) { -}; + t = j / divisions; -// File:src/objects/Bone.js + tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); + ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + points.push( new THREE.Vector2( tx, ty ) ); -THREE.Bone = function ( skin ) { + } - THREE.Object3D.call( this ); + break; - this.type = 'Bone'; + case THREE.PathActions.CSPLINE_THRU: - this.skin = skin; + laste = this.actions[ i - 1 ].args; -}; + var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] ); + var spts = [ last ]; -THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Bone.prototype.constructor = THREE.Bone; + var n = divisions * args[ 0 ].length; -// File:src/objects/Skeleton.js + spts = spts.concat( args[ 0 ] ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + var spline = new THREE.SplineCurve( spts ); -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { + for ( j = 1; j <= n; j ++ ) { - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + points.push( spline.getPointAt( j / n ) ) ; - this.identityMatrix = new THREE.Matrix4(); + } - // copy the bone array + break; - bones = bones || []; + case THREE.PathActions.ARC: - this.bones = bones.slice( 0 ); + var aX = args[ 0 ], aY = args[ 1 ], + aRadius = args[ 2 ], + aStartAngle = args[ 3 ], aEndAngle = args[ 4 ], + aClockwise = !! args[ 5 ]; - // create a bone texture or an array of floats + var deltaAngle = aEndAngle - aStartAngle; + var angle; + var tdivisions = divisions * 2; - if ( this.useVertexTexture ) { + for ( j = 1; j <= tdivisions; j ++ ) { - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones (8 * 8 / 4) - // 16x16 pixel texture max 64 bones (16 * 16 / 4) - // 32x32 pixel texture max 256 bones (32 * 32 / 4) - // 64x64 pixel texture max 1024 bones (64 * 64 / 4) + t = j / tdivisions; - var size; + if ( ! aClockwise ) { - if ( this.bones.length > 256 ) - size = 64; - else if ( this.bones.length > 64 ) - size = 32; - else if ( this.bones.length > 16 ) - size = 16; - else - size = 8; + t = 1 - t; - this.boneTextureWidth = size; - this.boneTextureHeight = size; + } - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); - this.boneTexture.minFilter = THREE.NearestFilter; - this.boneTexture.magFilter = THREE.NearestFilter; - this.boneTexture.generateMipmaps = false; - this.boneTexture.flipY = false; + angle = aStartAngle + t * deltaAngle; - } else { + tx = aX + aRadius * Math.cos( angle ); + ty = aY + aRadius * Math.sin( angle ); - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); - } + points.push( new THREE.Vector2( tx, ty ) ); - // use the supplied bone inverses or calculate the inverses + } - if ( boneInverses === undefined ) { + //console.log(points); - this.calculateInverses(); + break; + + case THREE.PathActions.ELLIPSE: - } else { + var aX = args[ 0 ], aY = args[ 1 ], + xRadius = args[ 2 ], + yRadius = args[ 3 ], + aStartAngle = args[ 4 ], aEndAngle = args[ 5 ], + aClockwise = !! args[ 6 ]; - if ( this.bones.length === boneInverses.length ) { - this.boneInverses = boneInverses.slice( 0 ); + var deltaAngle = aEndAngle - aStartAngle; + var angle; + var tdivisions = divisions * 2; - } else { + for ( j = 1; j <= tdivisions; j ++ ) { - THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + t = j / tdivisions; - this.boneInverses = []; + if ( ! aClockwise ) { - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + t = 1 - t; - this.boneInverses.push( new THREE.Matrix4() ); + } - } + angle = aStartAngle + t * deltaAngle; - } + tx = aX + xRadius * Math.cos( angle ); + ty = aY + yRadius * Math.sin( angle ); - } + //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); -}; + points.push( new THREE.Vector2( tx, ty ) ); -THREE.Skeleton.prototype.calculateInverses = function () { + } - this.boneInverses = []; + //console.log(points); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + break; - var inverse = new THREE.Matrix4(); + } // end switch - if ( this.bones[ b ] ) { + } - inverse.getInverse( this.bones[ b ].matrixWorld ); - } - this.boneInverses.push( inverse ); + // Normalize to remove the closing point by default. + var lastPoint = points[ points.length - 1]; + var EPSILON = 0.0000000001; + if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON && + Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON) + points.splice( points.length - 1, 1); + if ( closedPath ) { + + points.push( points[ 0 ] ); } -}; - -THREE.Skeleton.prototype.pose = function () { - - var bone; - - // recover the bind-time world matrices - - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + return points; - bone = this.bones[ b ]; +}; - if ( bone ) { +// +// Breaks path into shapes +// +// Assumptions (if parameter isCCW==true the opposite holds): +// - solid shapes are defined clockwise (CW) +// - holes are defined counterclockwise (CCW) +// +// If parameter noHoles==true: +// - all subPaths are regarded as solid shapes +// - definition order CW/CCW has no relevance +// - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); +THREE.Path.prototype.toShapes = function( isCCW, noHoles ) { - } + function extractSubpaths( inActions ) { - } + var i, il, item, action, args; - // compute the local matrices, positions, rotations and scales + var subPaths = [], lastPath = new THREE.Path(); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + for ( i = 0, il = inActions.length; i < il; i ++ ) { - bone = this.bones[ b ]; + item = inActions[ i ]; - if ( bone ) { + args = item.args; + action = item.action; - if ( bone.parent ) { + if ( action == THREE.PathActions.MOVE_TO ) { - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + if ( lastPath.actions.length != 0 ) { - } else { + subPaths.push( lastPath ); + lastPath = new THREE.Path(); - bone.matrix.copy( bone.matrixWorld ); + } } - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - - } - - } - -}; - -THREE.Skeleton.prototype.update = ( function () { - - var offsetMatrix = new THREE.Matrix4(); - - return function () { - - // flatten bone matrices to array - - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - - // compute the offset between the current and the original transform - - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); + lastPath[ action ].apply( lastPath, args ); } - if ( this.useVertexTexture ) { + if ( lastPath.actions.length != 0 ) { - this.boneTexture.needsUpdate = true; + subPaths.push( lastPath ); } - - }; - -} )(); - - -// File:src/objects/SkinnedMesh.js - -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ - -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { - - THREE.Mesh.call( this, geometry, material ); - - this.type = 'SkinnedMesh'; - this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); - - // init bones - - // TODO: remove bone creation as there is no reason (other than - // convenience) for THREE.SkinnedMesh to do this. - - var bones = []; - - if ( this.geometry && this.geometry.bones !== undefined ) { - - var bone, gbone, p, q, s; - - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - - gbone = this.geometry.bones[ b ]; - - p = gbone.pos; - q = gbone.rotq; - s = gbone.scl; - - bone = new THREE.Bone( this ); - bones.push( bone ); + // console.log(subPaths); - bone.name = gbone.name; - bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] ); - bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] ); + return subPaths; + } - if ( s !== undefined ) { + function toShapesNoHoles( inSubpaths ) { - bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] ); + var shapes = []; - } else { + for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) { - bone.scale.set( 1, 1, 1 ); + var tmpPath = inSubpaths[ i ]; - } + var tmpShape = new THREE.Shape(); + tmpShape.actions = tmpPath.actions; + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); } - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + //console.log("shape", shapes); - gbone = this.geometry.bones[ b ]; + return shapes; + }; - if ( gbone.parent !== - 1 ) { + function isPointInsidePolygon( inPt, inPolygon ) { + var EPSILON = 0.0000000001; - bones[ gbone.parent ].add( bones[ b ] ); + var polyLen = inPolygon.length; - } else { + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + var inside = false; + for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - this.add( bones[ b ] ); + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - } + if ( Math.abs(edgeDy) > EPSILON ) { // not parallel + if ( edgeDy < 0 ) { + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + } + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + if ( inPt.y == edgeLowPt.y ) { + if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! + } else { + var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if ( perpEdge == 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt + } + } else { // parallel or colinear + if ( inPt.y != edgeLowPt.y ) continue; // parallel + // egde lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; + } } + return inside; } - this.normalizeSkinWeights(); - - this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) ); - -}; - -THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh; + var subPaths = extractSubpaths( this.actions ); + if ( subPaths.length == 0 ) return []; -THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) { + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - this.skeleton = skeleton; - if ( bindMatrix === undefined ) { + var solid, tmpPath, tmpShape, shapes = []; - this.updateMatrixWorld( true ); + if ( subPaths.length == 1) { - bindMatrix = this.matrixWorld; + tmpPath = subPaths[0]; + tmpShape = new THREE.Shape(); + tmpShape.actions = tmpPath.actions; + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); - -}; - -THREE.SkinnedMesh.prototype.pose = function () { + var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - this.skeleton.pose(); + // console.log("Holes first", holesFirst); + + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; -}; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; -THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { + var i, il; - if ( this.geometry instanceof THREE.Geometry ) { + for ( i = 0, il = subPaths.length; i < il; i ++ ) { - for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = THREE.Shape.Utils.isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - var sw = this.geometry.skinWeights[ i ]; + if ( solid ) { - var scale = 1.0 / sw.lengthManhattan(); + if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++; - if ( scale !== Infinity ) { + newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints }; + newShapes[mainIdx].s.actions = tmpPath.actions; + newShapes[mainIdx].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[mainIdx] = []; - sw.multiplyScalar( scale ); + //console.log('cw', i); - } else { + } else { - sw.set( 1 ); // this will be normalized by the shader anyway + newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } ); - } + //console.log('ccw', i); } - } else { - - // skinning weights assumed to be normalized for THREE.BufferGeometry - } -}; - -THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) { - - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); - - if ( this.bindMode === "attached" ) { - - this.bindMatrixInverse.getInverse( this.matrixWorld ); - - } else if ( this.bindMode === "detached" ) { - - this.bindMatrixInverse.getInverse( this.bindMatrix ); + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[0] ) return toShapesNoHoles( subPaths ); - } else { - THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode ); + if ( newShapes.length > 1 ) { + var ambigious = false; + var toChange = []; + for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + betterShapeHoles[sIdx] = []; + } + for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + var sho = newShapeHoles[sIdx]; + for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + var ho = sho[hIdx]; + var hole_unassigned = true; + for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) { + if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push( ho ); + } else { + ambigious = true; + } + } + } + if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); } + } + } + // console.log("ambigious: ", ambigious); + if ( toChange.length > 0 ) { + // console.log("to change: ", toChange); + if (! ambigious) newShapeHoles = betterShapeHoles; + } } -}; - -THREE.SkinnedMesh.prototype.clone = function( object ) { - - if ( object === undefined ) { - - object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture ); - + var tmpHoles, j, jl; + for ( i = 0, il = newShapes.length; i < il; i ++ ) { + tmpShape = newShapes[i].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[i]; + for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + tmpShape.holes.push( tmpHoles[j].h ); + } } - THREE.Mesh.prototype.clone.call( this, object ); + //console.log("shape", shapes); - return object; + return shapes; }; - -// File:src/objects/MorphAnimMesh.js +// File:src/extras/core/Shape.js /** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.MorphAnimMesh = function ( geometry, material ) { - - THREE.Mesh.call( this, geometry, material ); - - this.type = 'MorphAnimMesh'; - - // API - - this.duration = 1000; // milliseconds - this.mirroredLoop = false; - this.time = 0; - - // internals + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - this.lastKeyframe = 0; - this.currentKeyframe = 0; +// STEP 1 Create a path. +// STEP 2 Turn path into shape. +// STEP 3 ExtrudeGeometry takes in Shape/Shapes +// STEP 3a - Extract points from each shape, turn to vertices +// STEP 3b - Triangulate each shape, add faces. - this.direction = 1; - this.directionBackwards = false; +THREE.Shape = function () { - this.setFrameRange( 0, this.geometry.morphTargets.length - 1 ); + THREE.Path.apply( this, arguments ); + this.holes = []; }; -THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh; +THREE.Shape.prototype = Object.create( THREE.Path.prototype ); +THREE.Shape.prototype.constructor = THREE.Shape; -THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { +// Convenience method to return ExtrudeGeometry - this.startKeyframe = start; - this.endKeyframe = end; +THREE.Shape.prototype.extrude = function ( options ) { - this.length = this.endKeyframe - this.startKeyframe + 1; + var extruded = new THREE.ExtrudeGeometry( this, options ); + return extruded; }; -THREE.MorphAnimMesh.prototype.setDirectionForward = function () { - - this.direction = 1; - this.directionBackwards = false; - -}; +// Convenience method to return ShapeGeometry -THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { +THREE.Shape.prototype.makeGeometry = function ( options ) { - this.direction = - 1; - this.directionBackwards = true; + var geometry = new THREE.ShapeGeometry( this, options ); + return geometry; }; -THREE.MorphAnimMesh.prototype.parseAnimations = function () { - - var geometry = this.geometry; +// Get points of holes - if ( ! geometry.animations ) geometry.animations = {}; +THREE.Shape.prototype.getPointsHoles = function ( divisions ) { - var firstAnimation, animations = geometry.animations; + var i, il = this.holes.length, holesPts = []; - var pattern = /([a-z]+)_?(\d+)/; + for ( i = 0; i < il; i ++ ) { - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends ); - var morph = geometry.morphTargets[ i ]; - var parts = morph.name.match( pattern ); + } - if ( parts && parts.length > 1 ) { + return holesPts; - var label = parts[ 1 ]; +}; - if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity }; +// Get points of holes (spaced by regular distance) - var animation = animations[ label ]; +THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) { - if ( i < animation.start ) animation.start = i; - if ( i > animation.end ) animation.end = i; + var i, il = this.holes.length, holesPts = []; - if ( ! firstAnimation ) firstAnimation = label; + for ( i = 0; i < il; i ++ ) { - } + holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends ); } - geometry.firstAnimation = firstAnimation; + return holesPts; }; -THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { - - if ( ! this.geometry.animations ) this.geometry.animations = {}; - - this.geometry.animations[ label ] = { start: start, end: end }; -}; +// Get points of shape and holes (keypoints based on segments parameter) -THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { +THREE.Shape.prototype.extractAllPoints = function ( divisions ) { - var animation = this.geometry.animations[ label ]; + return { - if ( animation ) { + shape: this.getTransformedPoints( divisions ), + holes: this.getPointsHoles( divisions ) - this.setFrameRange( animation.start, animation.end ); - this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); - this.time = 0; + }; - } else { +}; - THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' ); +THREE.Shape.prototype.extractPoints = function ( divisions ) { + if (this.useSpacedPoints) { + return this.extractAllSpacedPoints(divisions); } -}; + return this.extractAllPoints(divisions); -THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { +}; - var frameTime = this.duration / this.length; +// +// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) { +// +// return { +// +// shape: this.transform( bend, divisions ), +// holes: this.getPointsHoles( divisions, bend ) +// +// }; +// +// }; - this.time += this.direction * delta; +// Get points of shape and holes (spaced by regular distance) - if ( this.mirroredLoop ) { +THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) { - if ( this.time > this.duration || this.time < 0 ) { + return { - this.direction *= - 1; + shape: this.getTransformedSpacedPoints( divisions ), + holes: this.getSpacedPointsHoles( divisions ) - if ( this.time > this.duration ) { + }; - this.time = this.duration; - this.directionBackwards = true; +}; - } +/************************************************************** + * Utils + **************************************************************/ - if ( this.time < 0 ) { +THREE.Shape.Utils = { - this.time = 0; - this.directionBackwards = false; + triangulateShape: function ( contour, holes ) { + function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { + // inOtherPt needs to be colinear to the inSegment + if ( inSegPt1.x != inSegPt2.x ) { + if ( inSegPt1.x < inSegPt2.x ) { + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); + } else { + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); + } + } else { + if ( inSegPt1.y < inSegPt2.y ) { + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); + } else { + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); + } } - } - } else { + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { + var EPSILON = 0.0000000001; - this.time = this.time % this.duration; + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - if ( this.time < 0 ) this.time += this.duration; + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - } + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 ); + if ( Math.abs(limit) > EPSILON ) { // not parallel - if ( keyframe !== this.currentKeyframe ) { + var perpSeg2; + if ( limit > 0 ) { + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; + } else { + if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; + } - this.morphTargetInfluences[ this.lastKeyframe ] = 0; - this.morphTargetInfluences[ this.currentKeyframe ] = 1; + // i.e. to reduce rounding errors + // intersection at endpoint of segment#1? + if ( perpSeg2 == 0 ) { + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; + return [ inSeg1Pt1 ]; + } + if ( perpSeg2 == limit ) { + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; + return [ inSeg1Pt2 ]; + } + // intersection at endpoint of segment#2? + if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 == limit ) return [ inSeg2Pt2 ]; - this.morphTargetInfluences[ keyframe ] = 0; + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - this.lastKeyframe = this.currentKeyframe; - this.currentKeyframe = keyframe; + } else { // parallel or colinear + if ( ( perpSeg1 != 0 ) || + ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return []; - } + // they are collinear or degenerate + var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point? + var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point? + // both segments are points + if ( seg1Pt && seg2Pt ) { + if ( (inSeg1Pt1.x != inSeg2Pt1.x) || + (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points + return [ inSeg1Pt1 ]; // they are the same point + } + // segment#1 is a single point + if ( seg1Pt ) { + if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 + return [ inSeg1Pt1 ]; + } + // segment#2 is a single point + if ( seg2Pt ) { + if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; + } - var mix = ( this.time % frameTime ) / frameTime; + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if (seg1dx != 0) { // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; + } else { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; + } else { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; + } + } else { // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; + } else { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; + } else { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; + } + } + if ( seg1minVal <= seg2minVal ) { + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal == seg2minVal ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; + } else { + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal == seg2maxVal ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; + } + } + } - if ( this.directionBackwards ) { + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { + // The order of legs is important - mix = 1 - mix; + var EPSILON = 0.0000000001; - } + // translation of all points, so that Vertex is at (0,0) + var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; + var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; + var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - this.morphTargetInfluences[ this.currentKeyframe ] = mix; - this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix; + // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. + var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; + var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; -}; + if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg. -THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) { + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - var influences = this.morphTargetInfluences; + if ( from2toAngle > 0 ) { // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); + } else { // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); + } + } else { // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); + } + } - for ( var i = 0, l = influences.length; i < l; i ++ ) { - influences[ i ] = 0; + function removeHoles( contour, holes ) { - } + var shape = contour.concat(); // work on this shape + var hole; - if ( a > -1 ) influences[ a ] = 1 - t; - if ( b > -1 ) influences[ b ] = t; + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; -}; + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; -THREE.MorphAnimMesh.prototype.clone = function ( object ) { + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material ); + var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] ); + if (! insideAngle ) { + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; + } - object.duration = this.duration; - object.mirroredLoop = this.mirroredLoop; - object.time = this.time; + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - object.lastKeyframe = this.lastKeyframe; - object.currentKeyframe = this.currentKeyframe; + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - object.direction = this.direction; - object.directionBackwards = this.directionBackwards; + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - THREE.Mesh.prototype.clone.call( this, object ); + insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] ); + if (! insideAngle ) { + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; + } - return object; + return true; + } -}; + function intersectsShapeEdge( inShapePt, inHolePt ) { + // checks for intersections with shape edges + var sIdx, nextIdx, intersection; + for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { + nextIdx = sIdx + 1; nextIdx %= shape.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true ); + if ( intersection.length > 0 ) return true; + } -// File:src/objects/LOD.js + return false; + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + var indepHoles = []; -THREE.LOD = function () { + function intersectsHoleEdge( inShapePt, inHolePt ) { + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { + chkHole = holes[indepHoles[ihIdx]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { + nextIdx = hIdx + 1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true ); + if ( intersection.length > 0 ) return true; + } + } + return false; + } - THREE.Object3D.call( this ); + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; - this.objects = []; + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { -}; + indepHoles.push( h ); + } -THREE.LOD.prototype = Object.create( THREE.Object3D.prototype ); -THREE.LOD.prototype.constructor = THREE.LOD; + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { + counter --; + if ( counter < 0 ) { + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; + } -THREE.LOD.prototype.addLevel = function ( object, distance ) { + // search for shape-vertex and hole-vertex, + // which can be connected without intersections + for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { - if ( distance === undefined ) distance = 0; + shapePt = shape[ shapeIndex ]; + holeIndex = - 1; - distance = Math.abs( distance ); + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { + holeIdx = indepHoles[h]; - for ( var l = 0; l < this.objects.length; l ++ ) { + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[cutKey] !== undefined ) continue; - if ( distance < this.objects[ l ].distance ) { + hole = holes[holeIdx]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { + holePt = hole[ h2 ]; + if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - break; + holeIndex = h2; + indepHoles.splice(h, 1); - } + tmpShape1 = shape.slice( 0, shapeIndex + 1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex + 1 ); - } + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - this.objects.splice( l, 0, { distance: distance, object: object } ); - this.add( object ); + minShapeIndex = shapeIndex; -}; + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); -THREE.LOD.prototype.getObjectForDistance = function ( distance ) { + break; + } + if ( holeIndex >= 0 ) break; // hole-vertex found - for ( var i = 1, l = this.objects.length; i < l; i ++ ) { + failedCuts[cutKey] = true; // remember failure + } + if ( holeIndex >= 0 ) break; // hole-vertex found + } + } - if ( distance < this.objects[ i ].distance ) { + return shape; /* shape with no holes */ + } - break; - } + var i, il, f, face, + key, index, + allPointsMap = {}; - } + // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - return this.objects[ i - 1 ].object; + var allpoints = contour.concat(); -}; + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { -THREE.LOD.prototype.raycast = ( function () { + Array.prototype.push.apply( allpoints, holes[h] ); - var matrixPosition = new THREE.Vector3(); + } - return function ( raycaster, intersects ) { + //console.log( "allpoints",allpoints, allpoints.length ); - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + // prepare all points map - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + for ( i = 0, il = allpoints.length; i < il; i ++ ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + key = allpoints[ i ].x + ":" + allpoints[ i ].y; - }; + if ( allPointsMap[ key ] !== undefined ) { -}() ); + THREE.warn( "THREE.Shape: Duplicate point", key ); -THREE.LOD.prototype.update = function () { + } - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + allPointsMap[ key ] = i; - return function ( camera ) { + } - if ( this.objects.length > 1 ) { + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - var distance = v1.distanceTo( v2 ); + // check all face vertices against all points map - this.objects[ 0 ].object.visible = true; + for ( i = 0, il = triangles.length; i < il; i ++ ) { - for ( var i = 1, l = this.objects.length; i < l; i ++ ) { + face = triangles[ i ]; - if ( distance >= this.objects[ i ].distance ) { + for ( f = 0; f < 3; f ++ ) { - this.objects[ i - 1 ].object.visible = false; - this.objects[ i ].object.visible = true; + key = face[ f ].x + ":" + face[ f ].y; - } else { + index = allPointsMap[ key ]; - break; + if ( index !== undefined ) { + + face[ f ] = index; } } - for ( ; i < l; i ++ ) { + } - this.objects[ i ].object.visible = false; + return triangles.concat(); - } + }, - } + isClockWise: function ( pts ) { - }; + return THREE.FontUtils.Triangulate.area( pts ) < 0; -}(); + }, -THREE.LOD.prototype.clone = function ( object ) { + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - if ( object === undefined ) object = new THREE.LOD(); + // Quad Bezier Functions - THREE.Object3D.prototype.clone.call( this, object ); + b2p0: function ( t, p ) { - for ( var i = 0, l = this.objects.length; i < l; i ++ ) { - var x = this.objects[ i ].object.clone(); - x.visible = i === 0; - object.addLevel( x, this.objects[ i ].distance ); - } + var k = 1 - t; + return k * k * p; - return object; + }, -}; + b2p1: function ( t, p ) { -// File:src/objects/Sprite.js + return 2 * ( 1 - t ) * t * p; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.Sprite = function (material) { + b2p2: function ( t, p ) { - var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ); - var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] ); - var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] ); + return t * t * p; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + }, -// return function ( material ) { + b2: function ( t, p0, p1, p2 ) { - THREE.Object3D.call( this ); + return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 ); - this.type = 'Sprite'; + }, - this.geometry = geometry; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + // Cubic Bezier Functions -// }; + b3p0: function ( t, p ) { -}; + var k = 1 - t; + return k * k * k * p; -THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Sprite.prototype.constructor = THREE.Sprite; + }, -THREE.Sprite.prototype.raycast = ( function () { + b3p1: function ( t, p ) { - var matrixPosition = new THREE.Vector3(); + var k = 1 - t; + return 3 * k * k * t * p; - return function ( raycaster, intersects ) { + }, - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + b3p2: function ( t, p ) { - var distance = raycaster.ray.distanceToPoint( matrixPosition ); + var k = 1 - t; + return 3 * k * t * t * p; - if ( distance > this.scale.x ) { + }, - return; + b3p3: function ( t, p ) { - } + return t * t * t * p; - intersects.push( { + }, - distance: distance, - point: this.position, - face: null, - object: this + b3: function ( t, p0, p1, p2, p3 ) { - } ); + return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 ); - }; + } -}() ); +}; -THREE.Sprite.prototype.clone = function ( object ) { - if ( object === undefined ) object = new THREE.Sprite( this.material ); +// File:src/extras/curves/LineCurve.js - THREE.Object3D.prototype.clone.call( this, object ); +/************************************************************** + * Line + **************************************************************/ - return object; +THREE.LineCurve = function ( v1, v2 ) { + + this.v1 = v1; + this.v2 = v2; }; -// Backwards compatibility +THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); +THREE.LineCurve.prototype.constructor = THREE.LineCurve; -THREE.Particle = THREE.Sprite; +THREE.LineCurve.prototype.getPoint = function ( t ) { -// File:src/objects/LensFlare.js + var point = this.v2.clone().sub(this.v1); + point.multiplyScalar( t ).add( this.v1 ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + return point; -THREE.LensFlare = function ( texture, size, distance, blending, color ) { +}; - THREE.Object3D.call( this ); +// Line curve is linear, so we can overwrite default getPointAt - this.lensFlares = []; +THREE.LineCurve.prototype.getPointAt = function ( u ) { - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; + return this.getPoint( u ); - if ( texture !== undefined ) { +}; - this.add( texture, size, distance, blending, color ); +THREE.LineCurve.prototype.getTangent = function( t ) { - } + var tangent = this.v2.clone().sub(this.v1); + + return tangent.normalize(); }; -THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); -THREE.LensFlare.prototype.constructor = THREE.LensFlare; +// File:src/extras/curves/QuadraticBezierCurve.js +/************************************************************** + * Quadratic Bezier curve + **************************************************************/ -/* - * Add: adds another flare - */ -THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { +THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { - if ( size === undefined ) size = - 1; - if ( distance === undefined ) distance = 0; - if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new THREE.Color( 0xffffff ); - if ( blending === undefined ) blending = THREE.NormalBlending; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - distance = Math.min( distance, Math.max( 0, distance ) ); +}; - this.lensFlares.push( { - texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back - scale: 1, // scale - rotation: 1, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending // blending - } ); - -}; +THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); +THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; -/* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ -THREE.LensFlare.prototype.updateLensFlares = function () { +THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + var vector = new THREE.Vector2(); - for ( f = 0; f < fl; f ++ ) { + vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); + vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - flare = this.lensFlares[ f ]; + return vector; - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; +}; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - } +THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { -}; + var vector = new THREE.Vector2(); + vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ); + vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ); -// File:src/scenes/Scene.js + // returns unit vector -/** - * @author mrdoob / http://mrdoob.com/ - */ + return vector.normalize(); -THREE.Scene = function () { +}; - THREE.Object3D.call( this ); +// File:src/extras/curves/CubicBezierCurve.js - this.type = 'Scene'; +/************************************************************** + * Cubic Bezier curve + **************************************************************/ - this.fog = null; - this.overrideMaterial = null; +THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { - this.autoUpdate = true; // checked by the renderer + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; }; -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; - -THREE.Scene.prototype.clone = function ( object ) { - - if ( object === undefined ) object = new THREE.Scene(); +THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); +THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; - THREE.Object3D.prototype.clone.call( this, object ); +THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { - if ( this.fog !== null ) object.fog = this.fog.clone(); - if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone(); + var tx, ty; - object.autoUpdate = this.autoUpdate; - object.matrixAutoUpdate = this.matrixAutoUpdate; + tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - return object; + return new THREE.Vector2( tx, ty ); }; -// File:src/scenes/Fog.js - -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ +THREE.CubicBezierCurve.prototype.getTangent = function( t ) { -THREE.Fog = function ( color, near, far ) { + var tx, ty; - this.name = ''; + tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - this.color = new THREE.Color( color ); + var tangent = new THREE.Vector2( tx, ty ); + tangent.normalize(); - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + return tangent; }; -THREE.Fog.prototype.clone = function () { +// File:src/extras/curves/SplineCurve.js - return new THREE.Fog( this.color.getHex(), this.near, this.far ); +/************************************************************** + * Spline curve + **************************************************************/ + +THREE.SplineCurve = function ( points /* array of Vector2 */ ) { + + this.points = ( points == undefined ) ? [] : points; }; -// File:src/scenes/FogExp2.js +THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); +THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ +THREE.SplineCurve.prototype.getPoint = function ( t ) { -THREE.FogExp2 = function ( color, density ) { + var points = this.points; + var point = ( points.length - 1 ) * t; - this.name = ''; + var intPoint = Math.floor( point ); + var weight = point - intPoint; - this.color = new THREE.Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ] + var point1 = points[ intPoint ] + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ] + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ] -}; + var vector = new THREE.Vector2(); -THREE.FogExp2.prototype.clone = function () { + vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); + vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); - return new THREE.FogExp2( this.color.getHex(), this.density ); + return vector; }; -// File:src/renderers/shaders/ShaderChunk.js - -THREE.ShaderChunk = {}; +// File:src/extras/curves/EllipseCurve.js -// File:src/renderers/shaders/ShaderChunk/common.glsl +/************************************************************** + * Ellipse curve + **************************************************************/ -THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\nfloat square( in float a ) { return a*a; }\nvec2 square( in vec2 a ) { return vec2( a.x*a.x, a.y*a.y ); }\nvec3 square( in vec3 a ) { return vec3( a.x*a.x, a.y*a.y, a.z*a.z ); }\nvec4 square( in vec4 a ) { return vec4( a.x*a.x, a.y*a.y, a.z*a.z, a.w*a.w ); }\nfloat saturate( in float a ) { return clamp( a, 0.0, 1.0 ); }\nvec2 saturate( in vec2 a ) { return clamp( a, 0.0, 1.0 ); }\nvec3 saturate( in vec3 a ) { return clamp( a, 0.0, 1.0 ); }\nvec4 saturate( in vec4 a ) { return clamp( a, 0.0, 1.0 ); }\nfloat average( in float a ) { return a; }\nfloat average( in vec2 a ) { return ( a.x + a.y) * 0.5; }\nfloat average( in vec3 a ) { return ( a.x + a.y + a.z) / 3.0; }\nfloat average( in vec4 a ) { return ( a.x + a.y + a.z + a.w) * 0.25; }\nfloat whiteCompliment( in float a ) { return saturate( 1.0 - a ); }\nvec2 whiteCompliment( in vec2 a ) { return saturate( vec2(1.0) - a ); }\nvec3 whiteCompliment( in vec3 a ) { return saturate( vec3(1.0) - a ); }\nvec4 whiteCompliment( in vec4 a ) { return saturate( vec4(1.0) - a ); }\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal) {\n float distance = dot( planeNormal, point-pointOnPlane );\n return point - distance * planeNormal;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return pointOnLine + lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) );\n}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( 1.0 - lightDistance / cutoffDistance ), decayExponent );\n }\n return 1.0;\n}\n\nvec3 inputToLinear( in vec3 a ) {\n#ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\nvec3 linearToOutput( in vec3 a ) {\n#ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\n"; +THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) { -// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl + this.aX = aX; + this.aY = aY; -THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; + this.xRadius = xRadius; + this.yRadius = yRadius; -// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; -THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * attenuation;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * attenuation;\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * attenuation * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * attenuation * spotEffect;\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n"; + this.aClockwise = aClockwise; -// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl +}; -THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n"; +THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); +THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; -// File:src/renderers/shaders/ShaderChunk/default_vertex.glsl +THREE.EllipseCurve.prototype.getPoint = function ( t ) { -THREE.ShaderChunk[ 'default_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; + var deltaAngle = this.aEndAngle - this.aStartAngle; -// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl + if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2; + if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2; -THREE.ShaderChunk[ 'map_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif"; + var angle; -// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl + if ( this.aClockwise === true ) { -THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n"; + angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle ); -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl + } else { -THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif"; + angle = this.aStartAngle + t * deltaAngle; -// File:src/renderers/shaders/ShaderChunk/lightmap_pars_vertex.glsl + } + + var vector = new THREE.Vector2(); -THREE.ShaderChunk[ 'lightmap_pars_vertex'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif"; + vector.x = this.aX + this.xRadius * Math.cos( angle ); + vector.y = this.aY + this.yRadius * Math.sin( angle ); -// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl + return vector; -THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += pointLightColor[ i ] * pointDiffuseWeight * attenuation;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += spotLightColor[ i ] * spotDiffuseWeight * attenuation * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n totalSpecularLight += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) + totalSpecularLight + emissive;\n\n#endif\n"; +}; -// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl +// File:src/extras/curves/ArcCurve.js -THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif"; +/************************************************************** + * Arc curve + **************************************************************/ -// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl +THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { -THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif"; + THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); +}; -// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl +THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); +THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; -THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n"; +// File:src/extras/curves/LineCurve3.js -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl +/************************************************************** + * Line3D + **************************************************************/ -THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; +THREE.LineCurve3 = THREE.Curve.create( -// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl + function ( v1, v2 ) { -THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n"; + this.v1 = v1; + this.v2 = v2; -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl + }, -THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n"; + function ( t ) { -// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl + var vector = new THREE.Vector3(); -THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif"; + vector.subVectors( this.v2, this.v1 ); // diff + vector.multiplyScalar( t ); + vector.add( this.v1 ); -// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl + return vector; -THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl +); -THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif"; +// File:src/extras/curves/QuadraticBezierCurve3.js -// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl +/************************************************************** + * Quadratic Bezier 3D curve + **************************************************************/ -THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif"; +THREE.QuadraticBezierCurve3 = THREE.Curve.create( -// File:src/renderers/shaders/ShaderChunk/lightmap_vertex.glsl + function ( v0, v1, v2 ) { -THREE.ShaderChunk[ 'lightmap_vertex'] = "#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; -// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl + }, -THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n"; + function ( t ) { -// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl + var vector = new THREE.Vector3(); -THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n"; + vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); + vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); + vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z ); -// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl + return vector; -THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl +); -THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n"; +// File:src/extras/curves/CubicBezierCurve3.js -// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl +/************************************************************** + * Cubic Bezier 3D curve + **************************************************************/ -THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n"; +THREE.CubicBezierCurve3 = THREE.Curve.create( -// File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl + function ( v0, v1, v2, v3 ) { -THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; -// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl + }, -THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif"; + function ( t ) { -// File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl + var vector = new THREE.Vector3(); -THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n"; + vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); + vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); + vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ); -// File:src/renderers/shaders/ShaderChunk/map_pars_vertex.glsl + return vector; -THREE.ShaderChunk[ 'map_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl +); -THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n"; +// File:src/extras/curves/SplineCurve3.js -// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl +/************************************************************** + * Spline 3D curve + **************************************************************/ -THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif"; -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl +THREE.SplineCurve3 = THREE.Curve.create( -THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif"; + function ( points /* array of Vector3 */) { -// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl + this.points = ( points == undefined ) ? [] : points; -THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif"; + }, -// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl + function ( t ) { -THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif"; + var points = this.points; + var point = ( points.length - 1 ) * t; -// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl + var intPoint = Math.floor( point ); + var weight = point - intPoint; -THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = exp2( - square( fogDensity ) * square( depth ) * LOG2 );\n fogFactor = whiteCompliment( fogFactor );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif"; + var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; + var point1 = points[ intPoint ]; + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; -// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl + var vector = new THREE.Vector3(); -THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n"; + vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); + vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); + vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight ); -// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl + return vector; -THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + } -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl +); -THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n"; +// File:src/extras/curves/ClosedSplineCurve3.js -// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl +/************************************************************** + * Closed Spline 3D curve + **************************************************************/ -THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; -// File:src/renderers/shaders/ShaderChunk/map_vertex.glsl +THREE.ClosedSplineCurve3 = THREE.Curve.create( -THREE.ShaderChunk[ 'map_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; + function ( points /* array of Vector3 */) { -// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl + this.points = ( points == undefined ) ? [] : points; -THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n outgoingLight *= diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz;\n\n#endif"; + }, -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl + function ( t ) { -THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif"; + var points = this.points; + var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1 -// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl + var intPoint = Math.floor( point ); + var weight = point - intPoint; -THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif"; + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; -// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl + var point0 = points[ ( intPoint - 1 ) % points.length ]; + var point1 = points[ ( intPoint ) % points.length ]; + var point2 = points[ ( intPoint + 1 ) % points.length ]; + var point3 = points[ ( intPoint + 2 ) % points.length ]; -THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif"; + var vector = new THREE.Vector3(); -// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl + vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); + vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); + vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight ); -THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n"; + return vector; -// File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl + } -THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n // NOTE: I am unsure if this is correct in linear space. -bhouston, Dec 29, 2014\n shadowColor = inputToLinear( shadowColor );\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n"; +); -// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl +// File:src/extras/animation/AnimationHandler.js -THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n"; +/** + * @author mikael emtinger / http://gomo.se/ + */ -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl +THREE.AnimationHandler = { -THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif"; + LINEAR: 0, + CATMULLROM: 1, + CATMULLROM_FORWARD: 2, -// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl + // -THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n"; + add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); }, + get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); }, + remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); }, -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl + // -THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif"; + animations: [], -// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl + init: function ( data ) { -THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; + if ( data.initialized === true ) return data; -// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl + // loop through all keys -THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n"; + for ( var h = 0; h < data.hierarchy.length; h ++ ) { -// File:src/renderers/shaders/UniformsUtils.js + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { -/** - * Uniform Utilities - */ + // remove minus times -THREE.UniformsUtils = { + if ( data.hierarchy[ h ].keys[ k ].time < 0 ) { - merge: function ( uniforms ) { + data.hierarchy[ h ].keys[ k ].time = 0; - var merged = {}; + } - for ( var u = 0; u < uniforms.length; u ++ ) { + // create quaternions - var tmp = this.clone( uniforms[ u ] ); + if ( data.hierarchy[ h ].keys[ k ].rot !== undefined && + ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) { - for ( var p in tmp ) { + var quat = data.hierarchy[ h ].keys[ k ].rot; + data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat ); - merged[ p ] = tmp[ p ]; + } } - } + // prepare morph target keys - return merged; + if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) { - }, + // get all used - clone: function ( uniforms_src ) { + var usedMorphTargets = {}; - var uniforms_dst = {}; + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - for ( var u in uniforms_src ) { + for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - uniforms_dst[ u ] = {}; + var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ]; + usedMorphTargets[ morphTargetName ] = - 1; - for ( var p in uniforms_src[ u ] ) { + } - var parameter_src = uniforms_src[ u ][ p ]; + } - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + data.hierarchy[ h ].usedMorphTargets = usedMorphTargets; - uniforms_dst[ u ][ p ] = parameter_src.clone(); - } else if ( parameter_src instanceof Array ) { + // set all used on all frames - uniforms_dst[ u ][ p ] = parameter_src.slice(); + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - } else { + var influences = {}; - uniforms_dst[ u ][ p ] = parameter_src; + for ( var morphTargetName in usedMorphTargets ) { - } + for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { - } + if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) { - } + influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ]; + break; - return uniforms_dst; + } - } + } -}; + if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) { -// File:src/renderers/shaders/UniformsLib.js + influences[ morphTargetName ] = 0; -/** - * Uniforms library for shared webgl shaders - */ + } -THREE.UniformsLib = { + } - common: { + data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences; - "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, + } - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + } - "lightMap" : { type: "t", value: null }, - "specularMap" : { type: "t", value: null }, - "alphaMap" : { type: "t", value: null }, - "envMap" : { type: "t", value: null }, - "flipEnvMap" : { type: "f", value: - 1 }, - "reflectivity" : { type: "f", value: 1.0 }, - "refractionRatio" : { type: "f", value: 0.98 }, + // remove all keys that are on the same time - "morphTargetInfluences" : { type: "f", value: 0 } + for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) { - }, + if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) { - bump: { + data.hierarchy[ h ].keys.splice( k, 1 ); + k --; - "bumpMap" : { type: "t", value: null }, - "bumpScale" : { type: "f", value: 1 } + } - }, - - normalmap: { + } - "normalMap" : { type: "t", value: null }, - "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } - }, - fog : { + // set index - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { - }, + data.hierarchy[ h ].keys[ k ].index = k; - lights: { + } - "ambientLightColor" : { type: "fv", value: [] }, + } - "directionalLightDirection" : { type: "fv", value: [] }, - "directionalLightColor" : { type: "fv", value: [] }, + data.initialized = true; - "hemisphereLightDirection" : { type: "fv", value: [] }, - "hemisphereLightSkyColor" : { type: "fv", value: [] }, - "hemisphereLightGroundColor" : { type: "fv", value: [] }, + return data; - "pointLightColor" : { type: "fv", value: [] }, - "pointLightPosition" : { type: "fv", value: [] }, - "pointLightDistance" : { type: "fv1", value: [] }, - "pointLightDecay" : { type: "fv1", value: [] }, + }, - "spotLightColor" : { type: "fv", value: [] }, - "spotLightPosition" : { type: "fv", value: [] }, - "spotLightDirection" : { type: "fv", value: [] }, - "spotLightDistance" : { type: "fv1", value: [] }, - "spotLightAngleCos" : { type: "fv1", value: [] }, - "spotLightExponent" : { type: "fv1", value: [] }, - "spotLightDecay" : { type: "fv1", value: [] } + parse: function ( root ) { - }, + var parseRecurseHierarchy = function ( root, hierarchy ) { - particle: { + hierarchy.push( root ); - "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, - "size" : { type: "f", value: 1.0 }, - "scale" : { type: "f", value: 1.0 }, - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + for ( var c = 0; c < root.children.length; c ++ ) + parseRecurseHierarchy( root.children[ c ], hierarchy ); - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + }; - }, + // setup hierarchy - shadowmap: { + var hierarchy = []; - "shadowMap": { type: "tv", value: [] }, - "shadowMapSize": { type: "v2v", value: [] }, + if ( root instanceof THREE.SkinnedMesh ) { - "shadowBias" : { type: "fv1", value: [] }, - "shadowDarkness": { type: "fv1", value: [] }, + for ( var b = 0; b < root.skeleton.bones.length; b ++ ) { - "shadowMatrix" : { type: "m4v", value: [] } + hierarchy.push( root.skeleton.bones[ b ] ); - } + } -}; + } else { -// File:src/renderers/shaders/ShaderLib.js + parseRecurseHierarchy( root, hierarchy ); -/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + } + return hierarchy; -THREE.ShaderLib = { + }, - 'basic': { + play: function ( animation ) { - uniforms: THREE.UniformsUtils.merge( [ + if ( this.animations.indexOf( animation ) === - 1 ) { - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "shadowmap" ] + this.animations.push( animation ); - ] ), + } - vertexShader: [ + }, - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + stop: function ( animation ) { - "void main() {", + var index = this.animations.indexOf( animation ); - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], + if ( index !== - 1 ) { - " #ifdef USE_ENVMAP", + this.animations.splice( index, 1 ); - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + } - " #endif", + }, - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + update: function ( deltaTimeMS ) { - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + for ( var i = 0; i < this.animations.length; i ++ ) { - "}" + this.animations[ i ].resetBlendWeights( ); - ].join("\n"), + } - fragmentShader: [ + for ( var i = 0; i < this.animations.length; i ++ ) { - "uniform vec3 diffuse;", - "uniform float opacity;", + this.animations[ i ].update( deltaTimeMS ); - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + } - "void main() {", + } - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( diffuse, opacity );", +}; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], +// File:src/extras/animation/Animation.js - " outgoingLight = diffuseColor.rgb;", // simple shader +/** + * @author mikael emtinger / http://gomo.se/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - THREE.ShaderChunk[ "lightmap_fragment" ], // TODO: Light map on an otherwise unlit surface doesn't make sense. - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense. +THREE.Animation = function ( root, data ) { - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + this.root = root; + this.data = THREE.AnimationHandler.init( data ); + this.hierarchy = THREE.AnimationHandler.parse( root ); - THREE.ShaderChunk[ "fog_fragment" ], + this.currentTime = 0; + this.timeScale = 1; - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + this.isPlaying = false; + this.loop = true; + this.weight = 0; - "}" + this.interpolationType = THREE.AnimationHandler.LINEAR; - ].join("\n") +}; - }, +THREE.Animation.prototype = { - 'lambert': { + constructor: THREE.Animation, - uniforms: THREE.UniformsUtils.merge( [ + keyTypes: [ "pos", "rot", "scl" ], - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + play: function ( startTime, weight ) { - { - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } + this.currentTime = startTime !== undefined ? startTime : 0; + this.weight = weight !== undefined ? weight : 1; - ] ), + this.isPlaying = true; - vertexShader: [ + this.reset(); - "#define LAMBERT", + THREE.AnimationHandler.play( this ); - "varying vec3 vLightFront;", + }, - "#ifdef DOUBLE_SIDED", + stop: function() { - " varying vec3 vLightBack;", + this.isPlaying = false; - "#endif", + THREE.AnimationHandler.stop( this ); - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + }, - "void main() {", + reset: function () { - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + var object = this.hierarchy[ h ]; - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + if ( object.animationCache === undefined ) { - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_lambert_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + object.animationCache = { + animations: {}, + blending: { + positionWeight: 0.0, + quaternionWeight: 0.0, + scaleWeight: 0.0 + } + }; + } - "}" + var name = this.data.name; + var animations = object.animationCache.animations; + var animationCache = animations[ name ]; - ].join("\n"), + if ( animationCache === undefined ) { - fragmentShader: [ + animationCache = { + prevKey: { pos: 0, rot: 0, scl: 0 }, + nextKey: { pos: 0, rot: 0, scl: 0 }, + originalMatrix: object.matrix + }; - "uniform vec3 diffuse;", - "uniform vec3 emissive;", - "uniform float opacity;", + animations[ name ] = animationCache; - "varying vec3 vLightFront;", + } - "#ifdef DOUBLE_SIDED", + // Get keys to match our current time - " varying vec3 vLightBack;", + for ( var t = 0; t < 3; t ++ ) { - "#endif", + var type = this.keyTypes[ t ]; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var prevKey = this.data.hierarchy[ h ].keys[ 0 ]; + var nextKey = this.getNextKeyWith( type, h, 1 ); - "void main() {", + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( diffuse, opacity );", + prevKey = nextKey; + nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], + } - " #ifdef DOUBLE_SIDED", + animationCache.prevKey[ type ] = prevKey; + animationCache.nextKey[ type ] = nextKey; - //"float isFront = float( gl_FrontFacing );", - //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;", + } - " if ( gl_FrontFacing )", - " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", - " else", - " outgoingLight += diffuseColor.rgb * vLightBack + emissive;", + } - " #else", + }, - " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", + resetBlendWeights: function () { - " #endif", + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + var object = this.hierarchy[ h ]; + var animationCache = object.animationCache; - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + if ( animationCache !== undefined ) { - THREE.ShaderChunk[ "fog_fragment" ], + var blending = animationCache.blending; - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + blending.positionWeight = 0.0; + blending.quaternionWeight = 0.0; + blending.scaleWeight = 0.0; - "}" + } - ].join("\n") + } }, - 'phong': { + update: ( function() { - uniforms: THREE.UniformsUtils.merge( [ + var points = []; + var target = new THREE.Vector3(); + var newVector = new THREE.Vector3(); + var newQuat = new THREE.Quaternion(); - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "bump" ], - THREE.UniformsLib[ "normalmap" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + // Catmull-Rom spline - { - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, - "shininess": { type: "f", value: 30 }, - "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) } - } + var interpolateCatmullRom = function ( points, scale ) { - ] ), + var c = [], v3 = [], + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; - vertexShader: [ + point = ( points.length - 1 ) * scale; + intPoint = Math.floor( point ); + weight = point - intPoint; - "#define PHONG", + c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; + c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; - "varying vec3 vViewPosition;", + pa = points[ c[ 0 ] ]; + pb = points[ c[ 1 ] ]; + pc = points[ c[ 2 ] ]; + pd = points[ c[ 3 ] ]; - "#ifndef FLAT_SHADED", + w2 = weight * weight; + w3 = weight * w2; - " varying vec3 vNormal;", + v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); + v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); + v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); - "#endif", + return v3; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "map_pars_vertex" ], - THREE.ShaderChunk[ "lightmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_phong_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + }; - "void main() {", + var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) { - THREE.ShaderChunk[ "map_vertex" ], - THREE.ShaderChunk[ "lightmap_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED + }; - " vNormal = normalize( transformedNormal );", + return function ( delta ) { - "#endif", + if ( this.isPlaying === false ) return; - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + this.currentTime += delta * this.timeScale; - " vViewPosition = -mvPosition.xyz;", + if ( this.weight === 0 ) + return; - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_phong_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + // - "}" + var duration = this.data.length; - ].join("\n"), + if ( this.currentTime > duration || this.currentTime < 0 ) { - fragmentShader: [ + if ( this.loop ) { - "#define PHONG", + this.currentTime %= duration; - "uniform vec3 diffuse;", - "uniform vec3 emissive;", - "uniform vec3 specular;", - "uniform float shininess;", - "uniform float opacity;", + if ( this.currentTime < 0 ) + this.currentTime += duration; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "lights_phong_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "bumpmap_pars_fragment" ], - THREE.ShaderChunk[ "normalmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + this.reset(); - "void main() {", + } else { - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( diffuse, opacity );", + this.stop(); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], + } - THREE.ShaderChunk[ "lights_phong_fragment" ], + } - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + var object = this.hierarchy[ h ]; + var animationCache = object.animationCache.animations[this.data.name]; + var blending = object.animationCache.blending; - THREE.ShaderChunk[ "fog_fragment" ], + // loop through pos/rot/scl - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + for ( var t = 0; t < 3; t ++ ) { - "}" + // get keys - ].join("\n") + var type = this.keyTypes[ t ]; + var prevKey = animationCache.prevKey[ type ]; + var nextKey = animationCache.nextKey[ type ]; - }, + if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) || + ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) { - 'particle_basic': { + prevKey = this.data.hierarchy[ h ].keys[ 0 ]; + nextKey = this.getNextKeyWith( type, h, 1 ); - uniforms: THREE.UniformsUtils.merge( [ + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - THREE.UniformsLib[ "particle" ], - THREE.UniformsLib[ "shadowmap" ] + prevKey = nextKey; + nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); - ] ), + } - vertexShader: [ + animationCache.prevKey[ type ] = prevKey; + animationCache.nextKey[ type ] = nextKey; - "uniform float size;", - "uniform float scale;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time ); - "void main() {", + var prevXYZ = prevKey[ type ]; + var nextXYZ = nextKey[ type ]; - THREE.ShaderChunk[ "color_vertex" ], + if ( scale < 0 ) scale = 0; + if ( scale > 1 ) scale = 1; - " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", + // interpolate - " #ifdef USE_SIZEATTENUATION", - " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );", - " #else", - " gl_PointSize = size;", - " #endif", + if ( type === "pos" ) { - " gl_Position = projectionMatrix * mvPosition;", + if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) { - THREE.ShaderChunk[ "logdepthbuf_vertex" ], - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; + newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; + newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; - "}" + // blend + var proportionalWeight = this.weight / ( this.weight + blending.positionWeight ); + object.position.lerp( newVector, proportionalWeight ); + blending.positionWeight += this.weight; - ].join("\n"), + } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - fragmentShader: [ + points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ]; + points[ 1 ] = prevXYZ; + points[ 2 ] = nextXYZ; + points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ]; - "uniform vec3 psColor;", - "uniform float opacity;", + scale = scale * 0.33 + 0.33; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_particle_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var currentPoint = interpolateCatmullRom( points, scale ); + var proportionalWeight = this.weight / ( this.weight + blending.positionWeight ); + blending.positionWeight += this.weight; - "void main() {", + // blend - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( psColor, opacity );", + var vector = object.position; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_particle_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], + vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight; + vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight; + vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight; - " outgoingLight = diffuseColor.rgb;", // simple shader + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - THREE.ShaderChunk[ "shadowmap_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], + var forwardPoint = interpolateCatmullRom( points, scale * 1.01 ); - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] ); + target.sub( vector ); + target.y = 0; + target.normalize(); - "}" + var angle = Math.atan2( target.x, target.z ); + object.rotation.set( 0, angle, 0 ); - ].join("\n") + } - }, + } - 'dashed': { + } else if ( type === "rot" ) { - uniforms: THREE.UniformsUtils.merge( [ + THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale ); - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], + // Avoid paying the cost of an additional slerp if we don't have to + if ( blending.quaternionWeight === 0 ) { - { - "scale" : { type: "f", value: 1 }, - "dashSize" : { type: "f", value: 1 }, - "totalSize": { type: "f", value: 2 } - } + object.quaternion.copy(newQuat); + blending.quaternionWeight = this.weight; - ] ), + } else { - vertexShader: [ + var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight ); + THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight ); + blending.quaternionWeight += this.weight; - "uniform float scale;", - "attribute float lineDistance;", + } - "varying float vLineDistance;", + } else if ( type === "scl" ) { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; + newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; + newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; - "void main() {", + var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight ); + object.scale.lerp( newVector, proportionalWeight ); + blending.scaleWeight += this.weight; - THREE.ShaderChunk[ "color_vertex" ], + } - " vLineDistance = scale * lineDistance;", + } - " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - " gl_Position = projectionMatrix * mvPosition;", + } - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + return true; - "}" + }; - ].join("\n"), + } )(), - fragmentShader: [ + getNextKeyWith: function ( type, h, key ) { - "uniform vec3 diffuse;", - "uniform float opacity;", + var keys = this.data.hierarchy[ h ].keys; - "uniform float dashSize;", - "uniform float totalSize;", + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - "varying float vLineDistance;", + key = key < keys.length - 1 ? key : keys.length - 1; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + } else { - "void main() {", + key = key % keys.length; - " if ( mod( vLineDistance, totalSize ) > dashSize ) {", + } - " discard;", + for ( ; key < keys.length; key ++ ) { - " }", + if ( keys[ key ][ type ] !== undefined ) { - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( diffuse, opacity );", + return keys[ key ]; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], + } - " outgoingLight = diffuseColor.rgb;", // simple shader + } - THREE.ShaderChunk[ "fog_fragment" ], + return this.data.hierarchy[ h ].keys[ 0 ]; - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + }, - "}" + getPrevKeyWith: function ( type, h, key ) { - ].join("\n") + var keys = this.data.hierarchy[ h ].keys; - }, + if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || + this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { - 'depth': { + key = key > 0 ? key : 0; - uniforms: { + } else { - "mNear": { type: "f", value: 1.0 }, - "mFar" : { type: "f", value: 2000.0 }, - "opacity" : { type: "f", value: 1.0 } + key = key >= 0 ? key : key + keys.length; - }, + } - vertexShader: [ - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + for ( ; key >= 0; key -- ) { - "void main() {", + if ( keys[ key ][ type ] !== undefined ) { - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + return keys[ key ]; - "}" + } - ].join("\n"), + } - fragmentShader: [ + return this.data.hierarchy[ h ].keys[ keys.length - 1 ]; - "uniform float mNear;", - "uniform float mFar;", - "uniform float opacity;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], +}; - "void main() {", +// File:src/extras/animation/KeyFrameAnimation.js - THREE.ShaderChunk[ "logdepthbuf_fragment" ], +/** + * @author mikael emtinger / http://gomo.se/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author khang duong + * @author erik kitson + */ - " #ifdef USE_LOGDEPTHBUF_EXT", +THREE.KeyFrameAnimation = function ( data ) { - " float depth = gl_FragDepthEXT / gl_FragCoord.w;", + this.root = data.node; + this.data = THREE.AnimationHandler.init( data ); + this.hierarchy = THREE.AnimationHandler.parse( this.root ); + this.currentTime = 0; + this.timeScale = 0.001; + this.isPlaying = false; + this.isPaused = true; + this.loop = true; - " #else", + // initialize to first keyframes - " float depth = gl_FragCoord.z / gl_FragCoord.w;", + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - " #endif", + var keys = this.data.hierarchy[h].keys, + sids = this.data.hierarchy[h].sids, + obj = this.hierarchy[h]; - " float color = 1.0 - smoothstep( mNear, mFar, depth );", - " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects + if ( keys.length && sids ) { - "}" + for ( var s = 0; s < sids.length; s ++ ) { - ].join("\n") + var sid = sids[ s ], + next = this.getNextKeyWith( sid, h, 0 ); - }, + if ( next ) { - 'normal': { + next.apply( sid ); - uniforms: { + } - "opacity" : { type: "f", value: 1.0 } + } - }, + obj.matrixAutoUpdate = false; + this.data.hierarchy[h].node.updateMatrix(); + obj.matrixWorldNeedsUpdate = true; - vertexShader: [ + } - "varying vec3 vNormal;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], +}; - "void main() {", +THREE.KeyFrameAnimation.prototype = { - " vNormal = normalize( normalMatrix * normal );", + constructor: THREE.KeyFrameAnimation, - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + play: function ( startTime ) { - "}" + this.currentTime = startTime !== undefined ? startTime : 0; - ].join("\n"), + if ( this.isPlaying === false ) { - fragmentShader: [ + this.isPlaying = true; - "uniform float opacity;", - "varying vec3 vNormal;", + // reset key cache - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var h, hl = this.hierarchy.length, + object, + node; - "void main() {", + for ( h = 0; h < hl; h ++ ) { - " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", + object = this.hierarchy[ h ]; + node = this.data.hierarchy[ h ]; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + if ( node.animationCache === undefined ) { - "}" + node.animationCache = {}; + node.animationCache.prevKey = null; + node.animationCache.nextKey = null; + node.animationCache.originalMatrix = object.matrix; - ].join("\n") + } - }, + var keys = this.data.hierarchy[h].keys; - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + if (keys.length) { - 'cube': { + node.animationCache.prevKey = keys[ 0 ]; + node.animationCache.nextKey = keys[ 1 ]; - uniforms: { "tCube": { type: "t", value: null }, - "tFlip": { type: "f", value: - 1 } }, + this.startTime = Math.min( keys[0].time, this.startTime ); + this.endTime = Math.max( keys[keys.length - 1].time, this.endTime ); - vertexShader: [ + } - "varying vec3 vWorldPosition;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + this.update( 0 ); - "void main() {", + } - " vWorldPosition = transformDirection( position, modelMatrix );", + this.isPaused = false; - " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", + THREE.AnimationHandler.play( this ); - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + }, - "}" + stop: function () { - ].join("\n"), + this.isPlaying = false; + this.isPaused = false; - fragmentShader: [ + THREE.AnimationHandler.stop( this ); - "uniform samplerCube tCube;", - "uniform float tFlip;", + // reset JIT matrix and remove cache - "varying vec3 vWorldPosition;", + for ( var h = 0; h < this.data.hierarchy.length; h ++ ) { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var obj = this.hierarchy[ h ]; + var node = this.data.hierarchy[ h ]; - "void main() {", + if ( node.animationCache !== undefined ) { - " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", + var original = node.animationCache.originalMatrix; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + original.copy( obj.matrix ); + obj.matrix = original; - "}" + delete node.animationCache; - ].join("\n") + } + + } }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + update: function ( delta ) { - 'equirect': { + if ( this.isPlaying === false ) return; - uniforms: { "tEquirect": { type: "t", value: null }, - "tFlip": { type: "f", value: - 1 } }, + this.currentTime += delta * this.timeScale; - vertexShader: [ + // - "varying vec3 vWorldPosition;", + var duration = this.data.length; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + if ( this.loop === true && this.currentTime > duration ) { - "void main() {", + this.currentTime %= duration; - " vWorldPosition = transformDirection( position, modelMatrix );", + } - " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", + this.currentTime = Math.min( this.currentTime, duration ); - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { - "}" + var object = this.hierarchy[ h ]; + var node = this.data.hierarchy[ h ]; - ].join("\n"), + var keys = node.keys, + animationCache = node.animationCache; - fragmentShader: [ - "uniform sampler2D tEquirect;", - "uniform float tFlip;", + if ( keys.length ) { - "varying vec3 vWorldPosition;", + var prevKey = animationCache.prevKey; + var nextKey = animationCache.nextKey; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + if ( nextKey.time <= this.currentTime ) { - "void main() {", + while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { - // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", - "vec3 direction = normalize( vWorldPosition );", - "vec2 sampleUV;", - "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );", - "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", - "gl_FragColor = texture2D( tEquirect, sampleUV );", + prevKey = nextKey; + nextKey = keys[ prevKey.index + 1 ]; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + } - "}" + animationCache.prevKey = prevKey; + animationCache.nextKey = nextKey; - ].join("\n") + } - }, + if ( nextKey.time >= this.currentTime ) { - /* Depth encoding into RGBA texture - * - * based on SpiderGL shadow map example - * http://spidergl.org/example.php?id=6 - * - * originally from - * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD - * - * see also - * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ - */ + prevKey.interpolate( nextKey, this.currentTime ); - 'depthRGBA': { + } else { - uniforms: {}, + prevKey.interpolate( nextKey, nextKey.time ); - vertexShader: [ + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + this.data.hierarchy[ h ].node.updateMatrix(); + object.matrixWorldNeedsUpdate = true; - "void main() {", + } - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "default_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + } - "}" + }, - ].join("\n"), + getNextKeyWith: function ( sid, h, key ) { - fragmentShader: [ + var keys = this.data.hierarchy[ h ].keys; + key = key % keys.length; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + for ( ; key < keys.length; key ++ ) { - "vec4 pack_depth( const in float depth ) {", + if ( keys[ key ].hasTarget( sid ) ) { - " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", - " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", - " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );", - " res -= res.xxyz * bit_mask;", - " return res;", + return keys[ key ]; - "}", + } - "void main() {", + } - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + return keys[ 0 ]; - " #ifdef USE_LOGDEPTHBUF_EXT", + }, - " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );", + getPrevKeyWith: function ( sid, h, key ) { - " #else", + var keys = this.data.hierarchy[ h ].keys; + key = key >= 0 ? key : key + keys.length; - " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", + for ( ; key >= 0; key -- ) { - " #endif", + if ( keys[ key ].hasTarget( sid ) ) { - //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", - //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", - //"gl_FragData[ 0 ] = pack_depth( z );", - //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", + return keys[ key ]; - "}" + } - ].join("\n") + } + + return keys[ keys.length - 1 ]; } }; -// File:src/renderers/WebGLRenderTarget.js +// File:src/extras/animation/MorphAnimation.js /** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com + * @author willy-vvu / http://willy-vvu.github.io */ -THREE.WebGLRenderTarget = function ( width, height, options ) { +THREE.MorphAnimation = function ( mesh ) { - this.width = width; - this.height = height; + this.mesh = mesh; + this.frames = mesh.morphTargetInfluences.length; + this.currentTime = 0; + this.duration = 1000; + this.loop = true; + this.lastFrame = 0; + this.currentFrame = 0; - options = options || {}; - - this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping; - - this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter; - this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter; - - this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1; - - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); - - this.format = options.format !== undefined ? options.format : THREE.RGBAFormat; - this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType; + this.isPlaying = false; - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; +}; - this.generateMipmaps = true; +THREE.MorphAnimation.prototype = { - this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null; + constructor: THREE.MorphAnimation, -}; + play: function () { -THREE.WebGLRenderTarget.prototype = { + this.isPlaying = true; - constructor: THREE.WebGLRenderTarget, + }, - setSize: function ( width, height ) { + pause: function () { - this.width = width; - this.height = height; + this.isPlaying = false; }, - clone: function () { + update: function ( delta ) { - var tmp = new THREE.WebGLRenderTarget( this.width, this.height ); + if ( this.isPlaying === false ) return; - tmp.wrapS = this.wrapS; - tmp.wrapT = this.wrapT; + this.currentTime += delta; - tmp.magFilter = this.magFilter; - tmp.minFilter = this.minFilter; + if ( this.loop === true && this.currentTime > this.duration ) { - tmp.anisotropy = this.anisotropy; + this.currentTime %= this.duration; - tmp.offset.copy( this.offset ); - tmp.repeat.copy( this.repeat ); + } - tmp.format = this.format; - tmp.type = this.type; + this.currentTime = Math.min( this.currentTime, this.duration ); - tmp.depthBuffer = this.depthBuffer; - tmp.stencilBuffer = this.stencilBuffer; + var interpolation = this.duration / this.frames; + var frame = Math.floor( this.currentTime / interpolation ); - tmp.generateMipmaps = this.generateMipmaps; + var influences = this.mesh.morphTargetInfluences; - tmp.shareDepthFrom = this.shareDepthFrom; + if ( frame != this.currentFrame ) { - return tmp; + influences[ this.lastFrame ] = 0; + influences[ this.currentFrame ] = 1; + influences[ frame ] = 0; - }, + this.lastFrame = this.currentFrame; + this.currentFrame = frame; - dispose: function () { + } - this.dispatchEvent( { type: 'dispose' } ); + influences[ frame ] = ( this.currentTime % interpolation ) / interpolation; + influences[ this.lastFrame ] = 1 - influences[ frame ]; } }; -THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype ); - -// File:src/renderers/WebGLRenderTargetCube.js +// File:src/extras/geometries/BoxGeometry.js /** - * @author alteredq / http://alteredqualia.com + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as */ -THREE.WebGLRenderTargetCube = function ( width, height, options ) { - - THREE.WebGLRenderTarget.call( this, width, height, options ); +THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + THREE.Geometry.call( this ); -}; + this.type = 'BoxGeometry'; -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; -// File:src/renderers/webgl/WebGLExtensions.js + this.widthSegments = widthSegments || 1; + this.heightSegments = heightSegments || 1; + this.depthSegments = depthSegments || 1; -/** -* @author mrdoob / http://mrdoob.com/ -*/ + var scope = this; -THREE.WebGLExtensions = function ( gl ) { + var width_half = width / 2; + var height_half = height / 2; + var depth_half = depth / 2; - var extensions = {}; + buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px + buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx + buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py + buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny + buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz + buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz - this.get = function ( name ) { + function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) { - if ( extensions[ name ] !== undefined ) { + var w, ix, iy, + gridX = scope.widthSegments, + gridY = scope.heightSegments, + width_half = width / 2, + height_half = height / 2, + offset = scope.vertices.length; - return extensions[ name ]; + if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) { - } + w = 'z'; - var extension; + } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) { - switch ( name ) { + w = 'y'; + gridY = scope.depthSegments; - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - break; + } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) { - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - break; + w = 'x'; + gridX = scope.depthSegments; - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + } - default: - extension = gl.getExtension( name ); + var gridX1 = gridX + 1, + gridY1 = gridY + 1, + segment_width = width / gridX, + segment_height = height / gridY, + normal = new THREE.Vector3(); - } + normal[ w ] = depth > 0 ? 1 : - 1; - if ( extension === null ) { + for ( iy = 0; iy < gridY1; iy ++ ) { - THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + for ( ix = 0; ix < gridX1; ix ++ ) { - } + var vector = new THREE.Vector3(); + vector[ u ] = ( ix * segment_width - width_half ) * udir; + vector[ v ] = ( iy * segment_height - height_half ) * vdir; + vector[ w ] = depth; - extensions[ name ] = extension; + scope.vertices.push( vector ); - return extension; + } - }; + } -}; + for ( iy = 0; iy < gridY; iy ++ ) { -// File:src/renderers/webgl/WebGLProgram.js + for ( ix = 0; ix < gridX; ix ++ ) { -THREE.WebGLProgram = ( function () { + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - var programIdCount = 0; + var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY ); + var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ); + var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY ); + var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY ); - var generateDefines = function ( defines ) { + var face = new THREE.Face3( a + offset, b + offset, d + offset ); + face.normal.copy( normal ); + face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); + face.materialIndex = materialIndex; - var value, chunk, chunks = []; + scope.faces.push( face ); + scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - for ( var d in defines ) { + face = new THREE.Face3( b + offset, c + offset, d + offset ); + face.normal.copy( normal ); + face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); + face.materialIndex = materialIndex; - value = defines[ d ]; - if ( value === false ) continue; + scope.faces.push( face ); + scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - chunk = '#define ' + d + ' ' + value; - chunks.push( chunk ); + } } - return chunks.join( '\n' ); + } - }; + this.mergeVertices(); - var cacheUniformLocations = function ( gl, program, identifiers ) { +}; - var uniforms = {}; +THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; - for ( var i = 0, l = identifiers.length; i < l; i ++ ) { +// File:src/extras/geometries/CircleGeometry.js - var id = identifiers[ i ]; - uniforms[ id ] = gl.getUniformLocation( program, id ); +/** + * @author hughes + */ - } +THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { - return uniforms; + THREE.Geometry.call( this ); - }; + this.type = 'CircleGeometry'; - var cacheAttributeLocations = function ( gl, program, identifiers ) { + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - var attributes = {}; + radius = radius || 50; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; - for ( var i = 0, l = identifiers.length; i < l; i ++ ) { + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - var id = identifiers[ i ]; - attributes[ id ] = gl.getAttribLocation( program, id ); + var i, uvs = [], + center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 ); - } + this.vertices.push(center); + uvs.push( centerUV ); - return attributes; + for ( i = 0; i <= segments; i ++ ) { - }; + var vertex = new THREE.Vector3(); + var segment = thetaStart + i / segments * thetaLength; - return function ( renderer, code, material, parameters ) { + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - var _this = renderer; - var _gl = _this.context; + this.vertices.push( vertex ); + uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) ); - var defines = material.defines; - var uniforms = material.__webglShader.uniforms; - var attributes = material.attributes; + } - var vertexShader = material.__webglShader.vertexShader; - var fragmentShader = material.__webglShader.fragmentShader; + var n = new THREE.Vector3( 0, 0, 1 ); - var index0AttributeName = material.index0AttributeName; + for ( i = 1; i <= segments; i ++ ) { - if ( index0AttributeName === undefined && parameters.morphTargets === true ) { + this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) ); + this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] ); - // programs with morphTargets displace position out of attribute 0 + } - index0AttributeName = 'position'; + this.computeFaceNormals(); - } + this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; +}; - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { +THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; +// File:src/extras/geometries/CubeGeometry.js - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - } +THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + THREE.warn( 'THREE.CubeGeometry has been renamed to THREE.BoxGeometry.' ); + return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); - if ( parameters.envMap ) { + }; - switch ( material.envMap.mapping ) { +// File:src/extras/geometries/CylinderGeometry.js - case THREE.CubeReflectionMapping: - case THREE.CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; +/** + * @author mrdoob / http://mrdoob.com/ + */ - case THREE.EquirectangularReflectionMapping: - case THREE.EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; +THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - case THREE.SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + THREE.Geometry.call( this ); - } + this.type = 'CylinderGeometry'; - switch ( material.envMap.mapping ) { + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - case THREE.CubeRefractionMapping: - case THREE.EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + radiusTop = radiusTop !== undefined ? radiusTop : 20; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; + height = height !== undefined ? height : 100; - } + radialSegments = radialSegments || 8; + heightSegments = heightSegments || 1; - switch ( material.combine ) { + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI; - case THREE.MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + var heightHalf = height / 2; - case THREE.MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + var x, y, vertices = [], uvs = []; - case THREE.AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + for ( y = 0; y <= heightSegments; y ++ ) { - } + var verticesRow = []; + var uvsRow = []; - } + var v = y / heightSegments; + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + for ( x = 0; x <= radialSegments; x ++ ) { - // console.log( 'building new program ' ); + var u = x / radialSegments; - // + var vertex = new THREE.Vector3(); + vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); + vertex.y = - v * height + heightHalf; + vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); - var customDefines = generateDefines( defines ); + this.vertices.push( vertex ); - // + verticesRow.push( this.vertices.length - 1 ); + uvsRow.push( new THREE.Vector2( u, 1 - v ) ); - var program = _gl.createProgram(); + } - var prefix_vertex, prefix_fragment; + vertices.push( verticesRow ); + uvs.push( uvsRow ); - if ( material instanceof THREE.RawShaderMaterial ) { + } - prefix_vertex = ''; - prefix_fragment = ''; + var tanTheta = ( radiusBottom - radiusTop ) / height; + var na, nb; - } else { + for ( x = 0; x < radialSegments; x ++ ) { - prefix_vertex = [ + if ( radiusTop !== 0 ) { - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + na = this.vertices[ vertices[ 0 ][ x ] ].clone(); + nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone(); - customDefines, + } else { - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + na = this.vertices[ vertices[ 1 ][ x ] ].clone(); + nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone(); - _this.gammaInput ? '#define GAMMA_INPUT' : '', - _this.gammaOutput ? '#define GAMMA_OUTPUT' : '', - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } - '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights, - '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights, - '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights, - '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights, + na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize(); + nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize(); - '#define MAX_SHADOWS ' + parameters.maxShadows, + for ( y = 0; y < heightSegments; y ++ ) { - '#define MAX_BONES ' + parameters.maxBones, + var v1 = vertices[ y ][ x ]; + var v2 = vertices[ y + 1 ][ x ]; + var v3 = vertices[ y + 1 ][ x + 1 ]; + var v4 = vertices[ y ][ x + 1 ]; - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + var n1 = na.clone(); + var n2 = na.clone(); + var n3 = nb.clone(); + var n4 = nb.clone(); - parameters.flatShading ? '#define FLAT_SHADED': '', + var uv1 = uvs[ y ][ x ].clone(); + var uv2 = uvs[ y + 1 ][ x ].clone(); + var uv3 = uvs[ y + 1 ][ x + 1 ].clone(); + var uv4 = uvs[ y ][ x + 1 ].clone(); - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals ? '#define USE_MORPHNORMALS' : '', - parameters.wrapAround ? '#define WRAP_AROUND' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '', - parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '', + } - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', + // top cap + if ( openEnded === false && radiusTop > 0 ) { - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', + this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) ); - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', - 'attribute vec2 uv2;', + for ( x = 0; x < radialSegments; x ++ ) { - '#ifdef USE_COLOR', + var v1 = vertices[ 0 ][ x ]; + var v2 = vertices[ 0 ][ x + 1 ]; + var v3 = this.vertices.length - 1; - ' attribute vec3 color;', + var n1 = new THREE.Vector3( 0, 1, 0 ); + var n2 = new THREE.Vector3( 0, 1, 0 ); + var n3 = new THREE.Vector3( 0, 1, 0 ); - '#endif', + var uv1 = uvs[ 0 ][ x ].clone(); + var uv2 = uvs[ 0 ][ x + 1 ].clone(); + var uv3 = new THREE.Vector2( uv2.x, 0 ); - '#ifdef USE_MORPHTARGETS', + this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + } - ' #ifdef USE_MORPHNORMALS', + } - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + // bottom cap - ' #else', + if ( openEnded === false && radiusBottom > 0 ) { - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) ); - ' #endif', + for ( x = 0; x < radialSegments; x ++ ) { - '#endif', + var v1 = vertices[ heightSegments ][ x + 1 ]; + var v2 = vertices[ heightSegments ][ x ]; + var v3 = this.vertices.length - 1; - '#ifdef USE_SKINNING', + var n1 = new THREE.Vector3( 0, - 1, 0 ); + var n2 = new THREE.Vector3( 0, - 1, 0 ); + var n3 = new THREE.Vector3( 0, - 1, 0 ); - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', - - '#endif', + var uv1 = uvs[ heightSegments ][ x + 1 ].clone(); + var uv2 = uvs[ heightSegments ][ x ].clone(); + var uv3 = new THREE.Vector2( uv2.x, 1 ); - '' + this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - ].join( '\n' ); + } - prefix_fragment = [ + } - ( parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', + this.computeFaceNormals(); - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', +}; - customDefines, +THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; - '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights, - '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights, - '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights, - '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights, +// File:src/extras/geometries/ExtrudeGeometry.js - '#define MAX_SHADOWS ' + parameters.maxShadows, +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: <int>, // number of points on the curves + * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too + * amount: <int>, // Depth to extrude the shape + * + * bevelEnabled: <bool>, // turn on bevel + * bevelThickness: <float>, // how deep into the original shape bevel goes + * bevelSize: <float>, // how far from shape outline is bevel + * bevelSegments: <int>, // number of bevel layers + * + * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) + * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals + * + * material: <int> // material index for front and back faces + * extrudeMaterial: <int> // material index for extrusion and beveled faces + * uvGenerator: <Object> // object that provides UV generator functions + * + * } + **/ - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', +THREE.ExtrudeGeometry = function ( shapes, options ) { - _this.gammaInput ? '#define GAMMA_INPUT' : '', - _this.gammaOutput ? '#define GAMMA_OUTPUT' : '', - '#define GAMMA_FACTOR ' + gammaFactorDefine, + if ( typeof( shapes ) === "undefined" ) { + shapes = []; + return; + } - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', + THREE.Geometry.call( this ); - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapTypeDefine : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.envMap ? '#define ' + envMapBlendingDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + this.type = 'ExtrudeGeometry'; - parameters.flatShading ? '#define FLAT_SHADED': '', + shapes = shapes instanceof Array ? shapes : [ shapes ]; - parameters.metal ? '#define METAL' : '', - parameters.wrapAround ? '#define WRAP_AROUND' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + this.addShapeList( shapes, options ); - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '', - parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '', + this.computeFaceNormals(); - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', - '' + //this.computeVertexNormals(); - ].join( '\n' ); + //console.log( "took", ( Date.now() - startTime ) ); - } +}; - var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader ); - var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader ); +THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; - _gl.attachShader( program, glVertexShader ); - _gl.attachShader( program, glFragmentShader ); +THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { + var sl = shapes.length; - if ( index0AttributeName !== undefined ) { + for ( var s = 0; s < sl; s ++ ) { + var shape = shapes[ s ]; + this.addShape( shape, options ); + } +}; - // Force a particular attribute to index 0. - // because potentially expensive emulation is done by browser if attribute 0 is disabled. - // And, color, for example is often automatically bound to index 0 so disabling it +THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - _gl.bindAttribLocation( program, 0, index0AttributeName ); + var amount = options.amount !== undefined ? options.amount : 100; - } + var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 + var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 + var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - _gl.linkProgram( program ); + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - var programLogInfo = _gl.getProgramInfoLog( program ); + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { + var steps = options.steps !== undefined ? options.steps : 1; - THREE.error( 'THREE.WebGLProgram: shader error: ' + _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getPRogramInfoLog', programLogInfo ); + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - } + var material = options.material; + var extrudeMaterial = options.extrudeMaterial; - if ( programLogInfo !== '' ) { + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; - THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()' + programLogInfo ); - // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); - // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - } + extrudePts = extrudePath.getSpacedPoints( steps ); - // clean up + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - _gl.deleteShader( glVertexShader ); - _gl.deleteShader( glFragmentShader ); + // SETUP TNB variables - // cache uniform locations + // Reuse TNB from TubeGeomtry for now. + // TODO1 - have a .isClosed in spline? - var identifiers = [ + splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false); - 'viewMatrix', - 'modelViewMatrix', - 'projectionMatrix', - 'normalMatrix', - 'modelMatrix', - 'cameraPosition', - 'morphTargetInfluences', - 'bindMatrix', - 'bindMatrixInverse' + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - ]; + binormal = new THREE.Vector3(); + normal = new THREE.Vector3(); + position2 = new THREE.Vector3(); - if ( parameters.useVertexTexture ) { + } - identifiers.push( 'boneTexture' ); - identifiers.push( 'boneTextureWidth' ); - identifiers.push( 'boneTextureHeight' ); + // Safeguards if bevels are not enabled - } else { + if ( ! bevelEnabled ) { - identifiers.push( 'boneGlobalMatrices' ); + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - } + } - if ( parameters.logarithmicDepthBuffer ) { + // Variables initalization - identifiers.push('logDepthBufFC'); + var ahole, h, hl; // looping of holes + var scope = this; - } + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - for ( var u in uniforms ) { + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - identifiers.push( u ); + var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ; - } + if ( reverse ) { - this.uniforms = cacheUniformLocations( _gl, program, identifiers ); + vertices = vertices.reverse(); - // cache attributes locations + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - identifiers = [ + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - 'position', - 'normal', - 'uv', - 'uv2', - 'tangent', - 'color', - 'skinIndex', - 'skinWeight', - 'lineDistance' + ahole = holes[ h ]; - ]; + if ( THREE.Shape.Utils.isClockWise( ahole ) ) { - for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) { + holes[ h ] = ahole.reverse(); - identifiers.push( 'morphTarget' + i ); + } } - for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) { - - identifiers.push( 'morphNormal' + i ); + reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - } + } - for ( var a in attributes ) { - identifiers.push( a ); + var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes ); - } + /* Vertices */ - this.attributes = cacheAttributeLocations( _gl, program, identifiers ); - this.attributesKeys = Object.keys( this.attributes ); + var contour = vertices; // vertices has all points but contour has only points of circumference - // + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + ahole = holes[ h ]; - return this; + vertices = vertices.concat( ahole ); - }; + } -} )(); -// File:src/renderers/webgl/WebGLShader.js + function scalePt2 ( pt, vec, size ) { -THREE.WebGLShader = ( function () { + if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" ); - var addLineNumbers = function ( string ) { + return vec.clone().multiplyScalar( size ).add( pt ); - var lines = string.split( '\n' ); + } - for ( var i = 0; i < lines.length; i ++ ) { + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - } + // Find directions for point movement - return lines.join( '\n' ); - }; + function getBevelVec( inPt, inPrev, inNext ) { - return function ( gl, type, string ) { + var EPSILON = 0.0000000001; + + // computes for inPt the corresponding point inPt' on a new contour + // shiftet by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. + + var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - var shader = gl.createShader( type ); + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for colinear edges + var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear + + // length of vectors for normalizing + + var v_prev_len = Math.sqrt( v_prev_lensq ); + var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + + // shift adjacent points by unit vectors to the left + + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + // vector from inPt to intersection point + + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ) + if ( v_trans_lensq <= 2 ) { + return new THREE.Vector2( v_trans_x, v_trans_y ); + } else { + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + } + + } else { // handle special case of colinear edges - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + var direction_eq = false; // assumes: opposite + if ( v_prev_x > EPSILON ) { + if ( v_next_x > EPSILON ) { direction_eq = true; } + } else { + if ( v_prev_x < - EPSILON ) { + if ( v_next_x < - EPSILON ) { direction_eq = true; } + } else { + if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; } + } + } - THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); + if ( direction_eq ) { + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); + } else { + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); + } } - if ( gl.getShaderInfoLog( shader ) !== '' ) { + return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); + } - } - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + var contourMovements = []; - return shader; + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - }; + if ( j === il ) j = 0; + if ( k === il ) k = 0; -} )(); + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) -// File:src/renderers/webgl/WebGLState.js + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + } -THREE.WebGLState = function ( gl, paramThreeToGL ) { + var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - var newAttributes = new Uint8Array( 16 ); - var enabledAttributes = new Uint8Array( 16 ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; + ahole = holes[ h ]; - var currentDepthTest = null; - var currentDepthWrite = null; + oneHoleMovements = []; - var currentColorWrite = null; + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - var currentDoubleSided = null; - var currentFlipSided = null; + if ( j === il ) j = 0; + if ( k === il ) k = 0; - var currentLineWidth = null; + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - var currentPolygonOffset = null; - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + } - this.initAttributes = function () { + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + } - newAttributes[ i ] = 0; - } + // Loop bevelSegments, 1 for the front, 1 for the back - }; + for ( b = 0; b < bevelSegments; b ++ ) { + //for ( b = bevelSegments; b > 0; b -- ) { - this.enableAttribute = function ( attribute ) { + t = b / bevelSegments; + z = bevelThickness * ( 1 - t ); - newAttributes[ attribute ] = 1; + //z = bevelThickness * t; + bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved + //bs = bevelSize * t ; // linear - if ( enabledAttributes[ attribute ] === 0 ) { + // contract shape - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + for ( i = 0, il = contour.length; i < il; i ++ ) { + + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); } - }; + // expand holes - this.disableUnusedAttributes = function () { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) { + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + for ( i = 0, il = ahole.length; i < il; i ++ ) { - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); } } - }; + } - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) { + bs = bevelSize; - if ( blending !== currentBlending ) { + // Back facing vertices - if ( blending === THREE.NoBlending ) { + for ( i = 0; i < vlen; i ++ ) { - gl.disable( gl.BLEND ); + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - } else if ( blending === THREE.AdditiveBlending ) { + if ( ! extrudeByPath ) { - gl.enable( gl.BLEND ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + v( vert.x, vert.y, 0 ); - } else if ( blending === THREE.SubtractiveBlending ) { + } else { - // TODO: Find blendFuncSeparate() combination - gl.enable( gl.BLEND ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - } else if ( blending === THREE.MultiplyBlending ) { + normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x); + binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y); - // TODO: Find blendFuncSeparate() combination - gl.enable( gl.BLEND ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + position2.copy( extrudePts[0] ).add(normal).add(binormal); - } else if ( blending === THREE.CustomBlending ) { + v( position2.x, position2.y, position2.z ); - gl.enable( gl.BLEND ); + } - } else { + } - gl.enable( gl.BLEND ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + // Add stepped vertices... + // Including front facing vertices - } + var s; - currentBlending = blending; + for ( s = 1; s <= steps; s ++ ) { - } + for ( i = 0; i < vlen; i ++ ) { - if ( blending === THREE.CustomBlending ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + if ( ! extrudeByPath ) { - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + v( vert.x, vert.y, amount / steps * s ); - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + } else { - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - } + normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y ); - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + position2.copy( extrudePts[s] ).add( normal ).add( binormal ); - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + v( position2.x, position2.y, position2.z ); } - } else { - - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - } - }; - - this.setDepthTest = function ( depthTest ) { + } - if ( currentDepthTest !== depthTest ) { - if ( depthTest ) { + // Add bevel segments planes - gl.enable( gl.DEPTH_TEST ); + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - } else { + t = b / bevelSegments; + z = bevelThickness * ( 1 - t ); + //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) ); + bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ; - gl.disable( gl.DEPTH_TEST ); + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - currentDepthTest = depthTest; + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, amount + z ); } - }; - - this.setDepthWrite = function ( depthWrite ) { + // expand holes - if ( currentDepthWrite !== depthWrite ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - gl.depthMask( depthWrite ); - currentDepthWrite = depthWrite; + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - } + for ( i = 0, il = ahole.length; i < il; i ++ ) { - }; + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - this.setColorWrite = function ( colorWrite ) { + if ( ! extrudeByPath ) { - if ( currentColorWrite !== colorWrite ) { + v( vert.x, vert.y, amount + z ); - gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite ); - currentColorWrite = colorWrite; + } else { - } + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - }; + } - this.setDoubleSided = function ( doubleSided ) { + } - if ( currentDoubleSided !== doubleSided ) { + } - if ( doubleSided ) { + } - gl.disable( gl.CULL_FACE ); + /* Faces */ - } else { + // Top and bottom faces - gl.enable( gl.CULL_FACE ); + buildLidFaces(); - } + // Sides faces - currentDoubleSided = doubleSided; + buildSideFaces(); - } - }; + ///// Internal functions - this.setFlipSided = function ( flipSided ) { + function buildLidFaces() { - if ( currentFlipSided !== flipSided ) { + if ( bevelEnabled ) { - if ( flipSided ) { + var layer = 0 ; // steps + 1 + var offset = vlen * layer; - gl.frontFace( gl.CW ); + // Bottom faces - } else { + for ( i = 0; i < flen; i ++ ) { - gl.frontFace( gl.CCW ); + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); } - currentFlipSided = flipSided; + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - }; + for ( i = 0; i < flen; i ++ ) { - this.setLineWidth = function ( width ) { + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - if ( width !== currentLineWidth ) { + } - gl.lineWidth( width ); + } else { - currentLineWidth = width; + // Bottom faces - } + for ( i = 0; i < flen; i ++ ) { - }; + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - this.setPolygonOffset = function ( polygonoffset, factor, units ) { + } - if ( currentPolygonOffset !== polygonoffset ) { + // Top faces - if ( polygonoffset ) { + for ( i = 0; i < flen; i ++ ) { - gl.enable( gl.POLYGON_OFFSET_FILL ); + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - } else { + } + } - gl.disable( gl.POLYGON_OFFSET_FILL ); + } - } + // Create faces for the z-sides of the shape - currentPolygonOffset = polygonoffset; + function buildSideFaces() { - } + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - gl.polygonOffset( factor, units ); + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + //, true + layeroffset += ahole.length; } - }; + } - this.reset = function () { + function sidewalls( contour, layeroffset ) { - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + var j, k; + i = contour.length; - enabledAttributes[ i ] = 0; + while ( -- i >= 0 ) { - } + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - currentBlending = null; - currentDepthTest = null; - currentDepthWrite = null; - currentColorWrite = null; - currentDoubleSided = null; - currentFlipSided = null; + //console.log('b', i,j, i-1, k,vertices.length); - }; + var s = 0, sl = steps + bevelSegments * 2; -}; + for ( s = 0; s < sl; s ++ ) { -// File:src/renderers/webgl/plugins/LensFlarePlugin.js + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; -THREE.LensFlarePlugin = function ( renderer, flares ) { + f4( a, b, c, d, contour, s, sl, j, k ); - var gl = renderer.context; + } + } - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; - var hasVertexTexture; + } - var tempTexture, occlusionTexture; - var init = function () { + function v( x, y, z ) { - var vertices = new Float32Array( [ - -1, -1, 0, 0, - 1, -1, 1, 0, - 1, 1, 1, 1, - -1, 1, 0, 1 - ] ); + scope.vertices.push( new THREE.Vector3( x, y, z ) ); - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + } - // buffers + function f3( a, b, c ) { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + // normal, color, material + scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + var uvs = uvgen.generateTopUV( scope, a, b, c ); - // textures + scope.faceVertexUvs[ 0 ].push( uvs ); - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + } - gl.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - gl.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; + d += shapesOffset; - hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0; + scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) ); + scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) ); - var shader; + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - if ( hasVertexTexture ) { + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - shader = { + } - vertexShader: [ +}; - "uniform lowp int renderType;", +THREE.ExtrudeGeometry.WorldUVGenerator = { - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + generateTopUV: function ( geometry, indexA, indexB, indexC ) { - "uniform sampler2D occlusionMap;", + var vertices = geometry.vertices; - "attribute vec2 position;", - "attribute vec2 uv;", + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; - "varying vec2 vUV;", - "varying float vVisibility;", + return [ + new THREE.Vector2( a.x, a.y ), + new THREE.Vector2( b.x, b.y ), + new THREE.Vector2( c.x, c.y ) + ]; - "void main() {", + }, - "vUV = uv;", + generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { - "vec2 pos = position;", + var vertices = geometry.vertices; - "if( renderType == 2 ) {", + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; + var d = vertices[ indexD ]; - "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", + if ( Math.abs( a.y - b.y ) < 0.01 ) { + return [ + new THREE.Vector2( a.x, 1 - a.z ), + new THREE.Vector2( b.x, 1 - b.z ), + new THREE.Vector2( c.x, 1 - c.z ), + new THREE.Vector2( d.x, 1 - d.z ) + ]; + } else { + return [ + new THREE.Vector2( a.y, 1 - a.z ), + new THREE.Vector2( b.y, 1 - b.z ), + new THREE.Vector2( c.y, 1 - c.z ), + new THREE.Vector2( d.y, 1 - d.z ) + ]; + } + } +}; - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", +// File:src/extras/geometries/ShapeGeometry.js - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", +/** + * @author jonobr1 / http://jonobr1.com + * + * Creates a one-sided polygonal geometry from a path shape. Similar to + * ExtrudeGeometry. + * + * parameters = { + * + * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT. + * + * material: <int> // material index for front and back faces + * uvGenerator: <Object> // object that provides UV generator functions + * + * } + **/ - "}", +THREE.ShapeGeometry = function ( shapes, options ) { - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + THREE.Geometry.call( this ); - "}" + this.type = 'ShapeGeometry'; - ].join( "\n" ), + if ( shapes instanceof Array === false ) shapes = [ shapes ]; - fragmentShader: [ + this.addShapeList( shapes, options ); - "uniform lowp int renderType;", + this.computeFaceNormals(); - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", +}; - "varying vec2 vUV;", - "varying float vVisibility;", +THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; - "void main() {", +/** + * Add an array of shapes to THREE.ShapeGeometry. + */ +THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - // pink square + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - "if( renderType == 0 ) {", + this.addShape( shapes[ i ], options ); - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + } - // restore + return this; - "} else if( renderType == 1 ) {", +}; - "gl_FragColor = texture2D( map, vUV );", +/** + * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. + */ +THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { - // flare + if ( options === undefined ) options = {}; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - "} else {", + var material = options.material; + var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + // - "}", + var i, l, hole; - "}" + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - ].join( "\n" ) + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - }; + var reverse = ! THREE.Shape.Utils.isClockWise( vertices ); - } else { + if ( reverse ) { - shader = { + vertices = vertices.reverse(); - vertexShader: [ + // Maybe we should also check if holes are in the opposite direction, just to be safe... - "uniform lowp int renderType;", + for ( i = 0, l = holes.length; i < l; i ++ ) { - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + hole = holes[ i ]; - "attribute vec2 position;", - "attribute vec2 uv;", + if ( THREE.Shape.Utils.isClockWise( hole ) ) { - "varying vec2 vUV;", + holes[ i ] = hole.reverse(); - "void main() {", + } - "vUV = uv;", + } - "vec2 pos = position;", + reverse = false; - "if( renderType == 2 ) {", + } - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + var faces = THREE.Shape.Utils.triangulateShape( vertices, holes ); - "}", + // Vertices - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + var contour = vertices; - "}" + for ( i = 0, l = holes.length; i < l; i ++ ) { - ].join( "\n" ), + hole = holes[ i ]; + vertices = vertices.concat( hole ); - fragmentShader: [ + } - "precision mediump float;", + // - "uniform lowp int renderType;", + var vert, vlen = vertices.length; + var face, flen = faces.length; - "uniform sampler2D map;", - "uniform sampler2D occlusionMap;", - "uniform float opacity;", - "uniform vec3 color;", + for ( i = 0; i < vlen; i ++ ) { - "varying vec2 vUV;", + vert = vertices[ i ]; - "void main() {", + this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); - // pink square + } - "if( renderType == 0 ) {", + for ( i = 0; i < flen; i ++ ) { - "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );", + face = faces[ i ]; - // restore + var a = face[ 0 ] + shapesOffset; + var b = face[ 1 ] + shapesOffset; + var c = face[ 2 ] + shapesOffset; - "} else if( renderType == 1 ) {", + this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); + this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); - "gl_FragColor = texture2D( map, vUV );", + } - // flare +}; - "} else {", +// File:src/extras/geometries/LatheGeometry.js - "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;", - "visibility = ( 1.0 - visibility / 4.0 );", +/** + * @author astrodud / http://astrodud.isgreat.org/ + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://exocortex.com + */ - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * visibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", +// points - to create a closed torus, one must use a set of points +// like so: [ a, b, c, d, a ], see first is the same as last. +// segments - the number of circumference segments to create +// phiStart - the starting radian +// phiLength - the radian (0 to 2*PI) range of the lathed section +// 2*pi is a closed lathe, less than 2PI is a portion. - "}", +THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { - "}" + THREE.Geometry.call( this ); - ].join( "\n" ) + this.type = 'LatheGeometry'; - }; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - } + segments = segments || 12; + phiStart = phiStart || 0; + phiLength = phiLength || 2 * Math.PI; - program = createProgram( shader ); + var inversePointLength = 1.0 / ( points.length - 1 ); + var inverseSegments = 1.0 / segments; - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - } + for ( var i = 0, il = segments; i <= il; i ++ ) { - uniforms = { - renderType: gl.getUniformLocation( program, "renderType" ), - map: gl.getUniformLocation( program, "map" ), - occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), - opacity: gl.getUniformLocation( program, "opacity" ), - color: gl.getUniformLocation( program, "color" ), - scale: gl.getUniformLocation( program, "scale" ), - rotation: gl.getUniformLocation( program, "rotation" ), - screenPosition: gl.getUniformLocation( program, "screenPosition" ) - }; - - }; - - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ - - this.render = function ( scene, camera, viewportWidth, viewportHeight ) { - - if ( flares.length === 0 ) return; + var phi = phiStart + i * inverseSegments * phiLength; - var tempPosition = new THREE.Vector3(); + var c = Math.cos( phi ), + s = Math.sin( phi ); - var invAspect = viewportHeight / viewportWidth, - halfViewportWidth = viewportWidth * 0.5, - halfViewportHeight = viewportHeight * 0.5; + for ( var j = 0, jl = points.length; j < jl; j ++ ) { - var size = 16 / viewportHeight, - scale = new THREE.Vector2( size * invAspect, size ); + var pt = points[ j ]; - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); + var vertex = new THREE.Vector3(); - if ( program === undefined ) { + vertex.x = c * pt.x - s * pt.y; + vertex.y = s * pt.x + c * pt.y; + vertex.z = pt.z; - init(); + this.vertices.push( vertex ); } - gl.useProgram( program ); - - gl.enableVertexAttribArray( attributes.vertex ); - gl.enableVertexAttribArray( attributes.uv ); - - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/unforms - - gl.uniform1i( uniforms.occlusionMap, 0 ); - gl.uniform1i( uniforms.map, 1 ); - - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + } - gl.disable( gl.CULL_FACE ); - gl.depthMask( false ); + var np = points.length; - for ( var i = 0, l = flares.length; i < l; i ++ ) { + for ( var i = 0, il = segments; i < il; i ++ ) { - size = 16 / viewportHeight; - scale.set( size * invAspect, size ); + for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) { - // calc object screen position + var base = j + np * i; + var a = base; + var b = base + np; + var c = base + 1 + np; + var d = base + 1; - var flare = flares[ i ]; + var u0 = i * inverseSegments; + var v0 = j * inversePointLength; + var u1 = u0 + inverseSegments; + var v1 = v0 + inversePointLength; - tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] ); + this.faces.push( new THREE.Face3( a, b, d ) ); - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); + this.faceVertexUvs[ 0 ].push( [ - // setup arrays for gl programs + new THREE.Vector2( u0, v0 ), + new THREE.Vector2( u1, v0 ), + new THREE.Vector2( u0, v1 ) - screenPosition.copy( tempPosition ) + ] ); - screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth; - screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight; + this.faces.push( new THREE.Face3( b, c, d ) ); - // screen cull + this.faceVertexUvs[ 0 ].push( [ - if ( hasVertexTexture || ( - screenPositionPixels.x > 0 && - screenPositionPixels.x < viewportWidth && - screenPositionPixels.y > 0 && - screenPositionPixels.y < viewportHeight ) ) { + new THREE.Vector2( u1, v0 ), + new THREE.Vector2( u1, v1 ), + new THREE.Vector2( u0, v1 ) - // save current RGB to temp texture + ] ); - gl.activeTexture( gl.TEXTURE1 ); - gl.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); + } - // render pink quad + } - gl.uniform1i( uniforms.renderType, 0 ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + this.mergeVertices(); + this.computeFaceNormals(); + this.computeVertexNormals(); - gl.disable( gl.BLEND ); - gl.enable( gl.DEPTH_TEST ); +}; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); +THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; +// File:src/extras/geometries/PlaneGeometry.js - // copy result to occlusionMap +/** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - gl.activeTexture( gl.TEXTURE0 ); - gl.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 ); +THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { + console.info( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' ); - // restore graphics + THREE.Geometry.call( this ); - gl.uniform1i( uniforms.renderType, 1 ); - gl.disable( gl.DEPTH_TEST ); + this.type = 'PlaneGeometry'; - gl.activeTexture( gl.TEXTURE1 ); - gl.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - // update object positions +}; - flare.positionScreen.copy( screenPosition ) +THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; - if ( flare.customUpdateCallback ) { +// File:src/extras/geometries/PlaneBufferGeometry.js - flare.customUpdateCallback( flare ); +/** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - } else { +THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { - flare.updateLensFlares(); + THREE.BufferGeometry.call( this ); - } + this.type = 'PlaneBufferGeometry'; - // render flares + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - gl.uniform1i( uniforms.renderType, 2 ); - gl.enable( gl.BLEND ); + var width_half = width / 2; + var height_half = height / 2; - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + var gridX = widthSegments || 1; + var gridY = heightSegments || 1; - var sprite = flare.lensFlares[ j ]; + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + var segment_width = width / gridX; + var segment_height = height / gridY; - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + var vertices = new Float32Array( gridX1 * gridY1 * 3 ); + var normals = new Float32Array( gridX1 * gridY1 * 3 ); + var uvs = new Float32Array( gridX1 * gridY1 * 2 ); - size = sprite.size * sprite.scale / viewportHeight; + var offset = 0; + var offset2 = 0; - scale.x = size * invAspect; - scale.y = size; + for ( var iy = 0; iy < gridY1; iy ++ ) { - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + var y = iy * segment_height - height_half; - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + for ( var ix = 0; ix < gridX1; ix ++ ) { - renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture( sprite.texture, 1 ); + var x = ix * segment_width - width_half; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - } + normals[ offset + 2 ] = 1; - } + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - } + offset += 3; + offset2 += 2; } - // restore gl - - gl.enable( gl.CULL_FACE ); - gl.enable( gl.DEPTH_TEST ); - gl.depthMask( true ); - - renderer.resetGLState(); - - }; + } - function createProgram ( shader ) { + offset = 0; - var program = gl.createProgram(); + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + for ( var iy = 0; iy < gridY; iy ++ ) { - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + for ( var ix = 0; ix < gridX; ix ++ ) { - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; - gl.linkProgram( program ); + offset += 6; - return program; + } } + this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + }; -// File:src/renderers/webgl/plugins/ShadowMapPlugin.js +THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); +THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; + +// File:src/extras/geometries/RingGeometry.js /** - * @author alteredq / http://alteredqualia.com/ + * @author Kaleb Murphy */ -THREE.ShadowMapPlugin = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) { - - var _gl = _renderer.context; - - var _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, - - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), - - _min = new THREE.Vector3(), - _max = new THREE.Vector3(), +THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - _matrixPosition = new THREE.Vector3(), + THREE.Geometry.call( this ); - _renderList = []; + this.type = 'RingGeometry'; - // init + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - var depthShader = THREE.ShaderLib[ "depthRGBA" ]; - var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); + innerRadius = innerRadius || 0; + outerRadius = outerRadius || 50; - _depthMaterial = new THREE.ShaderMaterial( { - uniforms: depthUniforms, - vertexShader: depthShader.vertexShader, - fragmentShader: depthShader.fragmentShader - } ); + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - _depthMaterialMorph = new THREE.ShaderMaterial( { - uniforms: depthUniforms, - vertexShader: depthShader.vertexShader, - fragmentShader: depthShader.fragmentShader, - morphTargets: true - } ); + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8; - _depthMaterialSkin = new THREE.ShaderMaterial( { - uniforms: depthUniforms, - vertexShader: depthShader.vertexShader, - fragmentShader: depthShader.fragmentShader, - skinning: true - } ); + var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - _depthMaterialMorphSkin = new THREE.ShaderMaterial( { - uniforms: depthUniforms, - vertexShader: depthShader.vertexShader, - fragmentShader: depthShader.fragmentShader, - morphTargets: true, - skinning: true - } ); + for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring - _depthMaterial._shadowPass = true; - _depthMaterialMorph._shadowPass = true; - _depthMaterialSkin._shadowPass = true; - _depthMaterialMorphSkin._shadowPass = true; + for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle - this.render = function ( scene, camera ) { + var vertex = new THREE.Vector3(); + var segment = thetaStart + o / thetaSegments * thetaLength; + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - if ( _renderer.shadowMapEnabled === false ) return; + this.vertices.push( vertex ); + uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) ); + } - var i, il, j, jl, n, + radius += radiusStep; - shadowMap, shadowMatrix, shadowCamera, - buffer, material, - webglObject, object, light, + } - lights = [], - k = 0, + var n = new THREE.Vector3( 0, 0, 1 ); - fog = null; + for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring - // set GL state for depth map + var thetaSegment = i * (thetaSegments + 1); - _gl.clearColor( 1, 1, 1, 1 ); - _gl.disable( _gl.BLEND ); + for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle - _gl.enable( _gl.CULL_FACE ); - _gl.frontFace( _gl.CCW ); + var segment = o + thetaSegment; - if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { + var v1 = segment; + var v2 = segment + thetaSegments + 1; + var v3 = segment + thetaSegments + 2; - _gl.cullFace( _gl.FRONT ); + this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); + this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); - } else { + v1 = segment; + v2 = segment + thetaSegments + 2; + v3 = segment + 1; - _gl.cullFace( _gl.BACK ); + this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); + this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); } + } - _renderer.state.setDepthTest( true ); - - // preprocess lights - // - skip lights that are not casting shadows - // - create virtual lights for cascaded shadow maps + this.computeFaceNormals(); - for ( i = 0, il = _lights.length; i < il; i ++ ) { + this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - light = _lights[ i ]; +}; - if ( ! light.castShadow ) continue; +THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; - if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) { - for ( n = 0; n < light.shadowCascadeCount; n ++ ) { +// File:src/extras/geometries/SphereGeometry.js - var virtualLight; +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( ! light.shadowCascadeArray[ n ] ) { +THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - virtualLight = createVirtualLight( light, n ); - virtualLight.originalCamera = camera; + THREE.Geometry.call( this ); - var gyro = new THREE.Gyroscope(); - gyro.position.copy( light.shadowCascadeOffset ); + this.type = 'SphereGeometry'; - gyro.add( virtualLight ); - gyro.add( virtualLight.target ); + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - camera.add( gyro ); + radius = radius || 50; - light.shadowCascadeArray[ n ] = virtualLight; + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); - //console.log( "Created virtualLight", virtualLight ); + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; - } else { + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; - virtualLight = light.shadowCascadeArray[ n ]; + var x, y, vertices = [], uvs = []; - } + for ( y = 0; y <= heightSegments; y ++ ) { - updateVirtualLight( light, n ); + var verticesRow = []; + var uvsRow = []; - lights[ k ] = virtualLight; - k ++; + for ( x = 0; x <= widthSegments; x ++ ) { - } + var u = x / widthSegments; + var v = y / heightSegments; - } else { + var vertex = new THREE.Vector3(); + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - lights[ k ] = light; - k ++; + this.vertices.push( vertex ); - } + verticesRow.push( this.vertices.length - 1 ); + uvsRow.push( new THREE.Vector2( u, 1 - v ) ); } - // render depth map + vertices.push( verticesRow ); + uvs.push( uvsRow ); - for ( i = 0, il = lights.length; i < il; i ++ ) { + } - light = lights[ i ]; + for ( y = 0; y < heightSegments; y ++ ) { - if ( ! light.shadowMap ) { + for ( x = 0; x < widthSegments; x ++ ) { - var shadowFilter = THREE.LinearFilter; + var v1 = vertices[ y ][ x + 1 ]; + var v2 = vertices[ y ][ x ]; + var v3 = vertices[ y + 1 ][ x ]; + var v4 = vertices[ y + 1 ][ x + 1 ]; - if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) { + var n1 = this.vertices[ v1 ].clone().normalize(); + var n2 = this.vertices[ v2 ].clone().normalize(); + var n3 = this.vertices[ v3 ].clone().normalize(); + var n4 = this.vertices[ v4 ].clone().normalize(); - shadowFilter = THREE.NearestFilter; + var uv1 = uvs[ y ][ x + 1 ].clone(); + var uv2 = uvs[ y ][ x ].clone(); + var uv3 = uvs[ y + 1 ][ x ].clone(); + var uv4 = uvs[ y + 1 ][ x + 1 ].clone(); - } + if ( Math.abs( this.vertices[ v1 ].y ) === radius ) { - var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat }; + uv1.x = ( uv1.x + uv2.x ) / 2; + this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] ); - light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars ); - light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight ); + } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) { - light.shadowMatrix = new THREE.Matrix4(); + uv3.x = ( uv3.x + uv4.x ) / 2; + this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); - } + } else { - if ( ! light.shadowCamera ) { + this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); - if ( light instanceof THREE.SpotLight ) { + this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); + this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); - light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar ); + } - } else if ( light instanceof THREE.DirectionalLight ) { + } - light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar ); + } - } else { + this.computeFaceNormals(); - THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light ); - continue; + this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - } +}; - scene.add( light.shadowCamera ); +THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - - } - - if ( light.shadowCameraVisible && ! light.cameraHelper ) { - - light.cameraHelper = new THREE.CameraHelper( light.shadowCamera ); - scene.add( light.cameraHelper ); +// File:src/extras/geometries/TextGeometry.js - } +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * For creating 3D text geometry in three.js + * + * Text = 3D Text + * + * parameters = { + * size: <float>, // size of the text + * height: <float>, // thickness to extrude text + * curveSegments: <int>, // number of points on the curves + * + * font: <string>, // font name + * weight: <string>, // font weight (normal, bold) + * style: <string>, // font style (normal, italics) + * + * bevelEnabled: <bool>, // turn on bevel + * bevelThickness: <float>, // how deep into text bevel goes + * bevelSize: <float>, // how far from text outline is bevel + * } + * + */ - if ( light.isVirtual && virtualLight.originalCamera == camera ) { +/* Usage Examples - updateShadowCamera( camera, light ); + // TextGeometry wrapper - } + var text3d = new TextGeometry( text, options ); - shadowMap = light.shadowMap; - shadowMatrix = light.shadowMatrix; - shadowCamera = light.shadowCamera; + // Complete manner - // + var textShapes = THREE.FontUtils.generateShapes( text, options ); + var text3d = new ExtrudeGeometry( textShapes, options ); - shadowCamera.position.setFromMatrixPosition( light.matrixWorld ); - _matrixPosition.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _matrixPosition ); - shadowCamera.updateMatrixWorld(); +*/ - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - // +THREE.TextGeometry = function ( text, parameters ) { - if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible; - if ( light.shadowCameraVisible ) light.cameraHelper.update(); + parameters = parameters || {}; - // compute shadow matrix + var textShapes = THREE.FontUtils.generateShapes( text, parameters ); - shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 - ); + // translate parameters to ExtrudeGeometry API - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + parameters.amount = parameters.height !== undefined ? parameters.height : 50; - // update camera matrices and frustum + // defaults - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - // render shadow map + THREE.ExtrudeGeometry.call( this, textShapes, parameters ); - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); + this.type = 'TextGeometry'; - // set object matrices & frustum culling +}; - _renderList.length = 0; +THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); +THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; - projectObject( scene, scene, shadowCamera ); +// File:src/extras/geometries/TorusGeometry.js +/** + * @author oosmoxiecode + * @author mrdoob / http://mrdoob.com/ + * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 + */ - // render regular objects +THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { - var objectMaterial, useMorphing, useSkinning; + THREE.Geometry.call( this ); - for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { + this.type = 'TorusGeometry'; - webglObject = _renderList[ j ]; + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - object = webglObject.object; - buffer = webglObject.buffer; + radius = radius || 100; + tube = tube || 40; + radialSegments = radialSegments || 8; + tubularSegments = tubularSegments || 6; + arc = arc || Math.PI * 2; - // culling is overriden globally for all objects - // while rendering depth map + var center = new THREE.Vector3(), uvs = [], normals = []; - // need to deal with MeshFaceMaterial somehow - // in that case just use the first of material.materials for now - // (proper solution would require to break objects by materials - // similarly to regular rendering and then set corresponding - // depth materials per each chunk instead of just once per object) + for ( var j = 0; j <= radialSegments; j ++ ) { - objectMaterial = getObjectMaterial( object ); + for ( var i = 0; i <= tubularSegments; i ++ ) { - useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; - useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - if ( object.customDepthMaterial ) { + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); - material = object.customDepthMaterial; + var vertex = new THREE.Vector3(); + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); - } else if ( useSkinning ) { + this.vertices.push( vertex ); - material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; + uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) ); + normals.push( vertex.clone().sub( center ).normalize() ); - } else if ( useMorphing ) { + } - material = _depthMaterialMorph; + } - } else { + for ( var j = 1; j <= radialSegments; j ++ ) { - material = _depthMaterial; + for ( var i = 1; i <= tubularSegments; i ++ ) { - } + var a = ( tubularSegments + 1 ) * j + i - 1; + var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + var d = ( tubularSegments + 1 ) * j + i; - _renderer.setMaterialFaces( objectMaterial ); + var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] ); + this.faces.push( face ); + this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] ); - if ( buffer instanceof THREE.BufferGeometry ) { + face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] ); + this.faces.push( face ); + this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] ); - _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object ); + } - } else { + } - _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object ); + this.computeFaceNormals(); - } +}; - } +THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; - // set matrices and render immediate objects +// File:src/extras/geometries/TorusKnotGeometry.js - for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) { +/** + * @author oosmoxiecode + * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 + */ - webglObject = _webglObjectsImmediate[ j ]; - object = webglObject.object; +THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) { - if ( object.visible && object.castShadow ) { + THREE.Geometry.call( this ); - object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + this.type = 'TorusKnotGeometry'; - _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object ); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + p: p, + q: q, + heightScale: heightScale + }; - } + radius = radius || 100; + tube = tube || 40; + radialSegments = radialSegments || 64; + tubularSegments = tubularSegments || 8; + p = p || 2; + q = q || 3; + heightScale = heightScale || 1; + + var grid = new Array( radialSegments ); + var tang = new THREE.Vector3(); + var n = new THREE.Vector3(); + var bitan = new THREE.Vector3(); - } + for ( var i = 0; i < radialSegments; ++ i ) { - } + grid[ i ] = new Array( tubularSegments ); + var u = i / radialSegments * 2 * p * Math.PI; + var p1 = getPos( u, q, p, radius, heightScale ); + var p2 = getPos( u + 0.01, q, p, radius, heightScale ); + tang.subVectors( p2, p1 ); + n.addVectors( p2, p1 ); - // restore GL state + bitan.crossVectors( tang, n ); + n.crossVectors( bitan, tang ); + bitan.normalize(); + n.normalize(); - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); + for ( var j = 0; j < tubularSegments; ++ j ) { - _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); - _gl.enable( _gl.BLEND ); + var v = j / tubularSegments * 2 * Math.PI; + var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + var cy = tube * Math.sin( v ); - if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) { + var pos = new THREE.Vector3(); + pos.x = p1.x + cx * n.x + cy * bitan.x; + pos.y = p1.y + cx * n.y + cy * bitan.y; + pos.z = p1.z + cx * n.z + cy * bitan.z; - _gl.cullFace( _gl.BACK ); + grid[ i ][ j ] = this.vertices.push( pos ) - 1; } - _renderer.resetGLState(); - - }; + } - function projectObject( scene, object, shadowCamera ) { + for ( var i = 0; i < radialSegments; ++ i ) { - if ( object.visible ) { + for ( var j = 0; j < tubularSegments; ++ j ) { - var webglObjects = _webglObjects[ object.id ]; + var ip = ( i + 1 ) % radialSegments; + var jp = ( j + 1 ) % tubularSegments; - if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { + var a = grid[ i ][ j ]; + var b = grid[ ip ][ j ]; + var c = grid[ ip ][ jp ]; + var d = grid[ i ][ jp ]; - for ( var i = 0, l = webglObjects.length; i < l; i ++ ) { + var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments ); + var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments ); + var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments ); + var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments ); - var webglObject = webglObjects[ i ]; + this.faces.push( new THREE.Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - _renderList.push( webglObject ); + this.faces.push( new THREE.Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - } + } + } - } + this.computeFaceNormals(); + this.computeVertexNormals(); - for ( var i = 0, l = object.children.length; i < l; i ++ ) { + function getPos( u, in_q, in_p, radius, heightScale ) { - projectObject( scene, object.children[ i ], shadowCamera ); + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = in_q / in_p * u; + var cs = Math.cos( quOverP ); - } + var tx = radius * ( 2 + cs ) * 0.5 * cu; + var ty = radius * ( 2 + cs ) * su * 0.5; + var tz = heightScale * radius * Math.sin( quOverP ) * 0.5; - } + return new THREE.Vector3( tx, ty, tz ); } - function createVirtualLight( light, cascade ) { +}; - var virtualLight = new THREE.DirectionalLight(); +THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; - virtualLight.isVirtual = true; +// File:src/extras/geometries/TubeGeometry.js - virtualLight.onlyShadow = true; - virtualLight.castShadow = true; +/** + * @author WestLangley / https://github.com/WestLangley + * @author zz85 / https://github.com/zz85 + * @author miningold / https://github.com/miningold + * @author jonobr1 / https://github.com/jonobr1 + * + * Modified from the TorusKnotGeometry by @oosmoxiecode + * + * Creates a tube which extrudes along a 3d spline + * + * Uses parallel transport frames as described in + * http://www.cs.indiana.edu/pub/techreports/TR425.pdf + */ - virtualLight.shadowCameraNear = light.shadowCameraNear; - virtualLight.shadowCameraFar = light.shadowCameraFar; +THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) { - virtualLight.shadowCameraLeft = light.shadowCameraLeft; - virtualLight.shadowCameraRight = light.shadowCameraRight; - virtualLight.shadowCameraBottom = light.shadowCameraBottom; - virtualLight.shadowCameraTop = light.shadowCameraTop; + THREE.Geometry.call( this ); - virtualLight.shadowCameraVisible = light.shadowCameraVisible; + this.type = 'TubeGeometry'; - virtualLight.shadowDarkness = light.shadowDarkness; + this.parameters = { + path: path, + segments: segments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; - virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ]; - virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ]; + segments = segments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; + taper = taper || THREE.TubeGeometry.NoTaper; - virtualLight.pointsWorld = []; - virtualLight.pointsFrustum = []; + var grid = []; - var pointsWorld = virtualLight.pointsWorld, - pointsFrustum = virtualLight.pointsFrustum; + var scope = this, - for ( var i = 0; i < 8; i ++ ) { + tangent, + normal, + binormal, - pointsWorld[ i ] = new THREE.Vector3(); - pointsFrustum[ i ] = new THREE.Vector3(); + numpoints = segments + 1, - } + u, v, r, - var nearZ = light.shadowCascadeNearZ[ cascade ]; - var farZ = light.shadowCascadeFarZ[ cascade ]; + cx, cy, + pos, pos2 = new THREE.Vector3(), + i, j, + ip, jp, + a, b, c, d, + uva, uvb, uvc, uvd; - pointsFrustum[ 0 ].set( - 1, - 1, nearZ ); - pointsFrustum[ 1 ].set( 1, - 1, nearZ ); - pointsFrustum[ 2 ].set( - 1, 1, nearZ ); - pointsFrustum[ 3 ].set( 1, 1, nearZ ); + var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; - pointsFrustum[ 4 ].set( - 1, - 1, farZ ); - pointsFrustum[ 5 ].set( 1, - 1, farZ ); - pointsFrustum[ 6 ].set( - 1, 1, farZ ); - pointsFrustum[ 7 ].set( 1, 1, farZ ); + // proxy internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - return virtualLight; + function vert( x, y, z ) { + + return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; } - // Synchronize virtual light with the original light + // consruct the grid - function updateVirtualLight( light, cascade ) { + for ( i = 0; i < numpoints; i ++ ) { - var virtualLight = light.shadowCascadeArray[ cascade ]; + grid[ i ] = []; - virtualLight.position.copy( light.position ); - virtualLight.target.position.copy( light.target.position ); - virtualLight.lookAt( virtualLight.target ); + u = i / ( numpoints - 1 ); - virtualLight.shadowCameraVisible = light.shadowCameraVisible; - virtualLight.shadowDarkness = light.shadowDarkness; + pos = path.getPointAt( u ); - virtualLight.shadowBias = light.shadowCascadeBias[ cascade ]; + tangent = tangents[ i ]; + normal = normals[ i ]; + binormal = binormals[ i ]; - var nearZ = light.shadowCascadeNearZ[ cascade ]; - var farZ = light.shadowCascadeFarZ[ cascade ]; + r = radius * taper( u ); - var pointsFrustum = virtualLight.pointsFrustum; + for ( j = 0; j < radialSegments; j ++ ) { - pointsFrustum[ 0 ].z = nearZ; - pointsFrustum[ 1 ].z = nearZ; - pointsFrustum[ 2 ].z = nearZ; - pointsFrustum[ 3 ].z = nearZ; + v = j / radialSegments * 2 * Math.PI; - pointsFrustum[ 4 ].z = farZ; - pointsFrustum[ 5 ].z = farZ; - pointsFrustum[ 6 ].z = farZ; - pointsFrustum[ 7 ].z = farZ; + cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + cy = r * Math.sin( v ); - } + pos2.copy( pos ); + pos2.x += cx * normal.x + cy * binormal.x; + pos2.y += cx * normal.y + cy * binormal.y; + pos2.z += cx * normal.z + cy * binormal.z; - // Fit shadow camera's ortho frustum to camera frustum + grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); - function updateShadowCamera( camera, light ) { + } + } - var shadowCamera = light.shadowCamera, - pointsFrustum = light.pointsFrustum, - pointsWorld = light.pointsWorld; - _min.set( Infinity, Infinity, Infinity ); - _max.set( - Infinity, - Infinity, - Infinity ); + // construct the mesh - for ( var i = 0; i < 8; i ++ ) { + for ( i = 0; i < segments; i ++ ) { - var p = pointsWorld[ i ]; + for ( j = 0; j < radialSegments; j ++ ) { - p.copy( pointsFrustum[ i ] ); - p.unproject( camera ); + ip = ( closed ) ? (i + 1) % segments : i + 1; + jp = (j + 1) % radialSegments; - p.applyMatrix4( shadowCamera.matrixWorldInverse ); + a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** + b = grid[ ip ][ j ]; + c = grid[ ip ][ jp ]; + d = grid[ i ][ jp ]; - if ( p.x < _min.x ) _min.x = p.x; - if ( p.x > _max.x ) _max.x = p.x; + uva = new THREE.Vector2( i / segments, j / radialSegments ); + uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments ); - if ( p.y < _min.y ) _min.y = p.y; - if ( p.y > _max.y ) _max.y = p.y; + this.faces.push( new THREE.Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - if ( p.z < _min.z ) _min.z = p.z; - if ( p.z > _max.z ) _max.z = p.z; + this.faces.push( new THREE.Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); } + } - shadowCamera.left = _min.x; - shadowCamera.right = _max.x; - shadowCamera.top = _max.y; - shadowCamera.bottom = _min.y; + this.computeFaceNormals(); + this.computeVertexNormals(); - // can't really fit near/far - //shadowCamera.near = _min.z; - //shadowCamera.far = _max.z; +}; - shadowCamera.updateProjectionMatrix(); +THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; - } +THREE.TubeGeometry.NoTaper = function ( u ) { - // For the moment just ignore objects that have multiple materials with different animation methods - // Only the first material will be taken into account for deciding which depth material to use for shadow maps + return 1; - function getObjectMaterial( object ) { +}; - return object.material instanceof THREE.MeshFaceMaterial - ? object.material.materials[ 0 ] - : object.material; +THREE.TubeGeometry.SinusoidalTaper = function ( u ) { - }; + return Math.sin( Math.PI * u ); }; -// File:src/renderers/webgl/plugins/SpritePlugin.js +// For computing of Frenet frames, exposing the tangents, normals and binormals the spline +THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var normal = new THREE.Vector3(), -THREE.SpritePlugin = function ( renderer, sprites ) { + tangents = [], + normals = [], + binormals = [], - var gl = renderer.context; + vec = new THREE.Vector3(), + mat = new THREE.Matrix4(), - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + numpoints = segments + 1, + theta, + epsilon = 0.0001, + smallest, - var texture; + tx, ty, tz, + i, u; - // decompose matrixWorld - var spritePosition = new THREE.Vector3(); - var spriteRotation = new THREE.Quaternion(); - var spriteScale = new THREE.Vector3(); + // expose internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - var init = function () { - - var vertices = new Float32Array( [ - - 0.5, - 0.5, 0, 0, - 0.5, - 0.5, 1, 0, - 0.5, 0.5, 1, 1, - - 0.5, 0.5, 0, 1 - ] ); - - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); - - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); - - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + // compute the tangent vectors for each segment on the path - program = createProgram(); + for ( i = 0; i < numpoints; i ++ ) { - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + u = i / ( numpoints - 1 ); - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + tangents[ i ] = path.getTangentAt( u ); + tangents[ i ].normalize(); - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + } - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + initialNormal3(); - modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + /* + function initialNormal1(lastBinormal) { + // fixed start binormal. Has dangers of 0 vectors + normals[ 0 ] = new THREE.Vector3(); + binormals[ 0 ] = new THREE.Vector3(); + if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); + normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + } - fogType: gl.getUniformLocation( program, 'fogType' ), - fogDensity: gl.getUniformLocation( program, 'fogDensity' ), - fogNear: gl.getUniformLocation( program, 'fogNear' ), - fogFar: gl.getUniformLocation( program, 'fogFar' ), - fogColor: gl.getUniformLocation( program, 'fogColor' ), + function initialNormal2() { - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + // This uses the Frenet-Serret formula for deriving binormal + var t2 = path.getTangentAt( epsilon ); - var canvas = document.createElement( 'canvas' ); - canvas.width = 8; - canvas.height = 8; + normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); + binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - texture = new THREE.Texture( canvas ); - texture.needsUpdate = true; + } + */ - }; + function initialNormal3() { + // select an initial normal vector perpenicular to the first tangent vector, + // and in the direction of the smallest tangent xyz component - this.render = function ( scene, camera ) { + normals[ 0 ] = new THREE.Vector3(); + binormals[ 0 ] = new THREE.Vector3(); + smallest = Number.MAX_VALUE; + tx = Math.abs( tangents[ 0 ].x ); + ty = Math.abs( tangents[ 0 ].y ); + tz = Math.abs( tangents[ 0 ].z ); - if ( sprites.length === 0 ) return; + if ( tx <= smallest ) { + smallest = tx; + normal.set( 1, 0, 0 ); + } - // setup gl + if ( ty <= smallest ) { + smallest = ty; + normal.set( 0, 1, 0 ); + } - if ( program === undefined ) { + if ( tz <= smallest ) { + normal.set( 0, 0, 1 ); + } - init(); + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - } + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + } - gl.useProgram( program ); - gl.enableVertexAttribArray( attributes.position ); - gl.enableVertexAttribArray( attributes.uv ); + // compute the slowly-varying normal and binormal vectors for each segment on the path - gl.disable( gl.CULL_FACE ); - gl.enable( gl.BLEND ); + for ( i = 1; i < numpoints; i ++ ) { - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + normals[ i ] = normals[ i - 1 ].clone(); - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + binormals[ i ] = binormals[ i - 1 ].clone(); - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - gl.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + if ( vec.length() > epsilon ) { - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + vec.normalize(); - if ( fog ) { + theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - if ( fog instanceof THREE.Fog ) { + } - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + } - } else if ( fog instanceof THREE.FogExp2 ) { - gl.uniform1f( uniforms.fogDensity, fog.density ); + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + if ( closed ) { - } + theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta /= ( numpoints - 1 ); - } else { + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + theta = - theta; } + for ( i = 1; i < numpoints; i ++ ) { - // update positions and sort + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + } - var sprite = sprites[ i ]; + } +}; - sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite._modelViewMatrix.elements[ 14 ]; +// File:src/extras/geometries/PolyhedronGeometry.js - } +/** + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley +*/ - sprites.sort( painterSortStable ); +THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { - // render all sprites + THREE.Geometry.call( this ); - var scale = []; + this.type = 'PolyhedronGeometry'; - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - var sprite = sprites[ i ]; - var material = sprite.material; + radius = radius || 1; + detail = detail || 0; - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements ); + var that = this; - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - var fogType = 0; + } - if ( scene.fog && material.fog ) { + var p = this.vertices; - fogType = sceneFogType; + var faces = []; - } + for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { - if ( oldFogType !== fogType ) { + var v1 = p[ indices[ i ] ]; + var v2 = p[ indices[ i + 1 ] ]; + var v3 = p[ indices[ i + 2 ] ]; - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - } + } - if ( material.map !== null ) { + var centroid = new THREE.Vector3(); - gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + for ( var i = 0, l = faces.length; i < l; i ++ ) { - } else { + subdivide( faces[ i ], detail ); - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + } - } - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + // Handle case when face straddles the seam - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - renderer.state.setDepthTest( material.depthTest ); - renderer.state.setDepthWrite( material.depthWrite ); + var uvs = this.faceVertexUvs[ 0 ][ i ]; - if ( material.map && material.map.image && material.map.image.width ) { + var x0 = uvs[ 0 ].x; + var x1 = uvs[ 1 ].x; + var x2 = uvs[ 2 ].x; - renderer.setTexture( material.map, 0 ); + var max = Math.max( x0, Math.max( x1, x2 ) ); + var min = Math.min( x0, Math.min( x1, x2 ) ); - } else { + if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary - renderer.setTexture( texture, 0 ); + if ( x0 < 0.2 ) uvs[ 0 ].x += 1; + if ( x1 < 0.2 ) uvs[ 1 ].x += 1; + if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - } + } - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + } - } - // restore gl + // Apply radius - gl.enable( gl.CULL_FACE ); + for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - renderer.resetGLState(); + this.vertices[ i ].multiplyScalar( radius ); - }; + } - function createProgram () { - var program = gl.createProgram(); + // Merge vertices - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + this.mergeVertices(); - gl.shaderSource( vertexShader, [ + this.computeFaceNormals(); - 'precision ' + renderer.getPrecision() + ' float;', + this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', - 'attribute vec2 position;', - 'attribute vec2 uv;', + // Project vector onto sphere's surface - 'varying vec2 vUV;', + function prepare( vector ) { - 'void main() {', + var vertex = vector.normalize().clone(); + vertex.index = that.vertices.push( vertex ) - 1; - 'vUV = uvOffset + uv * uvScale;', + // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. - 'vec2 alignedPosition = position * scale;', + var u = azimuth( vector ) / 2 / Math.PI + 0.5; + var v = inclination( vector ) / Math.PI + 0.5; + vertex.uv = new THREE.Vector2( u, 1 - v ); - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + return vertex; - 'vec4 finalPosition;', + } - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', - 'gl_Position = finalPosition;', + // Approximate a curved face with recursively sub-divided triangles. - '}' + function make( v1, v2, v3 ) { - ].join( '\n' ) ); + var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + that.faces.push( face ); - gl.shaderSource( fragmentShader, [ + centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - 'precision ' + renderer.getPrecision() + ' float;', + var azi = azimuth( centroid ); - 'uniform vec3 color;', - 'uniform sampler2D map;', - 'uniform float opacity;', + that.faceVertexUvs[ 0 ].push( [ + correctUV( v1.uv, v1, azi ), + correctUV( v2.uv, v2, azi ), + correctUV( v3.uv, v3, azi ) + ] ); - 'uniform int fogType;', - 'uniform vec3 fogColor;', - 'uniform float fogDensity;', - 'uniform float fogNear;', - 'uniform float fogFar;', - 'uniform float alphaTest;', + } - 'varying vec2 vUV;', - 'void main() {', + // Analytically subdivide a face to the required detail level. - 'vec4 texture = texture2D( map, vUV );', + function subdivide( face, detail ) { - 'if ( texture.a < alphaTest ) discard;', + var cols = Math.pow(2, detail); + var a = prepare( that.vertices[ face.a ] ); + var b = prepare( that.vertices[ face.b ] ); + var c = prepare( that.vertices[ face.c ] ); + var v = []; - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + // Construct all of the vertices for this subdivision. - 'if ( fogType > 0 ) {', + for ( var i = 0 ; i <= cols; i ++ ) { - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + v[ i ] = []; - 'if ( fogType == 1 ) {', + var aj = prepare( a.clone().lerp( c, i / cols ) ); + var bj = prepare( b.clone().lerp( c, i / cols ) ); + var rows = cols - i; - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + for ( var j = 0; j <= rows; j ++) { - '} else {', + if ( j == 0 && i == cols ) { - 'const float LOG2 = 1.442695;', - 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + v[ i ][ j ] = aj; - '}', + } else { - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', + v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); - '}', + } - '}' + } - ].join( '\n' ) ); + } - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + // Construct all of the faces. - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + for ( var i = 0; i < cols ; i ++ ) { - gl.linkProgram( program ); + for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) { - return program; + var k = Math.floor( j / 2 ); - }; + if ( j % 2 == 0 ) { - function painterSortStable ( a, b ) { + make( + v[ i ][ k + 1], + v[ i + 1 ][ k ], + v[ i ][ k ] + ); - if ( a.z !== b.z ) { + } else { - return b.z - a.z; + make( + v[ i ][ k + 1 ], + v[ i + 1][ k + 1], + v[ i + 1 ][ k ] + ); - } else { + } - return b.id - a.id; + } } - }; - -}; + } -// File:src/extras/GeometryUtils.js -/** - * @author mrdoob / http://mrdoob.com/ - */ + // Angle around the Y axis, counter-clockwise when looking from above. -THREE.GeometryUtils = { + function azimuth( vector ) { - merge: function ( geometry1, geometry2, materialIndexOffset ) { + return Math.atan2( vector.z, - vector.x ); - THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); + } - var matrix; - if ( geometry2 instanceof THREE.Mesh ) { + // Angle above the XZ plane. - geometry2.matrixAutoUpdate && geometry2.updateMatrix(); + function inclination( vector ) { - matrix = geometry2.matrix; - geometry2 = geometry2.geometry; + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - } + } - geometry1.merge( geometry2, matrix, materialIndexOffset ); - }, + // Texture fixing helper. Spheres have some odd behaviours. - center: function ( geometry ) { + function correctUV( uv, vector, azimuth ) { - THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); - return geometry.center(); + 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.clone(); } + }; -// File:src/extras/ImageUtils.js +THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; + +// File:src/extras/geometries/DodecahedronGeometry.js /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author Daosheng Mu / https://github.com/DaoshengMu/ + * @author Abe Pazos / https://hamoid.com */ -THREE.ImageUtils = { +THREE.DodecahedronGeometry = function ( radius, detail ) { - crossOrigin: undefined, + this.parameters = { + radius: radius, + detail: detail + }; - loadTexture: function ( url, mapping, onLoad, onError ) { + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - var loader = new THREE.ImageLoader(); - loader.crossOrigin = this.crossOrigin; + var vertices = [ - var texture = new THREE.Texture( undefined, mapping ); + // (±1, ±1, ±1) + -1, -1, -1, -1, -1, 1, + -1, 1, -1, -1, 1, 1, + 1, -1, -1, 1, -1, 1, + 1, 1, -1, 1, 1, 1, - loader.load( url, function ( image ) { + // (0, ±1/φ, ±φ) + 0, -r, -t, 0, -r, t, + 0, r, -t, 0, r, t, - texture.image = image; - texture.needsUpdate = true; + // (±1/φ, ±φ, 0) + -r, -t, 0, -r, t, 0, + r, -t, 0, r, t, 0, - if ( onLoad ) onLoad( texture ); + // (±φ, 0, ±1/φ) + -t, 0, -r, t, 0, -r, + -t, 0, r, t, 0, r + ]; - }, undefined, function ( event ) { + var indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; - if ( onError ) onError( event ); + THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - } ); +}; - texture.sourceFile = url; +THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; - return texture; +// File:src/extras/geometries/IcosahedronGeometry.js - }, +/** + * @author timothypratley / https://github.com/timothypratley + */ - loadTextureCube: function ( array, mapping, onLoad, onError ) { +THREE.IcosahedronGeometry = function ( radius, detail ) { - var images = []; + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var loader = new THREE.ImageLoader(); - loader.crossOrigin = this.crossOrigin; + var vertices = [ + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 + ]; - var texture = new THREE.CubeTexture( images, mapping ); + var indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; - // no flipping needed for cube textures + THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - texture.flipY = false; + this.type = 'IcosahedronGeometry'; - var loaded = 0; + this.parameters = { + radius: radius, + detail: detail + }; +}; - var loadTexture = function ( i ) { +THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; - loader.load( array[ i ], function ( image ) { +// File:src/extras/geometries/OctahedronGeometry.js - texture.images[ i ] = image; +/** + * @author timothypratley / https://github.com/timothypratley + */ - loaded += 1; +THREE.OctahedronGeometry = function ( radius, detail ) { - if ( loaded === 6 ) { + this.parameters = { + radius: radius, + detail: detail + }; - texture.needsUpdate = true; + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1 + ]; - if ( onLoad ) onLoad( texture ); + var indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 + ]; - } + THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - }, undefined, onError ); + this.type = 'OctahedronGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; +}; - for ( var i = 0, il = array.length; i < il; ++ i ) { +THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; - loadTexture( i ); +// File:src/extras/geometries/TetrahedronGeometry.js - } +/** + * @author timothypratley / https://github.com/timothypratley + */ - return texture; +THREE.TetrahedronGeometry = function ( radius, detail ) { - }, + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - loadCompressedTexture: function () { + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ) + THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - }, + this.type = 'TetrahedronGeometry'; - loadCompressedTextureCube: function () { + this.parameters = { + radius: radius, + detail: detail + }; - THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ) +}; - }, +THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; - getNormalMap: function ( image, depth ) { +// File:src/extras/geometries/ParametricGeometry.js - // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/ +/** + * @author zz85 / https://github.com/zz85 + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 + * + * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); + * + */ - var cross = function ( a, b ) { +THREE.ParametricGeometry = function ( func, slices, stacks ) { - return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ]; + THREE.Geometry.call( this ); - } + this.type = 'ParametricGeometry'; - var subtract = function ( a, b ) { + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ]; + var verts = this.vertices; + var faces = this.faces; + var uvs = this.faceVertexUvs[ 0 ]; - } + var i, j, p; + var u, v; - var normalize = function ( a ) { + var sliceCount = slices + 1; - var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] ); - return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ]; + for ( i = 0; i <= stacks; i ++ ) { - } + v = i / stacks; - depth = depth | 1; + for ( j = 0; j <= slices; j ++ ) { - var width = image.width; - var height = image.height; + u = j / slices; - // TODO: Make this work in Qt Quick + p = func( u, v ); + verts.push( p ); - var canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; + } + } - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0 ); + var a, b, c, d; + var uva, uvb, uvc, uvd; - var data = context.getImageData( 0, 0, width, height ).data; - var imageData = context.createImageData( width, height ); - var output = imageData.data; + for ( i = 0; i < stacks; i ++ ) { - for ( var x = 0; x < width; x ++ ) { + for ( j = 0; j < slices; j ++ ) { - for ( var y = 0; y < height; y ++ ) { + a = i * sliceCount + j; + b = i * sliceCount + j + 1; + c = (i + 1) * sliceCount + j + 1; + d = (i + 1) * sliceCount + j; - var ly = y - 1 < 0 ? 0 : y - 1; - var uy = y + 1 > height - 1 ? height - 1 : y + 1; - var lx = x - 1 < 0 ? 0 : x - 1; - var ux = x + 1 > width - 1 ? width - 1 : x + 1; + uva = new THREE.Vector2( j / slices, i / stacks ); + uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks ); - var points = []; - var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ]; - points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] ); - points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] ); - points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] ); - points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] ); + faces.push( new THREE.Face3( a, b, d ) ); + uvs.push( [ uva, uvb, uvd ] ); - var normals = []; - var num_points = points.length; + faces.push( new THREE.Face3( b, c, d ) ); + uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - for ( var i = 0; i < num_points; i ++ ) { + } - var v1 = points[ i ]; - var v2 = points[ ( i + 1 ) % num_points ]; - v1 = subtract( v1, origin ); - v2 = subtract( v2, origin ); - normals.push( normalize( cross( v1, v2 ) ) ); + } - } + // console.log(this); - var normal = [ 0, 0, 0 ]; + // magic bullet + // var diff = this.mergeVertices(); + // console.log('removed ', diff, ' vertices by merging'); - for ( var i = 0; i < normals.length; i ++ ) { + this.computeFaceNormals(); + this.computeVertexNormals(); - normal[ 0 ] += normals[ i ][ 0 ]; - normal[ 1 ] += normals[ i ][ 1 ]; - normal[ 2 ] += normals[ i ][ 2 ]; +}; - } +THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); +THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; - normal[ 0 ] /= normals.length; - normal[ 1 ] /= normals.length; - normal[ 2 ] /= normals.length; +// File:src/extras/helpers/AxisHelper.js - var idx = ( y * width + x ) * 4; +/** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0; - output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0; - output[ idx + 3 ] = 255; +THREE.AxisHelper = function ( size ) { - } + size = size || 1; - } + var vertices = new Float32Array( [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ] ); - context.putImageData( imageData, 0, 0 ); + var colors = new Float32Array( [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ] ); - return canvas; + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); - }, + var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); - generateDataTexture: function ( width, height, color ) { + THREE.Line.call( this, geometry, material, THREE.LinePieces ); - var size = width * height; - var data = new Uint8Array( 3 * size ); +}; - var r = Math.floor( color.r * 255 ); - var g = Math.floor( color.g * 255 ); - var b = Math.floor( color.b * 255 ); +THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; - for ( var i = 0; i < size; i ++ ) { +// File:src/extras/helpers/ArrowHelper.js - data[ i * 3 ] = r; - data[ i * 3 + 1 ] = g; - data[ i * 3 + 2 ] = b; +/** + * @author WestLangley / http://github.com/WestLangley + * @author zz85 / http://github.com/zz85 + * @author bhouston / http://exocortex.com + * + * Creates an arrow for visualizing directions + * + * Parameters: + * dir - Vector3 + * origin - Vector3 + * length - Number + * color - color in hex value + * headLength - Number + * headWidth - Number + */ - } +THREE.ArrowHelper = ( function () { - var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat ); - texture.needsUpdate = true; + var lineGeometry = new THREE.Geometry(); + lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - return texture; + var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 ); + coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); - } + return function ( dir, origin, length, color, headLength, headWidth ) { -}; + // dir is assumed to be normalized -// File:src/extras/SceneUtils.js + THREE.Object3D.call( this ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; -THREE.SceneUtils = { + this.position.copy( origin ); - createMultiMaterialObject: function ( geometry, materials ) { + this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - var group = new THREE.Object3D(); + this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); - for ( var i = 0, l = materials.length; i < l; i ++ ) { + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); + } - } +}() ); - return group; +THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); +THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; - }, +THREE.ArrowHelper.prototype.setDirection = ( function () { - detach: function ( child, parent, scene ) { + var axis = new THREE.Vector3(); + var radians; - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); + return function ( dir ) { - }, + // dir is assumed to be normalized - attach: function ( child, scene, parent ) { + if ( dir.y > 0.99999 ) { - var matrixWorldInverse = new THREE.Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); + this.quaternion.set( 0, 0, 0, 1 ); - scene.remove( child ); - parent.add( child ); + } else if ( dir.y < - 0.99999 ) { - } + this.quaternion.set( 1, 0, 0, 0 ); -}; + } else { -// File:src/extras/FontUtils.js + axis.set( dir.z, 0, - dir.x ).normalize(); -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * For Text operations in three.js (See TextGeometry) - * - * It uses techniques used in: - * - * typeface.js and canvastext - * For converting fonts and rendering with javascript - * http://typeface.neocracy.org - * - * Triangulation ported from AS3 - * Simple Polygon Triangulation - * http://actionsnippet.com/?p=1462 - * - * A Method to triangulate shapes with holes - * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/ - * - */ + radians = Math.acos( dir.y ); -THREE.FontUtils = { + this.quaternion.setFromAxisAngle( axis, radians ); - faces: {}, + } - // Just for now. face[weight][style] + }; - face: 'helvetiker', - weight: 'normal', - style: 'normal', - size: 150, - divisions: 10, +}() ); - getFace: function () { +THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { - try { + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - return this.faces[ this.face ][ this.weight ][ this.style ]; + this.line.scale.set( 1, length - headLength, 1 ); + this.line.updateMatrix(); - } catch (e) { + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); - throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing." +}; - }; +THREE.ArrowHelper.prototype.setColor = function ( color ) { - }, + this.line.material.color.set( color ); + this.cone.material.color.set( color ); - loadFace: function ( data ) { +}; - var family = data.familyName.toLowerCase(); +// File:src/extras/helpers/BoxHelper.js - var ThreeFont = this; +/** + * @author mrdoob / http://mrdoob.com/ + */ - ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {}; +THREE.BoxHelper = function ( object ) { - ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {}; - ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) ); - ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data; + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces ); - return data; + if ( object !== undefined ) { - }, + this.update( object ); - drawText: function ( text ) { + } - // RenderText +}; - var i, - face = this.getFace(), - scale = this.size / face.resolution, - offset = 0, - chars = String( text ).split( '' ), - length = chars.length; +THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; - var fontPaths = []; +THREE.BoxHelper.prototype.update = function ( object ) { - for ( i = 0; i < length; i ++ ) { + var geometry = object.geometry; - var path = new THREE.Path(); + if ( geometry.boundingBox === null ) { - var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path ); - offset += ret.offset; + geometry.computeBoundingBox(); - fontPaths.push( ret.path ); + } - } + var min = geometry.boundingBox.min; + var max = geometry.boundingBox.max; - // get the width + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ - var width = offset / 2; - // - // for ( p = 0; p < allPts.length; p++ ) { - // - // allPts[ p ].x -= width; - // - // } + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ - //var extract = this.extractPoints( allPts, characterPts ); - //extract.contour = allPts; + var vertices = this.geometry.attributes.position.array; - //extract.paths = fontPaths; - //extract.offset = width; + vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z; + vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z; - return { paths: fontPaths, offset: width }; + vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z; + vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z; - }, + vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z; + vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z; + vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z; + vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z; + // + vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z; + vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z; - extractGlyphPoints: function ( c, face, scale, offset, path ) { + vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z; + vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z; - var pts = []; + vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z; + vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z; - var i, i2, divisions, - outline, action, length, - scaleX, scaleY, - x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, - laste, - glyph = face.glyphs[ c ] || face.glyphs[ '?' ]; + vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z; + vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z; - if ( ! glyph ) return; + // - if ( glyph.o ) { + vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z; + vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z; - outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - length = outline.length; + vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z; + vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z; - scaleX = scale; - scaleY = scale; + vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z; + vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z; - for ( i = 0; i < length; ) { + vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z; + vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z; - action = outline[ i ++ ]; + this.geometry.attributes.position.needsUpdate = true; - //console.log( action ); + this.geometry.computeBoundingSphere(); - switch ( action ) { + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - case 'm': +}; - // Move To +// File:src/extras/helpers/BoundingBoxHelper.js - x = outline[ i ++ ] * scaleX + offset; - y = outline[ i ++ ] * scaleY; +/** + * @author WestLangley / http://github.com/WestLangley + */ - path.moveTo( x, y ); - break; +// a helper to show the world-axis-aligned bounding box for an object - case 'l': +THREE.BoundingBoxHelper = function ( object, hex ) { - // Line To + var color = ( hex !== undefined ) ? hex : 0x888888; - x = outline[ i ++ ] * scaleX + offset; - y = outline[ i ++ ] * scaleY; - path.lineTo( x, y ); - break; + this.object = object; - case 'q': + this.box = new THREE.Box3(); - // QuadraticCurveTo + THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); - cpx = outline[ i ++ ] * scaleX + offset; - cpy = outline[ i ++ ] * scaleY; - cpx1 = outline[ i ++ ] * scaleX + offset; - cpy1 = outline[ i ++ ] * scaleY; +}; - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); +THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); +THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; - laste = pts[ pts.length - 1 ]; +THREE.BoundingBoxHelper.prototype.update = function () { - if ( laste ) { + this.box.setFromObject( this.object ); - cpx0 = laste.x; - cpy0 = laste.y; + this.box.size( this.scale ); - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { + this.box.center( this.position ); - var t = i2 / divisions; - THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); - } +}; - } +// File:src/extras/helpers/CameraHelper.js - break; +/** + * @author alteredq / http://alteredqualia.com/ + * + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * http://evanw.github.com/lightgl.js/tests/shadowmap.html + */ - case 'b': +THREE.CameraHelper = function ( camera ) { - // Cubic Bezier Curve + var geometry = new THREE.Geometry(); + var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); - cpx = outline[ i ++ ] * scaleX + offset; - cpy = outline[ i ++ ] * scaleY; - cpx1 = outline[ i ++ ] * scaleX + offset; - cpy1 = outline[ i ++ ] * scaleY; - cpx2 = outline[ i ++ ] * scaleX + offset; - cpy2 = outline[ i ++ ] * scaleY; + var pointMap = {}; - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + // colors - laste = pts[ pts.length - 1 ]; + var hexFrustum = 0xffaa00; + var hexCone = 0xff0000; + var hexUp = 0x00aaff; + var hexTarget = 0xffffff; + var hexCross = 0x333333; - if ( laste ) { + // near - cpx0 = laste.x; - cpy0 = laste.y; + addLine( "n1", "n2", hexFrustum ); + addLine( "n2", "n4", hexFrustum ); + addLine( "n4", "n3", hexFrustum ); + addLine( "n3", "n1", hexFrustum ); - for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) { + // far - var t = i2 / divisions; - THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); + addLine( "f1", "f2", hexFrustum ); + addLine( "f2", "f4", hexFrustum ); + addLine( "f4", "f3", hexFrustum ); + addLine( "f3", "f1", hexFrustum ); - } + // sides - } + addLine( "n1", "f1", hexFrustum ); + addLine( "n2", "f2", hexFrustum ); + addLine( "n3", "f3", hexFrustum ); + addLine( "n4", "f4", hexFrustum ); - break; + // cone - } + addLine( "p", "n1", hexCone ); + addLine( "p", "n2", hexCone ); + addLine( "p", "n3", hexCone ); + addLine( "p", "n4", hexCone ); - } - } + // up + addLine( "u1", "u2", hexUp ); + addLine( "u2", "u3", hexUp ); + addLine( "u3", "u1", hexUp ); + // target - return { offset: glyph.ha * scale, path:path }; - } + addLine( "c", "t", hexTarget ); + addLine( "p", "c", hexCross ); -}; + // cross + addLine( "cn1", "cn2", hexCross ); + addLine( "cn3", "cn4", hexCross ); -THREE.FontUtils.generateShapes = function ( text, parameters ) { + addLine( "cf1", "cf2", hexCross ); + addLine( "cf3", "cf4", hexCross ); - // Parameters + function addLine( a, b, hex ) { - parameters = parameters || {}; + addPoint( a, hex ); + addPoint( b, hex ); - var size = parameters.size !== undefined ? parameters.size : 100; - var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4; + } - var font = parameters.font !== undefined ? parameters.font : 'helvetiker'; - var weight = parameters.weight !== undefined ? parameters.weight : 'normal'; - var style = parameters.style !== undefined ? parameters.style : 'normal'; + function addPoint( id, hex ) { - THREE.FontUtils.size = size; - THREE.FontUtils.divisions = curveSegments; + geometry.vertices.push( new THREE.Vector3() ); + geometry.colors.push( new THREE.Color( hex ) ); - THREE.FontUtils.face = font; - THREE.FontUtils.weight = weight; - THREE.FontUtils.style = style; + if ( pointMap[ id ] === undefined ) { - // Get a Font data json object + pointMap[ id ] = []; - var data = THREE.FontUtils.drawText( text ); + } - var paths = data.paths; - var shapes = []; + pointMap[ id ].push( geometry.vertices.length - 1 ); - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + } - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + THREE.Line.call( this, geometry, material, THREE.LinePieces ); - } + this.camera = camera; + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - return shapes; + this.pointMap = pointMap; + + this.update(); }; +THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; -/** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ +THREE.CameraHelper.prototype.update = function () { + var geometry, pointMap; + + var vector = new THREE.Vector3(); + var camera = new THREE.Camera(); -//( function ( namespace ) { + var setPoint = function ( point, x, y, z ) { - var EPSILON = 0.0000000001; + vector.set( x, y, z ).unproject( camera ); - // takes in an contour array and returns + var points = pointMap[ point ]; -THREE.FontUtils.process = function ( contour, indices ) { + if ( points !== undefined ) { - var n = contour.length; + for ( var i = 0, il = points.length; i < il; i ++ ) { - if ( n < 3 ) return null; + geometry.vertices[ points[ i ] ].copy( vector ); - var result = [], - verts = [], - vertIndices = []; + } - /* we want a counter-clockwise polygon in verts */ + } - var u, v, w; + }; - if ( THREE.FontUtils.area( contour ) > 0.0 ) { + return function () { - for ( v = 0; v < n; v ++ ) verts[ v ] = v; + geometry = this.geometry; + pointMap = this.pointMap; - } else { + var w = 1, h = 1; - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; + // we need just camera projection matrix + // world matrix must be identity - } + camera.projectionMatrix.copy( this.camera.projectionMatrix ); - var nv = n; + // center / target - /* remove nv - 2 vertices, creating 1 triangle every time */ + setPoint( "c", 0, 0, - 1 ); + setPoint( "t", 0, 0, 1 ); - var count = 2 * nv; /* error detection */ + // near - for ( v = nv - 1; nv > 2; ) { + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); - /* if we loop, it is probably a non-simple polygon */ + // far - if ( ( count -- ) <= 0 ) { + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); + setPoint( "f4", w, h, 1 ); - //** Triangulate: ERROR - probable bad polygon! + // up - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' ); + setPoint( "u1", w * 0.7, h * 1.1, - 1 ); + setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); + setPoint( "u3", 0, h * 2, - 1 ); - if ( indices ) return vertIndices; - return result; + // cross - } + setPoint( "cf1", - w, 0, 1 ); + setPoint( "cf2", w, 0, 1 ); + setPoint( "cf3", 0, - h, 1 ); + setPoint( "cf4", 0, h, 1 ); - /* three consecutive vertices in current polygon, <u,v,w> */ + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ + geometry.verticesNeedUpdate = true; - if ( THREE.FontUtils.snip( contour, u, v, w, nv, verts ) ) { + }; - var a, b, c, s, t; +}(); - /* true names of the vertices */ +// File:src/extras/helpers/DirectionalLightHelper.js - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - /* output Triangle */ +THREE.DirectionalLightHelper = function ( light, size ) { - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); + THREE.Object3D.call( this ); + this.light = light; + this.light.updateMatrixWorld(); - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - /* remove v from the remaining polygon */ + size = size || 1; - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { + var geometry = new THREE.Geometry(); + geometry.vertices.push( + new THREE.Vector3( - size, size, 0 ), + new THREE.Vector3( size, size, 0 ), + new THREE.Vector3( size, - size, 0 ), + new THREE.Vector3( - size, - size, 0 ), + new THREE.Vector3( - size, size, 0 ) + ); - verts[ s ] = verts[ t ]; + var material = new THREE.LineBasicMaterial( { fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - } + this.lightPlane = new THREE.Line( geometry, material ); + this.add( this.lightPlane ); - nv --; + geometry = new THREE.Geometry(); + geometry.vertices.push( + new THREE.Vector3(), + new THREE.Vector3() + ); - /* reset error detection counter */ + material = new THREE.LineBasicMaterial( { fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - count = 2 * nv; + this.targetLine = new THREE.Line( geometry, material ); + this.add( this.targetLine ); - } + this.update(); - } +}; - if ( indices ) return vertIndices; - return result; +THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); +THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; - }; +THREE.DirectionalLightHelper.prototype.dispose = function () { - // calculate area of the contour polygon + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); +}; -THREE.FontUtils.area = function ( contour ) { +THREE.DirectionalLightHelper.prototype.update = function () { - var n = contour.length; - var a = 0.0; + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); + var v3 = new THREE.Vector3(); - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { + return function () { - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + v1.setFromMatrixPosition( this.light.matrixWorld ); + v2.setFromMatrixPosition( this.light.target.matrixWorld ); + v3.subVectors( v2, v1 ); - } + this.lightPlane.lookAt( v3 ); + this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - return a * 0.5; + this.targetLine.geometry.vertices[ 1 ].copy( v3 ); + this.targetLine.geometry.verticesNeedUpdate = true; + this.targetLine.material.color.copy( this.lightPlane.material.color ); }; -THREE.FontUtils.snip = function ( contour, u, v, w, n, verts ) { +}(); - var p; - var ax, ay, bx, by; - var cx, cy, px, py; +// File:src/extras/helpers/EdgesHelper.js - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; +/** + * @author WestLangley / http://github.com/WestLangley + * @param object THREE.Mesh whose geometry will be used + * @param hex line color + * @param thresholdAngle the minimim angle (in degrees), + * between the face normals of adjacent faces, + * that is required to render an edge. A value of 10 means + * an edge is only rendered if the angle is at least 10 degrees. + */ - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; +THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; + var color = ( hex !== undefined ) ? hex : 0xffffff; + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; + var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) ); - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; + var edge = [ 0, 0 ], hash = {}; + var sortFunction = function ( a, b ) { return a - b }; - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; + var keys = [ 'a', 'b', 'c' ]; + var geometry = new THREE.BufferGeometry(); - for ( p = 0; p < n; p ++ ) { + var geometry2; - px = contour[ verts[ p ] ].x - py = contour[ verts[ p ] ].y + if ( object.geometry instanceof THREE.BufferGeometry ) { - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; + geometry2 = new THREE.Geometry(); + geometry2.fromBufferGeometry( object.geometry ); - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; + } else { - // see if p is inside triangle abc + geometry2 = object.geometry.clone(); - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; + } - if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false; + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - } + var vertices = geometry2.vertices; + var faces = geometry2.faces; + var numEdges = 0; - return true; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - }; + var face = faces[ i ]; + for ( var j = 0; j < 3; j ++ ) { -THREE.FontUtils.Triangulate = THREE.FontUtils.process; -THREE.FontUtils.Triangulate.area = THREE.FontUtils.area; + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); -//return namespace; + var key = edge.toString(); -//} )( THREE.FontUtils ); + if ( hash[ key ] === undefined ) { -// To use the typeface.js face files, hook up the API -var _typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace }; -THREE.typeface_js = _typeface_js; + hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; + numEdges ++; -// File:src/extras/audio/Audio.js + } else { -/** - * @author mrdoob / http://mrdoob.com/ - */ + hash[ key ].face2 = i; -THREE.Audio = function ( listener ) { + } - THREE.Object3D.call( this ); + } - this.type = 'Audio'; + } - this.context = listener.context; - this.source = this.context.createBufferSource(); - this.source.onended = this.onEnded.bind(this); + var coords = new Float32Array( numEdges * 2 * 3 ); - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + var index = 0; - this.panner = this.context.createPanner(); - this.panner.connect( this.gain ); + for ( var key in hash ) { - this.autoplay = false; + var h = hash[ key ]; - this.startTime = 0; - this.isPlaying = false; + if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { -}; + var vertex = vertices[ h.vert1 ]; + coords[ index ++ ] = vertex.x; + coords[ index ++ ] = vertex.y; + coords[ index ++ ] = vertex.z; -THREE.Audio.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Audio.prototype.constructor = THREE.Audio; + vertex = vertices[ h.vert2 ]; + coords[ index ++ ] = vertex.x; + coords[ index ++ ] = vertex.y; + coords[ index ++ ] = vertex.z; -THREE.Audio.prototype.load = function ( file ) { + } - var scope = this; + } - var request = new XMLHttpRequest(); - request.open( 'GET', file, true ); - request.responseType = 'arraybuffer'; - request.onload = function ( e ) { + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - scope.context.decodeAudioData( this.response, function ( buffer ) { + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); - scope.source.buffer = buffer; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - if( scope.autoplay ) scope.play(); +}; - } ); +THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; - }; - request.send(); +// File:src/extras/helpers/FaceNormalsHelper.js - return this; +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley +*/ -}; +THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { -THREE.Audio.prototype.play = function () { + this.object = object; - if ( this.isPlaying === true ) { + this.size = ( size !== undefined ) ? size : 1; - THREE.warn( 'THREE.Audio: Audio is already playing.' ); - return; + var color = ( hex !== undefined ) ? hex : 0xffff00; - } + var width = ( linewidth !== undefined ) ? linewidth : 1; - var source = this.context.createBufferSource(); + var geometry = new THREE.Geometry(); - source.buffer = this.source.buffer; - source.loop = this.source.loop; - source.onended = this.source.onended; - source.connect( this.panner ); - source.start( 0, this.startTime ); + var faces = this.object.geometry.faces; - this.isPlaying = true; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - this.source = source; + geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() ); -}; + } -THREE.Audio.prototype.pause = function () { + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); - this.source.stop(); - this.startTime = this.context.currentTime; + this.matrixAutoUpdate = false; + + this.normalMatrix = new THREE.Matrix3(); + + this.update(); }; -THREE.Audio.prototype.stop = function () { +THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; - this.source.stop(); - this.startTime = 0; +THREE.FaceNormalsHelper.prototype.update = function () { -}; + var vertices = this.geometry.vertices; -THREE.Audio.prototype.onEnded = function() { + var object = this.object; + var objectVertices = object.geometry.vertices; + var objectFaces = object.geometry.faces; + var objectWorldMatrix = object.matrixWorld; - this.isPlaying = false; + object.updateMatrixWorld( true ); -}; + this.normalMatrix.getNormalMatrix( objectWorldMatrix ); -THREE.Audio.prototype.setLoop = function ( value ) { + for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) { - this.source.loop = value; + var face = objectFaces[ i ]; -}; + vertices[ i2 ].copy( objectVertices[ face.a ] ) + .add( objectVertices[ face.b ] ) + .add( objectVertices[ face.c ] ) + .divideScalar( 3 ) + .applyMatrix4( objectWorldMatrix ); -THREE.Audio.prototype.setRefDistance = function ( value ) { + vertices[ i2 + 1 ].copy( face.normal ) + .applyMatrix3( this.normalMatrix ) + .normalize() + .multiplyScalar( this.size ) + .add( vertices[ i2 ] ); - this.panner.refDistance = value; + } + + this.geometry.verticesNeedUpdate = true; + + return this; }; -THREE.Audio.prototype.setRolloffFactor = function ( value ) { - this.panner.rolloffFactor = value; +// File:src/extras/helpers/GridHelper.js -}; +/** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.Audio.prototype.setVolume = function ( value ) { +THREE.GridHelper = function ( size, step ) { - this.gain.gain.value = value; + var geometry = new THREE.Geometry(); + var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); -}; + this.color1 = new THREE.Color( 0x444444 ); + this.color2 = new THREE.Color( 0x888888 ); -THREE.Audio.prototype.updateMatrixWorld = ( function () { + for ( var i = - size; i <= size; i += step ) { - var position = new THREE.Vector3(); + geometry.vertices.push( + new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ), + new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size ) + ); - return function ( force ) { + var color = i === 0 ? this.color1 : this.color2; - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + geometry.colors.push( color, color, color, color ); - position.setFromMatrixPosition( this.matrixWorld ); + } - this.panner.setPosition( position.x, position.y, position.z ); + THREE.Line.call( this, geometry, material, THREE.LinePieces ); - }; +}; -} )(); +THREE.GridHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.GridHelper.prototype.constructor = THREE.GridHelper; -// File:src/extras/audio/AudioListener.js +THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) { + + this.color1.set( colorCenterLine ); + this.color2.set( colorGrid ); + + this.geometry.colorsNeedUpdate = true; + +} + +// File:src/extras/helpers/HemisphereLightHelper.js /** + * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.AudioListener = function () { +THREE.HemisphereLightHelper = function ( light, sphereSize ) { THREE.Object3D.call( this ); - this.type = 'AudioListener'; - - this.context = new ( window.AudioContext || window.webkitAudioContext )(); - -}; + this.light = light; + this.light.updateMatrixWorld(); -THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype ); -THREE.AudioListener.prototype.constructor = THREE.AudioListener; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; -THREE.AudioListener.prototype.updateMatrixWorld = ( function () { + this.colors = [ new THREE.Color(), new THREE.Color() ]; - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3(); + var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); + geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - var orientation = new THREE.Vector3(); - var velocity = new THREE.Vector3(); + for ( var i = 0, il = 8; i < il; i ++ ) { - var positionPrev = new THREE.Vector3(); + geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - return function ( force ) { + } - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); - var listener = this.context.listener; - var up = this.up; + this.lightSphere = new THREE.Mesh( geometry, material ); + this.add( this.lightSphere ); - this.matrixWorld.decompose( position, quaternion, scale ); + this.update(); - orientation.set( 0, 0, -1 ).applyQuaternion( quaternion ); - velocity.subVectors( position, positionPrev ); +}; - listener.setPosition( position.x, position.y, position.z ); - listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); - listener.setVelocity( velocity.x, velocity.y, velocity.z ); +THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); +THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; - positionPrev.copy( position ); +THREE.HemisphereLightHelper.prototype.dispose = function () { + this.lightSphere.geometry.dispose(); + this.lightSphere.material.dispose(); +}; - }; +THREE.HemisphereLightHelper.prototype.update = function () { -} )(); + var vector = new THREE.Vector3(); -// File:src/extras/core/Curve.js + return function () { -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of Curve methods - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTagentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following classes subclasses THREE.Curve: - * - * -- 2d classes -- - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.CubicBezierCurve - * THREE.SplineCurve - * THREE.ArcCurve - * THREE.EllipseCurve - * - * -- 3d classes -- - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * THREE.CubicBezierCurve3 - * THREE.SplineCurve3 - * THREE.ClosedSplineCurve3 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ + this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); -/************************************************************** - * Abstract Curve base class - **************************************************************/ + this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + this.lightSphere.geometry.colorsNeedUpdate = true; -THREE.Curve = function () { + } -}; +}(); -// Virtual base class method to overwrite and implement in subclasses -// - t [0 .. 1] +// File:src/extras/helpers/PointLightHelper.js -THREE.Curve.prototype.getPoint = function ( t ) { +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); - return null; +THREE.PointLightHelper = function ( light, sphereSize ) { -}; + this.light = light; + this.light.updateMatrixWorld(); -// Get point at relative position in curve according to arc length -// - u [0 .. 1] + var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); + var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); -THREE.Curve.prototype.getPointAt = function ( u ) { + THREE.Mesh.call( this, geometry, material ); - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; -}; + /* + var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); -// Get sequence of points using getPoint( t ) + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); -THREE.Curve.prototype.getPoints = function ( divisions ) { + var d = light.distance; - if ( ! divisions ) divisions = 5; + if ( d === 0.0 ) { - var d, pts = []; + this.lightDistance.visible = false; - for ( d = 0; d <= divisions; d ++ ) { + } else { - pts.push( this.getPoint( d / divisions ) ); + this.lightDistance.scale.set( d, d, d ); } - return pts; + this.add( this.lightDistance ); + */ }; -// Get sequence of points using getPointAt( u ) - -THREE.Curve.prototype.getSpacedPoints = function ( divisions ) { +THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); +THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; - if ( ! divisions ) divisions = 5; +THREE.PointLightHelper.prototype.dispose = function () { - var d, pts = []; + this.geometry.dispose(); + this.material.dispose(); +}; - for ( d = 0; d <= divisions; d ++ ) { +THREE.PointLightHelper.prototype.update = function () { - pts.push( this.getPointAt( d / divisions ) ); + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - } + /* + var d = this.light.distance; - return pts; + if ( d === 0.0 ) { -}; + this.lightDistance.visible = false; -// Get total curve arc length + } else { -THREE.Curve.prototype.getLength = function () { + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + } + */ }; -// Get list of cumulative segment lengths - -THREE.Curve.prototype.getLengths = function ( divisions ) { +// File:src/extras/helpers/SkeletonHelper.js - if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200; +/** + * @author Sean Griffin / http://twitter.com/sgrif + * @author Michael Guerrero / http://realitymeltdown.com + * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com + */ - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length == divisions + 1 ) - && ! this.needsUpdate) { +THREE.SkeletonHelper = function ( object ) { - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; + this.bones = this.getBoneList( object ); - } + var geometry = new THREE.Geometry(); - this.needsUpdate = false; + for ( var i = 0; i < this.bones.length; i ++ ) { - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; + var bone = this.bones[ i ]; - cache.push( 0 ); + if ( bone.parent instanceof THREE.Bone ) { - for ( p = 1; p <= divisions; p ++ ) { + geometry.vertices.push( new THREE.Vector3() ); + geometry.vertices.push( new THREE.Vector3() ); + geometry.colors.push( new THREE.Color( 0, 0, 1 ) ); + geometry.colors.push( new THREE.Color( 0, 1, 0 ) ); - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + } } - this.cacheArcLengths = cache; + var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - return cache; // { sums: cache, sum:sum }; Sum is in the last element. + THREE.Line.call( this, geometry, material, THREE.LinePieces ); -}; + this.root = object; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + + this.update(); -THREE.Curve.prototype.updateArcLengths = function() { - this.needsUpdate = true; - this.getLengths(); }; -// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance -THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { +THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; - var arcLengths = this.getLengths(); +THREE.SkeletonHelper.prototype.getBoneList = function( object ) { - var i = 0, il = arcLengths.length; + var boneList = []; - var targetArcLength; // The targeted u distance value to get + if ( object instanceof THREE.Bone ) { - if ( distance ) { + boneList.push( object ); - targetArcLength = distance; + } - } else { + for ( var i = 0; i < object.children.length; i ++ ) { - targetArcLength = u * arcLengths[ il - 1 ]; + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); } - //var time = Date.now(); + return boneList; - // binary search for the index with largest value smaller than target u distance +}; - var low = 0, high = il - 1, comparison; +THREE.SkeletonHelper.prototype.update = function () { - while ( low <= high ) { + var geometry = this.geometry; - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); - comparison = arcLengths[ i ] - targetArcLength; + var boneMatrix = new THREE.Matrix4(); - if ( comparison < 0 ) { + var j = 0; - low = i + 1; + for ( var i = 0; i < this.bones.length; i ++ ) { - } else if ( comparison > 0 ) { + var bone = this.bones[ i ]; - high = i - 1; + if ( bone.parent instanceof THREE.Bone ) { - } else { + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); - high = i; - break; + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); - // DONE + j += 2; } } - i = high; + geometry.verticesNeedUpdate = true; - //console.log('b' , i, low, high, Date.now()- time); + geometry.computeBoundingSphere(); - if ( arcLengths[ i ] == targetArcLength ) { +}; - var t = i / ( il - 1 ); - return t; +// File:src/extras/helpers/SpotLightHelper.js - } +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley +*/ - // we could get finer grain at lengths, or use simple interpolatation between two points +THREE.SpotLightHelper = function ( light ) { - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + THREE.Object3D.call( this ); - var segmentLength = lengthAfter - lengthBefore; + this.light = light; + this.light.updateMatrixWorld(); - // determine where we are between the 'before' and 'after' points + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true ); - // add that fractional amount to t + geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); + geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - var t = ( i + segmentFraction ) / ( il - 1 ); + var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - return t; + this.cone = new THREE.Mesh( geometry, material ); + this.add( this.cone ); + + this.update(); }; -// Returns a unit vector tangent at t -// 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.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); +THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; -THREE.Curve.prototype.getTangent = function( t ) { +THREE.SpotLightHelper.prototype.dispose = function () { + this.cone.geometry.dispose(); + this.cone.material.dispose(); +}; - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; +THREE.SpotLightHelper.prototype.update = function () { - // Capping in case of danger + var vector = new THREE.Vector3(); + var vector2 = new THREE.Vector3(); - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + return function () { - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + var coneLength = this.light.distance ? this.light.distance : 10000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - var vec = pt2.clone().sub(pt1); - return vec.normalize(); + this.cone.scale.set( coneWidth, coneWidth, coneLength ); -}; + vector.setFromMatrixPosition( this.light.matrixWorld ); + vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + this.cone.lookAt( vector2.sub( vector ) ); -THREE.Curve.prototype.getTangentAt = function ( u ) { + this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + }; -}; +}(); +// File:src/extras/helpers/VertexNormalsHelper.js +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley +*/ +THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { + this.object = object; -/************************************************************** - * Utils - **************************************************************/ + this.size = ( size !== undefined ) ? size : 1; -THREE.Curve.Utils = { + var color = ( hex !== undefined ) ? hex : 0xff0000; - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { + var width = ( linewidth !== undefined ) ? linewidth : 1; - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); + var geometry = new THREE.Geometry(); - }, + var faces = object.geometry.faces; - // Puay Bing, thanks for helping with this derivative! + for ( var i = 0, l = faces.length; i < l; i ++ ) { - tangentCubicBezier: function (t, p0, p1, p2, p3 ) { + var face = faces[ i ]; - return - 3 * p0 * (1 - t) * (1 - t) + - 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) + - 6 * t * p2 * (1 - t) - 3 * t * t * p2 + - 3 * t * t * p3; + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - }, + geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() ); - tangentSpline: function ( t, p0, p1, p2, p3 ) { + } - // To check if my formulas are correct + } - var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 - var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t - var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 - var h11 = 3 * t * t - 2 * t; // t3 − t2 + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); - return h00 + h10 + h01 + h11; + this.matrixAutoUpdate = false; - }, + this.normalMatrix = new THREE.Matrix3(); - // Catmull-Rom + this.update(); - interpolate: function( p0, p1, p2, p3, t ) { +}; - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; +THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; - } +THREE.VertexNormalsHelper.prototype.update = ( function ( object ) { -}; + var v1 = new THREE.Vector3(); + return function( object ) { -// TODO: Transformation for Curves? + var keys = [ 'a', 'b', 'c', 'd' ]; -/************************************************************** - * 3D Curves - **************************************************************/ + this.object.updateMatrixWorld( true ); -// A Factory method for creating new curve subclasses + this.normalMatrix.getNormalMatrix( this.object.matrixWorld ); -THREE.Curve.create = function ( constructor, getPointFunc ) { + var vertices = this.geometry.vertices; - constructor.prototype = Object.create( THREE.Curve.prototype ); - constructor.prototype.constructor = constructor; - constructor.prototype.getPoint = getPointFunc; + var verts = this.object.geometry.vertices; - return constructor; + var faces = this.object.geometry.faces; -}; + var worldMatrix = this.object.matrixWorld; -// File:src/extras/core/CurvePath.js + var idx = 0; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + for ( var i = 0, l = faces.length; i < l; i ++ ) { -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + var face = faces[ i ]; -THREE.CurvePath = function () { + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - this.curves = []; - this.bends = []; - - this.autoClose = false; // Automatically closes the path -}; + var vertexId = face[ keys[ j ] ]; + var vertex = verts[ vertexId ]; -THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype ); -THREE.CurvePath.prototype.constructor = THREE.CurvePath; + var normal = face.vertexNormals[ j ]; -THREE.CurvePath.prototype.add = function ( curve ) { + vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); - this.curves.push( curve ); + v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size ); -}; + v1.add( vertices[ idx ] ); + idx = idx + 1; -THREE.CurvePath.prototype.checkConnection = function() { - // TODO - // If the ending of curve is not connected to the starting - // or the next curve, then, this is not a real path -}; + vertices[ idx ].copy( v1 ); + idx = idx + 1; -THREE.CurvePath.prototype.closePath = function() { - // TODO Test - // and verify for vector3 (needs to implement equals) - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[0].getPoint(0); - var endPoint = this.curves[this.curves.length - 1].getPoint(1); - - if (! startPoint.equals(endPoint)) { - this.curves.push( new THREE.LineCurve(endPoint, startPoint) ); - } - -}; + } -// To get accurate point with reference to -// entire path distance at time t, -// following has to be done: + } -// 1. Length of each sub path have to be known -// 2. Locate and identify type of curve -// 3. Get t for the curve -// 4. Return curve.getPointAt(t') + this.geometry.verticesNeedUpdate = true; -THREE.CurvePath.prototype.getPoint = function( t ) { + return this; - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0, diff, curve; + } - // To think about boundaries points. +}()); - while ( i < curveLengths.length ) { +// File:src/extras/helpers/VertexTangentsHelper.js - if ( curveLengths[ i ] >= d ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley +*/ - diff = curveLengths[ i ] - d; - curve = this.curves[ i ]; +THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) { - var u = 1 - diff / curve.getLength(); + this.object = object; - return curve.getPointAt( u ); + this.size = ( size !== undefined ) ? size : 1; - } + var color = ( hex !== undefined ) ? hex : 0x0000ff; - i ++; + var width = ( linewidth !== undefined ) ? linewidth : 1; - } + var geometry = new THREE.Geometry(); - return null; + var faces = object.geometry.faces; - // loop where sum != 0, sum > d , sum+1 <d + for ( var i = 0, l = faces.length; i < l; i ++ ) { -}; + var face = faces[ i ]; -/* -THREE.CurvePath.prototype.getTangent = function( t ) { -};*/ + for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { + geometry.vertices.push( new THREE.Vector3() ); + geometry.vertices.push( new THREE.Vector3() ); -// We cannot use the default THREE.Curve getPoint() with getLength() because in -// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath -// getPoint() depends on getLength + } -THREE.CurvePath.prototype.getLength = function() { + } - var lens = this.getCurveLengths(); - return lens[ lens.length - 1 ]; + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); + + this.matrixAutoUpdate = false; + + this.update(); }; -// Compute lengths and cache them -// We cannot overwrite getLengths() because UtoT mapping uses it. +THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper; -THREE.CurvePath.prototype.getCurveLengths = function() { +THREE.VertexTangentsHelper.prototype.update = ( function ( object ) { - // We use cache values if curves and cache array are same length + var v1 = new THREE.Vector3(); - if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) { + return function( object ) { - return this.cacheLengths; + var keys = [ 'a', 'b', 'c', 'd' ]; - }; + this.object.updateMatrixWorld( true ); - // Get length of subsurve - // Push sums into cached array + var vertices = this.geometry.vertices; - var lengths = [], sums = 0; - var i, il = this.curves.length; + var verts = this.object.geometry.vertices; - for ( i = 0; i < il; i ++ ) { + var faces = this.object.geometry.faces; - sums += this.curves[ i ].getLength(); - lengths.push( sums ); + var worldMatrix = this.object.matrixWorld; - } + var idx = 0; - this.cacheLengths = lengths; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - return lengths; + var face = faces[ i ]; -}; + for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { + var vertexId = face[ keys[ j ] ]; + var vertex = verts[ vertexId ]; + var tangent = face.vertexTangents[ j ]; -// Returns min and max coordinates + vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); -THREE.CurvePath.prototype.getBoundingBox = function () { + v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size ); - var points = this.getPoints(); + v1.add( vertices[ idx ] ); + idx = idx + 1; - var maxX, maxY, maxZ; - var minX, minY, minZ; + vertices[ idx ].copy( v1 ); + idx = idx + 1; - maxX = maxY = Number.NEGATIVE_INFINITY; - minX = minY = Number.POSITIVE_INFINITY; + } - var p, i, il, sum; + } - var v3 = points[0] instanceof THREE.Vector3; + this.geometry.verticesNeedUpdate = true; - sum = v3 ? new THREE.Vector3() : new THREE.Vector2(); + return this; - for ( i = 0, il = points.length; i < il; i ++ ) { + } - p = points[ i ]; +}()); - if ( p.x > maxX ) maxX = p.x; - else if ( p.x < minX ) minX = p.x; +// File:src/extras/helpers/WireframeHelper.js - if ( p.y > maxY ) maxY = p.y; - else if ( p.y < minY ) minY = p.y; +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( v3 ) { +THREE.WireframeHelper = function ( object, hex ) { - if ( p.z > maxZ ) maxZ = p.z; - else if ( p.z < minZ ) minZ = p.z; + var color = ( hex !== undefined ) ? hex : 0xffffff; - } + var edge = [ 0, 0 ], hash = {}; + var sortFunction = function ( a, b ) { return a - b }; - sum.add( p ); + var keys = [ 'a', 'b', 'c' ]; + var geometry = new THREE.BufferGeometry(); - } + if ( object.geometry instanceof THREE.Geometry ) { - var ret = { + var vertices = object.geometry.vertices; + var faces = object.geometry.faces; + var numEdges = 0; - minX: minX, - minY: minY, - maxX: maxX, - maxY: maxY + // allocate maximal size + var edges = new Uint32Array( 6 * faces.length ); - }; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - if ( v3 ) { + var face = faces[ i ]; - ret.maxZ = maxZ; - ret.minZ = minZ; + for ( var j = 0; j < 3; j ++ ) { - } + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - return ret; + var key = edge.toString(); -}; + if ( hash[ key ] === undefined ) { -/************************************************************** - * Create Geometries Helpers - **************************************************************/ + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; -/// Generate geometry from path points (for Line or Points objects) + } -THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) { + } - var pts = this.getPoints( divisions, true ); - return this.createGeometry( pts ); + } -}; + var coords = new Float32Array( numEdges * 2 * 3 ); -// Generate geometry from equidistance sampling along the path + for ( var i = 0, l = numEdges; i < l; i ++ ) { -THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) { + for ( var j = 0; j < 2; j ++ ) { - var pts = this.getSpacedPoints( divisions, true ); - return this.createGeometry( pts ); + var vertex = vertices[ edges [ 2 * i + j] ]; -}; + var index = 6 * i + 3 * j; + coords[ index + 0 ] = vertex.x; + coords[ index + 1 ] = vertex.y; + coords[ index + 2 ] = vertex.z; -THREE.CurvePath.prototype.createGeometry = function( points ) { + } - var geometry = new THREE.Geometry(); + } - for ( var i = 0; i < points.length; i ++ ) { + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) ); + } else if ( object.geometry instanceof THREE.BufferGeometry ) { - } + if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry - return geometry; + var vertices = object.geometry.attributes.position.array; + var indices = object.geometry.attributes.index.array; + var drawcalls = object.geometry.drawcalls; + var numEdges = 0; -}; + if ( drawcalls.length === 0 ) { + drawcalls = [ { count : indices.length, index : 0, start : 0 } ]; -/************************************************************** - * Bend / Wrap Helper Methods - **************************************************************/ + } -// Wrap path / Bend modifiers? + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); -THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) { + for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) { - this.bends.push( bendpath ); + var start = drawcalls[ o ].start; + var count = drawcalls[ o ].count; + var index = drawcalls[ o ].index; -}; + for ( var i = start, il = start + count; i < il; i += 3 ) { -THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) { + for ( var j = 0; j < 3; j ++ ) { - var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints - var i, il; + edge[ 0 ] = index + indices[ i + j ]; + edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); - if ( ! bends ) { + var key = edge.toString(); - bends = this.bends; + if ( hash[ key ] === undefined ) { - } + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - for ( i = 0, il = bends.length; i < il; i ++ ) { + } - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); + } - } + } - return oldPts; + } -}; + var coords = new Float32Array( numEdges * 2 * 3 ); -THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) { + for ( var i = 0, l = numEdges; i < l; i ++ ) { - var oldPts = this.getSpacedPoints( segments ); + for ( var j = 0; j < 2; j ++ ) { - var i, il; + var index = 6 * i + 3 * j; + var index2 = 3 * edges[ 2 * i + j]; + coords[ index + 0 ] = vertices[ index2 ]; + coords[ index + 1 ] = vertices[ index2 + 1 ]; + coords[ index + 2 ] = vertices[ index2 + 2 ]; - if ( ! bends ) { + } - bends = this.bends; + } - } + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - for ( i = 0, il = bends.length; i < il; i ++ ) { + } else { // non-indexed BufferGeometry - oldPts = this.getWrapPoints( oldPts, bends[ i ] ); + var vertices = object.geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; - } + var coords = new Float32Array( numEdges * 2 * 3 ); - return oldPts; + for ( var i = 0, l = numTris; i < l; i ++ ) { -}; + for ( var j = 0; j < 3; j ++ ) { -// This returns getPoints() bend/wrapped around the contour of a path. -// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html + var index = 18 * i + 6 * j; -THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) { + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; - var bounds = this.getBoundingBox(); + var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); + coords[ index + 3 ] = vertices[ index2 ]; + coords[ index + 4 ] = vertices[ index2 + 1 ]; + coords[ index + 5 ] = vertices[ index2 + 2 ]; - var i, il, p, oldX, oldY, xNorm; + } - for ( i = 0, il = oldPts.length; i < il; i ++ ) { + } - p = oldPts[ i ]; + geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - oldX = p.x; - oldY = p.y; + } - xNorm = oldX / bounds.maxX; + } - // If using actual distance, for length > path, requires line extrusions - //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance + THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); - xNorm = path.getUtoTmapping( xNorm, oldX ); + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - // check for out of bounds? +}; - var pathPt = path.getPoint( xNorm ); - var normal = path.getTangent( xNorm ); - normal.set( - normal.y, normal.x ).multiplyScalar( oldY ); +THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype ); +THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; - p.x = pathPt.x + normal.x; - p.y = pathPt.y + normal.y; +// File:src/extras/objects/ImmediateRenderObject.js - } +/** + * @author alteredq / http://alteredqualia.com/ + */ - return oldPts; +THREE.ImmediateRenderObject = function () { + + THREE.Object3D.call( this ); + + this.render = function ( renderCallback ) {}; }; +THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); +THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; -// File:src/extras/core/Gyroscope.js +// File:src/extras/objects/MorphBlendMesh.js /** * @author alteredq / http://alteredqualia.com/ */ -THREE.Gyroscope = function () { +THREE.MorphBlendMesh = function( geometry, material ) { - THREE.Object3D.call( this ); + THREE.Mesh.call( this, geometry, material ); -}; + this.animationsMap = {}; + this.animationsList = []; -THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Gyroscope.prototype.constructor = THREE.Gyroscope; + // prepare default animation + // (all frames played together in 1 second) -THREE.Gyroscope.prototype.updateMatrixWorld = function () { + var numFrames = this.geometry.morphTargets.length; - var translationObject = new THREE.Vector3(); - var quaternionObject = new THREE.Quaternion(); - var scaleObject = new THREE.Vector3(); + var name = "__default"; - var translationWorld = new THREE.Vector3(); - var quaternionWorld = new THREE.Quaternion(); - var scaleWorld = new THREE.Vector3(); + var startFrame = 0; + var endFrame = numFrames - 1; - return function ( force ) { + var fps = numFrames / 1; - this.matrixAutoUpdate && this.updateMatrix(); + this.createAnimation( name, startFrame, endFrame, fps ); + this.setAnimationWeight( name, 1 ); - // update matrixWorld +}; - if ( this.matrixWorldNeedsUpdate || force ) { +THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); +THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; - if ( this.parent ) { +THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + var animation = { - this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld ); - this.matrix.decompose( translationObject, quaternionObject, scaleObject ); + startFrame: start, + endFrame: end, - this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld ); + length: end - start + 1, + fps: fps, + duration: ( end - start ) / fps, - } else { + lastFrame: 0, + currentFrame: 0, - this.matrixWorld.copy( this.matrix ); + active: false, - } + time: 0, + direction: 1, + weight: 1, + directionBackwards: false, + mirroredLoop: false - this.matrixWorldNeedsUpdate = false; + }; - force = true; + this.animationsMap[ name ] = animation; + this.animationsList.push( animation ); - } +}; - // update children +THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + var pattern = /([a-z]+)_?(\d+)/; - this.children[ i ].updateMatrixWorld( force ); + var firstAnimation, frameRanges = {}; - } + var geometry = this.geometry; - }; - -}(); + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { -// File:src/extras/core/Path.js + var morph = geometry.morphTargets[ i ]; + var chunks = morph.name.match( pattern ); -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ + if ( chunks && chunks.length > 1 ) { -THREE.Path = function ( points ) { + var name = chunks[ 1 ]; - THREE.CurvePath.call(this); + if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; - this.actions = []; + var range = frameRanges[ name ]; - if ( points ) { + if ( i < range.start ) range.start = i; + if ( i > range.end ) range.end = i; - this.fromPoints( points ); + if ( ! firstAnimation ) firstAnimation = name; + + } } -}; + for ( var name in frameRanges ) { -THREE.Path.prototype = Object.create( THREE.CurvePath.prototype ); -THREE.Path.prototype.constructor = THREE.Path; + var range = frameRanges[ name ]; + this.createAnimation( name, range.start, range.end, fps ); -THREE.PathActions = { + } + + this.firstAnimation = firstAnimation; - MOVE_TO: 'moveTo', - LINE_TO: 'lineTo', - QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve - BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve - CSPLINE_THRU: 'splineThru', // Catmull-rom spline - ARC: 'arc', // Circle - ELLIPSE: 'ellipse' }; -// TODO Clean up PATH API +THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { -// Create path using straight lines to connect all points -// - vectors: array of Vector2 + var animation = this.animationsMap[ name ]; -THREE.Path.prototype.fromPoints = function ( vectors ) { + if ( animation ) { - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + animation.direction = 1; + animation.directionBackwards = false; - for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) { + } - this.lineTo( vectors[ v ].x, vectors[ v ].y ); +}; - }; +THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { -}; + var animation = this.animationsMap[ name ]; -// startPath() endPath()? + if ( animation ) { -THREE.Path.prototype.moveTo = function ( x, y ) { + animation.direction = - 1; + animation.directionBackwards = true; - var args = Array.prototype.slice.call( arguments ); - this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } ); + } }; -THREE.Path.prototype.lineTo = function ( x, y ) { - - var args = Array.prototype.slice.call( arguments ); +THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - var lastargs = this.actions[ this.actions.length - 1 ].args; + var animation = this.animationsMap[ name ]; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; + if ( animation ) { - var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); + animation.fps = fps; + animation.duration = ( animation.end - animation.start ) / animation.fps; - this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } ); + } }; -THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); +THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - var lastargs = this.actions[ this.actions.length - 1 ].args; + var animation = this.animationsMap[ name ]; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; + if ( animation ) { - var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); + animation.duration = duration; + animation.fps = ( animation.end - animation.start ) / animation.duration; - this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); + } }; -THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, - aCP2x, aCP2y, - aX, aY ) { - - var args = Array.prototype.slice.call( arguments ); +THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - var lastargs = this.actions[ this.actions.length - 1 ].args; + var animation = this.animationsMap[ name ]; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; + if ( animation ) { - var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) ); - this.curves.push( curve ); + animation.weight = weight; - this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } ); + } }; -THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) { +THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - var args = Array.prototype.slice.call( arguments ); - var lastargs = this.actions[ this.actions.length - 1 ].args; + var animation = this.animationsMap[ name ]; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; -//--- - var npts = [ new THREE.Vector2( x0, y0 ) ]; - Array.prototype.push.apply( npts, pts ); + if ( animation ) { - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); + animation.time = time; - this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } ); + } }; -// FUTURE: Change the API or follow canvas API? +THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { -THREE.Path.prototype.arc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { + var time = 0; - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; + var animation = this.animationsMap[ name ]; - this.absarc(aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + if ( animation ) { - }; + time = animation.time; - THREE.Path.prototype.absarc = function ( aX, aY, aRadius, - aStartAngle, aEndAngle, aClockwise ) { - this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); - }; + } -THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { + return time; - var lastargs = this.actions[ this.actions.length - 1].args; - var x0 = lastargs[ lastargs.length - 2 ]; - var y0 = lastargs[ lastargs.length - 1 ]; +}; - this.absellipse(aX + x0, aY + y0, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); +THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - }; + var duration = - 1; + var animation = this.animationsMap[ name ]; -THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ) { + if ( animation ) { - var args = Array.prototype.slice.call( arguments ); - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, - aStartAngle, aEndAngle, aClockwise ); - this.curves.push( curve ); + duration = animation.duration; - var lastPoint = curve.getPoint(1); - args.push(lastPoint.x); - args.push(lastPoint.y); + } - this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } ); + return duration; - }; +}; -THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) { +THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { - if ( ! divisions ) divisions = 40; + var animation = this.animationsMap[ name ]; - var points = []; + if ( animation ) { - for ( var i = 0; i < divisions; i ++ ) { + animation.time = 0; + animation.active = true; - points.push( this.getPoint( i / divisions ) ); + } else { - //if( !this.getPoint( i / divisions ) ) throw "DIE"; + THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); } - // if ( closedPath ) { - // - // points.push( points[ 0 ] ); - // - // } +}; - return points; +THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { -}; + var animation = this.animationsMap[ name ]; -/* Return an array of vectors based on contour of the path */ + if ( animation ) { -THREE.Path.prototype.getPoints = function( divisions, closedPath ) { + animation.active = false; - if (this.useSpacedPoints) { - console.log('tata'); - return this.getSpacedPoints( divisions, closedPath ); } - divisions = divisions || 12; - - var points = []; +}; - var i, il, item, action, args; - var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0, - laste, j, - t, tx, ty; +THREE.MorphBlendMesh.prototype.update = function ( delta ) { - for ( i = 0, il = this.actions.length; i < il; i ++ ) { + for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - item = this.actions[ i ]; + var animation = this.animationsList[ i ]; - action = item.action; - args = item.args; + if ( ! animation.active ) continue; - switch ( action ) { + var frameTime = animation.duration / animation.length; - case THREE.PathActions.MOVE_TO: + animation.time += animation.direction * delta; - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); + if ( animation.mirroredLoop ) { - break; + if ( animation.time > animation.duration || animation.time < 0 ) { - case THREE.PathActions.LINE_TO: + animation.direction *= - 1; - points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) ); + if ( animation.time > animation.duration ) { - break; + animation.time = animation.duration; + animation.directionBackwards = true; - case THREE.PathActions.QUADRATIC_CURVE_TO: + } - cpx = args[ 2 ]; - cpy = args[ 3 ]; + if ( animation.time < 0 ) { - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; + animation.time = 0; + animation.directionBackwards = false; - if ( points.length > 0 ) { + } - laste = points[ points.length - 1 ]; + } - cpx0 = laste.x; - cpy0 = laste.y; + } else { - } else { + animation.time = animation.time % animation.duration; - laste = this.actions[ i - 1 ].args; + if ( animation.time < 0 ) animation.time += animation.duration; - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; + } - } + var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var weight = animation.weight; - for ( j = 1; j <= divisions; j ++ ) { + if ( keyframe !== animation.currentFrame ) { - t = j / divisions; + this.morphTargetInfluences[ animation.lastFrame ] = 0; + this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; - tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx ); - ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy ); + this.morphTargetInfluences[ keyframe ] = 0; - points.push( new THREE.Vector2( tx, ty ) ); + animation.lastFrame = animation.currentFrame; + animation.currentFrame = keyframe; - } + } - break; + var mix = ( animation.time % frameTime ) / frameTime; - case THREE.PathActions.BEZIER_CURVE_TO: + if ( animation.directionBackwards ) mix = 1 - mix; - cpx = args[ 4 ]; - cpy = args[ 5 ]; + this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; + this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; - cpx1 = args[ 0 ]; - cpy1 = args[ 1 ]; + } - cpx2 = args[ 2 ]; - cpy2 = args[ 3 ]; +}; - if ( points.length > 0 ) { +// File:src/qml/QmlImageElement.js - laste = points[ points.length - 1 ]; +var __texImageToImageMap = {}; - cpx0 = laste.x; - cpy0 = laste.y; +function Image () { + this.crossOrigin = undefined; + this._src = undefined; + this._onSuccessCallback = undefined; + this._onProgressCallback = undefined; + this._onErrorCallback = undefined; + this._width = 0; + this._height = 0; + this._texImage = TextureImageFactory.newTexImage(); + __texImageToImageMap[""+this._texImage.id()] = this; - } else { + // Setup mapping between the native QObject image and this image + var _this = this; - laste = this.actions[ i - 1 ].args; + this._texImage.imageLoaded.connect(function() { _this.notifySuccess(_this) }); + this._texImage.imageLoadingFailed.connect(function() { _this.notifyError(_this) }); - cpx0 = laste[ laste.length - 2 ]; - cpy0 = laste[ laste.length - 1 ]; + this.__defineGetter__("src", function(){ + return _this._src; + }); - } + this.__defineSetter__("src", function(url){ + if (url && url !== '' && url !== _this._src) { + _this._texImage.src = ""+url; + _this._texImage.name = ""+url; + } + _this._src = url; + }); + this.__defineGetter__("width", function(){ + return (_this._texImage !== undefined)?_this._texImage.width:0; + }); - for ( j = 1; j <= divisions; j ++ ) { + this.__defineSetter__("width", function(url){ + console.log("TODO: Implement image resize"); + }); - t = j / divisions; + this.__defineGetter__("height", function(){ + return (_this._texImage !== undefined)?_this._texImage.height:0; + }); - tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx ); - ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy ); + this.__defineSetter__("height", function(url){ + console.log("TODO: Implement image resize"); + }); +}; - points.push( new THREE.Vector2( tx, ty ) ); +Image.prototype = { + constructor: Image, - } + addEventListener: function( eventName, callback, flag ) { + if (eventName === 'load') { + this._onSuccessCallback = callback; + } else if (eventName === 'progress') { + this._onProgressCallback = callback; + } else if (eventName === 'error') { + this._onErrorCallback = callback; + } + }, - break; + notifySuccess: function(image) { + if (this._onSuccessCallback !== undefined) { + this._onSuccessCallback(new Event()); + } + }, - case THREE.PathActions.CSPLINE_THRU: + notifyProgress: function(image) { + if (this._onProgressCallback !== undefined) { + this._onProgressCallback(new Event()); + } + }, - laste = this.actions[ i - 1 ].args; + notifyError: function(image) { + if (this._onErrorCallback !== undefined) { + this._onErrorCallback(new Event()); + } + }, - var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] ); - var spts = [ last ]; + texImage: function() { + return this._texImage; + }, - var n = divisions * args[ 0 ].length; + data: function() { + console.error("Image.data not implemented!"); + } +}; - spts = spts.concat( args[ 0 ] ); +// TODO: Support for resizing: +//where.image.width = width; +//where.image.height = height; +//where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height ); - var spline = new THREE.SplineCurve( spts ); +// File:src/qml/QmlHtmlElements.js - for ( j = 1; j <= n; j ++ ) { +// HTML document and Element wrappers/stubs - points.push( spline.getPointAt( j / n ) ) ; +function document() { +} - } +document.createElement = function(type) { + if (type === "img") { + return new Image(); + } else if (type === 'div') { + return new HtmlDiv(); + } - break; + return new HtmlElement(); +} - case THREE.PathActions.ARC: +document.createTextNode = function(value) { + return new HtmlElement(); +} - var aX = args[ 0 ], aY = args[ 1 ], - aRadius = args[ 2 ], - aStartAngle = args[ 3 ], aEndAngle = args[ 4 ], - aClockwise = !! args[ 5 ]; +function Event() { +} - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; +Event.prototype = { + constructor: Event +} - for ( j = 1; j <= tdivisions; j ++ ) { +function HtmlStyle() { + this.position = undefined; + this.right = undefined; + this.top = undefined; + this.fontSize = undefined; + this.textAlign = undefined; + this.background = undefined; + this.color = undefined; + this.width = undefined; + this.width = undefined; + this.padding = undefined; + this.zIndex = undefined; +} - t = j / tdivisions; +function HtmlElement() { + this.style = new HtmlStyle(); +} - if ( ! aClockwise ) { +HtmlElement.prototype = { + constructor: HtmlElement, - t = 1 - t; + appendChild: function(child) { + } +} - } +function HtmlDiv() { + this.innerHTML = ""; + this.style = new HtmlStyle(); +} - angle = aStartAngle + t * deltaAngle; - tx = aX + aRadius * Math.cos( angle ); - ty = aY + aRadius * Math.sin( angle ); - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); +// File:src/qml/Canvas3DRenderer.js - points.push( new THREE.Vector2( tx, ty ) ); +/** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author pasikeranen / pasi.keranen@theqtcompany.com + */ - } +THREE.Canvas3DRenderer = function ( parameters ) { - //console.log(points); + console.log( 'THREE.Canvas3DRenderer', THREE.REVISION ); - break; - - case THREE.PathActions.ELLIPSE: + parameters = parameters || {}; - var aX = args[ 0 ], aY = args[ 1 ], - xRadius = args[ 2 ], - yRadius = args[ 3 ], - aStartAngle = args[ 4 ], aEndAngle = args[ 5 ], - aClockwise = !! args[ 6 ]; + if (parameters.canvas === undefined) { + console.error("parameter.canvas must be set when using THREE.Canvas3DRenderer"); + return; + } + var _canvas = parameters.canvas, + _context = parameters.context !== undefined ? parameters.context : null, - var deltaAngle = aEndAngle - aStartAngle; - var angle; - var tdivisions = divisions * 2; + pixelRatio = 1, - for ( j = 1; j <= tdivisions; j ++ ) { + _precision = parameters.precision !== undefined ? parameters.precision : 'highp', - t = j / tdivisions; + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, + _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false, - if ( ! aClockwise ) { + _clearColor = new THREE.Color( 0x000000 ), + _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0; - t = 1 - t; + var lights = []; - } + var _webglObjects = {}; + var _webglObjectsImmediate = []; - angle = aStartAngle + t * deltaAngle; + var opaqueObjects = []; + var transparentObjects = []; - tx = aX + xRadius * Math.cos( angle ); - ty = aY + yRadius * Math.sin( angle ); + var sprites = []; + var lensFlares = []; - //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty); + // public properties - points.push( new THREE.Vector2( tx, ty ) ); + this.domElement = _canvas; + this.context = null; + pixelRatio = parameters.devicePixelRatio !== undefined + ? parameters.devicePixelRatio + : self.pixelRatio !== undefined + ? self.pixelRatio + : 1; - } + // clearing - //console.log(points); + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - break; + // scene graph - } // end switch + this.sortObjects = true; - } + // physically based shading + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; + // shadow map - // Normalize to remove the closing point by default. - var lastPoint = points[ points.length - 1]; - var EPSILON = 0.0000000001; - if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON && - Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON) - points.splice( points.length - 1, 1); - if ( closedPath ) { - - points.push( points[ 0 ] ); + this.shadowMapEnabled = false; + this.shadowMapType = THREE.PCFShadowMap; + this.shadowMapCullFace = THREE.CullFaceFront; + this.shadowMapDebug = false; + this.shadowMapCascade = false; - } + // morphs - return points; + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; -}; + // flags -// -// Breaks path into shapes -// -// Assumptions (if parameter isCCW==true the opposite holds): -// - solid shapes are defined clockwise (CW) -// - holes are defined counterclockwise (CCW) -// -// If parameter noHoles==true: -// - all subPaths are regarded as solid shapes -// - definition order CW/CCW has no relevance -// + this.autoScaleCubemaps = true; -THREE.Path.prototype.toShapes = function( isCCW, noHoles ) { + // info - function extractSubpaths( inActions ) { + this.info = { - var i, il, item, action, args; + memory: { - var subPaths = [], lastPath = new THREE.Path(); + programs: 0, + geometries: 0, + textures: 0 - for ( i = 0, il = inActions.length; i < il; i ++ ) { + }, - item = inActions[ i ]; + render: { - args = item.args; - action = item.action; + calls: 0, + vertices: 0, + faces: 0, + points: 0 - if ( action == THREE.PathActions.MOVE_TO ) { + } - if ( lastPath.actions.length != 0 ) { + }; - subPaths.push( lastPath ); - lastPath = new THREE.Path(); + // internal properties - } + var _this = this, - } + _programs = [], - lastPath[ action ].apply( lastPath, args ); + // internal state cache - } + _currentProgram = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, - if ( lastPath.actions.length != 0 ) { + _usedTextureUnits = 0, - subPaths.push( lastPath ); + _viewportX = 0, + _viewportY = 0, + _viewportWidth = _canvas.width, + _viewportHeight = _canvas.height, + _currentWidth = 0, + _currentHeight = 0, - } + // frustum - // console.log(subPaths); + _frustum = new THREE.Frustum(), - return subPaths; - } + // camera matrices cache - function toShapesNoHoles( inSubpaths ) { + _projScreenMatrix = new THREE.Matrix4(), - var shapes = []; + _vector3 = new THREE.Vector3(), - for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) { + // light arrays cache - var tmpPath = inSubpaths[ i ]; + _direction = new THREE.Vector3(), - var tmpShape = new THREE.Shape(); - tmpShape.actions = tmpPath.actions; - tmpShape.curves = tmpPath.curves; + _lightsNeedUpdate = true, - shapes.push( tmpShape ); - } + _lights = { - //console.log("shape", shapes); + ambient: [ 0, 0, 0 ], + directional: { length: 0, colors:[], positions: [] }, + point: { length: 0, colors: [], positions: [], distances: [], decays: [] }, + spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] }, + hemi: { length: 0, skyColors: [], groundColors: [], positions: [] } - return shapes; }; - function isPointInsidePolygon( inPt, inPolygon ) { - var EPSILON = 0.0000000001; + // initialize - var polyLen = inPolygon.length; + var _gl; - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + try { - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - if ( Math.abs(edgeDy) > EPSILON ) { // not parallel - if ( edgeDy < 0 ) { - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + + if ( _gl === null ) { + + if ( _canvas.getContext( 'webgl') !== null ) { + + throw 'Error creating WebGL context with your selected attributes.'; + + } else { + + throw 'Error creating WebGL context.'; - if ( inPt.y == edgeLowPt.y ) { - if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! - } else { - var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); - if ( perpEdge == 0 ) return true; // inPt is on contour ? - if ( perpEdge < 0 ) continue; - inside = ! inside; // true intersection left of inPt - } - } else { // parallel or colinear - if ( inPt.y != edgeLowPt.y ) continue; // parallel - // egde lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! - // continue; } + } - return inside; +// _canvas.addEventListener( 'webglcontextlost', function ( event ) { +// +// event.preventDefault(); +// +// resetGLState(); +// setDefaultGLState(); +// +// _webglObjects = {}; +// +// }, false); +// + } catch ( error ) { + + THREE.error( 'THREE.Canvas3DRenderer: ' + error ); + } + var state = new THREE.WebGLState( _gl, paramThreeToGL ); + + if ( _gl.getShaderPrecisionFormat === undefined ) { - var subPaths = extractSubpaths( this.actions ); - if ( subPaths.length == 0 ) return []; + _gl.getShaderPrecisionFormat = function () { - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + return { + 'rangeMin': 1, + 'rangeMax': 1, + 'precision': 1 + }; + } - var solid, tmpPath, tmpShape, shapes = []; + } - if ( subPaths.length == 1) { + var extensions = new THREE.WebGLExtensions( _gl ); - tmpPath = subPaths[0]; - tmpShape = new THREE.Shape(); - tmpShape.actions = tmpPath.actions; - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + extensions.get( 'OES_texture_float' ); + extensions.get( 'OES_texture_float_linear' ); + extensions.get( 'OES_texture_half_float' ); + extensions.get( 'OES_texture_half_float_linear' ); + extensions.get( 'OES_standard_derivatives' ); + + if ( _logarithmicDepthBuffer ) { + + extensions.get( 'EXT_frag_depth' ); } - var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + // - // console.log("Holes first", holesFirst); - - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + var glClearColor = function ( r, g, b, a ) { - newShapes[mainIdx] = undefined; - newShapeHoles[mainIdx] = []; + if ( _premultipliedAlpha === true ) { - var i, il; + r *= a; g *= a; b *= a; - for ( i = 0, il = subPaths.length; i < il; i ++ ) { + } - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = THREE.Shape.Utils.isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + _gl.clearColor( r, g, b, a ); - if ( solid ) { + }; - if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++; + var setDefaultGLState = function () { - newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints }; - newShapes[mainIdx].s.actions = tmpPath.actions; - newShapes[mainIdx].s.curves = tmpPath.curves; - - if ( holesFirst ) mainIdx ++; - newShapeHoles[mainIdx] = []; + _gl.clearColor( 0, 0, 0, 1 ); + _gl.clearDepth( 1 ); + _gl.clearStencil( 0 ); - //console.log('cw', i); + _gl.enable( _gl.DEPTH_TEST ); + _gl.depthFunc( _gl.LEQUAL ); - } else { + _gl.frontFace( _gl.CCW ); + _gl.cullFace( _gl.BACK ); + _gl.enable( _gl.CULL_FACE ); - newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } ); + _gl.enable( _gl.BLEND ); + _gl.blendEquation( _gl.FUNC_ADD ); + _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); - //console.log('ccw', i); + _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); - } + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } + }; - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[0] ) return toShapesNoHoles( subPaths ); + var resetGLState = function () { + _currentProgram = null; + _currentCamera = null; - if ( newShapes.length > 1 ) { - var ambigious = false; - var toChange = []; + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - betterShapeHoles[sIdx] = []; - } - for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - var sho = newShapeHoles[sIdx]; - for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - var ho = sho[hIdx]; - var hole_unassigned = true; - for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) { - if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { - hole_unassigned = false; - betterShapeHoles[s2Idx].push( ho ); - } else { - ambigious = true; - } - } - } - if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); } - } - } - // console.log("ambigious: ", ambigious); - if ( toChange.length > 0 ) { - // console.log("to change: ", toChange); - if (! ambigious) newShapeHoles = betterShapeHoles; - } - } + _lightsNeedUpdate = true; - var tmpHoles, j, jl; - for ( i = 0, il = newShapes.length; i < il; i ++ ) { - tmpShape = newShapes[i].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[i]; - for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - tmpShape.holes.push( tmpHoles[j].h ); - } - } + state.reset(); - //console.log("shape", shapes); + }; - return shapes; + setDefaultGLState(); -}; + this.context = _gl; + this.state = state; -// File:src/extras/core/Shape.js + // GPU capabilities -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); + var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); + var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); -// STEP 1 Create a path. -// STEP 2 Turn path into shape. -// STEP 3 ExtrudeGeometry takes in Shape/Shapes -// STEP 3a - Extract points from each shape, turn to vertices -// STEP 3b - Triangulate each shape, add faces. + var _supportsVertexTextures = _maxVertexTextures > 0; + var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' ); -THREE.Shape = function () { + // - THREE.Path.apply( this, arguments ); - this.holes = []; + var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); + var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); -}; + var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); + var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); -THREE.Shape.prototype = Object.create( THREE.Path.prototype ); -THREE.Shape.prototype.constructor = THREE.Shape; + var getCompressedTextureFormats = ( function () { -// Convenience method to return ExtrudeGeometry + var array; -THREE.Shape.prototype.extrude = function ( options ) { + return function () { - var extruded = new THREE.ExtrudeGeometry( this, options ); - return extruded; + if ( array !== undefined ) { -}; + return array; -// Convenience method to return ShapeGeometry + } -THREE.Shape.prototype.makeGeometry = function ( options ) { + array = []; - var geometry = new THREE.ShapeGeometry( this, options ); - return geometry; + if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) { -}; + var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ); -// Get points of holes + for ( var i = 0; i < formats.length; i ++ ) { -THREE.Shape.prototype.getPointsHoles = function ( divisions ) { + array.push( formats[ i ] ); - var i, il = this.holes.length, holesPts = []; + } - for ( i = 0; i < il; i ++ ) { + } - holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends ); + return array; - } + }; - return holesPts; + } )(); -}; + // clamp precision to maximum available -// Get points of holes (spaced by regular distance) + var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; + var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; -THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) { + if ( _precision === 'highp' && ! highpAvailable ) { - var i, il = this.holes.length, holesPts = []; + if ( mediumpAvailable ) { - for ( i = 0; i < il; i ++ ) { + _precision = 'mediump'; + THREE.warn( 'THREE.Canvas3DRenderer: highp not supported, using mediump.' ); - holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends ); + } else { + + _precision = 'lowp'; + THREE.warn( 'THREE.Canvas3DRenderer: highp and mediump not supported, using lowp.' ); + + } } - return holesPts; + if ( _precision === 'mediump' && ! mediumpAvailable ) { -}; + _precision = 'lowp'; + THREE.warn( 'THREE.Canvas3DRenderer: mediump not supported, using lowp.' ); + } -// Get points of shape and holes (keypoints based on segments parameter) + // Plugins -THREE.Shape.prototype.extractAllPoints = function ( divisions ) { + var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate ); - return { + var spritePlugin = new THREE.SpritePlugin( this, sprites ); + var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); - shape: this.getTransformedPoints( divisions ), - holes: this.getPointsHoles( divisions ) + // API + + this.getContext = function () { + + return _gl; }; -}; + this.forceContextLoss = function () { -THREE.Shape.prototype.extractPoints = function ( divisions ) { + //extensions.get( 'WEBGL_lose_context' ).loseContext(); - if (this.useSpacedPoints) { - return this.extractAllSpacedPoints(divisions); - } + }; - return this.extractAllPoints(divisions); + this.supportsVertexTextures = function () { -}; + return _supportsVertexTextures; -// -// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) { -// -// return { -// -// shape: this.transform( bend, divisions ), -// holes: this.getPointsHoles( divisions, bend ) -// -// }; -// -// }; + }; -// Get points of shape and holes (spaced by regular distance) + this.supportsFloatTextures = function () { -THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) { + return extensions.get( 'OES_texture_float' ); - return { + }; - shape: this.getTransformedSpacedPoints( divisions ), - holes: this.getSpacedPointsHoles( divisions ) + this.supportsHalfFloatTextures = function () { + + return extensions.get( 'OES_texture_half_float' ); }; -}; + this.supportsStandardDerivatives = function () { -/************************************************************** - * Utils - **************************************************************/ + return extensions.get( 'OES_standard_derivatives' ); -THREE.Shape.Utils = { + }; - triangulateShape: function ( contour, holes ) { + this.supportsCompressedTextureS3TC = function () { - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - // inOtherPt needs to be colinear to the inSegment - if ( inSegPt1.x != inSegPt2.x ) { - if ( inSegPt1.x < inSegPt2.x ) { - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - } else { - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } - } else { - if ( inSegPt1.y < inSegPt2.y ) { - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - } else { - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - } - } - } + return extensions.get( 'WEBGL_compressed_texture_s3tc' ); - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - var EPSILON = 0.0000000001; + }; - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; + this.supportsCompressedTexturePVRTC = function () { - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; + return extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; + }; - if ( Math.abs(limit) > EPSILON ) { // not parallel + this.supportsBlendMinMax = function () { - var perpSeg2; - if ( limit > 0 ) { - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - } else { - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - } + return extensions.get( 'EXT_blend_minmax' ); - // i.e. to reduce rounding errors - // intersection at endpoint of segment#1? - if ( perpSeg2 == 0 ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; - return [ inSeg1Pt1 ]; - } - if ( perpSeg2 == limit ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return []; - return [ inSeg1Pt2 ]; - } - // intersection at endpoint of segment#2? - if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 == limit ) return [ inSeg2Pt2 ]; + }; - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; + this.getMaxAnisotropy = ( function () { - } else { // parallel or colinear - if ( ( perpSeg1 != 0 ) || - ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return []; + var value; - // they are collinear or degenerate - var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point? - var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { - if ( (inSeg1Pt1.x != inSeg2Pt1.x) || - (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point - } - // segment#1 is a single point - if ( seg1Pt ) { - if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; - } - // segment#2 is a single point - if ( seg2Pt ) { - if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; - } + return function () { + + if ( value !== undefined ) { + + return value; - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if (seg1dx != 0) { // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - } - } else { // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - } else { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - } - } - if ( seg1minVal <= seg2minVal ) { - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal == seg2minVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; - } else { - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal == seg2maxVal ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; - } } + + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; + + return value; + } - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - // The order of legs is important + } )(); - var EPSILON = 0.0000000001; + this.getPrecision = function () { - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; + return _precision; - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; + }; - if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg. + this.getPixelRatio = function () { - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); + return pixelRatio; + + }; + + this.setPixelRatio = function ( value ) { + + pixelRatio = value; + + }; + + this.setSize = function ( width, height, updateStyle ) { + + _canvas.pixelSize = Qt.size(width * pixelRatio, height * pixelRatio) + + if ( updateStyle !== false ) { + +// Update styles is ignored in Canvas3D +// _canvas.style.width = width + 'px'; +// _canvas.style.height = height + 'px'; - if ( from2toAngle > 0 ) { // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } else { // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - } - } else { // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); - } } + this.setViewport( 0, 0, width, height ); + + }; - function removeHoles( contour, holes ) { + this.setViewport = function ( x, y, width, height ) { - var shape = contour.concat(); // work on this shape - var hole; + _viewportX = x * pixelRatio; + _viewportY = y * pixelRatio; - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; + _viewportWidth = width * pixelRatio; + _viewportHeight = height * pixelRatio; - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; + _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; + }; - var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; - } + this.setScissor = function ( x, y, width, height ) { - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; + _gl.scissor( + x * pixelRatio, + y * pixelRatio, + width * pixelRatio, + height * pixelRatio + ); - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; + }; - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; + this.enableScissorTest = function ( enable ) { - insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] ); - if (! insideAngle ) { - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; - } + if (enable) + _gl.enable( _gl.SCISSOR_TEST ) + else + _gl.disable( _gl.SCISSOR_TEST ); + + }; + + // Clearing + + this.getClearColor = function () { + + return _clearColor; + + }; + + this.setClearColor = function ( color, alpha ) { + + _clearColor.set( color ); + + _clearAlpha = alpha !== undefined ? alpha : 1; + + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + + }; + + this.getClearAlpha = function () { + + return _clearAlpha; + + }; + + this.setClearAlpha = function ( alpha ) { + + _clearAlpha = alpha; + + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + + }; + + this.clear = function ( color, depth, stencil ) { + + var bits = 0; + + if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + + _gl.clear( bits ); + + }; + + this.clearColor = function () { + + _gl.clear( _gl.COLOR_BUFFER_BIT ); + + }; + + this.clearDepth = function () { + + _gl.clear( _gl.DEPTH_BUFFER_BIT ); + + }; + + this.clearStencil = function () { + + _gl.clear( _gl.STENCIL_BUFFER_BIT ); + + }; + + this.clearTarget = function ( renderTarget, color, depth, stencil ) { + + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); + + }; + + // Reset + + this.resetGLState = resetGLState; + + // Buffer allocation + + function createParticleBuffers ( geometry ) { + + geometry.__webglVertexBuffer = _gl.createBuffer(); + geometry.__webglVertexBuffer.name = "Particle__webglVertexBuffer"; + geometry.__webglColorBuffer = _gl.createBuffer(); + geometry.__webglColorBuffer.name = "Particle__webglColorBuffer"; + + _this.info.memory.geometries ++; + + }; + + function createLineBuffers ( geometry ) { + + geometry.__webglVertexBuffer = _gl.createBuffer(); + geometry.__webglColorBuffer = _gl.createBuffer(); + geometry.__webglLineDistanceBuffer = _gl.createBuffer(); + geometry.__webglVertexBuffer.name = "Line__webglVertexBuffer"; + geometry.__webglColorBuffer.name = "Line__webglColorBuffer"; + geometry.__webglLineDistanceBuffer.name = "Line__webglLineDistanceBuffer"; + + _this.info.memory.geometries ++; + + }; + + function createMeshBuffers ( geometryGroup ) { + + geometryGroup.__webglVertexBuffer = _gl.createBuffer(); + geometryGroup.__webglNormalBuffer = _gl.createBuffer(); + geometryGroup.__webglTangentBuffer = _gl.createBuffer(); + geometryGroup.__webglColorBuffer = _gl.createBuffer(); + geometryGroup.__webglUVBuffer = _gl.createBuffer(); + geometryGroup.__webglUV2Buffer = _gl.createBuffer(); + geometryGroup.__webglVertexBuffer.name = "Mesh__webglVertexBuffer"; + geometryGroup.__webglNormalBuffer.name = "Mesh__webglNormalBuffer"; + geometryGroup.__webglTangentBuffer.name = "Mesh__webglTangentBuffer"; + geometryGroup.__webglColorBuffer.name = "Mesh__webglColorBuffer"; + geometryGroup.__webglUVBuffer.name = "Mesh__webglUVBuffer"; + geometryGroup.__webglUV2Buffer.name = "Mesh__webglUV2Buffer"; + + geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); + geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); + geometryGroup.__webglSkinIndicesBuffer.name = "Mesh__webglSkinIndicesBuffer"; + geometryGroup.__webglSkinWeightsBuffer.name = "Mesh__webglSkinWeightsBuffer"; + + geometryGroup.__webglFaceBuffer = _gl.createBuffer(); + geometryGroup.__webglLineBuffer = _gl.createBuffer(); + geometryGroup.__webglFaceBuffer.name = "Mesh__webglFaceBuffer"; + geometryGroup.__webglLineBuffer.name = "Mesh__webglLineBuffer"; + + var m, ml; + var numMorphTargets = geometryGroup.numMorphTargets; + + if ( numMorphTargets ) { + + geometryGroup.__webglMorphTargetsBuffers = []; + + for ( m = 0, ml = numMorphTargets; m < ml; m ++ ) { + var buf = _gl.createBuffer(); + buf.name = "Mesh__MorphTarget_"+m; + geometryGroup.__webglMorphTargetsBuffers.push(buf); - return true; } - function intersectsShapeEdge( inShapePt, inHolePt ) { - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { - nextIdx = sIdx + 1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } + } + + var numMorphNormals = geometryGroup.numMorphNormals; + + if ( numMorphNormals ) { + + geometryGroup.__webglMorphNormalsBuffers = []; + + for ( m = 0, ml = numMorphNormals; m < ml; m ++ ) { + var nbuf = _gl.createBuffer(); + nbuf.name = "Mesh__MorphNormal_"+m; + geometryGroup.__webglMorphNormalsBuffers.push( nbuf ); - return false; } - var indepHoles = []; + } + + _this.info.memory.geometries ++; + + }; + + // Events + + var onObjectRemoved = function ( event ) { + + var object = event.target; + + object.traverse( function ( child ) { + + child.removeEventListener( 'remove', onObjectRemoved ); + + removeObject( child ); + + } ); + + }; + + var onGeometryDispose = function ( event ) { + + var geometry = event.target; + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + deallocateGeometry( geometry ); + + }; + + var onTextureDispose = function ( event ) { + + var texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + _this.info.memory.textures --; + + + }; + + var onRenderTargetDispose = function ( event ) { + + var renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + _this.info.memory.textures --; + + }; + + var onMaterialDispose = function ( event ) { + + var material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + }; + + // Buffer deallocation + + var deleteBuffers = function ( geometry ) { + + var buffers = [ + '__webglVertexBuffer', + '__webglNormalBuffer', + '__webglTangentBuffer', + '__webglColorBuffer', + '__webglUVBuffer', + '__webglUV2Buffer', + + '__webglSkinIndicesBuffer', + '__webglSkinWeightsBuffer', + + '__webglFaceBuffer', + '__webglLineBuffer', + + '__webglLineDistanceBuffer' + ]; + + for ( var i = 0, l = buffers.length; i < l; i ++ ) { + + var name = buffers[ i ]; + + if ( geometry[ name ] !== undefined ) { + + _gl.deleteBuffer( geometry[ name ] ); + + delete geometry[ name ]; - function intersectsHoleEdge( inShapePt, inHolePt ) { - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { - chkHole = holes[indepHoles[ihIdx]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { - nextIdx = hIdx + 1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true ); - if ( intersection.length > 0 ) return true; - } - } - return false; } - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; + } - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + // custom attributes - indepHoles.push( h ); + if ( geometry.__webglCustomAttributesList !== undefined ) { + + for ( var name in geometry.__webglCustomAttributesList ) { + + _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer ); } - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { - counter --; - if ( counter < 0 ) { - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; + delete geometry.__webglCustomAttributesList; + + } + + _this.info.memory.geometries --; + + }; + + var deallocateGeometry = function ( geometry ) { + + delete geometry.__webglInit; + + if ( geometry instanceof THREE.BufferGeometry ) { + + for ( var name in geometry.attributes ) { + + var attribute = geometry.attributes[ name ]; + + if ( attribute.buffer !== undefined ) { + + _gl.deleteBuffer( attribute.buffer ); + + delete attribute.buffer; + } - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { + } - shapePt = shape[ shapeIndex ]; - holeIndex = - 1; + _this.info.memory.geometries --; - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { - holeIdx = indepHoles[h]; + } else { - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[cutKey] !== undefined ) continue; + var geometryGroupsList = geometryGroups[ geometry.id ]; - hole = holes[holeIdx]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - holePt = hole[ h2 ]; - if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; + if ( geometryGroupsList !== undefined ) { - holeIndex = h2; - indepHoles.splice(h, 1); + for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) { - tmpShape1 = shape.slice( 0, shapeIndex + 1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex + 1 ); + var geometryGroup = geometryGroupsList[ i ]; - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); + if ( geometryGroup.numMorphTargets !== undefined ) { - minShapeIndex = shapeIndex; + for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); + _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); - break; } - if ( holeIndex >= 0 ) break; // hole-vertex found - failedCuts[cutKey] = true; // remember failure + delete geometryGroup.__webglMorphTargetsBuffers; + } - if ( holeIndex >= 0 ) break; // hole-vertex found + + if ( geometryGroup.numMorphNormals !== undefined ) { + + for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { + + _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); + + } + + delete geometryGroup.__webglMorphNormalsBuffers; + + } + + deleteBuffers( geometryGroup ); + } + + delete geometryGroups[ geometry.id ]; + + } else { + + deleteBuffers( geometry ); + } - return shape; /* shape with no holes */ } + // TOFIX: Workaround for deleted geometry being currently bound - var i, il, f, face, - key, index, - allPointsMap = {}; + _currentGeometryProgram = ''; - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. + }; - var allpoints = contour.concat(); + var deallocateTexture = function ( texture ) { - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + if ( texture.image && texture.image.__webglTextureCube ) { - Array.prototype.push.apply( allpoints, holes[h] ); + // cube texture + + _gl.deleteTexture( texture.image.__webglTextureCube ); + + delete texture.image.__webglTextureCube; + + } else { + + // 2D texture + + if ( texture.__webglInit === undefined ) return; + + _gl.deleteTexture( texture.__webglTexture ); + + delete texture.__webglTexture; + delete texture.__webglInit; } - //console.log( "allpoints",allpoints, allpoints.length ); + }; - // prepare all points map + var deallocateRenderTarget = function ( renderTarget ) { - for ( i = 0, il = allpoints.length; i < il; i ++ ) { + if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return; - key = allpoints[ i ].x + ":" + allpoints[ i ].y; + _gl.deleteTexture( renderTarget.__webglTexture ); - if ( allPointsMap[ key ] !== undefined ) { + delete renderTarget.__webglTexture; - THREE.warn( "THREE.Shape: Duplicate point", key ); + if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { - } + for ( var i = 0; i < 6; i ++ ) { - allPointsMap[ key ] = i; + _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); + _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); - } + } - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); + } else { - var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); + _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); + _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); - // check all face vertices against all points map + } - for ( i = 0, il = triangles.length; i < il; i ++ ) { + delete renderTarget.__webglFramebuffer; + delete renderTarget.__webglRenderbuffer; - face = triangles[ i ]; + }; - for ( f = 0; f < 3; f ++ ) { + var deallocateMaterial = function ( material ) { - key = face[ f ].x + ":" + face[ f ].y; + var program = material.program.program; - index = allPointsMap[ key ]; + if ( program === undefined ) return; - if ( index !== undefined ) { + material.program = undefined; - face[ f ] = index; + // only deallocate GL program if this was the last use of shared program + // assumed there is only single copy of any program in the _programs list + // (that's how it's constructed) - } + var i, il, programInfo; + var deleteProgram = false; - } + for ( i = 0, il = _programs.length; i < il; i ++ ) { - } + programInfo = _programs[ i ]; - return triangles.concat(); + if ( programInfo.program === program ) { - }, + programInfo.usedTimes --; - isClockWise: function ( pts ) { + if ( programInfo.usedTimes === 0 ) { - return THREE.FontUtils.Triangulate.area( pts ) < 0; + deleteProgram = true; - }, + } - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve + break; - // Quad Bezier Functions + } - b2p0: function ( t, p ) { + } - var k = 1 - t; - return k * k * p; + if ( deleteProgram === true ) { - }, + // avoid using array.splice, this is costlier than creating new array from scratch - b2p1: function ( t, p ) { + var newPrograms = []; - return 2 * ( 1 - t ) * t * p; + for ( i = 0, il = _programs.length; i < il; i ++ ) { - }, + programInfo = _programs[ i ]; - b2p2: function ( t, p ) { + if ( programInfo.program !== program ) { - return t * t * p; + newPrograms.push( programInfo ); - }, + } - b2: function ( t, p0, p1, p2 ) { + } - return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 ); + _programs = newPrograms; - }, + _gl.deleteProgram( program ); - // Cubic Bezier Functions + _this.info.memory.programs --; - b3p0: function ( t, p ) { + } - var k = 1 - t; - return k * k * k * p; + }; - }, + // Buffer initialization - b3p1: function ( t, p ) { + function initCustomAttributes ( object ) { - var k = 1 - t; - return 3 * k * k * t * p; + var geometry = object.geometry; + var material = object.material; - }, + var nvertices = geometry.vertices.length; - b3p2: function ( t, p ) { + if ( material.attributes ) { - var k = 1 - t; - return 3 * k * t * t * p; + if ( geometry.__webglCustomAttributesList === undefined ) { - }, + geometry.__webglCustomAttributesList = []; - b3p3: function ( t, p ) { + } - return t * t * t * p; + for ( var name in material.attributes ) { - }, + var attribute = material.attributes[ name ]; - b3: function ( t, p0, p1, p2, p3 ) { + if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { - return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 ); + attribute.__webglInitialized = true; - } + var size = 1; // "f" and "i" -}; + if ( attribute.type === 'v2' ) size = 2; + else if ( attribute.type === 'v3' ) size = 3; + else if ( attribute.type === 'v4' ) size = 4; + else if ( attribute.type === 'c' ) size = 3; + attribute.size = size; -// File:src/extras/curves/LineCurve.js + attribute.array = new Float32Array( nvertices * size ); + attribute.array.name = ""+attribute+"attribute.array"; -/************************************************************** - * Line - **************************************************************/ + attribute.buffer = _gl.createBuffer(); + attribute.buffer.belongsToAttribute = name; -THREE.LineCurve = function ( v1, v2 ) { + attribute.needsUpdate = true; - this.v1 = v1; - this.v2 = v2; + } -}; + geometry.__webglCustomAttributesList.push( attribute ); -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.LineCurve.prototype.constructor = THREE.LineCurve; + } -THREE.LineCurve.prototype.getPoint = function ( t ) { + } - var point = this.v2.clone().sub(this.v1); - point.multiplyScalar( t ).add( this.v1 ); + }; - return point; + function initParticleBuffers ( geometry, object ) { -}; + var nvertices = geometry.vertices.length; -// Line curve is linear, so we can overwrite default getPointAt + geometry.__vertexArray = new Float32Array( nvertices * 3 ); + geometry.__colorArray = new Float32Array( nvertices * 3 ); + geometry.__vertexArray.name = "geometry.__vertexArray"; + geometry.__colorArray.name = "geometry.__colorArray"; -THREE.LineCurve.prototype.getPointAt = function ( u ) { + geometry.__webglParticleCount = nvertices; - return this.getPoint( u ); + initCustomAttributes( object ); -}; + }; -THREE.LineCurve.prototype.getTangent = function( t ) { + function initLineBuffers ( geometry, object ) { - var tangent = this.v2.clone().sub(this.v1); + var nvertices = geometry.vertices.length; - return tangent.normalize(); + geometry.__vertexArray = new Float32Array( nvertices * 3 ); + geometry.__colorArray = new Float32Array( nvertices * 3 ); + geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); + geometry.__vertexArray.name = "geometry.__vertexArray"; + geometry.__colorArray.name = "geometry.__colorArray"; + geometry.__lineDistanceArray.name = "geometry.__lineDistanceArray"; -}; + geometry.__webglLineCount = nvertices; -// File:src/extras/curves/QuadraticBezierCurve.js + initCustomAttributes( object ); -/************************************************************** - * Quadratic Bezier curve - **************************************************************/ + }; + function initMeshBuffers ( geometryGroup, object ) { -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { + var geometry = object.geometry, + faces3 = geometryGroup.faces3, - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + nvertices = faces3.length * 3, + ntris = faces3.length * 1, + nlines = faces3.length * 3, -}; + material = getBufferMaterial( object, geometryGroup ); -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; + geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); + geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); + geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); + geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); + geometryGroup.__vertexArray.name = "geometryGroup.__vertexArray"; + geometryGroup.__normalArray.name = "geometryGroup.__normalArray"; + geometryGroup.__colorArray.name = "geometryGroup.__colorArray"; + geometryGroup.__uvArray.name = "geometryGroup.__uvArray"; + if ( geometry.faceVertexUvs.length > 1 ) { -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { + geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); + geometryGroup.__uv2Array.name = "geometryGroup.__uv2Array"; - var vector = new THREE.Vector2(); + } - vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); + if ( geometry.hasTangents ) { - return vector; + geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); + geometryGroup.__tangentArray.name = "geometryGroup.__tangentArray"; -}; + } + if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { + geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); + geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); + geometryGroup.__skinIndexArray.name = "geometryGroup.__skinIndexArray"; + geometryGroup.__skinWeightArray.name = "geometryGroup.__skinWeightArray"; + } - var vector = new THREE.Vector2(); + var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 - vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ); - vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ); + geometryGroup.__typeArray = UintArray; + geometryGroup.__faceArray = new UintArray( ntris * 3 ); + geometryGroup.__lineArray = new UintArray( nlines * 2 ); + geometryGroup.__faceArray.name = "geometryGroup.__faceArray"; + geometryGroup.__lineArray.name = "geometryGroup.__lineArray"; - // returns unit vector + var m, ml; + var numMorphTargets = geometryGroup.numMorphTargets; - return vector.normalize(); + if ( numMorphTargets ) { -}; + geometryGroup.__morphTargetsArrays = []; -// File:src/extras/curves/CubicBezierCurve.js + for ( m = 0, ml = numMorphTargets; m < ml; m ++ ) { + var mta = new Float32Array( nvertices * 3 ); + mta.name = "morphTargetArray_"+m; + geometryGroup.__morphTargetsArrays.push(mta); + } -/************************************************************** - * Cubic Bezier curve - **************************************************************/ + } -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { + var numMorphNormals = geometryGroup.numMorphNormals; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + if ( numMorphNormals ) { -}; + geometryGroup.__morphNormalsArrays = []; -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; + for ( m = 0, ml = numMorphNormals; m < ml; m ++ ) { + var mna = new Float32Array( nvertices * 3 ); + mna.name = "morphNormalsArray_"+m; + geometryGroup.__morphNormalsArrays.push( mna ); + } -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { + } - var tx, ty; + geometryGroup.__webglFaceCount = ntris * 3; + geometryGroup.__webglLineCount = nlines * 2; - tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - return new THREE.Vector2( tx, ty ); + // custom attributes -}; + if ( material.attributes ) { -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { + if ( geometryGroup.__webglCustomAttributesList === undefined ) { - var tx, ty; + geometryGroup.__webglCustomAttributesList = []; - tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); + } - var tangent = new THREE.Vector2( tx, ty ); - tangent.normalize(); + for ( var name in material.attributes ) { - return tangent; + // Do a shallow copy of the attribute object so different geometryGroup chunks use different + // attribute buffers which are correctly indexed in the setMeshBuffers function -}; + var originalAttribute = material.attributes[ name ]; -// File:src/extras/curves/SplineCurve.js + var attribute = {}; -/************************************************************** - * Spline curve - **************************************************************/ + for ( var property in originalAttribute ) { -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { + attribute[ property ] = originalAttribute[ property ]; - this.points = ( points == undefined ) ? [] : points; + } -}; + if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) { -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; + attribute.__webglInitialized = true; -THREE.SplineCurve.prototype.getPoint = function ( t ) { + var size = 1; // "f" and "i" - var points = this.points; - var point = ( points.length - 1 ) * t; + if ( attribute.type === 'v2' ) size = 2; + else if ( attribute.type === 'v3' ) size = 3; + else if ( attribute.type === 'v4' ) size = 4; + else if ( attribute.type === 'c' ) size = 3; - var intPoint = Math.floor( point ); - var weight = point - intPoint; + attribute.size = size; - var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ] - var point1 = points[ intPoint ] - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ] - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ] + attribute.array = new Float32Array( nvertices * size ); - var vector = new THREE.Vector2(); + attribute.buffer = _gl.createBuffer(); + attribute.buffer.belongsToAttribute = name; - vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); - vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); + originalAttribute.needsUpdate = true; + attribute.__original = originalAttribute; - return vector; + } -}; + geometryGroup.__webglCustomAttributesList.push( attribute ); -// File:src/extras/curves/EllipseCurve.js + } -/************************************************************** - * Ellipse curve - **************************************************************/ + } -THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) { + geometryGroup.__inittedArrays = true; - this.aX = aX; - this.aY = aY; + }; - this.xRadius = xRadius; - this.yRadius = yRadius; + function getBufferMaterial( object, geometryGroup ) { - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + return object.material instanceof THREE.MeshFaceMaterial + ? object.material.materials[ geometryGroup.materialIndex ] + : object.material; - this.aClockwise = aClockwise; + } -}; + function materialNeedsFaceNormals ( material ) { -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; + return material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading; -THREE.EllipseCurve.prototype.getPoint = function ( t ) { + } - var deltaAngle = this.aEndAngle - this.aStartAngle; + // Buffer setting - if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2; - if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2; + function setParticleBuffers ( geometry, hint, object ) { - var angle; + var v, c, vertex, offset, color, - if ( this.aClockwise === true ) { + vertices = geometry.vertices, + vl = vertices.length, - angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle ); + colors = geometry.colors, + cl = colors.length, - } else { + vertexArray = geometry.__vertexArray, + colorArray = geometry.__colorArray, - angle = this.aStartAngle + t * deltaAngle; + dirtyVertices = geometry.verticesNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, - } - - var vector = new THREE.Vector2(); + customAttributes = geometry.__webglCustomAttributesList, + i, il, + ca, cal, value, + customAttribute; - vector.x = this.aX + this.xRadius * Math.cos( angle ); - vector.y = this.aY + this.yRadius * Math.sin( angle ); + if ( dirtyVertices ) { - return vector; + for ( v = 0; v < vl; v ++ ) { -}; + vertex = vertices[ v ]; -// File:src/extras/curves/ArcCurve.js + offset = v * 3; -/************************************************************** - * Arc curve - **************************************************************/ + vertexArray[ offset ] = vertex.x; + vertexArray[ offset + 1 ] = vertex.y; + vertexArray[ offset + 2 ] = vertex.z; -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); -}; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; + } -// File:src/extras/curves/LineCurve3.js + if ( dirtyColors ) { -/************************************************************** - * Line3D - **************************************************************/ + for ( c = 0; c < cl; c ++ ) { -THREE.LineCurve3 = THREE.Curve.create( + color = colors[ c ]; - function ( v1, v2 ) { + offset = c * 3; - this.v1 = v1; - this.v2 = v2; + colorArray[ offset ] = color.r; + colorArray[ offset + 1 ] = color.g; + colorArray[ offset + 2 ] = color.b; - }, + } - function ( t ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - var vector = new THREE.Vector3(); + } - vector.subVectors( this.v2, this.v1 ); // diff - vector.multiplyScalar( t ); - vector.add( this.v1 ); + if ( customAttributes ) { - return vector; + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - } + customAttribute = customAttributes[ i ]; -); + if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) { -// File:src/extras/curves/QuadraticBezierCurve3.js + cal = customAttribute.value.length; -/************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ + offset = 0; -THREE.QuadraticBezierCurve3 = THREE.Curve.create( + if ( customAttribute.size === 1 ) { - function ( v0, v1, v2 ) { + for ( ca = 0; ca < cal; ca ++ ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + customAttribute.array[ ca ] = customAttribute.value[ ca ]; - }, + } - function ( t ) { + } else if ( customAttribute.size === 2 ) { - var vector = new THREE.Vector3(); + for ( ca = 0; ca < cal; ca ++ ) { - vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x ); - vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y ); - vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z ); + value = customAttribute.value[ ca ]; - return vector; + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; - } + offset += 2; -); + } -// File:src/extras/curves/CubicBezierCurve3.js + } else if ( customAttribute.size === 3 ) { -/************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ + if ( customAttribute.type === 'c' ) { -THREE.CubicBezierCurve3 = THREE.Curve.create( + for ( ca = 0; ca < cal; ca ++ ) { - function ( v0, v1, v2, v3 ) { + value = customAttribute.value[ ca ]; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + customAttribute.array[ offset ] = value.r; + customAttribute.array[ offset + 1 ] = value.g; + customAttribute.array[ offset + 2 ] = value.b; - }, + offset += 3; - function ( t ) { + } - var vector = new THREE.Vector3(); + } else { - vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ); - vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ); - vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ); + for ( ca = 0; ca < cal; ca ++ ) { - return vector; + value = customAttribute.value[ ca ]; - } + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; -); + offset += 3; -// File:src/extras/curves/SplineCurve3.js + } -/************************************************************** - * Spline 3D curve - **************************************************************/ + } + } else if ( customAttribute.size === 4 ) { -THREE.SplineCurve3 = THREE.Curve.create( + for ( ca = 0; ca < cal; ca ++ ) { - function ( points /* array of Vector3 */) { + value = customAttribute.value[ ca ]; - this.points = ( points == undefined ) ? [] : points; + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; + customAttribute.array[ offset + 3 ] = value.w; - }, + offset += 4; - function ( t ) { + } - var points = this.points; - var point = ( points.length - 1 ) * t; + } - var intPoint = Math.floor( point ); - var weight = point - intPoint; + } - var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - var vector = new THREE.Vector3(); + customAttribute.needsUpdate = false; - vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); - vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); - vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight ); + } - return vector; + } } -); + function setLineBuffers ( geometry, hint ) { -// File:src/extras/curves/ClosedSplineCurve3.js + var v, c, d, vertex, offset, color, -/************************************************************** - * Closed Spline 3D curve - **************************************************************/ + vertices = geometry.vertices, + colors = geometry.colors, + lineDistances = geometry.lineDistances, + vl = vertices.length, + cl = colors.length, + dl = lineDistances.length, -THREE.ClosedSplineCurve3 = THREE.Curve.create( + vertexArray = geometry.__vertexArray, + colorArray = geometry.__colorArray, + lineDistanceArray = geometry.__lineDistanceArray, - function ( points /* array of Vector3 */) { + dirtyVertices = geometry.verticesNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, + dirtyLineDistances = geometry.lineDistancesNeedUpdate, - this.points = ( points == undefined ) ? [] : points; + customAttributes = geometry.__webglCustomAttributesList, - }, + i, il, + ca, cal, value, + customAttribute; - function ( t ) { + if ( dirtyVertices ) { - var points = this.points; - var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1 + for ( v = 0; v < vl; v ++ ) { - var intPoint = Math.floor( point ); - var weight = point - intPoint; + vertex = vertices[ v ]; - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; + offset = v * 3; - var point0 = points[ ( intPoint - 1 ) % points.length ]; - var point1 = points[ ( intPoint ) % points.length ]; - var point2 = points[ ( intPoint + 1 ) % points.length ]; - var point3 = points[ ( intPoint + 2 ) % points.length ]; + vertexArray[ offset ] = vertex.x; + vertexArray[ offset + 1 ] = vertex.y; + vertexArray[ offset + 2 ] = vertex.z; - var vector = new THREE.Vector3(); + } - vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight ); - vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight ); - vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); - return vector; + } - } + if ( dirtyColors ) { -); + for ( c = 0; c < cl; c ++ ) { -// File:src/extras/animation/AnimationHandler.js + color = colors[ c ]; -/** - * @author mikael emtinger / http://gomo.se/ - */ + offset = c * 3; -THREE.AnimationHandler = { + colorArray[ offset ] = color.r; + colorArray[ offset + 1 ] = color.g; + colorArray[ offset + 2 ] = color.b; - LINEAR: 0, - CATMULLROM: 1, - CATMULLROM_FORWARD: 2, + } - // + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); }, - get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); }, - remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); }, + } - // + if ( dirtyLineDistances ) { - animations: [], + for ( d = 0; d < dl; d ++ ) { - init: function ( data ) { + lineDistanceArray[ d ] = lineDistances[ d ]; - if ( data.initialized === true ) return data; + } - // loop through all keys + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); - for ( var h = 0; h < data.hierarchy.length; h ++ ) { + } - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { + if ( customAttributes ) { - // remove minus times + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - if ( data.hierarchy[ h ].keys[ k ].time < 0 ) { + customAttribute = customAttributes[ i ]; - data.hierarchy[ h ].keys[ k ].time = 0; + if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) { - } + offset = 0; - // create quaternions + cal = customAttribute.value.length; - if ( data.hierarchy[ h ].keys[ k ].rot !== undefined && - ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) { + if ( customAttribute.size === 1 ) { - var quat = data.hierarchy[ h ].keys[ k ].rot; - data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat ); + for ( ca = 0; ca < cal; ca ++ ) { - } + customAttribute.array[ ca ] = customAttribute.value[ ca ]; - } + } - // prepare morph target keys + } else if ( customAttribute.size === 2 ) { - if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) { + for ( ca = 0; ca < cal; ca ++ ) { - // get all used + value = customAttribute.value[ ca ]; - var usedMorphTargets = {}; + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { + offset += 2; - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { + } - var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ]; - usedMorphTargets[ morphTargetName ] = - 1; + } else if ( customAttribute.size === 3 ) { - } + if ( customAttribute.type === 'c' ) { - } + for ( ca = 0; ca < cal; ca ++ ) { - data.hierarchy[ h ].usedMorphTargets = usedMorphTargets; + value = customAttribute.value[ ca ]; + customAttribute.array[ offset ] = value.r; + customAttribute.array[ offset + 1 ] = value.g; + customAttribute.array[ offset + 2 ] = value.b; - // set all used on all frames + offset += 3; - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { + } - var influences = {}; + } else { - for ( var morphTargetName in usedMorphTargets ) { + for ( ca = 0; ca < cal; ca ++ ) { - for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) { + value = customAttribute.value[ ca ]; - if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) { + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; - influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ]; - break; + offset += 3; } } - if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) { + } else if ( customAttribute.size === 4 ) { - influences[ morphTargetName ] = 0; + for ( ca = 0; ca < cal; ca ++ ) { + + value = customAttribute.value[ ca ]; + + customAttribute.array[ offset ] = value.x; + customAttribute.array[ offset + 1 ] = value.y; + customAttribute.array[ offset + 2 ] = value.z; + customAttribute.array[ offset + 3 ] = value.w; + + offset += 4; } } - data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences; + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); + + customAttribute.needsUpdate = false; } } + } - // remove all keys that are on the same time - - for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) { - - if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) { - - data.hierarchy[ h ].keys.splice( k, 1 ); - k --; + } - } + function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { - } + if ( ! geometryGroup.__inittedArrays ) { + return; - // set index + } - for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) { + var needsFaceNormals = materialNeedsFaceNormals( material ); - data.hierarchy[ h ].keys[ k ].index = k; + var f, fl, fi, face, + vertexNormals, faceNormal, + vertexColors, faceColor, + vertexTangents, + uv, uv2, v1, v2, v3, t1, t2, t3, n1, n2, n3, + c1, c2, c3, + sw1, sw2, sw3, + si1, si2, si3, + i, il, + vn, uvi, uv2i, + vk, vkl, vka, + nka, chf, faceVertexNormals, - } + vertexIndex = 0, - } + offset = 0, + offset_uv = 0, + offset_uv2 = 0, + offset_face = 0, + offset_normal = 0, + offset_tangent = 0, + offset_line = 0, + offset_color = 0, + offset_skin = 0, + offset_morphTarget = 0, + offset_custom = 0, - data.initialized = true; + value, - return data; + vertexArray = geometryGroup.__vertexArray, + uvArray = geometryGroup.__uvArray, + uv2Array = geometryGroup.__uv2Array, + normalArray = geometryGroup.__normalArray, + tangentArray = geometryGroup.__tangentArray, + colorArray = geometryGroup.__colorArray, - }, + skinIndexArray = geometryGroup.__skinIndexArray, + skinWeightArray = geometryGroup.__skinWeightArray, - parse: function ( root ) { + morphTargetsArrays = geometryGroup.__morphTargetsArrays, + morphNormalsArrays = geometryGroup.__morphNormalsArrays, - var parseRecurseHierarchy = function ( root, hierarchy ) { + customAttributes = geometryGroup.__webglCustomAttributesList, + customAttribute, - hierarchy.push( root ); + faceArray = geometryGroup.__faceArray, + lineArray = geometryGroup.__lineArray, - for ( var c = 0; c < root.children.length; c ++ ) - parseRecurseHierarchy( root.children[ c ], hierarchy ); + geometry = object.geometry, // this is shared for all chunks - }; + dirtyVertices = geometry.verticesNeedUpdate, + dirtyElements = geometry.elementsNeedUpdate, + dirtyUvs = geometry.uvsNeedUpdate, + dirtyNormals = geometry.normalsNeedUpdate, + dirtyTangents = geometry.tangentsNeedUpdate, + dirtyColors = geometry.colorsNeedUpdate, + dirtyMorphTargets = geometry.morphTargetsNeedUpdate, - // setup hierarchy + vertices = geometry.vertices, + chunk_faces3 = geometryGroup.faces3, + obj_faces = geometry.faces, - var hierarchy = []; + obj_uvs = geometry.faceVertexUvs[ 0 ], + obj_uvs2 = geometry.faceVertexUvs[ 1 ], - if ( root instanceof THREE.SkinnedMesh ) { + obj_skinIndices = geometry.skinIndices, + obj_skinWeights = geometry.skinWeights, - for ( var b = 0; b < root.skeleton.bones.length; b ++ ) { + morphTargets = geometry.morphTargets, + morphNormals = geometry.morphNormals; - hierarchy.push( root.skeleton.bones[ b ] ); + if ( dirtyVertices ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } else { + face = obj_faces[ chunk_faces3[ f ] ]; - parseRecurseHierarchy( root, hierarchy ); + v1 = vertices[ face.a ]; + v2 = vertices[ face.b ]; + v3 = vertices[ face.c ]; - } + vertexArray[ offset ] = v1.x; + vertexArray[ offset + 1 ] = v1.y; + vertexArray[ offset + 2 ] = v1.z; - return hierarchy; + vertexArray[ offset + 3 ] = v2.x; + vertexArray[ offset + 4 ] = v2.y; + vertexArray[ offset + 5 ] = v2.z; - }, + vertexArray[ offset + 6 ] = v3.x; + vertexArray[ offset + 7 ] = v3.y; + vertexArray[ offset + 8 ] = v3.z; - play: function ( animation ) { + offset += 9; - if ( this.animations.indexOf( animation ) === - 1 ) { + } - this.animations.push( animation ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } - }, + if ( dirtyMorphTargets ) { - stop: function ( animation ) { + for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { - var index = this.animations.indexOf( animation ); + offset_morphTarget = 0; - if ( index !== - 1 ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - this.animations.splice( index, 1 ); + chf = chunk_faces3[ f ]; + face = obj_faces[ chf ]; - } + // morph positions - }, + v1 = morphTargets[ vk ].vertices[ face.a ]; + v2 = morphTargets[ vk ].vertices[ face.b ]; + v3 = morphTargets[ vk ].vertices[ face.c ]; - update: function ( deltaTimeMS ) { + vka = morphTargetsArrays[ vk ]; - for ( var i = 0; i < this.animations.length; i ++ ) { + vka[ offset_morphTarget ] = v1.x; + vka[ offset_morphTarget + 1 ] = v1.y; + vka[ offset_morphTarget + 2 ] = v1.z; - this.animations[ i ].resetBlendWeights( ); + vka[ offset_morphTarget + 3 ] = v2.x; + vka[ offset_morphTarget + 4 ] = v2.y; + vka[ offset_morphTarget + 5 ] = v2.z; - } + vka[ offset_morphTarget + 6 ] = v3.x; + vka[ offset_morphTarget + 7 ] = v3.y; + vka[ offset_morphTarget + 8 ] = v3.z; - for ( var i = 0; i < this.animations.length; i ++ ) { + // morph normals - this.animations[ i ].update( deltaTimeMS ); + if ( material.morphNormals ) { - } + if ( needsFaceNormals ) { - } + n1 = morphNormals[ vk ].faceNormals[ chf ]; + n2 = n1; + n3 = n1; -}; + } else { -// File:src/extras/animation/Animation.js + faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + n1 = faceVertexNormals.a; + n2 = faceVertexNormals.b; + n3 = faceVertexNormals.c; -THREE.Animation = function ( root, data ) { + } - this.root = root; - this.data = THREE.AnimationHandler.init( data ); - this.hierarchy = THREE.AnimationHandler.parse( root ); + nka = morphNormalsArrays[ vk ]; - this.currentTime = 0; - this.timeScale = 1; + nka[ offset_morphTarget ] = n1.x; + nka[ offset_morphTarget + 1 ] = n1.y; + nka[ offset_morphTarget + 2 ] = n1.z; - this.isPlaying = false; - this.loop = true; - this.weight = 0; + nka[ offset_morphTarget + 3 ] = n2.x; + nka[ offset_morphTarget + 4 ] = n2.y; + nka[ offset_morphTarget + 5 ] = n2.z; - this.interpolationType = THREE.AnimationHandler.LINEAR; + nka[ offset_morphTarget + 6 ] = n3.x; + nka[ offset_morphTarget + 7 ] = n3.y; + nka[ offset_morphTarget + 8 ] = n3.z; -}; + } -THREE.Animation.prototype = { + // - constructor: THREE.Animation, + offset_morphTarget += 9; - keyTypes: [ "pos", "rot", "scl" ], + } - play: function ( startTime, weight ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); + _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); - this.currentTime = startTime !== undefined ? startTime : 0; - this.weight = weight !== undefined ? weight : 1; + if ( material.morphNormals ) { - this.isPlaying = true; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); + _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); - this.reset(); + } - THREE.AnimationHandler.play( this ); + } - }, + } - stop: function() { + if ( obj_skinWeights.length ) { - this.isPlaying = false; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - THREE.AnimationHandler.stop( this ); + face = obj_faces[ chunk_faces3[ f ] ]; - }, + // weights - reset: function () { + sw1 = obj_skinWeights[ face.a ]; + sw2 = obj_skinWeights[ face.b ]; + sw3 = obj_skinWeights[ face.c ]; - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + skinWeightArray[ offset_skin ] = sw1.x; + skinWeightArray[ offset_skin + 1 ] = sw1.y; + skinWeightArray[ offset_skin + 2 ] = sw1.z; + skinWeightArray[ offset_skin + 3 ] = sw1.w; - var object = this.hierarchy[ h ]; + skinWeightArray[ offset_skin + 4 ] = sw2.x; + skinWeightArray[ offset_skin + 5 ] = sw2.y; + skinWeightArray[ offset_skin + 6 ] = sw2.z; + skinWeightArray[ offset_skin + 7 ] = sw2.w; - if ( object.animationCache === undefined ) { + skinWeightArray[ offset_skin + 8 ] = sw3.x; + skinWeightArray[ offset_skin + 9 ] = sw3.y; + skinWeightArray[ offset_skin + 10 ] = sw3.z; + skinWeightArray[ offset_skin + 11 ] = sw3.w; - object.animationCache = { - animations: {}, - blending: { - positionWeight: 0.0, - quaternionWeight: 0.0, - scaleWeight: 0.0 - } - }; - } + // indices - var name = this.data.name; - var animations = object.animationCache.animations; - var animationCache = animations[ name ]; + si1 = obj_skinIndices[ face.a ]; + si2 = obj_skinIndices[ face.b ]; + si3 = obj_skinIndices[ face.c ]; - if ( animationCache === undefined ) { + skinIndexArray[ offset_skin ] = si1.x; + skinIndexArray[ offset_skin + 1 ] = si1.y; + skinIndexArray[ offset_skin + 2 ] = si1.z; + skinIndexArray[ offset_skin + 3 ] = si1.w; - animationCache = { - prevKey: { pos: 0, rot: 0, scl: 0 }, - nextKey: { pos: 0, rot: 0, scl: 0 }, - originalMatrix: object.matrix - }; + skinIndexArray[ offset_skin + 4 ] = si2.x; + skinIndexArray[ offset_skin + 5 ] = si2.y; + skinIndexArray[ offset_skin + 6 ] = si2.z; + skinIndexArray[ offset_skin + 7 ] = si2.w; - animations[ name ] = animationCache; + skinIndexArray[ offset_skin + 8 ] = si3.x; + skinIndexArray[ offset_skin + 9 ] = si3.y; + skinIndexArray[ offset_skin + 10 ] = si3.z; + skinIndexArray[ offset_skin + 11 ] = si3.w; + + offset_skin += 12; } - // Get keys to match our current time + if ( offset_skin > 0 ) { - for ( var t = 0; t < 3; t ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); - var type = this.keyTypes[ t ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); + + } - var prevKey = this.data.hierarchy[ h ].keys[ 0 ]; - var nextKey = this.getNextKeyWith( type, h, 1 ); + } - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { + if ( dirtyColors ) { - prevKey = nextKey; - nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + face = obj_faces[ chunk_faces3[ f ] ]; - animationCache.prevKey[ type ] = prevKey; - animationCache.nextKey[ type ] = nextKey; + vertexColors = face.vertexColors; + faceColor = face.color; - } + if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) { - } + c1 = vertexColors[ 0 ]; + c2 = vertexColors[ 1 ]; + c3 = vertexColors[ 2 ]; - }, + } else { - resetBlendWeights: function () { + c1 = faceColor; + c2 = faceColor; + c3 = faceColor; - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + } - var object = this.hierarchy[ h ]; - var animationCache = object.animationCache; + colorArray[ offset_color ] = c1.r; + colorArray[ offset_color + 1 ] = c1.g; + colorArray[ offset_color + 2 ] = c1.b; - if ( animationCache !== undefined ) { + colorArray[ offset_color + 3 ] = c2.r; + colorArray[ offset_color + 4 ] = c2.g; + colorArray[ offset_color + 5 ] = c2.b; - var blending = animationCache.blending; + colorArray[ offset_color + 6 ] = c3.r; + colorArray[ offset_color + 7 ] = c3.g; + colorArray[ offset_color + 8 ] = c3.b; - blending.positionWeight = 0.0; - blending.quaternionWeight = 0.0; - blending.scaleWeight = 0.0; + offset_color += 9; } - } + if ( offset_color > 0 ) { - }, + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); - update: ( function() { + } - var points = []; - var target = new THREE.Vector3(); - var newVector = new THREE.Vector3(); - var newQuat = new THREE.Quaternion(); + } - // Catmull-Rom spline + if ( dirtyTangents && geometry.hasTangents ) { - var interpolateCatmullRom = function ( points, scale ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - var c = [], v3 = [], - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + face = obj_faces[ chunk_faces3[ f ] ]; - point = ( points.length - 1 ) * scale; - intPoint = Math.floor( point ); - weight = point - intPoint; + vertexTangents = face.vertexTangents; - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1; - c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2; + t1 = vertexTangents[ 0 ]; + t2 = vertexTangents[ 1 ]; + t3 = vertexTangents[ 2 ]; - pa = points[ c[ 0 ] ]; - pb = points[ c[ 1 ] ]; - pc = points[ c[ 2 ] ]; - pd = points[ c[ 3 ] ]; + tangentArray[ offset_tangent ] = t1.x; + tangentArray[ offset_tangent + 1 ] = t1.y; + tangentArray[ offset_tangent + 2 ] = t1.z; + tangentArray[ offset_tangent + 3 ] = t1.w; - w2 = weight * weight; - w3 = weight * w2; + tangentArray[ offset_tangent + 4 ] = t2.x; + tangentArray[ offset_tangent + 5 ] = t2.y; + tangentArray[ offset_tangent + 6 ] = t2.z; + tangentArray[ offset_tangent + 7 ] = t2.w; - v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 ); - v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 ); - v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 ); + tangentArray[ offset_tangent + 8 ] = t3.x; + tangentArray[ offset_tangent + 9 ] = t3.y; + tangentArray[ offset_tangent + 10 ] = t3.z; + tangentArray[ offset_tangent + 11 ] = t3.w; - return v3; + offset_tangent += 12; - }; + } - var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + } - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + if ( dirtyNormals ) { - }; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - return function ( delta ) { + face = obj_faces[ chunk_faces3[ f ] ]; - if ( this.isPlaying === false ) return; + vertexNormals = face.vertexNormals; + faceNormal = face.normal; - this.currentTime += delta * this.timeScale; + if ( vertexNormals.length === 3 && needsFaceNormals === false ) { - if ( this.weight === 0 ) - return; + for ( i = 0; i < 3; i ++ ) { - // + vn = vertexNormals[ i ]; - var duration = this.data.length; + normalArray[ offset_normal ] = vn.x; + normalArray[ offset_normal + 1 ] = vn.y; + normalArray[ offset_normal + 2 ] = vn.z; - if ( this.currentTime > duration || this.currentTime < 0 ) { + offset_normal += 3; - if ( this.loop ) { + } - this.currentTime %= duration; + } else { - if ( this.currentTime < 0 ) - this.currentTime += duration; + for ( i = 0; i < 3; i ++ ) { - this.reset(); + normalArray[ offset_normal ] = faceNormal.x; + normalArray[ offset_normal + 1 ] = faceNormal.y; + normalArray[ offset_normal + 2 ] = faceNormal.z; - } else { + offset_normal += 3; - this.stop(); + } } } - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); - var object = this.hierarchy[ h ]; - var animationCache = object.animationCache.animations[this.data.name]; - var blending = object.animationCache.blending; + } - // loop through pos/rot/scl + if ( dirtyUvs && obj_uvs ) { - for ( var t = 0; t < 3; t ++ ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - // get keys + fi = chunk_faces3[ f ]; - var type = this.keyTypes[ t ]; - var prevKey = animationCache.prevKey[ type ]; - var nextKey = animationCache.nextKey[ type ]; + uv = obj_uvs[ fi ]; - if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) || - ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) { + if ( uv === undefined ) continue; - prevKey = this.data.hierarchy[ h ].keys[ 0 ]; - nextKey = this.getNextKeyWith( type, h, 1 ); + for ( i = 0; i < 3; i ++ ) { - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { + uvi = uv[ i ]; - prevKey = nextKey; - nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 ); + uvArray[ offset_uv ] = uvi.x; + uvArray[ offset_uv + 1 ] = uvi.y; - } + offset_uv += 2; - animationCache.prevKey[ type ] = prevKey; - animationCache.nextKey[ type ] = nextKey; + } - } + } - var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time ); + if ( offset_uv > 0 ) { - var prevXYZ = prevKey[ type ]; - var nextXYZ = nextKey[ type ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); - if ( scale < 0 ) scale = 0; - if ( scale > 1 ) scale = 1; + } - // interpolate + } - if ( type === "pos" ) { + if ( dirtyUvs && obj_uvs2 ) { - if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; + fi = chunk_faces3[ f ]; - // blend - var proportionalWeight = this.weight / ( this.weight + blending.positionWeight ); - object.position.lerp( newVector, proportionalWeight ); - blending.positionWeight += this.weight; + uv2 = obj_uvs2[ fi ]; - } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + if ( uv2 === undefined ) continue; - points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ]; - points[ 1 ] = prevXYZ; - points[ 2 ] = nextXYZ; - points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ]; + for ( i = 0; i < 3; i ++ ) { - scale = scale * 0.33 + 0.33; + uv2i = uv2[ i ]; - var currentPoint = interpolateCatmullRom( points, scale ); - var proportionalWeight = this.weight / ( this.weight + blending.positionWeight ); - blending.positionWeight += this.weight; + uv2Array[ offset_uv2 ] = uv2i.x; + uv2Array[ offset_uv2 + 1 ] = uv2i.y; - // blend + offset_uv2 += 2; - var vector = object.position; + } - vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight; - vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight; - vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight; + } - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + if ( offset_uv2 > 0 ) { - var forwardPoint = interpolateCatmullRom( points, scale * 1.01 ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); - target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] ); - target.sub( vector ); - target.y = 0; - target.normalize(); + } - var angle = Math.atan2( target.x, target.z ); - object.rotation.set( 0, angle, 0 ); + } - } + if ( dirtyElements ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } else if ( type === "rot" ) { + faceArray[ offset_face ] = vertexIndex; + faceArray[ offset_face + 1 ] = vertexIndex + 1; + faceArray[ offset_face + 2 ] = vertexIndex + 2; - THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale ); + offset_face += 3; - // Avoid paying the cost of an additional slerp if we don't have to - if ( blending.quaternionWeight === 0 ) { + lineArray[ offset_line ] = vertexIndex; + lineArray[ offset_line + 1 ] = vertexIndex + 1; - object.quaternion.copy(newQuat); - blending.quaternionWeight = this.weight; + lineArray[ offset_line + 2 ] = vertexIndex; + lineArray[ offset_line + 3 ] = vertexIndex + 2; - } else { + lineArray[ offset_line + 4 ] = vertexIndex + 1; + lineArray[ offset_line + 5 ] = vertexIndex + 2; - var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight ); - THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight ); - blending.quaternionWeight += this.weight; + offset_line += 6; - } + vertexIndex += 3; - } else if ( type === "scl" ) { + } - newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale; - newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale; - newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale; + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); + _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); - var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight ); - object.scale.lerp( newVector, proportionalWeight ); - blending.scaleWeight += this.weight; + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); + _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); - } + } - } + if ( customAttributes ) { - } + for ( i = 0, il = customAttributes.length; i < il; i ++ ) { - return true; + customAttribute = customAttributes[ i ]; - }; + if ( ! customAttribute.__original.needsUpdate ) continue; - } )(), + offset_custom = 0; - getNextKeyWith: function ( type, h, key ) { + if ( customAttribute.size === 1 ) { - var keys = this.data.hierarchy[ h ].keys; + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - key = key < keys.length - 1 ? key : keys.length - 1; + face = obj_faces[ chunk_faces3[ f ] ]; - } else { + customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; + customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; + customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; - key = key % keys.length; + offset_custom += 3; - } + } - for ( ; key < keys.length; key ++ ) { + } else if ( customAttribute.boundTo === 'faces' ) { - if ( keys[ key ][ type ] !== undefined ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - return keys[ key ]; + value = customAttribute.value[ chunk_faces3[ f ] ]; - } + customAttribute.array[ offset_custom ] = value; + customAttribute.array[ offset_custom + 1 ] = value; + customAttribute.array[ offset_custom + 2 ] = value; - } + offset_custom += 3; - return this.data.hierarchy[ h ].keys[ 0 ]; + } - }, + } - getPrevKeyWith: function ( type, h, key ) { + } else if ( customAttribute.size === 2 ) { - var keys = this.data.hierarchy[ h ].keys; + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM || - this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) { + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - key = key > 0 ? key : 0; + face = obj_faces[ chunk_faces3[ f ] ]; - } else { + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; - key = key >= 0 ? key : key + keys.length; + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; - } + customAttribute.array[ offset_custom + 2 ] = v2.x; + customAttribute.array[ offset_custom + 3 ] = v2.y; + customAttribute.array[ offset_custom + 4 ] = v3.x; + customAttribute.array[ offset_custom + 5 ] = v3.y; - for ( ; key >= 0; key -- ) { + offset_custom += 6; - if ( keys[ key ][ type ] !== undefined ) { + } - return keys[ key ]; + } else if ( customAttribute.boundTo === 'faces' ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + value = customAttribute.value[ chunk_faces3[ f ] ]; - return this.data.hierarchy[ h ].keys[ keys.length - 1 ]; + v1 = value; + v2 = value; + v3 = value; - } + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; -}; + customAttribute.array[ offset_custom + 2 ] = v2.x; + customAttribute.array[ offset_custom + 3 ] = v2.y; -// File:src/extras/animation/KeyFrameAnimation.js + customAttribute.array[ offset_custom + 4 ] = v3.x; + customAttribute.array[ offset_custom + 5 ] = v3.y; -/** - * @author mikael emtinger / http://gomo.se/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author khang duong - * @author erik kitson - */ + offset_custom += 6; -THREE.KeyFrameAnimation = function ( data ) { + } - this.root = data.node; - this.data = THREE.AnimationHandler.init( data ); - this.hierarchy = THREE.AnimationHandler.parse( this.root ); - this.currentTime = 0; - this.timeScale = 0.001; - this.isPlaying = false; - this.isPaused = true; - this.loop = true; + } - // initialize to first keyframes + } else if ( customAttribute.size === 3 ) { - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + var pp; - var keys = this.data.hierarchy[h].keys, - sids = this.data.hierarchy[h].sids, - obj = this.hierarchy[h]; + if ( customAttribute.type === 'c' ) { - if ( keys.length && sids ) { + pp = [ 'r', 'g', 'b' ]; - for ( var s = 0; s < sids.length; s ++ ) { + } else { - var sid = sids[ s ], - next = this.getNextKeyWith( sid, h, 0 ); + pp = [ 'x', 'y', 'z' ]; - if ( next ) { + } - next.apply( sid ); + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - } + face = obj_faces[ chunk_faces3[ f ] ]; - obj.matrixAutoUpdate = false; - this.data.hierarchy[h].node.updateMatrix(); - obj.matrixWorldNeedsUpdate = true; + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; - } + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - } + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; -}; + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; -THREE.KeyFrameAnimation.prototype = { + offset_custom += 9; - constructor: THREE.KeyFrameAnimation, + } - play: function ( startTime ) { + } else if ( customAttribute.boundTo === 'faces' ) { - this.currentTime = startTime !== undefined ? startTime : 0; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - if ( this.isPlaying === false ) { + value = customAttribute.value[ chunk_faces3[ f ] ]; - this.isPlaying = true; + v1 = value; + v2 = value; + v3 = value; - // reset key cache + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - var h, hl = this.hierarchy.length, - object, - node; + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - for ( h = 0; h < hl; h ++ ) { + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - object = this.hierarchy[ h ]; - node = this.data.hierarchy[ h ]; + offset_custom += 9; - if ( node.animationCache === undefined ) { + } - node.animationCache = {}; - node.animationCache.prevKey = null; - node.animationCache.nextKey = null; - node.animationCache.originalMatrix = object.matrix; + } else if ( customAttribute.boundTo === 'faceVertices' ) { - } + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - var keys = this.data.hierarchy[h].keys; + value = customAttribute.value[ chunk_faces3[ f ] ]; - if (keys.length) { + v1 = value[ 0 ]; + v2 = value[ 1 ]; + v3 = value[ 2 ]; - node.animationCache.prevKey = keys[ 0 ]; - node.animationCache.nextKey = keys[ 1 ]; + customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; - this.startTime = Math.min( keys[0].time, this.startTime ); - this.endTime = Math.max( keys[keys.length - 1].time, this.endTime ); + customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; - } + customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; + customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; + customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; - } + offset_custom += 9; - this.update( 0 ); + } - } + } - this.isPaused = false; + } else if ( customAttribute.size === 4 ) { - THREE.AnimationHandler.play( this ); + if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) { - }, + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - stop: function () { + face = obj_faces[ chunk_faces3[ f ] ]; - this.isPlaying = false; - this.isPaused = false; + v1 = customAttribute.value[ face.a ]; + v2 = customAttribute.value[ face.b ]; + v3 = customAttribute.value[ face.c ]; + + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - THREE.AnimationHandler.stop( this ); + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - // reset JIT matrix and remove cache + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - for ( var h = 0; h < this.data.hierarchy.length; h ++ ) { + offset_custom += 12; - var obj = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; + } - if ( node.animationCache !== undefined ) { + } else if ( customAttribute.boundTo === 'faces' ) { - var original = node.animationCache.originalMatrix; + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - original.copy( obj.matrix ); - obj.matrix = original; + value = customAttribute.value[ chunk_faces3[ f ] ]; - delete node.animationCache; + v1 = value; + v2 = value; + v3 = value; - } + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - } + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - }, + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - update: function ( delta ) { + offset_custom += 12; - if ( this.isPlaying === false ) return; + } - this.currentTime += delta * this.timeScale; + } else if ( customAttribute.boundTo === 'faceVertices' ) { - // + for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { - var duration = this.data.length; + value = customAttribute.value[ chunk_faces3[ f ] ]; - if ( this.loop === true && this.currentTime > duration ) { + v1 = value[ 0 ]; + v2 = value[ 1 ]; + v3 = value[ 2 ]; - this.currentTime %= duration; + customAttribute.array[ offset_custom ] = v1.x; + customAttribute.array[ offset_custom + 1 ] = v1.y; + customAttribute.array[ offset_custom + 2 ] = v1.z; + customAttribute.array[ offset_custom + 3 ] = v1.w; - } + customAttribute.array[ offset_custom + 4 ] = v2.x; + customAttribute.array[ offset_custom + 5 ] = v2.y; + customAttribute.array[ offset_custom + 6 ] = v2.z; + customAttribute.array[ offset_custom + 7 ] = v2.w; - this.currentTime = Math.min( this.currentTime, duration ); + customAttribute.array[ offset_custom + 8 ] = v3.x; + customAttribute.array[ offset_custom + 9 ] = v3.y; + customAttribute.array[ offset_custom + 10 ] = v3.z; + customAttribute.array[ offset_custom + 11 ] = v3.w; - for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) { + offset_custom += 12; - var object = this.hierarchy[ h ]; - var node = this.data.hierarchy[ h ]; + } - var keys = node.keys, - animationCache = node.animationCache; + } + } - if ( keys.length ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); - var prevKey = animationCache.prevKey; - var nextKey = animationCache.nextKey; + } - if ( nextKey.time <= this.currentTime ) { + } - while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) { + if ( dispose ) { - prevKey = nextKey; - nextKey = keys[ prevKey.index + 1 ]; + delete geometryGroup.__inittedArrays; + delete geometryGroup.__colorArray; + delete geometryGroup.__normalArray; + delete geometryGroup.__tangentArray; + delete geometryGroup.__uvArray; + delete geometryGroup.__uv2Array; + delete geometryGroup.__faceArray; + delete geometryGroup.__vertexArray; + delete geometryGroup.__lineArray; + delete geometryGroup.__skinIndexArray; + delete geometryGroup.__skinWeightArray; - } + } - animationCache.prevKey = prevKey; - animationCache.nextKey = nextKey; + }; - } + // Buffer rendering - if ( nextKey.time >= this.currentTime ) { + this.renderBufferImmediate = function ( object, program, material ) { - prevKey.interpolate( nextKey, this.currentTime ); + state.initAttributes(); - } else { + if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); + if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); + if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); + if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); - prevKey.interpolate( nextKey, nextKey.time ); + if ( object.hasPositions ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - this.data.hierarchy[ h ].node.updateMatrix(); - object.matrixWorldNeedsUpdate = true; + state.enableAttribute( program.attributes.position ); - } + _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } - }, - - getNextKeyWith: function ( sid, h, key ) { + if ( object.hasNormals ) { - var keys = this.data.hierarchy[ h ].keys; - key = key % keys.length; + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); - for ( ; key < keys.length; key ++ ) { + if ( material instanceof THREE.MeshPhongMaterial === false && + material.shading === THREE.FlatShading ) { - if ( keys[ key ].hasTarget( sid ) ) { + var nx, ny, nz, + nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, + normalArray, + i, il = object.count * 3; - return keys[ key ]; + for ( i = 0; i < il; i += 9 ) { - } + normalArray = object.normalArray; - } + nax = normalArray[ i ]; + nay = normalArray[ i + 1 ]; + naz = normalArray[ i + 2 ]; - return keys[ 0 ]; + nbx = normalArray[ i + 3 ]; + nby = normalArray[ i + 4 ]; + nbz = normalArray[ i + 5 ]; - }, + ncx = normalArray[ i + 6 ]; + ncy = normalArray[ i + 7 ]; + ncz = normalArray[ i + 8 ]; - getPrevKeyWith: function ( sid, h, key ) { + nx = ( nax + nbx + ncx ) / 3; + ny = ( nay + nby + ncy ) / 3; + nz = ( naz + nbz + ncz ) / 3; - var keys = this.data.hierarchy[ h ].keys; - key = key >= 0 ? key : key + keys.length; + normalArray[ i ] = nx; + normalArray[ i + 1 ] = ny; + normalArray[ i + 2 ] = nz; - for ( ; key >= 0; key -- ) { + normalArray[ i + 3 ] = nx; + normalArray[ i + 4 ] = ny; + normalArray[ i + 5 ] = nz; - if ( keys[ key ].hasTarget( sid ) ) { + normalArray[ i + 6 ] = nx; + normalArray[ i + 7 ] = ny; + normalArray[ i + 8 ] = nz; - return keys[ key ]; + } } - } - - return keys[ keys.length - 1 ]; + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( program.attributes.normal ); -}; + _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); -// File:src/extras/animation/MorphAnimation.js + } -/** - * @author mrdoob / http://mrdoob.com - * @author willy-vvu / http://willy-vvu.github.io - */ + if ( object.hasUvs && material.map ) { -THREE.MorphAnimation = function ( mesh ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - this.mesh = mesh; - this.frames = mesh.morphTargetInfluences.length; - this.currentTime = 0; - this.duration = 1000; - this.loop = true; - this.lastFrame = 0; - this.currentFrame = 0; + state.enableAttribute( program.attributes.uv ); - this.isPlaying = false; + _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); -}; + } -THREE.MorphAnimation.prototype = { + if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { - constructor: THREE.MorphAnimation, + _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - play: function () { + state.enableAttribute( program.attributes.color ); - this.isPlaying = true; + _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - }, + } - pause: function () { + state.disableUnusedAttributes(); - this.isPlaying = false; + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - }, + object.count = 0; - update: function ( delta ) { + }; - if ( this.isPlaying === false ) return; + function setupVertexAttributes( material, program, geometry, startIndex ) { - this.currentTime += delta; + var geometryAttributes = geometry.attributes; - if ( this.loop === true && this.currentTime > this.duration ) { + var programAttributes = program.attributes; + var programAttributesKeys = program.attributesKeys; - this.currentTime %= this.duration; + for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) { - } + var key = programAttributesKeys[ i ]; + var programAttribute = programAttributes[ key ]; - this.currentTime = Math.min( this.currentTime, this.duration ); + if ( programAttribute >= 0 ) { - var interpolation = this.duration / this.frames; - var frame = Math.floor( this.currentTime / interpolation ); + var geometryAttribute = geometryAttributes[ key ]; - var influences = this.mesh.morphTargetInfluences; + if ( geometryAttribute !== undefined ) { - if ( frame != this.currentFrame ) { + var size = geometryAttribute.itemSize; - influences[ this.lastFrame ] = 0; - influences[ this.currentFrame ] = 1; - influences[ frame ] = 0; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer ); - this.lastFrame = this.currentFrame; - this.currentFrame = frame; + state.enableAttribute( programAttribute ); - } + _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32 - influences[ frame ] = ( this.currentTime % interpolation ) / interpolation; - influences[ this.lastFrame ] = 1 - influences[ frame ]; + } else if ( material.defaultAttributeValues !== undefined ) { - } + if ( material.defaultAttributeValues[ key ].length === 2 ) { -}; + _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] ); -// File:src/extras/geometries/BoxGeometry.js + } else if ( material.defaultAttributeValues[ key ].length === 3 ) { -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ + _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] ); -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } - THREE.Geometry.call( this ); + } - this.type = 'BoxGeometry'; + } - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + } - this.widthSegments = widthSegments || 1; - this.heightSegments = heightSegments || 1; - this.depthSegments = depthSegments || 1; + state.disableUnusedAttributes(); - var scope = this; + } - var width_half = width / 2; - var height_half = height / 2; - var depth_half = depth / 2; + this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { - buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px - buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx - buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py - buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny - buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz - buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz + if ( material.visible === false ) return; - function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) { + updateObject( object ); - var w, ix, iy, - gridX = scope.widthSegments, - gridY = scope.heightSegments, - width_half = width / 2, - height_half = height / 2, - offset = scope.vertices.length; + var program = setProgram( camera, lights, fog, material, object ); - if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) { + var updateBuffers = false, + wireframeBit = material.wireframe ? 1 : 0, + geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit; - w = 'z'; + if ( geometryProgram !== _currentGeometryProgram ) { - } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) { + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - w = 'y'; - gridY = scope.depthSegments; + } - } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) { + if ( updateBuffers ) { - w = 'x'; - gridX = scope.depthSegments; + state.initAttributes(); } - var gridX1 = gridX + 1, - gridY1 = gridY + 1, - segment_width = width / gridX, - segment_height = height / gridY, - normal = new THREE.Vector3(); - - normal[ w ] = depth > 0 ? 1 : - 1; + // render mesh - for ( iy = 0; iy < gridY1; iy ++ ) { + if ( object instanceof THREE.Mesh ) { - for ( ix = 0; ix < gridX1; ix ++ ) { + var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES; - var vector = new THREE.Vector3(); - vector[ u ] = ( ix * segment_width - width_half ) * udir; - vector[ v ] = ( iy * segment_height - height_half ) * vdir; - vector[ w ] = depth; + var index = geometry.attributes.index; - scope.vertices.push( vector ); + if ( index ) { - } + // indexed triangles - } + var type, size; - for ( iy = 0; iy < gridY; iy ++ ) { + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { - for ( ix = 0; ix < gridX; ix ++ ) { + type = _gl.UNSIGNED_INT; + size = 4; - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + } else { - var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY ); - var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ); - var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY ); - var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY ); + type = _gl.UNSIGNED_SHORT; + size = 2; - var face = new THREE.Face3( a + offset, b + offset, d + offset ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - face.materialIndex = materialIndex; + } - scope.faces.push( face ); - scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + var offsets = geometry.offsets; - face = new THREE.Face3( b + offset, c + offset, d + offset ); - face.normal.copy( normal ); - face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() ); - face.materialIndex = materialIndex; + if ( offsets.length === 0 ) { - scope.faces.push( face ); - scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + if ( updateBuffers ) { - } + setupVertexAttributes( material, program, geometry, 0 ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - } + } - } + _gl.drawElements( mode, index.array.length, type, 0 ); - this.mergeVertices(); + _this.info.render.calls ++; + _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared + _this.info.render.faces += index.array.length / 3; -}; + } else { -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; + // if there is more than 1 chunk + // must set attribute pointers to use new offsets for each chunk + // even if geometry and materials didn't change -// File:src/extras/geometries/CircleGeometry.js + updateBuffers = true; -/** - * @author hughes - */ + for ( var i = 0, il = offsets.length; i < il; i ++ ) { -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { + var startIndex = offsets[ i ].index; - THREE.Geometry.call( this ); + if ( updateBuffers ) { - this.type = 'CircleGeometry'; + setupVertexAttributes( material, program, geometry, startIndex ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - radius = radius || 50; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + // render indexed triangles - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); - var i, uvs = [], - center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 ); + _this.info.render.calls ++; + _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared + _this.info.render.faces += offsets[ i ].count / 3; - this.vertices.push(center); - uvs.push( centerUV ); + } - for ( i = 0; i <= segments; i ++ ) { + } - var vertex = new THREE.Vector3(); - var segment = thetaStart + i / segments * thetaLength; + } else { - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + // non-indexed triangles - this.vertices.push( vertex ); - uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) ); + if ( updateBuffers ) { - } + setupVertexAttributes( material, program, geometry, 0 ); - var n = new THREE.Vector3( 0, 0, 1 ); + } - for ( i = 1; i <= segments; i ++ ) { + var position = geometry.attributes[ 'position' ]; - this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] ); + // render non-indexed triangles - } + _gl.drawArrays( mode, 0, position.array.length / position.itemSize ); - this.computeFaceNormals(); + _this.info.render.calls ++; + _this.info.render.vertices += position.array.length / position.itemSize; + _this.info.render.faces += position.array.length / ( 3 * position.itemSize ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + } -}; + } else if ( object instanceof THREE.PointCloud ) { -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; + // render particles -// File:src/extras/geometries/CubeGeometry.js + var mode = _gl.POINTS; -/** - * @author mrdoob / http://mrdoob.com/ - */ + var index = geometry.attributes.index; + if ( index ) { -THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + // indexed points - THREE.warn( 'THREE.CubeGeometry has been renamed to THREE.BoxGeometry.' ); - return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); + var type, size; - }; + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { -// File:src/extras/geometries/CylinderGeometry.js + type = _gl.UNSIGNED_INT; + size = 4; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } else { -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + type = _gl.UNSIGNED_SHORT; + size = 2; - THREE.Geometry.call( this ); + } - this.type = 'CylinderGeometry'; + var offsets = geometry.offsets; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( offsets.length === 0 ) { - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + if ( updateBuffers ) { - radialSegments = radialSegments || 8; - heightSegments = heightSegments || 1; + setupVertexAttributes( material, program, geometry, 0 ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI; + } - var heightHalf = height / 2; + _gl.drawElements( mode, index.array.length, type, 0); - var x, y, vertices = [], uvs = []; + _this.info.render.calls ++; + _this.info.render.points += index.array.length; - for ( y = 0; y <= heightSegments; y ++ ) { + } else { - var verticesRow = []; - var uvsRow = []; + // if there is more than 1 chunk + // must set attribute pointers to use new offsets for each chunk + // even if geometry and materials didn't change - var v = y / heightSegments; - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + if ( offsets.length > 1 ) updateBuffers = true; - for ( x = 0; x <= radialSegments; x ++ ) { + for ( var i = 0, il = offsets.length; i < il; i ++ ) { - var u = x / radialSegments; + var startIndex = offsets[ i ].index; - var vertex = new THREE.Vector3(); - vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); - vertex.y = - v * height + heightHalf; - vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); + if ( updateBuffers ) { - this.vertices.push( vertex ); + setupVertexAttributes( material, program, geometry, startIndex ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - verticesRow.push( this.vertices.length - 1 ); - uvsRow.push( new THREE.Vector2( u, 1 - v ) ); + } - } + // render indexed points - vertices.push( verticesRow ); - uvs.push( uvsRow ); + _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); - } + _this.info.render.calls ++; + _this.info.render.points += offsets[ i ].count; - var tanTheta = ( radiusBottom - radiusTop ) / height; - var na, nb; + } - for ( x = 0; x < radialSegments; x ++ ) { + } - if ( radiusTop !== 0 ) { + } else { - na = this.vertices[ vertices[ 0 ][ x ] ].clone(); - nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone(); + // non-indexed points - } else { + if ( updateBuffers ) { - na = this.vertices[ vertices[ 1 ][ x ] ].clone(); - nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone(); + setupVertexAttributes( material, program, geometry, 0 ); - } + } - na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize(); - nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize(); + var position = geometry.attributes.position; + var offsets = geometry.offsets; - for ( y = 0; y < heightSegments; y ++ ) { + if ( offsets.length === 0 ) { - var v1 = vertices[ y ][ x ]; - var v2 = vertices[ y + 1 ][ x ]; - var v3 = vertices[ y + 1 ][ x + 1 ]; - var v4 = vertices[ y ][ x + 1 ]; + _gl.drawArrays( mode, 0, position.array.length / 3 ); - var n1 = na.clone(); - var n2 = na.clone(); - var n3 = nb.clone(); - var n4 = nb.clone(); + _this.info.render.calls ++; + _this.info.render.points += position.array.length / 3; - var uv1 = uvs[ y ][ x ].clone(); - var uv2 = uvs[ y + 1 ][ x ].clone(); - var uv3 = uvs[ y + 1 ][ x + 1 ].clone(); - var uv4 = uvs[ y ][ x + 1 ].clone(); + } else { - this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); + for ( var i = 0, il = offsets.length; i < il; i ++ ) { - this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); + _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count ); - } + _this.info.render.calls ++; + _this.info.render.points += offsets[ i ].count; - } + } - // top cap + } - if ( openEnded === false && radiusTop > 0 ) { + } - this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) ); + } else if ( object instanceof THREE.Line ) { - for ( x = 0; x < radialSegments; x ++ ) { + var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; - var v1 = vertices[ 0 ][ x ]; - var v2 = vertices[ 0 ][ x + 1 ]; - var v3 = this.vertices.length - 1; + state.setLineWidth( material.linewidth * pixelRatio ); - var n1 = new THREE.Vector3( 0, 1, 0 ); - var n2 = new THREE.Vector3( 0, 1, 0 ); - var n3 = new THREE.Vector3( 0, 1, 0 ); + var index = geometry.attributes.index; - var uv1 = uvs[ 0 ][ x ].clone(); - var uv2 = uvs[ 0 ][ x + 1 ].clone(); - var uv3 = new THREE.Vector2( uv2.x, 0 ); + if ( index ) { - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); + // indexed lines - } + var type, size; - } + if ( index.array instanceof Uint32Array ) { - // bottom cap + type = _gl.UNSIGNED_INT; + size = 4; - if ( openEnded === false && radiusBottom > 0 ) { + } else { - this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) ); + type = _gl.UNSIGNED_SHORT; + size = 2; - for ( x = 0; x < radialSegments; x ++ ) { + } - var v1 = vertices[ heightSegments ][ x + 1 ]; - var v2 = vertices[ heightSegments ][ x ]; - var v3 = this.vertices.length - 1; + var offsets = geometry.offsets; - var n1 = new THREE.Vector3( 0, - 1, 0 ); - var n2 = new THREE.Vector3( 0, - 1, 0 ); - var n3 = new THREE.Vector3( 0, - 1, 0 ); + if ( offsets.length === 0 ) { - var uv1 = uvs[ heightSegments ][ x + 1 ].clone(); - var uv2 = uvs[ heightSegments ][ x ].clone(); - var uv3 = new THREE.Vector2( uv2.x, 1 ); + if ( updateBuffers ) { - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); + setupVertexAttributes( material, program, geometry, 0 ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - } + } - } + _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array - this.computeFaceNormals(); + _this.info.render.calls ++; + _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared -}; + } else { -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; + // if there is more than 1 chunk + // must set attribute pointers to use new offsets for each chunk + // even if geometry and materials didn't change -// File:src/extras/geometries/ExtrudeGeometry.js + if ( offsets.length > 1 ) updateBuffers = true; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: <int>, // number of points on the curves - * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too - * amount: <int>, // Depth to extrude the shape - * - * bevelEnabled: <bool>, // turn on bevel - * bevelThickness: <float>, // how deep into the original shape bevel goes - * bevelSize: <float>, // how far from shape outline is bevel - * bevelSegments: <int>, // number of bevel layers - * - * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) - * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals - * - * material: <int> // material index for front and back faces - * extrudeMaterial: <int> // material index for extrusion and beveled faces - * uvGenerator: <Object> // object that provides UV generator functions - * - * } - **/ + for ( var i = 0, il = offsets.length; i < il; i ++ ) { -THREE.ExtrudeGeometry = function ( shapes, options ) { + var startIndex = offsets[ i ].index; - if ( typeof( shapes ) === "undefined" ) { - shapes = []; - return; - } + if ( updateBuffers ) { - THREE.Geometry.call( this ); + setupVertexAttributes( material, program, geometry, startIndex ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); - this.type = 'ExtrudeGeometry'; + } - shapes = shapes instanceof Array ? shapes : [ shapes ]; + // render indexed lines - this.addShapeList( shapes, options ); + _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array - this.computeFaceNormals(); + _this.info.render.calls ++; + _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides + } - //this.computeVertexNormals(); + } - //console.log( "took", ( Date.now() - startTime ) ); + } else { -}; + // non-indexed lines -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; + if ( updateBuffers ) { -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - var sl = shapes.length; + setupVertexAttributes( material, program, geometry, 0 ); - for ( var s = 0; s < sl; s ++ ) { - var shape = shapes[ s ]; - this.addShape( shape, options ); - } -}; + } -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { + var position = geometry.attributes.position; + var offsets = geometry.offsets; - var amount = options.amount !== undefined ? options.amount : 100; + if ( offsets.length === 0 ) { - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + _gl.drawArrays( mode, 0, position.array.length / 3 ); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + _this.info.render.calls ++; + _this.info.render.vertices += position.array.length / 3; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + } else { - var steps = options.steps !== undefined ? options.steps : 1; + for ( var i = 0, il = offsets.length; i < il; i ++ ) { - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count ); - var material = options.material; - var extrudeMaterial = options.extrudeMaterial; + _this.info.render.calls ++; + _this.info.render.vertices += offsets[ i ].count; - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; + } - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + } - extrudePts = extrudePath.getSpacedPoints( steps ); + } - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + } - // SETUP TNB variables + }; - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? + this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false); + if ( material.visible === false ) return; - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + updateObject( object ); - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); + var program = setProgram( camera, lights, fog, material, object ); - } + var attributes = program.attributes; - // Safeguards if bevels are not enabled + var updateBuffers = false, + wireframeBit = material.wireframe ? 1 : 0, + geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit; - if ( ! bevelEnabled ) { + if ( geometryProgram !== _currentGeometryProgram ) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - } + } - // Variables initalization + if ( updateBuffers ) { - var ahole, h, hl; // looping of holes - var scope = this; + state.initAttributes(); - var shapesOffset = this.vertices.length; + } - var shapePoints = shape.extractPoints( curveSegments ); + // vertices - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + if ( ! material.morphTargets && attributes.position >= 0 ) { - var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ; + if ( updateBuffers ) { - if ( reverse ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - vertices = vertices.reverse(); + state.enableAttribute( attributes.position ); - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; + } else { - if ( THREE.Shape.Utils.isClockWise( ahole ) ) { + if ( object.morphTargetBase ) { - holes[ h ] = ahole.reverse(); + setupMorphTargets( material, geometryGroup, object ); } } - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - } + if ( updateBuffers ) { + // custom attributes - var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes ); + // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers - /* Vertices */ + if ( geometryGroup.__webglCustomAttributesList ) { - var contour = vertices; // vertices has all points but contour has only points of circumference + for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + var attribute = geometryGroup.__webglCustomAttributesList[ i ]; - ahole = holes[ h ]; + if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { - vertices = vertices.concat( ahole ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); - } + state.enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); + _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); - function scalePt2 ( pt, vec, size ) { + } - if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" ); + } - return vec.clone().multiplyScalar( size ).add( pt ); + } - } - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + // colors + if ( attributes.color >= 0 ) { - // Find directions for point movement + if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); - function getBevelVec( inPt, inPrev, inNext ) { + state.enableAttribute( attributes.color ); - var EPSILON = 0.0000000001; - - // computes for inPt the corresponding point inPt' on a new contour - // shiftet by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. - - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + } else if ( material.defaultAttributeValues !== undefined ) { - var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; - - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - - // check for colinear edges - var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - - if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear - - // length of vectors for normalizing - - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - - // shift adjacent points by unit vectors to the left - - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - - // scaling factor for v_prev to intersection point - - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - - // vector from inPt to intersection point - - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ) - if ( v_trans_lensq <= 2 ) { - return new THREE.Vector2( v_trans_x, v_trans_y ); - } else { - shrink_by = Math.sqrt( v_trans_lensq / 2 ); - } - - } else { // handle special case of colinear edges - var direction_eq = false; // assumes: opposite - if ( v_prev_x > EPSILON ) { - if ( v_next_x > EPSILON ) { direction_eq = true; } - } else { - if ( v_prev_x < - EPSILON ) { - if ( v_next_x < - EPSILON ) { direction_eq = true; } - } else { - if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; } + _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); + } - } - if ( direction_eq ) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = - v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); - } else { - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); } - } - - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - - } - - - var contourMovements = []; + // normals - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + if ( attributes.normal >= 0 ) { - if ( j === il ) j = 0; - if ( k === il ) k = 0; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + state.enableAttribute( attributes.normal ); - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - } + } - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); + // tangents - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + if ( attributes.tangent >= 0 ) { - ahole = holes[ h ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); - oneHoleMovements = []; + state.enableAttribute( attributes.tangent ); - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); - if ( j === il ) j = 0; - if ( k === il ) k = 0; + } - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + // uvs - } + if ( attributes.uv >= 0 ) { - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + if ( object.geometry.faceVertexUvs[ 0 ] ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); + state.enableAttribute( attributes.uv ); - // Loop bevelSegments, 1 for the front, 1 for the back + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - for ( b = 0; b < bevelSegments; b ++ ) { - //for ( b = bevelSegments; b > 0; b -- ) { + } else if ( material.defaultAttributeValues !== undefined ) { - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); - //z = bevelThickness * t; - bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved - //bs = bevelSize * t ; // linear + _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); - // contract shape + } - for ( i = 0, il = contour.length; i < il; i ++ ) { + } - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + if ( attributes.uv2 >= 0 ) { - v( vert.x, vert.y, - z ); + if ( object.geometry.faceVertexUvs[ 1 ] ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); - // expand holes + state.enableAttribute( attributes.uv2 ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + } else if ( material.defaultAttributeValues !== undefined ) { - for ( i = 0, il = ahole.length; i < il; i ++ ) { - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); - v( vert.x, vert.y, - z ); + } } - } + if ( material.skinning && + attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); - bs = bevelSize; + state.enableAttribute( attributes.skinIndex ); - // Back facing vertices + _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); - for ( i = 0; i < vlen; i ++ ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + state.enableAttribute( attributes.skinWeight ); - if ( ! extrudeByPath ) { + _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); - v( vert.x, vert.y, 0 ); + } - } else { + // line distances - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + if ( attributes.lineDistance >= 0 ) { - normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x); - binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); - position2.copy( extrudePts[0] ).add(normal).add(binormal); + state.enableAttribute( attributes.lineDistance ); - v( position2.x, position2.y, position2.z ); + _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); + + } } - } + state.disableUnusedAttributes(); - // Add stepped vertices... - // Including front facing vertices + // render mesh - var s; + if ( object instanceof THREE.Mesh ) { - for ( s = 1; s <= steps; s ++ ) { + var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; - for ( i = 0; i < vlen; i ++ ) { + // wireframe - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + if ( material.wireframe ) { - if ( ! extrudeByPath ) { + state.setLineWidth( material.wireframeLinewidth * pixelRatio ); - v( vert.x, vert.y, amount / steps * s ); + if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); + _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); - } else { + // triangles - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + } else { - normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y ); + if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); + _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); - position2.copy( extrudePts[s] ).add( normal ).add( binormal ); + } - v( position2.x, position2.y, position2.z ); + _this.info.render.calls ++; + _this.info.render.vertices += geometryGroup.__webglFaceCount; + _this.info.render.faces += geometryGroup.__webglFaceCount / 3; - } + // render lines - } + } else if ( object instanceof THREE.Line ) { - } + var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; + state.setLineWidth( material.linewidth * pixelRatio ); - // Add bevel segments planes + _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount ); - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + _this.info.render.calls ++; - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); - //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) ); - bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ; + // render particles - // contract shape + } else if ( object instanceof THREE.PointCloud ) { - for ( i = 0, il = contour.length; i < il; i ++ ) { + _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + _this.info.render.calls ++; + _this.info.render.points += geometryGroup.__webglParticleCount; } - // expand holes + }; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + function setupMorphTargets ( material, geometryGroup, object ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + // set base - for ( i = 0, il = ahole.length; i < il; i ++ ) { + var attributes = material.program.attributes; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) { - if ( ! extrudeByPath ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); - v( vert.x, vert.y, amount + z ); + state.enableAttribute( attributes.position ); - } else { + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + } else if ( attributes.position >= 0 ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); - } + state.enableAttribute( attributes.position ); + + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } - } + if ( object.morphTargetForcedOrder.length ) { - /* Faces */ + // set forced order - // Top and bottom faces + var m = 0; + var order = object.morphTargetForcedOrder; + var influences = object.morphTargetInfluences; - buildLidFaces(); + var attribute; - // Sides faces + while ( m < material.numSupportedMorphTargets && m < order.length ) { - buildSideFaces(); + attribute = attributes[ 'morphTarget' + m ]; + if ( attribute >= 0 ) { - ///// Internal functions + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); - function buildLidFaces() { + state.enableAttribute( attribute ); - if ( bevelEnabled ) { + _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); - var layer = 0 ; // steps + 1 - var offset = vlen * layer; + } - // Bottom faces + attribute = attributes[ 'morphNormal' + m ]; - for ( i = 0; i < flen; i ++ ) { + if ( attribute >= 0 && material.morphNormals ) { - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); - } + state.enableAttribute( attribute ); - layer = steps + bevelSegments * 2; - offset = vlen * layer; + _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); - // Top faces + } - for ( i = 0; i < flen; i ++ ) { + object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + m ++; } } else { - // Bottom faces + // find the most influencing - for ( i = 0; i < flen; i ++ ) { + var activeInfluenceIndices = []; + var influences = object.morphTargetInfluences; + var morphTargets = object.geometry.morphTargets; - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + if ( influences.length > morphTargets.length ) { + + console.warn( 'THREE.Canvas3DRenderer: Influences array is bigger than morphTargets array.' ); + influences.length = morphTargets.length; } - // Top faces + for ( var i = 0, il = influences.length; i < il; i ++ ) { - for ( i = 0; i < flen; i ++ ) { + var influence = influences[ i ]; - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + activeInfluenceIndices.push( [ influence, i ] ); } - } - } + if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { - // Create faces for the z-sides of the shape + activeInfluenceIndices.sort( numericalSort ); + activeInfluenceIndices.length = material.numSupportedMorphTargets; - function buildSideFaces() { + } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + activeInfluenceIndices.sort( numericalSort ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } else if ( activeInfluenceIndices.length === 0 ) { - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + activeInfluenceIndices.push( [ 0, 0 ] ); - //, true - layeroffset += ahole.length; + } - } + var attribute; - } + for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) { - function sidewalls( contour, layeroffset ) { + if ( activeInfluenceIndices[ m ] ) { - var j, k; - i = contour.length; + var influenceIndex = activeInfluenceIndices[ m ][ 1 ]; - while ( -- i >= 0 ) { + attribute = attributes[ 'morphTarget' + m ]; - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + if ( attribute >= 0 ) { - //console.log('b', i,j, i-1, k,vertices.length); + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); - var s = 0, sl = steps + bevelSegments * 2; + state.enableAttribute( attribute ); - for ( s = 0; s < sl; s ++ ) { + _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + } - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + attribute = attributes[ 'morphNormal' + m ]; - f4( a, b, c, d, contour, s, sl, j, k ); + if ( attribute >= 0 && material.morphNormals ) { - } - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); - } + state.enableAttribute( attribute ); + _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 ); - function v( x, y, z ) { + } - scope.vertices.push( new THREE.Vector3( x, y, z ) ); + object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; - } + } else { - function f3( a, b, c ) { + /* + _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; + if ( material.morphNormals ) { - // normal, color, material - scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); + _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); - var uvs = uvgen.generateTopUV( scope, a, b, c ); + } + */ - scope.faceVertexUvs[ 0 ].push( uvs ); + object.__webglMorphTargetInfluences[ m ] = 0; - } + } - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + } - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - d += shapesOffset; + } - scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) ); + // load updated influences uniform - var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); + if ( material.program.uniforms.morphTargetInfluences !== null ) { - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); + _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); + + } } -}; + // Sorting -THREE.ExtrudeGeometry.WorldUVGenerator = { + function painterSortStable ( a, b ) { - generateTopUV: function ( geometry, indexA, indexB, indexC ) { + if ( a.object.renderOrder !== b.object.renderOrder ) { - var vertices = geometry.vertices; + return a.object.renderOrder - b.object.renderOrder; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; + } else if ( a.material.id !== b.material.id ) { - return [ - new THREE.Vector2( a.x, a.y ), - new THREE.Vector2( b.x, b.y ), - new THREE.Vector2( c.x, c.y ) - ]; + return a.material.id - b.material.id; - }, + } else if ( a.z !== b.z ) { - generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { + return a.z - b.z; - var vertices = geometry.vertices; + } else { - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; - var d = vertices[ indexD ]; + return a.id - b.id; - if ( Math.abs( a.y - b.y ) < 0.01 ) { - return [ - new THREE.Vector2( a.x, 1 - a.z ), - new THREE.Vector2( b.x, 1 - b.z ), - new THREE.Vector2( c.x, 1 - c.z ), - new THREE.Vector2( d.x, 1 - d.z ) - ]; - } else { - return [ - new THREE.Vector2( a.y, 1 - a.z ), - new THREE.Vector2( b.y, 1 - b.z ), - new THREE.Vector2( c.y, 1 - c.z ), - new THREE.Vector2( d.y, 1 - d.z ) - ]; } - } -}; - -// File:src/extras/geometries/ShapeGeometry.js -/** - * @author jonobr1 / http://jonobr1.com - * - * Creates a one-sided polygonal geometry from a path shape. Similar to - * ExtrudeGeometry. - * - * parameters = { - * - * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT. - * - * material: <int> // material index for front and back faces - * uvGenerator: <Object> // object that provides UV generator functions - * - * } - **/ + } -THREE.ShapeGeometry = function ( shapes, options ) { + function reversePainterSortStable ( a, b ) { - THREE.Geometry.call( this ); + if ( a.object.renderOrder !== b.object.renderOrder ) { - this.type = 'ShapeGeometry'; + return a.object.renderOrder - b.object.renderOrder; - if ( shapes instanceof Array === false ) shapes = [ shapes ]; + } if ( a.z !== b.z ) { - this.addShapeList( shapes, options ); + return b.z - a.z; - this.computeFaceNormals(); + } else { -}; + return a.id - b.id; -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; + } -/** - * Add an array of shapes to THREE.ShapeGeometry. - */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { + } - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + function numericalSort ( a, b ) { - this.addShape( shapes[ i ], options ); + return b[ 0 ] - a[ 0 ]; } - return this; - -}; + // Rendering -/** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { + this.render = function ( scene, camera, renderTarget, forceClear ) { - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + if ( camera instanceof THREE.Camera === false ) { - var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + THREE.error( 'THREE.Canvas3DRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - // + } - var i, l, hole; + var fog = scene.fog; - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); + // reset caching for this frame - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; + _lightsNeedUpdate = true; - var reverse = ! THREE.Shape.Utils.isClockWise( vertices ); + // update scene graph - if ( reverse ) { + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - vertices = vertices.reverse(); + // update camera matrices and frustum - // Maybe we should also check if holes are in the opposite direction, just to be safe... + if ( camera.parent === undefined ) camera.updateMatrixWorld(); - for ( i = 0, l = holes.length; i < l; i ++ ) { + // update Skeleton objects - hole = holes[ i ]; + scene.traverse( function ( object ) { - if ( THREE.Shape.Utils.isClockWise( hole ) ) { + if ( object instanceof THREE.SkinnedMesh ) { - holes[ i ] = hole.reverse(); + object.skeleton.update(); } - } - - reverse = false; - - } - - var faces = THREE.Shape.Utils.triangulateShape( vertices, holes ); + } ); - // Vertices + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - var contour = vertices; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - for ( i = 0, l = holes.length; i < l; i ++ ) { + lights.length = 0; + opaqueObjects.length = 0; + transparentObjects.length = 0; - hole = holes[ i ]; - vertices = vertices.concat( hole ); + sprites.length = 0; + lensFlares.length = 0; - } + projectObject( scene ); - // + if ( _this.sortObjects === true ) { - var vert, vlen = vertices.length; - var face, flen = faces.length; + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - for ( i = 0; i < vlen; i ++ ) { + } - vert = vertices[ i ]; + // custom render plugins (pre pass) - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); + shadowMapPlugin.render( scene, camera ); - } + // - for ( i = 0; i < flen; i ++ ) { + _this.info.render.calls = 0; + _this.info.render.vertices = 0; + _this.info.render.faces = 0; + _this.info.render.points = 0; - face = faces[ i ]; + this.setRenderTarget( renderTarget ); - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; + if ( this.autoClear || forceClear ) { - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - } + } -}; + // set matrices for immediate objects -// File:src/extras/geometries/LatheGeometry.js + for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) { -/** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://exocortex.com - */ + var webglObject = _webglObjectsImmediate[ i ]; + var object = webglObject.object; -// points - to create a closed torus, one must use a set of points -// like so: [ a, b, c, d, a ], see first is the same as last. -// segments - the number of circumference segments to create -// phiStart - the starting radian -// phiLength - the radian (0 to 2*PI) range of the lathed section -// 2*pi is a closed lathe, less than 2PI is a portion. + if ( object.visible ) { -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { + setupMatrices( object, camera ); - THREE.Geometry.call( this ); + unrollImmediateBufferMaterial( webglObject ); - this.type = 'LatheGeometry'; + } - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + } - segments = segments || 12; - phiStart = phiStart || 0; - phiLength = phiLength || 2 * Math.PI; + if ( scene.overrideMaterial ) { - var inversePointLength = 1.0 / ( points.length - 1 ); - var inverseSegments = 1.0 / segments; + var overrideMaterial = scene.overrideMaterial; - for ( var i = 0, il = segments; i <= il; i ++ ) { + setMaterial( overrideMaterial ); - var phi = phiStart + i * inverseSegments * phiLength; + renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial ); + renderObjects( transparentObjects, camera, lights, fog, overrideMaterial ); + renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, overrideMaterial ); - var c = Math.cos( phi ), - s = Math.sin( phi ); + } else { - for ( var j = 0, jl = points.length; j < jl; j ++ ) { + // opaque pass (front-to-back order) - var pt = points[ j ]; + state.setBlending( THREE.NoBlending ); - var vertex = new THREE.Vector3(); + renderObjects( opaqueObjects, camera, lights, fog, null ); + renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, null ); - vertex.x = c * pt.x - s * pt.y; - vertex.y = s * pt.x + c * pt.y; - vertex.z = pt.z; + // transparent pass (back-to-front order) - this.vertices.push( vertex ); + renderObjects( transparentObjects, camera, lights, fog, null ); + renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, null ); } - } + // custom render plugins (post pass) - var np = points.length; + spritePlugin.render( scene, camera ); + lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight ); - for ( var i = 0, il = segments; i < il; i ++ ) { + // Generate mipmap if we're using any kind of mipmap filtering - for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) { + if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { - var base = j + np * i; - var a = base; - var b = base + np; - var c = base + 1 + np; - var d = base + 1; + updateRenderTargetMipmap( renderTarget ); - var u0 = i * inverseSegments; - var v0 = j * inversePointLength; - var u1 = u0 + inverseSegments; - var v1 = v0 + inversePointLength; + } - this.faces.push( new THREE.Face3( a, b, d ) ); + // Ensure depth buffer writing is enabled so it can be cleared on next render - this.faceVertexUvs[ 0 ].push( [ + state.setDepthTest( true ); + state.setDepthWrite( true ); + state.setColorWrite( true ); - new THREE.Vector2( u0, v0 ), - new THREE.Vector2( u1, v0 ), - new THREE.Vector2( u0, v1 ) + // _gl.finish(); - ] ); + }; - this.faces.push( new THREE.Face3( b, c, d ) ); + function projectObject( object ) { - this.faceVertexUvs[ 0 ].push( [ + if ( object.visible === false ) return; - new THREE.Vector2( u1, v0 ), - new THREE.Vector2( u1, v1 ), - new THREE.Vector2( u0, v1 ) + if ( object instanceof THREE.Scene || object instanceof THREE.Group ) { - ] ); + // skip + } else { - } + initObject( object ); - } + if ( object instanceof THREE.Light ) { - this.mergeVertices(); - this.computeFaceNormals(); - this.computeVertexNormals(); + lights.push( object ); -}; + } else if ( object instanceof THREE.Sprite ) { -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; + sprites.push( object ); -// File:src/extras/geometries/PlaneGeometry.js + } else if ( object instanceof THREE.LensFlare ) { -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + lensFlares.push( object ); -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { + } else { - console.info( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' ); + var webglObjects = _webglObjects[ object.id ]; - THREE.Geometry.call( this ); + if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { - this.type = 'PlaneGeometry'; + for ( var i = 0, l = webglObjects.length; i < l; i ++ ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + var webglObject = webglObjects[ i ]; - this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + unrollBufferMaterial( webglObject ); -}; + webglObject.render = true; -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; + if ( _this.sortObjects === true ) { -// File:src/extras/geometries/PlaneBufferGeometry.js + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + webglObject.z = _vector3.z; -THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { + } - THREE.BufferGeometry.call( this ); + } - this.type = 'PlaneBufferGeometry'; + } - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + } - var width_half = width / 2; - var height_half = height / 2; + } - var gridX = widthSegments || 1; - var gridY = heightSegments || 1; + for ( var i = 0, l = object.children.length; i < l; i ++ ) { - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + projectObject( object.children[ i ] ); - var segment_width = width / gridX; - var segment_height = height / gridY; + } - var vertices = new Float32Array( gridX1 * gridY1 * 3 ); - var normals = new Float32Array( gridX1 * gridY1 * 3 ); - var uvs = new Float32Array( gridX1 * gridY1 * 2 ); + } - var offset = 0; - var offset2 = 0; + function renderObjects( renderList, camera, lights, fog, overrideMaterial ) { - for ( var iy = 0; iy < gridY1; iy ++ ) { + var material; - var y = iy * segment_height - height_half; + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - for ( var ix = 0; ix < gridX1; ix ++ ) { + var webglObject = renderList[ i ]; - var x = ix * segment_width - width_half; + var object = webglObject.object; + var buffer = webglObject.buffer; - vertices[ offset ] = x; - vertices[ offset + 1 ] = - y; + setupMatrices( object, camera ); - normals[ offset + 2 ] = 1; + if ( overrideMaterial ) { - uvs[ offset2 ] = ix / gridX; - uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); + material = overrideMaterial; - offset += 3; - offset2 += 2; + } else { - } + material = webglObject.material; - } + if ( ! material ) continue; - offset = 0; + setMaterial( material ); - var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); + } - for ( var iy = 0; iy < gridY; iy ++ ) { + _this.setMaterialFaces( material ); - for ( var ix = 0; ix < gridX; ix ++ ) { + if ( buffer instanceof THREE.BufferGeometry ) { - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); - indices[ offset ] = a; - indices[ offset + 1 ] = b; - indices[ offset + 2 ] = d; + } else { - indices[ offset + 3 ] = b; - indices[ offset + 4 ] = c; - indices[ offset + 5 ] = d; + _this.renderBuffer( camera, lights, fog, material, buffer, object ); - offset += 6; + } } } - this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); - -}; - -THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; + function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) { -// File:src/extras/geometries/RingGeometry.js + var material; -/** - * @author Kaleb Murphy - */ + for ( var i = 0, l = renderList.length; i < l; i ++ ) { -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + var webglObject = renderList[ i ]; + var object = webglObject.object; - THREE.Geometry.call( this ); + if ( object.visible ) { - this.type = 'RingGeometry'; + if ( overrideMaterial ) { - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + material = overrideMaterial; - innerRadius = innerRadius || 0; - outerRadius = outerRadius || 50; + } else { - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + material = webglObject[ materialType ]; - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8; + if ( ! material ) continue; - var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + setMaterial( material ); - for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring + } - for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle + _this.renderImmediateObject( camera, lights, fog, material, object ); - var vertex = new THREE.Vector3(); - var segment = thetaStart + o / thetaSegments * thetaLength; - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + } - this.vertices.push( vertex ); - uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) ); } - radius += radiusStep; - } - var n = new THREE.Vector3( 0, 0, 1 ); - - for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring + this.renderImmediateObject = function ( camera, lights, fog, material, object ) { - var thetaSegment = i * (thetaSegments + 1); + var program = setProgram( camera, lights, fog, material, object ); - for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle + _currentGeometryProgram = ''; - var segment = o + thetaSegment; + _this.setMaterialFaces( material ); - var v1 = segment; - var v2 = segment + thetaSegments + 1; - var v3 = segment + thetaSegments + 2; + if ( object.immediateRenderCallback ) { - this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); + object.immediateRenderCallback( program, _gl, _frustum ); - v1 = segment; - v2 = segment + thetaSegments + 2; - v3 = segment + 1; + } else { - this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]); + object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } ); } - } - - this.computeFaceNormals(); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + }; -}; + function unrollImmediateBufferMaterial ( globject ) { -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; + var object = globject.object, + material = object.material; + if ( material.transparent ) { -// File:src/extras/geometries/SphereGeometry.js + globject.transparent = material; + globject.opaque = null; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } else { -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + globject.opaque = material; + globject.transparent = null; - THREE.Geometry.call( this ); + } - this.type = 'SphereGeometry'; + } - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + function unrollBufferMaterial ( globject ) { - radius = radius || 50; + var object = globject.object; + var buffer = globject.buffer; - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + var geometry = object.geometry; + var material = object.material; - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + if ( material instanceof THREE.MeshFaceMaterial ) { - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; - var x, y, vertices = [], uvs = []; + material = material.materials[ materialIndex ]; - for ( y = 0; y <= heightSegments; y ++ ) { + globject.material = material; - var verticesRow = []; - var uvsRow = []; + if ( material.transparent ) { - for ( x = 0; x <= widthSegments; x ++ ) { + transparentObjects.push( globject ); - var u = x / widthSegments; - var v = y / heightSegments; + } else { - var vertex = new THREE.Vector3(); - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + opaqueObjects.push( globject ); - this.vertices.push( vertex ); + } - verticesRow.push( this.vertices.length - 1 ); - uvsRow.push( new THREE.Vector2( u, 1 - v ) ); + } else if ( material ) { - } + globject.material = material; - vertices.push( verticesRow ); - uvs.push( uvsRow ); + if ( material.transparent ) { - } + transparentObjects.push( globject ); - for ( y = 0; y < heightSegments; y ++ ) { + } else { - for ( x = 0; x < widthSegments; x ++ ) { + opaqueObjects.push( globject ); - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; + } - var n1 = this.vertices[ v1 ].clone().normalize(); - var n2 = this.vertices[ v2 ].clone().normalize(); - var n3 = this.vertices[ v3 ].clone().normalize(); - var n4 = this.vertices[ v4 ].clone().normalize(); + } - var uv1 = uvs[ y ][ x + 1 ].clone(); - var uv2 = uvs[ y ][ x ].clone(); - var uv3 = uvs[ y + 1 ][ x ].clone(); - var uv4 = uvs[ y + 1 ][ x + 1 ].clone(); + } - if ( Math.abs( this.vertices[ v1 ].y ) === radius ) { + function initObject( object ) { - uv1.x = ( uv1.x + uv2.x ) / 2; - this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] ); + if ( object.__webglInit === undefined ) { - } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) { + object.__webglInit = true; + object._modelViewMatrix = new THREE.Matrix4(); + object._normalMatrix = new THREE.Matrix3(); - uv3.x = ( uv3.x + uv4.x ) / 2; - this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] ); + object.addEventListener( 'removed', onObjectRemoved ); - } else { + } - this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] ); + var geometry = object.geometry; - this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) ); - this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] ); + if ( geometry === undefined ) { - } + // ImmediateRenderObject - } + } else if ( geometry.__webglInit === undefined ) { - } + geometry.__webglInit = true; + geometry.addEventListener( 'dispose', onGeometryDispose ); - this.computeFaceNormals(); + if ( geometry instanceof THREE.BufferGeometry ) { - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + _this.info.memory.geometries ++; -}; + } else if ( object instanceof THREE.Mesh ) { -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; + initGeometryGroups( object, geometry ); -// File:src/extras/geometries/TextGeometry.js + } else if ( object instanceof THREE.Line ) { -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * For creating 3D text geometry in three.js - * - * Text = 3D Text - * - * parameters = { - * size: <float>, // size of the text - * height: <float>, // thickness to extrude text - * curveSegments: <int>, // number of points on the curves - * - * font: <string>, // font name - * weight: <string>, // font weight (normal, bold) - * style: <string>, // font style (normal, italics) - * - * bevelEnabled: <bool>, // turn on bevel - * bevelThickness: <float>, // how deep into text bevel goes - * bevelSize: <float>, // how far from text outline is bevel - * } - * - */ + if ( geometry.__webglVertexBuffer === undefined ) { -/* Usage Examples + createLineBuffers( geometry ); + initLineBuffers( geometry, object ); - // TextGeometry wrapper + geometry.verticesNeedUpdate = true; + geometry.colorsNeedUpdate = true; + geometry.lineDistancesNeedUpdate = true; - var text3d = new TextGeometry( text, options ); + } - // Complete manner + } else if ( object instanceof THREE.PointCloud ) { - var textShapes = THREE.FontUtils.generateShapes( text, options ); - var text3d = new ExtrudeGeometry( textShapes, options ); + if ( geometry.__webglVertexBuffer === undefined ) { -*/ + createParticleBuffers( geometry ); + initParticleBuffers( geometry, object ); + geometry.verticesNeedUpdate = true; + geometry.colorsNeedUpdate = true; -THREE.TextGeometry = function ( text, parameters ) { + } - parameters = parameters || {}; + } - var textShapes = THREE.FontUtils.generateShapes( text, parameters ); + } - // translate parameters to ExtrudeGeometry API + if ( object.__webglActive === undefined) { - parameters.amount = parameters.height !== undefined ? parameters.height : 50; + object.__webglActive = true; - // defaults + if ( object instanceof THREE.Mesh ) { - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + if ( geometry instanceof THREE.BufferGeometry ) { - THREE.ExtrudeGeometry.call( this, textShapes, parameters ); + addBuffer( _webglObjects, geometry, object ); - this.type = 'TextGeometry'; + } else if ( geometry instanceof THREE.Geometry ) { -}; + var geometryGroupsList = geometryGroups[ geometry.id ]; -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; + for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) { -// File:src/extras/geometries/TorusGeometry.js + addBuffer( _webglObjects, geometryGroupsList[ i ], object ); -/** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 - */ + } -THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { + } - THREE.Geometry.call( this ); + } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) { - this.type = 'TorusGeometry'; + addBuffer( _webglObjects, geometry, object ); - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { - radius = radius || 100; - tube = tube || 40; - radialSegments = radialSegments || 8; - tubularSegments = tubularSegments || 6; - arc = arc || Math.PI * 2; + addBufferImmediate( _webglObjectsImmediate, object ); - var center = new THREE.Vector3(), uvs = [], normals = []; + } - for ( var j = 0; j <= radialSegments; j ++ ) { + } - for ( var i = 0; i <= tubularSegments; i ++ ) { + } - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; + // Geometry splitting - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); + var geometryGroups = {}; + var geometryGroupCounter = 0; - var vertex = new THREE.Vector3(); - vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = tube * Math.sin( v ); + function makeGroups( geometry, usesFaceMaterial ) { - this.vertices.push( vertex ); + var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535; - uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) ); - normals.push( vertex.clone().sub( center ).normalize() ); + var groupHash, hash_map = {}; - } + var numMorphTargets = geometry.morphTargets.length; + var numMorphNormals = geometry.morphNormals.length; - } + var group; + var groups = {}; + var groupsList = []; - for ( var j = 1; j <= radialSegments; j ++ ) { + for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - for ( var i = 1; i <= tubularSegments; i ++ ) { + var face = geometry.faces[ f ]; + var materialIndex = usesFaceMaterial ? face.materialIndex : 0; - var a = ( tubularSegments + 1 ) * j + i - 1; - var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( tubularSegments + 1 ) * j + i; + if ( ! ( materialIndex in hash_map ) ) { - var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] ); - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] ); + hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 }; - face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] ); - this.faces.push( face ); - this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] ); + } - } + groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; - } + if ( ! ( groupHash in groups ) ) { - this.computeFaceNormals(); + group = { + id: geometryGroupCounter ++, + faces3: [], + materialIndex: materialIndex, + vertices: 0, + numMorphTargets: numMorphTargets, + numMorphNormals: numMorphNormals + }; -}; + groups[ groupHash ] = group; + groupsList.push( group ); -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; + } -// File:src/extras/geometries/TorusKnotGeometry.js + if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) { -/** - * @author oosmoxiecode - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 - */ + hash_map[ materialIndex ].counter += 1; + groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter; -THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) { + if ( ! ( groupHash in groups ) ) { - THREE.Geometry.call( this ); + group = { + id: geometryGroupCounter ++, + faces3: [], + materialIndex: materialIndex, + vertices: 0, + numMorphTargets: numMorphTargets, + numMorphNormals: numMorphNormals + }; - this.type = 'TorusKnotGeometry'; + groups[ groupHash ] = group; + groupsList.push( group ); - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - p: p, - q: q, - heightScale: heightScale - }; + } - radius = radius || 100; - tube = tube || 40; - radialSegments = radialSegments || 64; - tubularSegments = tubularSegments || 8; - p = p || 2; - q = q || 3; - heightScale = heightScale || 1; - - var grid = new Array( radialSegments ); - var tang = new THREE.Vector3(); - var n = new THREE.Vector3(); - var bitan = new THREE.Vector3(); + } - for ( var i = 0; i < radialSegments; ++ i ) { + groups[ groupHash ].faces3.push( f ); + groups[ groupHash ].vertices += 3; - grid[ i ] = new Array( tubularSegments ); - var u = i / radialSegments * 2 * p * Math.PI; - var p1 = getPos( u, q, p, radius, heightScale ); - var p2 = getPos( u + 0.01, q, p, radius, heightScale ); - tang.subVectors( p2, p1 ); - n.addVectors( p2, p1 ); + } - bitan.crossVectors( tang, n ); - n.crossVectors( bitan, tang ); - bitan.normalize(); - n.normalize(); + return groupsList; - for ( var j = 0; j < tubularSegments; ++ j ) { + } - var v = j / tubularSegments * 2 * Math.PI; - var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - var cy = tube * Math.sin( v ); + function initGeometryGroups( object, geometry ) { - var pos = new THREE.Vector3(); - pos.x = p1.x + cx * n.x + cy * bitan.x; - pos.y = p1.y + cx * n.y + cy * bitan.y; - pos.z = p1.z + cx * n.z + cy * bitan.z; + var material = object.material, addBuffers = false; - grid[ i ][ j ] = this.vertices.push( pos ) - 1; + if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) { - } + delete _webglObjects[ object.id ]; - } + geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial ); - for ( var i = 0; i < radialSegments; ++ i ) { + geometry.groupsNeedUpdate = false; - for ( var j = 0; j < tubularSegments; ++ j ) { + } - var ip = ( i + 1 ) % radialSegments; - var jp = ( j + 1 ) % tubularSegments; + var geometryGroupsList = geometryGroups[ geometry.id ]; - var a = grid[ i ][ j ]; - var b = grid[ ip ][ j ]; - var c = grid[ ip ][ jp ]; - var d = grid[ i ][ jp ]; + // create separate VBOs per geometry chunk - var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments ); - var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments ); - var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments ); - var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments ); + for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) { - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + var geometryGroup = geometryGroupsList[ i ]; - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + // initialise VBO on the first access - } - } + if ( geometryGroup.__webglVertexBuffer === undefined ) { - this.computeFaceNormals(); - this.computeVertexNormals(); + createMeshBuffers( geometryGroup ); + initMeshBuffers( geometryGroup, object ); - function getPos( u, in_q, in_p, radius, heightScale ) { + geometry.verticesNeedUpdate = true; + geometry.morphTargetsNeedUpdate = true; + geometry.elementsNeedUpdate = true; + geometry.uvsNeedUpdate = true; + geometry.normalsNeedUpdate = true; + geometry.tangentsNeedUpdate = true; + geometry.colorsNeedUpdate = true; - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = in_q / in_p * u; - var cs = Math.cos( quOverP ); + addBuffers = true; - var tx = radius * ( 2 + cs ) * 0.5 * cu; - var ty = radius * ( 2 + cs ) * su * 0.5; - var tz = heightScale * radius * Math.sin( quOverP ) * 0.5; + } else { - return new THREE.Vector3( tx, ty, tz ); + addBuffers = false; - } + } -}; + if ( addBuffers || object.__webglActive === undefined ) { -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; + addBuffer( _webglObjects, geometryGroup, object ); -// File:src/extras/geometries/TubeGeometry.js + } -/** - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * @author jonobr1 / https://github.com/jonobr1 - * - * Modified from the TorusKnotGeometry by @oosmoxiecode - * - * Creates a tube which extrudes along a 3d spline - * - * Uses parallel transport frames as described in - * http://www.cs.indiana.edu/pub/techreports/TR425.pdf - */ + } -THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) { + object.__webglActive = true; - THREE.Geometry.call( this ); + } - this.type = 'TubeGeometry'; + function addBuffer( objlist, buffer, object ) { + + var id = object.id; + objlist[id] = objlist[id] || []; + objlist[id].push( + { + id: id, + buffer: buffer, + object: object, + material: null, + z: 0 + } + ); - this.parameters = { - path: path, - segments: segments, - radius: radius, - radialSegments: radialSegments, - closed: closed }; - segments = segments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; - taper = taper || THREE.TubeGeometry.NoTaper; + function addBufferImmediate( objlist, object ) { - var grid = []; + objlist.push( + { + id: null, + object: object, + opaque: null, + transparent: null, + z: 0 + } + ); - var scope = this, + }; - tangent, - normal, - binormal, + // Objects updates - numpoints = segments + 1, + function updateObject( object ) { - u, v, r, + var geometry = object.geometry; - cx, cy, - pos, pos2 = new THREE.Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; + if ( geometry instanceof THREE.BufferGeometry ) { - var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; + var attributes = geometry.attributes; + var attributesKeys = geometry.attributesKeys; - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) { - function vert( x, y, z ) { + var key = attributesKeys[ i ]; + var attribute = attributes[ key ]; + var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; + if ( attribute.buffer === undefined ) { - } + attribute.buffer = _gl.createBuffer(); + _gl.bindBuffer( bufferType, attribute.buffer ); + _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW ); - // consruct the grid + attribute.needsUpdate = false; - for ( i = 0; i < numpoints; i ++ ) { + } else if ( attribute.needsUpdate === true ) { - grid[ i ] = []; + _gl.bindBuffer( bufferType, attribute.buffer ); - u = i / ( numpoints - 1 ); + if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges - pos = path.getPointAt( u ); + _gl.bufferSubData( bufferType, 0, attribute.array ); - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; + } else if ( attribute.updateRange.count === 0 ) { - r = radius * taper( u ); + console.error( 'THREE.Canvas3DRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' ); - for ( j = 0; j < radialSegments; j ++ ) { + } else { - v = j / radialSegments * 2 * Math.PI; + _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT, + attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) ); - cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = r * Math.sin( v ); + attribute.updateRange.count = 0; // reset range - pos2.copy( pos ); - pos2.x += cx * normal.x + cy * binormal.x; - pos2.y += cx * normal.y + cy * binormal.y; - pos2.z += cx * normal.z + cy * binormal.z; + } - grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); + attribute.needsUpdate = false; - } - } + } + } - // construct the mesh + } else if ( object instanceof THREE.Mesh ) { - for ( i = 0; i < segments; i ++ ) { + // check all geometry groups - for ( j = 0; j < radialSegments; j ++ ) { + if ( geometry.groupsNeedUpdate === true ) { - ip = ( closed ) ? (i + 1) % segments : i + 1; - jp = (j + 1) % radialSegments; + initGeometryGroups( object, geometry ); - a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = grid[ ip ][ j ]; - c = grid[ ip ][ jp ]; - d = grid[ i ][ jp ]; + } - uva = new THREE.Vector2( i / segments, j / radialSegments ); - uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments ); - uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); - uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments ); + var geometryGroupsList = geometryGroups[ geometry.id ]; - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) { - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + var geometryGroup = geometryGroupsList[ i ]; + var material = getBufferMaterial( object, geometryGroup ); - } - } + var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); - this.computeFaceNormals(); - this.computeVertexNormals(); + if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || + geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || + geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { -}; + setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material ); -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; + } -THREE.TubeGeometry.NoTaper = function ( u ) { + } - return 1; + geometry.verticesNeedUpdate = false; + geometry.morphTargetsNeedUpdate = false; + geometry.elementsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.tangentsNeedUpdate = false; -}; + if (material.attributes) clearCustomAttributes( material ); -THREE.TubeGeometry.SinusoidalTaper = function ( u ) { + } else if ( object instanceof THREE.Line ) { - return Math.sin( Math.PI * u ); + var material = getBufferMaterial( object, geometry ); + var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); -}; + if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { -// For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { + setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); - var normal = new THREE.Vector3(), + } - tangents = [], - normals = [], - binormals = [], + geometry.verticesNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.lineDistancesNeedUpdate = false; - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), + if (material.attributes) clearCustomAttributes( material ); - numpoints = segments + 1, - theta, - epsilon = 0.0001, - smallest, + } else if ( object instanceof THREE.PointCloud ) { - tx, ty, tz, - i, u; + var material = getBufferMaterial( object, geometry ); + var customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); + if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) { - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); - // compute the tangent vectors for each segment on the path + } - for ( i = 0; i < numpoints; i ++ ) { + geometry.verticesNeedUpdate = false; + geometry.colorsNeedUpdate = false; - u = i / ( numpoints - 1 ); + if(material.attributes) clearCustomAttributes( material ); - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); + } } - initialNormal3(); + // Objects updates - custom attributes check - /* - function initialNormal1(lastBinormal) { - // fixed start binormal. Has dangers of 0 vectors - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); - normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - } + function areCustomAttributesDirty( material ) { - function initialNormal2() { + for ( var name in material.attributes ) { - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); + if ( material.attributes[ name ].needsUpdate ) return true; - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + } - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + return false; } - */ - function initialNormal3() { - // select an initial normal vector perpenicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component + function clearCustomAttributes( material ) { - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - smallest = Number.MAX_VALUE; - tx = Math.abs( tangents[ 0 ].x ); - ty = Math.abs( tangents[ 0 ].y ); - tz = Math.abs( tangents[ 0 ].z ); + for ( var name in material.attributes ) { - if ( tx <= smallest ) { - smallest = tx; - normal.set( 1, 0, 0 ); - } + material.attributes[ name ].needsUpdate = false; - if ( ty <= smallest ) { - smallest = ty; - normal.set( 0, 1, 0 ); } - if ( tz <= smallest ) { - normal.set( 0, 0, 1 ); - } + } - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + // Objects removal - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - } + function removeObject( object ) { + if ( object instanceof THREE.Mesh || + object instanceof THREE.PointCloud || + object instanceof THREE.Line ) { - // compute the slowly-varying normal and binormal vectors for each segment on the path + delete _webglObjects[ object.id ]; - for ( i = 1; i < numpoints; i ++ ) { + } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { - normals[ i ] = normals[ i - 1 ].clone(); + removeInstances( _webglObjectsImmediate, object ); - binormals[ i ] = binormals[ i - 1 ].clone(); + } - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + delete object.__webglInit; + delete object._modelViewMatrix; + delete object._normalMatrix; - if ( vec.length() > epsilon ) { + delete object.__webglActive; - vec.normalize(); + } - theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + function removeInstances( objlist, object ) { - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + for ( var o = objlist.length - 1; o >= 0; o -- ) { - } + if ( objlist[ o ].object === object ) { - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + objlist.splice( o, 1 ); + + } + + } } + // Materials - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointCloudMaterial: 'particle_basic' + }; - if ( closed ) { + function initMaterial( material, lights, fog, object ) { - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); - theta /= ( numpoints - 1 ); + material.addEventListener( 'dispose', onMaterialDispose ); + + var shaderID = shaderIDs[ material.type ]; - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { + if ( shaderID ) { - theta = - theta; + var shader = THREE.ShaderLib[ shaderID ]; - } + material.__webglShader = { + uniforms: THREE.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + } - for ( i = 1; i < numpoints; i ++ ) { + } else { - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + material.__webglShader = { + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + } } - } -}; + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) -// File:src/extras/geometries/PolyhedronGeometry.js + var maxLightCount = allocateLights( lights ); + var maxShadows = allocateShadows( lights ); + var maxBones = allocateBones( object ); -/** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley -*/ + var parameters = { -THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { + precision: _precision, + supportsVertexTextures: _supportsVertexTextures, - THREE.Geometry.call( this ); + map: !! material.map, + envMap: !! material.envMap, + envMapMode: material.envMap && material.envMap.mapping, + lightMap: !! material.lightMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, - this.type = 'PolyhedronGeometry'; + combine: material.combine, - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + vertexColors: material.vertexColors, - radius = radius || 1; - detail = detail || 0; + fog: fog, + useFog: material.fog, + fogExp: fog instanceof THREE.FogExp2, - var that = this; + flatShading: material.shading === THREE.FlatShading, - for ( var i = 0, l = vertices.length; i < l; i += 3 ) { + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: _logarithmicDepthBuffer, - prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture, - } + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: _this.maxMorphTargets, + maxMorphNormals: _this.maxMorphNormals, - var p = this.vertices; + maxDirLights: maxLightCount.directional, + maxPointLights: maxLightCount.point, + maxSpotLights: maxLightCount.spot, + maxHemiLights: maxLightCount.hemi, - var faces = []; + maxShadows: maxShadows, + shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, + shadowMapType: _this.shadowMapType, + shadowMapDebug: _this.shadowMapDebug, + shadowMapCascade: _this.shadowMapCascade, - for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { + alphaTest: material.alphaTest, + metal: material.metal, + wrapAround: material.wrapAround, + doubleSided: material.side === THREE.DoubleSide, + flipSided: material.side === THREE.BackSide - var v1 = p[ indices[ i ] ]; - var v2 = p[ indices[ i + 1 ] ]; - var v3 = p[ indices[ i + 2 ] ]; + }; - faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + // Generate code - } + var chunks = []; - var centroid = new THREE.Vector3(); + if ( shaderID ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + chunks.push( shaderID ); - subdivide( faces[ i ], detail ); + } else { - } + chunks.push( material.fragmentShader ); + chunks.push( material.vertexShader ); + } - // Handle case when face straddles the seam + if ( material.defines !== undefined ) { - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { + for ( var name in material.defines ) { - var uvs = this.faceVertexUvs[ 0 ][ i ]; + chunks.push( name ); + chunks.push( material.defines[ name ] ); - var x0 = uvs[ 0 ].x; - var x1 = uvs[ 1 ].x; - var x2 = uvs[ 2 ].x; + } - var max = Math.max( x0, Math.max( x1, x2 ) ); - var min = Math.min( x0, Math.min( x1, x2 ) ); + } - if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary + for ( var name in parameters ) { - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; + chunks.push( name ); + chunks.push( parameters[ name ] ); } - } - - - // Apply radius + var code = chunks.join(); - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { + var program; - this.vertices[ i ].multiplyScalar( radius ); + // Check if code has been already compiled - } + for ( var p = 0, pl = _programs.length; p < pl; p ++ ) { + var programInfo = _programs[ p ]; - // Merge vertices + if ( programInfo.code === code ) { - this.mergeVertices(); + program = programInfo; + program.usedTimes ++; - this.computeFaceNormals(); + break; - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + } + } - // Project vector onto sphere's surface + if ( program === undefined ) { - function prepare( vector ) { + program = new THREE.WebGLProgram( _this, code, material, parameters ); + _programs.push( program ); - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; + _this.info.memory.programs = _programs.length; - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. + } - var u = azimuth( vector ) / 2 / Math.PI + 0.5; - var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new THREE.Vector2( u, 1 - v ); + material.program = program; - return vertex; + var attributes = program.attributes; - } + if ( material.morphTargets ) { + material.numSupportedMorphTargets = 0; - // Approximate a curved face with recursively sub-divided triangles. + var id, base = 'morphTarget'; - function make( v1, v2, v3 ) { + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - that.faces.push( face ); + id = base + i; - centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); + if ( attributes[ id ] >= 0 ) { - var azi = azimuth( centroid ); + material.numSupportedMorphTargets ++; - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); + } - } + } + } - // Analytically subdivide a face to the required detail level. + if ( material.morphNormals ) { - function subdivide( face, detail ) { + material.numSupportedMorphNormals = 0; - var cols = Math.pow(2, detail); - var a = prepare( that.vertices[ face.a ] ); - var b = prepare( that.vertices[ face.b ] ); - var c = prepare( that.vertices[ face.c ] ); - var v = []; + var id, base = 'morphNormal'; - // Construct all of the vertices for this subdivision. + for ( i = 0; i < _this.maxMorphNormals; i ++ ) { - for ( var i = 0 ; i <= cols; i ++ ) { + id = base + i; - v[ i ] = []; + if ( attributes[ id ] >= 0 ) { - var aj = prepare( a.clone().lerp( c, i / cols ) ); - var bj = prepare( b.clone().lerp( c, i / cols ) ); - var rows = cols - i; + material.numSupportedMorphNormals ++; - for ( var j = 0; j <= rows; j ++) { + } - if ( j == 0 && i == cols ) { + } - v[ i ][ j ] = aj; + } - } else { + material.uniformsList = []; - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); + for ( var u in material.__webglShader.uniforms ) { - } + var location = material.program.uniforms[ u ]; + if ( location ) { + material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] ); } } - // Construct all of the faces. + } - for ( var i = 0; i < cols ; i ++ ) { + function setMaterial( material ) { - for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) { + if ( material.transparent === true ) { - var k = Math.floor( j / 2 ); + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha ); - if ( j % 2 == 0 ) { + } else { - make( - v[ i ][ k + 1], - v[ i + 1 ][ k ], - v[ i ][ k ] - ); + state.setBlending( THREE.NoBlending ); - } else { + } - make( - v[ i ][ k + 1 ], - v[ i + 1][ k + 1], - v[ i + 1 ][ k ] - ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); + state.setColorWrite( material.colorWrite ); + state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - } + } - } + function setProgram( camera, lights, fog, material, object ) { - } + _usedTextureUnits = 0; - } + if ( material.needsUpdate ) { + if ( material.program ) deallocateMaterial( material ); - // Angle around the Y axis, counter-clockwise when looking from above. + initMaterial( material, lights, fog, object ); + material.needsUpdate = false; - function azimuth( vector ) { + } - return Math.atan2( vector.z, - vector.x ); + if ( material.morphTargets ) { - } + if ( ! object.__webglMorphTargetInfluences ) { + object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); - // Angle above the XZ plane. + } - function inclination( vector ) { + } - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - } + var program = material.program, + p_uniforms = program.uniforms, + m_uniforms = material.__webglShader.uniforms; + if ( program.id !== _currentProgram ) { - // Texture fixing helper. Spheres have some odd behaviours. + _gl.useProgram( program.program ); + _currentProgram = program.id; - function correctUV( uv, vector, azimuth ) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - 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.clone(); + } - } + if ( material.id !== _currentMaterialId ) { + if ( _currentMaterialId === -1 ) refreshLights = true; + _currentMaterialId = material.id; -}; + refreshMaterial = true; -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; + } -// File:src/extras/geometries/DodecahedronGeometry.js + if ( refreshProgram || camera !== _currentCamera ) { -/** - * @author Abe Pazos / https://hamoid.com - */ + _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); -THREE.DodecahedronGeometry = function ( radius, detail ) { + if ( _logarithmicDepthBuffer ) { - this.parameters = { - radius: radius, - detail: detail - }; + _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var r = 1 / t; + } - var vertices = [ - // (±1, ±1, ±1) - -1, -1, -1, -1, -1, 1, - -1, 1, -1, -1, 1, 1, - 1, -1, -1, 1, -1, 1, - 1, 1, -1, 1, 1, 1, + if ( camera !== _currentCamera ) _currentCamera = camera; - // (0, ±1/φ, ±φ) - 0, -r, -t, 0, -r, t, - 0, r, -t, 0, r, t, + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - // (±1/φ, ±φ, 0) - -r, -t, 0, -r, t, 0, - r, -t, 0, r, t, 0, + if ( material instanceof THREE.ShaderMaterial || + material instanceof THREE.MeshPhongMaterial || + material.envMap ) { - // (±φ, 0, ±1/φ) - -t, 0, -r, t, 0, -r, - -t, 0, r, t, 0, r - ]; + if ( p_uniforms.cameraPosition !== null ) { - var indices = [ - 3, 11, 7, 3, 7, 15, 3, 15, 13, - 7, 19, 17, 7, 17, 6, 7, 6, 15, - 17, 4, 8, 17, 8, 10, 17, 10, 6, - 8, 0, 16, 8, 16, 2, 8, 2, 10, - 0, 12, 1, 0, 1, 18, 0, 18, 16, - 6, 10, 2, 6, 2, 13, 6, 13, 15, - 2, 16, 18, 2, 18, 3, 2, 3, 13, - 18, 1, 9, 18, 9, 11, 18, 11, 3, - 4, 14, 12, 4, 12, 0, 4, 0, 8, - 11, 9, 5, 11, 5, 19, 11, 19, 7, - 19, 5, 14, 19, 14, 4, 19, 4, 17, - 1, 12, 14, 1, 14, 5, 1, 5, 9 - ]; + _vector3.setFromMatrixPosition( camera.matrixWorld ); + _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + } -}; + } -THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; + if ( material instanceof THREE.MeshPhongMaterial || + material instanceof THREE.MeshLambertMaterial || + material instanceof THREE.MeshBasicMaterial || + material instanceof THREE.ShaderMaterial || + material.skinning ) { -// File:src/extras/geometries/IcosahedronGeometry.js + if ( p_uniforms.viewMatrix !== null ) { -/** - * @author timothypratley / https://github.com/timothypratley - */ + _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); -THREE.IcosahedronGeometry = function ( radius, detail ) { + } - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + } - var vertices = [ - - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, - 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, - t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 - ]; + } - var indices = [ - 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, - 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, - 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, - 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 - ]; + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // not sure why, but otherwise weird things happen - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + if ( material.skinning ) { - this.type = 'IcosahedronGeometry'; + if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) { - this.parameters = { - radius: radius, - detail: detail - }; -}; + _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements ); -THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; + } -// File:src/extras/geometries/OctahedronGeometry.js + if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) { -/** - * @author timothypratley / https://github.com/timothypratley - */ + _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements ); -THREE.OctahedronGeometry = function ( radius, detail ) { + } - this.parameters = { - radius: radius, - detail: detail - }; + if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) { - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1 - ]; + if ( p_uniforms.boneTexture !== null ) { - var indices = [ - 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 - ]; + var textureUnit = getTextureUnit(); - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); + _this.setTexture( object.skeleton.boneTexture, textureUnit ); - this.type = 'OctahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; -}; + if ( p_uniforms.boneTextureWidth !== null ) { -THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; + _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth ); -// File:src/extras/geometries/TetrahedronGeometry.js + } -/** - * @author timothypratley / https://github.com/timothypratley - */ + if ( p_uniforms.boneTextureHeight !== null ) { -THREE.TetrahedronGeometry = function ( radius, detail ) { + _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight ); - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + } - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + } else if ( object.skeleton && object.skeleton.boneMatrices ) { - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + if ( p_uniforms.boneGlobalMatrices !== null ) { - this.type = 'TetrahedronGeometry'; + _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices ); - this.parameters = { - radius: radius, - detail: detail - }; + } -}; + } -THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; + } -// File:src/extras/geometries/ParametricGeometry.js + if ( refreshMaterial ) { -/** - * @author zz85 / https://github.com/zz85 - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 - * - * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); - * - */ + // refresh uniforms common to several materials -THREE.ParametricGeometry = function ( func, slices, stacks ) { + if ( fog && material.fog ) { - THREE.Geometry.call( this ); + refreshUniformsFog( m_uniforms, fog ); - this.type = 'ParametricGeometry'; + } - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + if ( material instanceof THREE.MeshPhongMaterial || + material instanceof THREE.MeshLambertMaterial || + material.lights ) { - var verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; + if ( _lightsNeedUpdate ) { - var i, j, p; - var u, v; + refreshLights = true; + setupLights( lights ); + _lightsNeedUpdate = false; + } - var sliceCount = slices + 1; + if ( refreshLights ) { + refreshUniformsLights( m_uniforms, _lights ); + markUniformsLightsNeedsUpdate( m_uniforms, true ); + } else { + markUniformsLightsNeedsUpdate( m_uniforms, false ); + } - for ( i = 0; i <= stacks; i ++ ) { + } - v = i / stacks; + if ( material instanceof THREE.MeshBasicMaterial || + material instanceof THREE.MeshLambertMaterial || + material instanceof THREE.MeshPhongMaterial ) { - for ( j = 0; j <= slices; j ++ ) { + refreshUniformsCommon( m_uniforms, material ); - u = j / slices; + } - p = func( u, v ); - verts.push( p ); + // refresh single material specific uniforms - } - } + if ( material instanceof THREE.LineBasicMaterial ) { - var a, b, c, d; - var uva, uvb, uvc, uvd; + refreshUniformsLine( m_uniforms, material ); - for ( i = 0; i < stacks; i ++ ) { + } else if ( material instanceof THREE.LineDashedMaterial ) { - for ( j = 0; j < slices; j ++ ) { + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = (i + 1) * sliceCount + j + 1; - d = (i + 1) * sliceCount + j; + } else if ( material instanceof THREE.PointCloudMaterial ) { - uva = new THREE.Vector2( j / slices, i / stacks ); - uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks ); - uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); - uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks ); + refreshUniformsParticle( m_uniforms, material ); - faces.push( new THREE.Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); + } else if ( material instanceof THREE.MeshPhongMaterial ) { - faces.push( new THREE.Face3( b, c, d ) ); - uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); + refreshUniformsPhong( m_uniforms, material ); - } + } else if ( material instanceof THREE.MeshLambertMaterial ) { - } + refreshUniformsLambert( m_uniforms, material ); - // console.log(this); + } else if ( material instanceof THREE.MeshDepthMaterial ) { - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); + m_uniforms.mNear.value = camera.near; + m_uniforms.mFar.value = camera.far; + m_uniforms.opacity.value = material.opacity; - this.computeFaceNormals(); - this.computeVertexNormals(); + } else if ( material instanceof THREE.MeshNormalMaterial ) { -}; + m_uniforms.opacity.value = material.opacity; -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; + } -// File:src/extras/helpers/AxisHelper.js + if ( object.receiveShadow && ! material._shadowPass ) { -/** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + refreshUniformsShadow( m_uniforms, lights ); -THREE.AxisHelper = function ( size ) { + } - size = size || 1; + // load common uniforms - var vertices = new Float32Array( [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ] ); + loadUniformsGeneric( material.uniformsList ); - var colors = new Float32Array( [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ] ); + } - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + loadUniformsMatrices( p_uniforms, object ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + if ( p_uniforms.modelMatrix !== null ) { - THREE.Line.call( this, geometry, material, THREE.LinePieces ); + _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); -}; + } -THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; + return program; -// File:src/extras/helpers/ArrowHelper.js + } -/** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://exocortex.com - * - * Creates an arrow for visualizing directions - * - * Parameters: - * dir - Vector3 - * origin - Vector3 - * length - Number - * color - color in hex value - * headLength - Number - * headWidth - Number - */ + // Uniforms (refresh uniforms objects) -THREE.ArrowHelper = ( function () { + function refreshUniformsCommon ( uniforms, material ) { - var lineGeometry = new THREE.Geometry(); - lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + uniforms.opacity.value = material.opacity; - var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); + uniforms.diffuse.value = material.color; - return function ( dir, origin, length, color, headLength, headWidth ) { + uniforms.map.value = material.map; + uniforms.lightMap.value = material.lightMap; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; - // dir is assumed to be normalized + if ( material.bumpMap ) { - THREE.Object3D.call( this ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - if ( color === undefined ) color = 0xffff00; - if ( length === undefined ) length = 1; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + } - this.position.copy( origin ); + if ( material.normalMap ) { - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + } - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map - } + var uvScaleMap; -}() ); + if ( material.map ) { -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; + uvScaleMap = material.map; -THREE.ArrowHelper.prototype.setDirection = ( function () { + } else if ( material.specularMap ) { - var axis = new THREE.Vector3(); - var radians; + uvScaleMap = material.specularMap; - return function ( dir ) { + } else if ( material.normalMap ) { - // dir is assumed to be normalized + uvScaleMap = material.normalMap; - if ( dir.y > 0.99999 ) { + } else if ( material.bumpMap ) { - this.quaternion.set( 0, 0, 0, 1 ); + uvScaleMap = material.bumpMap; - } else if ( dir.y < - 0.99999 ) { + } else if ( material.alphaMap ) { - this.quaternion.set( 1, 0, 0, 0 ); + uvScaleMap = material.alphaMap; - } else { + } - axis.set( dir.z, 0, - dir.x ).normalize(); + if ( uvScaleMap !== undefined ) { - radians = Math.acos( dir.y ); + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - this.quaternion.setFromAxisAngle( axis, radians ); + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); } - }; - -}() ); + uniforms.envMap.value = material.envMap; + uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1; -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + } - this.line.scale.set( 1, length - headLength, 1 ); - this.line.updateMatrix(); + function refreshUniformsLine ( uniforms, material ) { - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; -}; + } -THREE.ArrowHelper.prototype.setColor = function ( color ) { + function refreshUniformsDash ( uniforms, material ) { - this.line.material.color.set( color ); - this.cone.material.color.set( color ); + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; -}; + } -// File:src/extras/helpers/BoxHelper.js + function refreshUniformsParticle ( uniforms, material ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + uniforms.psColor.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size; + uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. -THREE.BoxHelper = function ( object ) { + uniforms.map.value = material.map; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) ); + if ( material.map !== null ) { - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces ); + var offset = material.map.offset; + var repeat = material.map.repeat; - if ( object !== undefined ) { + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - this.update( object ); + } } -}; + function refreshUniformsFog ( uniforms, fog ) { -THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; + uniforms.fogColor.value = fog.color; -THREE.BoxHelper.prototype.update = function ( object ) { + if ( fog instanceof THREE.Fog ) { - var geometry = object.geometry; + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - if ( geometry.boundingBox === null ) { + } else if ( fog instanceof THREE.FogExp2 ) { - geometry.computeBoundingBox(); + uniforms.fogDensity.value = fog.density; + + } } - var min = geometry.boundingBox.min; - var max = geometry.boundingBox.max; + function refreshUniformsPhong ( uniforms, material ) { - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + uniforms.shininess.value = material.shininess; - 0: max.x, max.y, max.z - 1: min.x, max.y, max.z - 2: min.x, min.y, max.z - 3: max.x, min.y, max.z - 4: max.x, max.y, min.z - 5: min.x, max.y, min.z - 6: min.x, min.y, min.z - 7: max.x, min.y, min.z - */ + uniforms.emissive.value = material.emissive; + uniforms.specular.value = material.specular; - var vertices = this.geometry.attributes.position.array; + if ( material.wrapAround ) { - vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z; - vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z; + uniforms.wrapRGB.value.copy( material.wrapRGB ); - vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z; - vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z; + } - vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z; - vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z; + } - vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z; - vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z; + function refreshUniformsLambert ( uniforms, material ) { - // + uniforms.emissive.value = material.emissive; - vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z; - vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z; + if ( material.wrapAround ) { - vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z; - vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z; + uniforms.wrapRGB.value.copy( material.wrapRGB ); - vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z; - vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z; + } - vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z; - vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z; + } - // + function refreshUniformsLights ( uniforms, lights ) { - vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z; - vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z; + uniforms.ambientLightColor.value = lights.ambient; - vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z; - vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z; + uniforms.directionalLightColor.value = lights.directional.colors; + uniforms.directionalLightDirection.value = lights.directional.positions; - vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z; - vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z; + uniforms.pointLightColor.value = lights.point.colors; + uniforms.pointLightPosition.value = lights.point.positions; + uniforms.pointLightDistance.value = lights.point.distances; + uniforms.pointLightDecay.value = lights.point.decays; - vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z; - vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z; + uniforms.spotLightColor.value = lights.spot.colors; + uniforms.spotLightPosition.value = lights.spot.positions; + uniforms.spotLightDistance.value = lights.spot.distances; + uniforms.spotLightDirection.value = lights.spot.directions; + uniforms.spotLightAngleCos.value = lights.spot.anglesCos; + uniforms.spotLightExponent.value = lights.spot.exponents; + uniforms.spotLightDecay.value = lights.spot.decays; - this.geometry.attributes.position.needsUpdate = true; + uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; + uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; + uniforms.hemisphereLightDirection.value = lights.hemi.positions; - this.geometry.computeBoundingSphere(); + } - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + // If uniforms are marked as clean, they don't need to be loaded to the GPU. -}; + function markUniformsLightsNeedsUpdate ( uniforms, value ) { -// File:src/extras/helpers/BoundingBoxHelper.js + uniforms.ambientLightColor.needsUpdate = value; -/** - * @author WestLangley / http://github.com/WestLangley - */ + uniforms.directionalLightColor.needsUpdate = value; + uniforms.directionalLightDirection.needsUpdate = value; -// a helper to show the world-axis-aligned bounding box for an object + uniforms.pointLightColor.needsUpdate = value; + uniforms.pointLightPosition.needsUpdate = value; + uniforms.pointLightDistance.needsUpdate = value; + uniforms.pointLightDecay.needsUpdate = value; -THREE.BoundingBoxHelper = function ( object, hex ) { + uniforms.spotLightColor.needsUpdate = value; + uniforms.spotLightPosition.needsUpdate = value; + uniforms.spotLightDistance.needsUpdate = value; + uniforms.spotLightDirection.needsUpdate = value; + uniforms.spotLightAngleCos.needsUpdate = value; + uniforms.spotLightExponent.needsUpdate = value; + uniforms.spotLightDecay.needsUpdate = value; - var color = ( hex !== undefined ) ? hex : 0x888888; + uniforms.hemisphereLightSkyColor.needsUpdate = value; + uniforms.hemisphereLightGroundColor.needsUpdate = value; + uniforms.hemisphereLightDirection.needsUpdate = value; - this.object = object; + } - this.box = new THREE.Box3(); + function refreshUniformsShadow ( uniforms, lights ) { - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); + if ( uniforms.shadowMatrix ) { -}; + var j = 0; -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; + for ( var i = 0, il = lights.length; i < il; i ++ ) { -THREE.BoundingBoxHelper.prototype.update = function () { + var light = lights[ i ]; - this.box.setFromObject( this.object ); + if ( ! light.castShadow ) continue; - this.box.size( this.scale ); + if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { - this.box.center( this.position ); + uniforms.shadowMap.value[ j ] = light.shadowMap; + uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; -}; + uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; -// File:src/extras/helpers/CameraHelper.js + uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; + uniforms.shadowBias.value[ j ] = light.shadowBias; -/** - * @author alteredq / http://alteredqualia.com/ - * - * - shows frustum, line of sight and up of the camera - * - suitable for fast updates - * - based on frustum visualization in lightgl.js shadowmap example - * http://evanw.github.com/lightgl.js/tests/shadowmap.html - */ + j ++; -THREE.CameraHelper = function ( camera ) { + } - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); + } - var pointMap = {}; + } - // colors + } - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; + // Uniforms (load to GPU) - // near + function loadUniformsMatrices ( uniforms, object ) { - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); + _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); - // far + if ( uniforms.normalMatrix ) { - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); + _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); - // sides + } - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); + } - // cone + function getTextureUnit() { - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); + var textureUnit = _usedTextureUnits; - // up + if ( textureUnit >= _maxTextures ) { - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); + THREE.warn( 'Canvas3DRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures ); - // target + } - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); + _usedTextureUnits += 1; - // cross + return textureUnit; - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); + } - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); + function loadUniformsGeneric ( uniforms ) { - function addLine( a, b, hex ) { + var texture, textureUnit, offset; - addPoint( a, hex ); - addPoint( b, hex ); + for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) { - } + var uniform = uniforms[ j ][ 0 ]; - function addPoint( id, hex ) { + // needsUpdate property is not added to all uniforms. + if ( uniform.needsUpdate === false ) continue; - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); + var type = uniform.type; + var value = uniform.value; + var location = uniforms[ j ][ 1 ]; - if ( pointMap[ id ] === undefined ) { + switch ( type ) { - pointMap[ id ] = []; + case '1i': + _gl.uniform1i( location, value ); + break; - } + case '1f': + _gl.uniform1f( location, value ); + break; - pointMap[ id ].push( geometry.vertices.length - 1 ); + case '2f': + _gl.uniform2f( location, value[ 0 ], value[ 1 ] ); + break; - } + case '3f': + _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] ); + break; - THREE.Line.call( this, geometry, material, THREE.LinePieces ); + case '4f': + _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] ); + break; + + case '1iv': + _gl.uniform1iv( location, value ); + break; + + case '3iv': + _gl.uniform3iv( location, value ); + break; + + case '1fv': + _gl.uniform1fv( location, value ); + break; + + case '2fv': + _gl.uniform2fv( location, value ); + break; - this.camera = camera; - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + case '3fv': + _gl.uniform3fv( location, value ); + break; - this.pointMap = pointMap; + case '4fv': + _gl.uniform4fv( location, value ); + break; - this.update(); + case 'Matrix3fv': + _gl.uniformMatrix3fv( location, false, value ); + break; -}; + case 'Matrix4fv': + _gl.uniformMatrix4fv( location, false, value ); + break; -THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; + // -THREE.CameraHelper.prototype.update = function () { + case 'i': - var geometry, pointMap; - - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); + // single integer + _gl.uniform1i( location, value ); - var setPoint = function ( point, x, y, z ) { + break; - vector.set( x, y, z ).unproject( camera ); + case 'f': - var points = pointMap[ point ]; + // single float + _gl.uniform1f( location, value ); - if ( points !== undefined ) { + break; - for ( var i = 0, il = points.length; i < il; i ++ ) { + case 'v2': - geometry.vertices[ points[ i ] ].copy( vector ); + // single THREE.Vector2 + _gl.uniform2f( location, value.x, value.y ); - } + break; - } + case 'v3': - }; + // single THREE.Vector3 + _gl.uniform3f( location, value.x, value.y, value.z ); - return function () { + break; - geometry = this.geometry; - pointMap = this.pointMap; + case 'v4': - var w = 1, h = 1; + // single THREE.Vector4 + _gl.uniform4f( location, value.x, value.y, value.z, value.w ); - // we need just camera projection matrix - // world matrix must be identity + break; - camera.projectionMatrix.copy( this.camera.projectionMatrix ); + case 'c': - // center / target + // single THREE.Color + _gl.uniform3f( location, value.r, value.g, value.b ); - setPoint( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + break; - // near + case 'iv1': - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + // flat array of integers (JS or typed array) + _gl.uniform1iv( location, value ); - // far + break; - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + case 'iv': - // up + // flat array of integers with 3 x N size (JS or typed array) + _gl.uniform3iv( location, value ); - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + break; - // cross + case 'fv1': - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + // flat array of floats (JS or typed array) + _gl.uniform1fv( location, value ); - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + break; - geometry.verticesNeedUpdate = true; + case 'fv': - }; + // flat array of floats with 3 x N size (JS or typed array) + _gl.uniform3fv( location, value ); -}(); + break; -// File:src/extras/helpers/DirectionalLightHelper.js + case 'v2v': -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + // array of THREE.Vector2 -THREE.DirectionalLightHelper = function ( light, size ) { + if ( uniform._array === undefined ) { - THREE.Object3D.call( this ); + uniform._array = new Float32Array( 2 * value.length ); - this.light = light; - this.light.updateMatrixWorld(); + } - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + for ( var i = 0, il = value.length; i < il; i ++ ) { - size = size || 1; + offset = i * 2; - var geometry = new THREE.Geometry(); - geometry.vertices.push( - new THREE.Vector3( - size, size, 0 ), - new THREE.Vector3( size, size, 0 ), - new THREE.Vector3( size, - size, 0 ), - new THREE.Vector3( - size, - size, 0 ), - new THREE.Vector3( - size, size, 0 ) - ); + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; - var material = new THREE.LineBasicMaterial( { fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + } - this.lightPlane = new THREE.Line( geometry, material ); - this.add( this.lightPlane ); + _gl.uniform2fv( location, uniform._array ); - geometry = new THREE.Geometry(); - geometry.vertices.push( - new THREE.Vector3(), - new THREE.Vector3() - ); + break; - material = new THREE.LineBasicMaterial( { fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + case 'v3v': - this.targetLine = new THREE.Line( geometry, material ); - this.add( this.targetLine ); + // array of THREE.Vector3 - this.update(); + if ( uniform._array === undefined ) { -}; + uniform._array = new Float32Array( 3 * value.length ); -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; + } -THREE.DirectionalLightHelper.prototype.dispose = function () { + for ( var i = 0, il = value.length; i < il; i ++ ) { - this.lightPlane.geometry.dispose(); - this.lightPlane.material.dispose(); - this.targetLine.geometry.dispose(); - this.targetLine.material.dispose(); -}; + offset = i * 3; -THREE.DirectionalLightHelper.prototype.update = function () { + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; + uniform._array[ offset + 2 ] = value[ i ].z; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); + } - return function () { + _gl.uniform3fv( location, uniform._array ); - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); + break; - this.lightPlane.lookAt( v3 ); - this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + case 'v4v': - this.targetLine.geometry.vertices[ 1 ].copy( v3 ); - this.targetLine.geometry.verticesNeedUpdate = true; - this.targetLine.material.color.copy( this.lightPlane.material.color ); + // array of THREE.Vector4 - }; + if ( uniform._array === undefined ) { -}(); + uniform._array = new Float32Array( 4 * value.length ); -// File:src/extras/helpers/EdgesHelper.js + } -/** - * @author WestLangley / http://github.com/WestLangley - * @param object THREE.Mesh whose geometry will be used - * @param hex line color - * @param thresholdAngle the minimim angle (in degrees), - * between the face normals of adjacent faces, - * that is required to render an edge. A value of 10 means - * an edge is only rendered if the angle is at least 10 degrees. - */ + for ( var i = 0, il = value.length; i < il; i ++ ) { -THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { + offset = i * 4; - var color = ( hex !== undefined ) ? hex : 0xffffff; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + uniform._array[ offset ] = value[ i ].x; + uniform._array[ offset + 1 ] = value[ i ].y; + uniform._array[ offset + 2 ] = value[ i ].z; + uniform._array[ offset + 3 ] = value[ i ].w; - var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) ); + } - var edge = [ 0, 0 ], hash = {}; - var sortFunction = function ( a, b ) { return a - b }; + _gl.uniform4fv( location, uniform._array ); - var keys = [ 'a', 'b', 'c' ]; - var geometry = new THREE.BufferGeometry(); + break; - var geometry2; + case 'm3': - if ( object.geometry instanceof THREE.BufferGeometry ) { + // single THREE.Matrix3 + _gl.uniformMatrix3fv( location, false, value.elements ); - geometry2 = new THREE.Geometry(); - geometry2.fromBufferGeometry( object.geometry ); + break; - } else { + case 'm3v': - geometry2 = object.geometry.clone(); + // array of THREE.Matrix3 - } + if ( uniform._array === undefined ) { - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + uniform._array = new Float32Array( 9 * value.length ); - var vertices = geometry2.vertices; - var faces = geometry2.faces; - var numEdges = 0; + } - for ( var i = 0, l = faces.length; i < l; i ++ ) { + for ( var i = 0, il = value.length; i < il; i ++ ) { - var face = faces[ i ]; + value[ i ].flattenToArrayOffset( uniform._array, i * 9 ); - for ( var j = 0; j < 3; j ++ ) { + } - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + _gl.uniformMatrix3fv( location, false, uniform._array ); - var key = edge.toString(); + break; - if ( hash[ key ] === undefined ) { + case 'm4': - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - numEdges ++; + // single THREE.Matrix4 + _gl.uniformMatrix4fv( location, false, value.elements ); - } else { + break; - hash[ key ].face2 = i; + case 'm4v': - } + // array of THREE.Matrix4 - } + if ( uniform._array === undefined ) { - } + uniform._array = new Float32Array( 16 * value.length ); - var coords = new Float32Array( numEdges * 2 * 3 ); + } - var index = 0; + for ( var i = 0, il = value.length; i < il; i ++ ) { - for ( var key in hash ) { + value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); - var h = hash[ key ]; + } - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { + _gl.uniformMatrix4fv( location, false, uniform._array ); - var vertex = vertices[ h.vert1 ]; - coords[ index ++ ] = vertex.x; - coords[ index ++ ] = vertex.y; - coords[ index ++ ] = vertex.z; + break; - vertex = vertices[ h.vert2 ]; - coords[ index ++ ] = vertex.x; - coords[ index ++ ] = vertex.y; - coords[ index ++ ] = vertex.z; + case 't': - } + // single THREE.Texture (2d or cube) - } + texture = value; + textureUnit = getTextureUnit(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + _gl.uniform1i( location, textureUnit ); - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); + if ( ! texture ) continue; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + if ( texture instanceof THREE.CubeTexture || + ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ -}; + setCubeTexture( texture, textureUnit ); -THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; + } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { -// File:src/extras/helpers/FaceNormalsHelper.js + setCubeTextureDynamic( texture, textureUnit ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + } else { -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { + _this.setTexture( texture, textureUnit ); - this.object = object; + } - this.size = ( size !== undefined ) ? size : 1; + break; - var color = ( hex !== undefined ) ? hex : 0xffff00; + case 'tv': - var width = ( linewidth !== undefined ) ? linewidth : 1; + // array of THREE.Texture (2d) - var geometry = new THREE.Geometry(); + if ( uniform._array === undefined ) { - var faces = this.object.geometry.faces; + uniform._array = []; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } - geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() ); + for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { - } + uniform._array[ i ] = getTextureUnit(); - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); + } - this.matrixAutoUpdate = false; + _gl.uniform1iv( location, uniform._array ); - this.normalMatrix = new THREE.Matrix3(); + for ( var i = 0, il = uniform.value.length; i < il; i ++ ) { - this.update(); + texture = uniform.value[ i ]; + textureUnit = uniform._array[ i ]; -}; + if ( ! texture ) continue; -THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; + _this.setTexture( texture, textureUnit ); -THREE.FaceNormalsHelper.prototype.update = function () { + } - var vertices = this.geometry.vertices; + break; - var object = this.object; - var objectVertices = object.geometry.vertices; - var objectFaces = object.geometry.faces; - var objectWorldMatrix = object.matrixWorld; + default: - object.updateMatrixWorld( true ); + THREE.warn( 'THREE.Canvas3DRenderer: Unknown uniform type: ' + type ); - this.normalMatrix.getNormalMatrix( objectWorldMatrix ); + } - for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) { + } - var face = objectFaces[ i ]; + } - vertices[ i2 ].copy( objectVertices[ face.a ] ) - .add( objectVertices[ face.b ] ) - .add( objectVertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( objectWorldMatrix ); + function setupMatrices ( object, camera ) { - vertices[ i2 + 1 ].copy( face.normal ) - .applyMatrix3( this.normalMatrix ) - .normalize() - .multiplyScalar( this.size ) - .add( vertices[ i2 ] ); + object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); } - this.geometry.verticesNeedUpdate = true; + function setColorLinear( array, offset, color, intensity ) { - return this; + array[ offset ] = color.r * intensity; + array[ offset + 1 ] = color.g * intensity; + array[ offset + 2 ] = color.b * intensity; -}; + } + function setupLights ( lights ) { -// File:src/extras/helpers/GridHelper.js + var l, ll, light, + r = 0, g = 0, b = 0, + color, skyColor, groundColor, + intensity, + distance, -/** - * @author mrdoob / http://mrdoob.com/ - */ + zlights = _lights, -THREE.GridHelper = function ( size, step ) { + dirColors = zlights.directional.colors, + dirPositions = zlights.directional.positions, - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + pointColors = zlights.point.colors, + pointPositions = zlights.point.positions, + pointDistances = zlights.point.distances, + pointDecays = zlights.point.decays, - this.color1 = new THREE.Color( 0x444444 ); - this.color2 = new THREE.Color( 0x888888 ); + spotColors = zlights.spot.colors, + spotPositions = zlights.spot.positions, + spotDistances = zlights.spot.distances, + spotDirections = zlights.spot.directions, + spotAnglesCos = zlights.spot.anglesCos, + spotExponents = zlights.spot.exponents, + spotDecays = zlights.spot.decays, - for ( var i = - size; i <= size; i += step ) { + hemiSkyColors = zlights.hemi.skyColors, + hemiGroundColors = zlights.hemi.groundColors, + hemiPositions = zlights.hemi.positions, - geometry.vertices.push( - new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ), - new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size ) - ); + dirLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0, - var color = i === 0 ? this.color1 : this.color2; + dirCount = 0, + pointCount = 0, + spotCount = 0, + hemiCount = 0, - geometry.colors.push( color, color, color, color ); + dirOffset = 0, + pointOffset = 0, + spotOffset = 0, + hemiOffset = 0; - } + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - THREE.Line.call( this, geometry, material, THREE.LinePieces ); + light = lights[ l ]; -}; + if ( light.onlyShadow ) continue; -THREE.GridHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.GridHelper.prototype.constructor = THREE.GridHelper; + color = light.color; + intensity = light.intensity; + distance = light.distance; -THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) { + if ( light instanceof THREE.AmbientLight ) { - this.color1.set( colorCenterLine ); - this.color2.set( colorGrid ); + if ( ! light.visible ) continue; - this.geometry.colorsNeedUpdate = true; + r += color.r; + g += color.g; + b += color.b; -} + } else if ( light instanceof THREE.DirectionalLight ) { -// File:src/extras/helpers/HemisphereLightHelper.js + dirCount += 1; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + if ( ! light.visible ) continue; -THREE.HemisphereLightHelper = function ( light, sphereSize ) { + _direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + _direction.sub( _vector3 ); + _direction.normalize(); - THREE.Object3D.call( this ); + dirOffset = dirLength * 3; - this.light = light; - this.light.updateMatrixWorld(); + dirPositions[ dirOffset ] = _direction.x; + dirPositions[ dirOffset + 1 ] = _direction.y; + dirPositions[ dirOffset + 2 ] = _direction.z; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + setColorLinear( dirColors, dirOffset, color, intensity ); - this.colors = [ new THREE.Color(), new THREE.Color() ]; + dirLength += 1; - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); + } else if ( light instanceof THREE.PointLight ) { - for ( var i = 0, il = 8; i < il; i ++ ) { + pointCount += 1; - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; + if ( ! light.visible ) continue; - } + pointOffset = pointLength * 3; - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); + setColorLinear( pointColors, pointOffset, color, intensity ); - this.lightSphere = new THREE.Mesh( geometry, material ); - this.add( this.lightSphere ); + _vector3.setFromMatrixPosition( light.matrixWorld ); - this.update(); + pointPositions[ pointOffset ] = _vector3.x; + pointPositions[ pointOffset + 1 ] = _vector3.y; + pointPositions[ pointOffset + 2 ] = _vector3.z; -}; + // distance is 0 if decay is 0, because there is no attenuation at all. + pointDistances[ pointLength ] = distance; + pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay; -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; + pointLength += 1; -THREE.HemisphereLightHelper.prototype.dispose = function () { - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); -}; + } else if ( light instanceof THREE.SpotLight ) { -THREE.HemisphereLightHelper.prototype.update = function () { + spotCount += 1; - var vector = new THREE.Vector3(); + if ( ! light.visible ) continue; - return function () { + spotOffset = spotLength * 3; - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); + setColorLinear( spotColors, spotOffset, color, intensity ); - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; + _direction.setFromMatrixPosition( light.matrixWorld ); - } + spotPositions[ spotOffset ] = _direction.x; + spotPositions[ spotOffset + 1 ] = _direction.y; + spotPositions[ spotOffset + 2 ] = _direction.z; -}(); + spotDistances[ spotLength ] = distance; -// File:src/extras/helpers/PointLightHelper.js + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + _direction.sub( _vector3 ); + _direction.normalize(); -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + spotDirections[ spotOffset ] = _direction.x; + spotDirections[ spotOffset + 1 ] = _direction.y; + spotDirections[ spotOffset + 2 ] = _direction.z; -THREE.PointLightHelper = function ( light, sphereSize ) { + spotAnglesCos[ spotLength ] = Math.cos( light.angle ); + spotExponents[ spotLength ] = light.exponent; + spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay; - this.light = light; - this.light.updateMatrixWorld(); + spotLength += 1; - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + } else if ( light instanceof THREE.HemisphereLight ) { - THREE.Mesh.call( this, geometry, material ); + hemiCount += 1; - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + if ( ! light.visible ) continue; - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + _direction.setFromMatrixPosition( light.matrixWorld ); + _direction.normalize(); - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + hemiOffset = hemiLength * 3; - var d = light.distance; + hemiPositions[ hemiOffset ] = _direction.x; + hemiPositions[ hemiOffset + 1 ] = _direction.y; + hemiPositions[ hemiOffset + 2 ] = _direction.z; - if ( d === 0.0 ) { + skyColor = light.color; + groundColor = light.groundColor; - this.lightDistance.visible = false; + setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); + setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); - } else { + hemiLength += 1; - this.lightDistance.scale.set( d, d, d ); + } - } + } - this.add( this.lightDistance ); - */ + // null eventual remains from removed lights + // (this is to avoid if in shader) -}; + for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; + for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; + for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; + for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; + for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; + zlights.directional.length = dirLength; + zlights.point.length = pointLength; + zlights.spot.length = spotLength; + zlights.hemi.length = hemiLength; -THREE.PointLightHelper.prototype.dispose = function () { + zlights.ambient[ 0 ] = r; + zlights.ambient[ 1 ] = g; + zlights.ambient[ 2 ] = b; - this.geometry.dispose(); - this.material.dispose(); -}; + } -THREE.PointLightHelper.prototype.update = function () { + // GL state setting - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - /* - var d = this.light.distance; + if ( cullFace === THREE.CullFaceNone ) { - if ( d === 0.0 ) { + _gl.disable( _gl.CULL_FACE ); - this.lightDistance.visible = false; + } else { - } else { + if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + _gl.frontFace( _gl.CW ); - } - */ + } else { -}; + _gl.frontFace( _gl.CCW ); -// File:src/extras/helpers/SkeletonHelper.js + } -/** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - */ + if ( cullFace === THREE.CullFaceBack ) { -THREE.SkeletonHelper = function ( object ) { + _gl.cullFace( _gl.BACK ); - this.bones = this.getBoneList( object ); + } else if ( cullFace === THREE.CullFaceFront ) { - var geometry = new THREE.Geometry(); + _gl.cullFace( _gl.FRONT ); - for ( var i = 0; i < this.bones.length; i ++ ) { + } else { - var bone = this.bones[ i ]; + _gl.cullFace( _gl.FRONT_AND_BACK ); - if ( bone.parent instanceof THREE.Bone ) { + } - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( 0, 0, 1 ) ); - geometry.colors.push( new THREE.Color( 0, 1, 0 ) ); + _gl.enable( _gl.CULL_FACE ); } - } + }; - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + this.setMaterialFaces = function ( material ) { - THREE.Line.call( this, geometry, material, THREE.LinePieces ); + state.setDoubleSided( material.side === THREE.DoubleSide ); + state.setFlipSided( material.side === THREE.BackSide ); - this.root = object; + }; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + // Textures - this.update(); + function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { -}; + var extension; + if ( isImagePowerOfTwo ) { -THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); -THREE.SkeletonHelper.prototype.getBoneList = function( object ) { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - var boneList = []; + } else { - if ( object instanceof THREE.Bone ) { + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - boneList.push( object ); + if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { - } + THREE.warn( 'THREE.Canvas3DRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' ); - for ( var i = 0; i < object.children.length; i ++ ) { + } - boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - } + if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) { - return boneList; + THREE.warn( 'THREE.Canvas3DRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' ); -}; + } -THREE.SkeletonHelper.prototype.update = function () { + } - var geometry = this.geometry; + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) { - var boneMatrix = new THREE.Matrix4(); + if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) { - var j = 0; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) ); + texture.__currentAnisotropy = texture.anisotropy; - for ( var i = 0; i < this.bones.length; i ++ ) { + } - var bone = this.bones[ i ]; + } - if ( bone.parent instanceof THREE.Bone ) { + } - boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); - geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + this.uploadTexture = function ( texture ) { - boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); + if ( texture instanceof THREE.QuickItemTexture ) { - j += 2; + var canvasTextureProvider = _gl.getExtension("QTCANVAS3D_texture_provider"); - } + texture.__webglInit = true; - } + if ( canvasTextureProvider !== null ) + texture.__webglTexture = canvasTextureProvider.createTextureFromSource(texture.quickItem); + else + texture.__webglTexture = 0; - geometry.verticesNeedUpdate = true; + _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - geometry.computeBoundingSphere(); + var isImagePowerOfTwo = THREE.Math.isPowerOfTwo( texture.quickItem.width ) && THREE.Math.isPowerOfTwo( texture.quickItem.height ); -}; + if (isImagePowerOfTwo) { + _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + } else if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + THREE.warn( 'THREE.Canvas3DRenderer: Quick item width and/or height are not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); + } + } else { -// File:src/extras/helpers/SpotLightHelper.js + if ( texture.__webglInit === undefined ) { -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + texture.__webglInit = true; -THREE.SpotLightHelper = function ( light ) { + texture.addEventListener( 'dispose', onTextureDispose ); - THREE.Object3D.call( this ); + texture.__webglTexture = _gl.createTexture(); - this.light = light; - this.light.updateMatrixWorld(); + _this.info.memory.textures ++; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + } - var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true ); + _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); + texture.image = clampToMaxSize( texture.image, _maxTextureSize ); - this.cone = new THREE.Mesh( geometry, material ); - this.add( this.cone ); + var image = texture.image, + isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - this.update(); + setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); -}; + var mipmap, mipmaps = texture.mipmaps; -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; + if ( texture instanceof THREE.DataTexture ) { -THREE.SpotLightHelper.prototype.dispose = function () { - this.cone.geometry.dispose(); - this.cone.material.dispose(); -}; + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels -THREE.SpotLightHelper.prototype.update = function () { + if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - return function () { + mipmap = mipmaps[ i ]; + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - var coneLength = this.light.distance ? this.light.distance : 10000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + } - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + texture.generateMipmaps = false; - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + } else { - this.cone.lookAt( vector2.sub( vector ) ); + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + } - }; + } else if ( texture instanceof THREE.CompressedTexture ) { -}(); + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { -// File:src/extras/helpers/VertexNormalsHelper.js + mipmap = mipmaps[ i ]; -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { + if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) { - this.object = object; + _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - this.size = ( size !== undefined ) ? size : 1; + } else { - var color = ( hex !== undefined ) ? hex : 0xff0000; + THREE.warn( "THREE.Canvas3DRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - var width = ( linewidth !== undefined ) ? linewidth : 1; + } - var geometry = new THREE.Geometry(); + } else { - var faces = object.geometry.faces; + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } - var face = faces[ i ]; + } - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + } else { // regular Texture (image, video, canvas) - geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() ); + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - } + if ( mipmaps.length > 0 && isImagePowerOfTwo ) { - } + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); + mipmap = mipmaps[ i ]; + _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - this.matrixAutoUpdate = false; + } - this.normalMatrix = new THREE.Matrix3(); + texture.generateMipmaps = false; - this.update(); + } else { -}; + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image.texImage() ); -THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; + } -THREE.VertexNormalsHelper.prototype.update = ( function ( object ) { + } - var v1 = new THREE.Vector3(); + if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + } - return function( object ) { + texture.needsUpdate = false; - var keys = [ 'a', 'b', 'c', 'd' ]; + if ( texture.onUpdate ) texture.onUpdate(); - this.object.updateMatrixWorld( true ); + }; - this.normalMatrix.getNormalMatrix( this.object.matrixWorld ); + this.setTexture = function ( texture, slot ) { - var vertices = this.geometry.vertices; + _gl.activeTexture( _gl.TEXTURE0 + slot ); - var verts = this.object.geometry.vertices; + if ( texture.needsUpdate ) { - var faces = this.object.geometry.faces; + _this.uploadTexture( texture ); - var worldMatrix = this.object.matrixWorld; + } else { - var idx = 0; + _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } - var face = faces[ i ]; + }; - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + function clampToMaxSize ( image, maxSize ) { - var vertexId = face[ keys[ j ] ]; - var vertex = verts[ vertexId ]; + if ( image.width > maxSize || image.height > maxSize ) { - var normal = face.vertexNormals[ j ]; + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); + var scale = maxSize / Math.max( image.width, image.height ); - v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size ); + var canvasWidth = Math.floor( image.width * scale ); + var canvasHeight = Math.floor( image.height * scale ); + var canvas = image.resize( canvasWidth, canvasHeight ); - v1.add( vertices[ idx ] ); - idx = idx + 1; - vertices[ idx ].copy( v1 ); - idx = idx + 1; + THREE.warn( 'THREE.Canvas3DRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvasWidth + 'x' + canvasHeight, image ); - } + return canvas; } - this.geometry.verticesNeedUpdate = true; - - return this; + return image; } -}()); - -// File:src/extras/helpers/VertexTangentsHelper.js + function setCubeTexture ( texture, slot ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + if ( texture.image.length === 6 ) { -THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) { + if ( texture.needsUpdate ) { - this.object = object; + if ( ! texture.image.__webglTextureCube ) { - this.size = ( size !== undefined ) ? size : 1; + texture.addEventListener( 'dispose', onTextureDispose ); - var color = ( hex !== undefined ) ? hex : 0x0000ff; + texture.image.__webglTextureCube = _gl.createTexture(); - var width = ( linewidth !== undefined ) ? linewidth : 1; + _this.info.memory.textures ++; - var geometry = new THREE.Geometry(); + } - var faces = object.geometry.faces; + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - var face = faces[ i ]; + var isCompressed = texture instanceof THREE.CompressedTexture; + var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; - for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { + var cubeImage = []; - geometry.vertices.push( new THREE.Vector3() ); - geometry.vertices.push( new THREE.Vector3() ); + for ( var i = 0; i < 6; i ++ ) { - } + if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) { - } + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces ); + } else { - this.matrixAutoUpdate = false; + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - this.update(); + } -}; + } -THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper; + var image = cubeImage[ 0 ], + isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); -THREE.VertexTangentsHelper.prototype.update = ( function ( object ) { + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); - var v1 = new THREE.Vector3(); + for ( var i = 0; i < 6; i ++ ) { - return function( object ) { + if ( ! isCompressed ) { - var keys = [ 'a', 'b', 'c', 'd' ]; + if ( isDataTexture ) { - this.object.updateMatrixWorld( true ); + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - var vertices = this.geometry.vertices; + } else { - var verts = this.object.geometry.vertices; + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ].texImage() ); - var faces = this.object.geometry.faces; + } - var worldMatrix = this.object.matrixWorld; + } else { - var idx = 0; + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - var face = faces[ i ]; + mipmap = mipmaps[ j ]; - for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) { + if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { - var vertexId = face[ keys[ j ] ]; - var vertex = verts[ vertexId ]; + if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) { - var tangent = face.vertexTangents[ j ]; + _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix ); + } else { - v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size ); + THREE.warn( "THREE.Canvas3DRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" ); - v1.add( vertices[ idx ] ); - idx = idx + 1; + } - vertices[ idx ].copy( v1 ); - idx = idx + 1; + } else { - } + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + } - this.geometry.verticesNeedUpdate = true; + } - return this; + } - } + } -}()); + if ( texture.generateMipmaps && isImagePowerOfTwo ) { -// File:src/extras/helpers/WireframeHelper.js + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.WireframeHelper = function ( object, hex ) { + texture.needsUpdate = false; - var color = ( hex !== undefined ) ? hex : 0xffffff; + if ( texture.onUpdate ) texture.onUpdate(); - var edge = [ 0, 0 ], hash = {}; - var sortFunction = function ( a, b ) { return a - b }; + } else { - var keys = [ 'a', 'b', 'c' ]; - var geometry = new THREE.BufferGeometry(); + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); - if ( object.geometry instanceof THREE.Geometry ) { + } - var vertices = object.geometry.vertices; - var faces = object.geometry.faces; - var numEdges = 0; + } - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); + } - for ( var i = 0, l = faces.length; i < l; i ++ ) { + function setCubeTextureDynamic ( texture, slot ) { - var face = faces[ i ]; + _gl.activeTexture( _gl.TEXTURE0 + slot ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); - for ( var j = 0; j < 3; j ++ ) { + } - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + // Render targets - var key = edge.toString(); + function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { - if ( hash[ key ] === undefined ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + } - } + function setupRenderBuffer ( renderbuffer, renderTarget ) { - } + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - } + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - var coords = new Float32Array( numEdges * 2 * 3 ); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + /* For some reason this is not working. Defaulting to RGBA4. + } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - for ( var j = 0; j < 2; j ++ ) { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + */ + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - var vertex = vertices[ edges [ 2 * i + j] ]; + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; + } else { - } + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); } - geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); - - } else if ( object.geometry instanceof THREE.BufferGeometry ) { + } - if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry + this.setRenderTarget = function ( renderTarget ) { - var vertices = object.geometry.attributes.position.array; - var indices = object.geometry.attributes.index.array; - var drawcalls = object.geometry.drawcalls; - var numEdges = 0; + var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - if ( drawcalls.length === 0 ) { + if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) { - drawcalls = [ { count : indices.length, index : 0, start : 0 } ]; + if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; + if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; - } + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + renderTarget.__webglTexture = _gl.createTexture(); - for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) { + _this.info.memory.textures ++; - var start = drawcalls[ o ].start; - var count = drawcalls[ o ].count; - var index = drawcalls[ o ].index; + // Setup texture, create render and frame buffers - for ( var i = start, il = start + count; i < il; i += 3 ) { + var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), + glFormat = paramThreeToGL( renderTarget.format ), + glType = paramThreeToGL( renderTarget.type ); - for ( var j = 0; j < 3; j ++ ) { + if ( isCube ) { - edge[ 0 ] = index + indices[ i + j ]; - edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); + renderTarget.__webglFramebuffer = []; + renderTarget.__webglRenderbuffer = []; - var key = edge.toString(); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); - if ( hash[ key ] === undefined ) { + for ( var i = 0; i < 6; i ++ ) { - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); - } + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - } + setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); } - } - - var coords = new Float32Array( numEdges * 2 * 3 ); + if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } else { - for ( var j = 0; j < 2; j ++ ) { + renderTarget.__webglFramebuffer = _gl.createFramebuffer(); - var index = 6 * i + 3 * j; - var index2 = 3 * edges[ 2 * i + j]; - coords[ index + 0 ] = vertices[ index2 ]; - coords[ index + 1 ] = vertices[ index2 + 1 ]; - coords[ index + 2 ] = vertices[ index2 + 2 ]; + if ( renderTarget.shareDepthFrom ) { - } + renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; - } + } else { - geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); - } else { // non-indexed BufferGeometry + } - var vertices = object.geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; + _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); - var coords = new Float32Array( numEdges * 2 * 3 ); + _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - for ( var i = 0, l = numTris; i < l; i ++ ) { + setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); - for ( var j = 0; j < 3; j ++ ) { + if ( renderTarget.shareDepthFrom ) { - var index = 18 * i + 6 * j; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); - coords[ index + 3 ] = vertices[ index2 ]; - coords[ index + 4 ] = vertices[ index2 + 1 ]; - coords[ index + 5 ] = vertices[ index2 + 2 ]; + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - } + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); - } + } - geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + } else { - } + setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); - } + } - THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces ); + if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + } -}; + // Release everything -THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype ); -THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; + if ( isCube ) { -// File:src/extras/objects/ImmediateRenderObject.js + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.ImmediateRenderObject = function () { + _gl.bindTexture( _gl.TEXTURE_2D, null ); - THREE.Object3D.call( this ); + } - this.render = function ( renderCallback ) {}; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); -}; + } -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; + var framebuffer, width, height, vx, vy; -// File:src/extras/objects/MorphBlendMesh.js + if ( renderTarget ) { -/** - * @author alteredq / http://alteredqualia.com/ - */ + if ( isCube ) { -THREE.MorphBlendMesh = function( geometry, material ) { + framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; - THREE.Mesh.call( this, geometry, material ); + } else { - this.animationsMap = {}; - this.animationsList = []; + framebuffer = renderTarget.__webglFramebuffer; - // prepare default animation - // (all frames played together in 1 second) + } - var numFrames = this.geometry.morphTargets.length; + width = renderTarget.width; + height = renderTarget.height; - var name = "__default"; + vx = 0; + vy = 0; - var startFrame = 0; - var endFrame = numFrames - 1; + } else { - var fps = numFrames / 1; + framebuffer = null; - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); + width = _viewportWidth; + height = _viewportHeight; -}; + vx = _viewportX; + vy = _viewportY; -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; + } -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + if ( framebuffer !== _currentFramebuffer ) { - var animation = { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.viewport( vx, vy, width, height ); - startFrame: start, - endFrame: end, + _currentFramebuffer = framebuffer; - length: end - start + 1, + } - fps: fps, - duration: ( end - start ) / fps, + _currentWidth = width; + _currentHeight = height; - lastFrame: 0, - currentFrame: 0, + }; - active: false, + this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) { - time: 0, - direction: 1, - weight: 1, + if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) { - directionBackwards: false, - mirroredLoop: false + console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - }; + } - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); + if ( renderTarget.__webglFramebuffer ) { -}; + if ( renderTarget.format !== THREE.RGBAFormat ) { -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { + console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' ); + return; - var pattern = /([a-z]+)_?(\d+)/; + } - var firstAnimation, frameRanges = {}; + var restore = false; - var geometry = this.geometry; + if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) { - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer ); - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); + restore = true; - if ( chunks && chunks.length > 1 ) { + } - var name = chunks[ 1 ]; + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer ); - var range = frameRanges[ name ]; + } else { - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; + console.error( 'THREE.Canvas3DRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - if ( ! firstAnimation ) firstAnimation = name; + } - } + if ( restore ) { - } + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - for ( var name in frameRanges ) { + } - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); + } - } + }; - this.firstAnimation = firstAnimation; + function updateRenderTargetMipmap ( renderTarget ) { -}; + if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - var animation = this.animationsMap[ name ]; + } else { - if ( animation ) { + _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); + _gl.generateMipmap( _gl.TEXTURE_2D ); + _gl.bindTexture( _gl.TEXTURE_2D, null ); - animation.direction = 1; - animation.directionBackwards = false; + } } -}; + // Fallback filters for non-power-of-2 textures -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { + function filterFallback ( f ) { - var animation = this.animationsMap[ name ]; + if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { - if ( animation ) { + return _gl.NEAREST; - animation.direction = - 1; - animation.directionBackwards = true; + } - } + return _gl.LINEAR; -}; + } -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { + // Map three.js constants to WebGL constants - var animation = this.animationsMap[ name ]; + function paramThreeToGL ( p ) { - if ( animation ) { + var extension; - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; + if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; + if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - } + if ( p === THREE.NearestFilter ) return _gl.NEAREST; + if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; -}; + if ( p === THREE.LinearFilter ) return _gl.LINEAR; + if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { + if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - var animation = this.animationsMap[ name ]; + if ( p === THREE.ByteType ) return _gl.BYTE; + if ( p === THREE.ShortType ) return _gl.SHORT; + if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === THREE.IntType ) return _gl.INT; + if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === THREE.FloatType ) return _gl.FLOAT; - if ( animation ) { + extension = extensions.get( 'OES_texture_half_float' ); - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; + if ( extension !== null ) { - } + if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; -}; + } -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + if ( p === THREE.AlphaFormat ) return _gl.ALPHA; + if ( p === THREE.RGBFormat ) return _gl.RGB; + if ( p === THREE.RGBAFormat ) return _gl.RGBA; + if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; + if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - var animation = this.animationsMap[ name ]; + if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; + if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - if ( animation ) { + if ( p === THREE.ZeroFactor ) return _gl.ZERO; + if ( p === THREE.OneFactor ) return _gl.ONE; + if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - animation.weight = weight; + if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; + if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - } + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); -}; + if ( extension !== null ) { -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - var animation = this.animationsMap[ name ]; + } - if ( animation ) { + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - animation.time = time; + if ( extension !== null ) { - } + if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; -}; + } -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { + extension = extensions.get( 'EXT_blend_minmax' ); - var time = 0; + if ( extension !== null ) { - var animation = this.animationsMap[ name ]; + if ( p === THREE.MinEquation ) return extension.MIN_EXT; + if ( p === THREE.MaxEquation ) return extension.MAX_EXT; - if ( animation ) { + } - time = animation.time; + return 0; } - return time; + // Allocations -}; + function allocateBones ( object ) { -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - var duration = - 1; + return 1024; - var animation = this.animationsMap[ name ]; + } else { - if ( animation ) { + // default for when object is not specified + // ( for example when prebuilding shader + // to be used with multiple objects ) + // + // - leave some extra space for other uniforms + // - limit here is ANGLE's 254 max uniform vectors + // (up to 54 should be safe) - duration = animation.duration; + var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - } + var maxBones = nVertexMatrices; - return duration; + if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { -}; + maxBones = Math.min( object.skeleton.bones.length, maxBones ); -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { + if ( maxBones < object.skeleton.bones.length ) { - var animation = this.animationsMap[ name ]; + THREE.warn( 'Canvas3DRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - if ( animation ) { + } - animation.time = 0; - animation.active = true; + } - } else { + return maxBones; - THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + } } -}; + function allocateLights( lights ) { -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { + var dirLights = 0; + var pointLights = 0; + var spotLights = 0; + var hemiLights = 0; - var animation = this.animationsMap[ name ]; + for ( var l = 0, ll = lights.length; l < ll; l ++ ) { - if ( animation ) { + var light = lights[ l ]; - animation.active = false; + if ( light.onlyShadow || light.visible === false ) continue; - } + if ( light instanceof THREE.DirectionalLight ) dirLights ++; + if ( light instanceof THREE.PointLight ) pointLights ++; + if ( light instanceof THREE.SpotLight ) spotLights ++; + if ( light instanceof THREE.HemisphereLight ) hemiLights ++; -}; + } -THREE.MorphBlendMesh.prototype.update = function ( delta ) { + return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights }; - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { + } - var animation = this.animationsList[ i ]; + function allocateShadows( lights ) { - if ( ! animation.active ) continue; + var maxShadows = 0; - var frameTime = animation.duration / animation.length; + for ( var l = 0, ll = lights.length; l < ll; l ++ ) { - animation.time += animation.direction * delta; + var light = lights[ l ]; - if ( animation.mirroredLoop ) { + if ( ! light.castShadow ) continue; - if ( animation.time > animation.duration || animation.time < 0 ) { + if ( light instanceof THREE.SpotLight ) maxShadows ++; + if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; - animation.direction *= - 1; + } - if ( animation.time > animation.duration ) { + return maxShadows; - animation.time = animation.duration; - animation.directionBackwards = true; + } - } + // DEPRECATED - if ( animation.time < 0 ) { + this.initMaterial = function () { - animation.time = 0; - animation.directionBackwards = false; + THREE.warn( 'THREE.Canvas3DRenderer: .initMaterial() has been removed.' ); - } + }; - } + this.addPrePlugin = function () { - } else { + THREE.warn( 'THREE.Canvas3DRenderer: .addPrePlugin() has been removed.' ); - animation.time = animation.time % animation.duration; + }; - if ( animation.time < 0 ) animation.time += animation.duration; + this.addPostPlugin = function () { - } + THREE.warn( 'THREE.Canvas3DRenderer: .addPostPlugin() has been removed.' ); - var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; + }; - if ( keyframe !== animation.currentFrame ) { + this.updateShadowMap = function () { - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + THREE.warn( 'THREE.Canvas3DRenderer: .updateShadowMap() has been removed.' ); - this.morphTargetInfluences[ keyframe ] = 0; + }; - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; +}; - } +// File:src/qml/QuickItemTexture.js - var mix = ( animation.time % frameTime ) / frameTime; +/** + * @author miheikki / miikka.heikkinen@theqtcompany.com + */ - if ( animation.directionBackwards ) mix = 1 - mix; +THREE.QuickItemTexture = function ( quickItem, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; + THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - } + this.generateMipmaps = false; + this._needsUpdate = true; + + this.quickItem = quickItem; }; +THREE.QuickItemTexture.prototype = Object.create( THREE.Texture.prototype ); +THREE.QuickItemTexture.prototype.constructor = THREE.QuickItemTexture; + diff --git a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/glcode.js b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/glcode.js index 8202b42181d0eb4816859aa5593e3125686b9f26..082d605d95110a59638d882c202568c32c1b3387 100644 --- a/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/glcode.js +++ b/share/qtcreator/templates/wizards/projects/qmake/qtcanvas3dapplication/threejs/glcode.js @@ -13,6 +13,7 @@ function initializeGL(canvas) { shading: THREE.SmoothShading }); var cubeGeometry = new THREE.BoxGeometry(1, 1, 1); cube = new THREE.Mesh(cubeGeometry, material); + cube.rotation.set(0.785, 0.785, 0.0); scene.add(cube); renderer = new THREE.Canvas3DRenderer( @@ -29,8 +30,5 @@ function resizeGL(canvas) { } function paintGL(canvas) { - cube.rotation.x += 0.01; - cube.rotation.y += 0.01; - renderer.render(scene, camera); }