diff --git a/build/three.js b/build/three.js index bb11aa65b8ee19..c882a1493c2bee 100644 --- a/build/three.js +++ b/build/three.js @@ -1,41761 +1,41648 @@ -// File:src/Three.js +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.THREE = global.THREE || {}))); +}(this, function (exports) { 'use strict'; -/** - * @author mrdoob / http://mrdoob.com/ - */ + // Polyfills -var THREE = { REVISION: '79' }; + if ( Number.EPSILON === undefined ) { -// + Number.EPSILON = Math.pow( 2, - 52 ); -if ( typeof define === 'function' && define.amd ) { + } - define( 'three', THREE ); + // -} else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) { + if ( Math.sign === undefined ) { - module.exports = THREE; + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign -} + Math.sign = function ( x ) { -// Polyfills + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; -if ( Number.EPSILON === undefined ) { + }; - Number.EPSILON = Math.pow( 2, - 52 ); + } -} + if ( Function.prototype.name === undefined ) { -// + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name -if ( Math.sign === undefined ) { + Object.defineProperty( Function.prototype, 'name', { - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + get: function () { - Math.sign = function ( x ) { + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + } - }; + } ); -} + } -if ( Function.prototype.name === undefined ) { + if ( Object.assign === undefined ) { - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - Object.defineProperty( Function.prototype, 'name', { + ( function () { - get: function () { + Object.assign = function ( target ) { - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + 'use strict'; - } + if ( target === undefined || target === null ) { - } ); + throw new TypeError( 'Cannot convert undefined or null to object' ); -} + } -if ( Object.assign === undefined ) { + var output = Object( target ); - // Missing in IE. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + for ( var index = 1; index < arguments.length; index ++ ) { - ( function () { + var source = arguments[ index ]; - Object.assign = function ( target ) { + if ( source !== undefined && source !== null ) { - 'use strict'; + for ( var nextKey in source ) { - if ( target === undefined || target === null ) { + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - throw new TypeError( 'Cannot convert undefined or null to object' ); + output[ nextKey ] = source[ nextKey ]; - } + } - var output = Object( target ); + } - for ( var index = 1; index < arguments.length; index ++ ) { + } - var source = arguments[ index ]; + } - if ( source !== undefined && source !== null ) { + return output; - for ( var nextKey in source ) { + }; - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + } )(); - output[ nextKey ] = source[ nextKey ]; + } - } + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ - } + function EventDispatcher () { + this.isEventDispatcher = true;}; - } + Object.assign( EventDispatcher.prototype, { - } + addEventListener: function ( type, listener ) { - return output; + if ( this._listeners === undefined ) this._listeners = {}; - }; + var listeners = this._listeners; - } )(); + if ( listeners[ type ] === undefined ) { -} + listeners[ type ] = []; -// + } -Object.assign( THREE, { + if ( listeners[ type ].indexOf( listener ) === - 1 ) { - // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button + listeners[ type ].push( listener ); - MOUSE: { LEFT: 0, MIDDLE: 1, RIGHT: 2 }, + } - // GL STATE CONSTANTS + }, - CullFaceNone: 0, - CullFaceBack: 1, - CullFaceFront: 2, - CullFaceFrontBack: 3, + hasEventListener: function ( type, listener ) { - FrontFaceDirectionCW: 0, - FrontFaceDirectionCCW: 1, + if ( this._listeners === undefined ) return false; - // SHADOWING TYPES + var listeners = this._listeners; - BasicShadowMap: 0, - PCFShadowMap: 1, - PCFSoftShadowMap: 2, + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - // MATERIAL CONSTANTS + return true; - // side + } - FrontSide: 0, - BackSide: 1, - DoubleSide: 2, + return false; - // shading + }, - FlatShading: 1, - SmoothShading: 2, + removeEventListener: function ( type, listener ) { - // colors + if ( this._listeners === undefined ) return; - NoColors: 0, - FaceColors: 1, - VertexColors: 2, + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - // blending modes + if ( listenerArray !== undefined ) { - NoBlending: 0, - NormalBlending: 1, - AdditiveBlending: 2, - SubtractiveBlending: 3, - MultiplyBlending: 4, - CustomBlending: 5, + var index = listenerArray.indexOf( listener ); - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) + if ( index !== - 1 ) { - AddEquation: 100, - SubtractEquation: 101, - ReverseSubtractEquation: 102, - MinEquation: 103, - MaxEquation: 104, + listenerArray.splice( index, 1 ); - // custom blending destination factors + } - ZeroFactor: 200, - OneFactor: 201, - SrcColorFactor: 202, - OneMinusSrcColorFactor: 203, - SrcAlphaFactor: 204, - OneMinusSrcAlphaFactor: 205, - DstAlphaFactor: 206, - OneMinusDstAlphaFactor: 207, + } - // custom blending source factors + }, - //ZeroFactor: 200, - //OneFactor: 201, - //SrcAlphaFactor: 204, - //OneMinusSrcAlphaFactor: 205, - //DstAlphaFactor: 206, - //OneMinusDstAlphaFactor: 207, - DstColorFactor: 208, - OneMinusDstColorFactor: 209, - SrcAlphaSaturateFactor: 210, + dispatchEvent: function ( event ) { - // depth modes + if ( this._listeners === undefined ) return; - NeverDepth: 0, - AlwaysDepth: 1, - LessDepth: 2, - LessEqualDepth: 3, - EqualDepth: 4, - GreaterEqualDepth: 5, - GreaterDepth: 6, - NotEqualDepth: 7, + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { - // TEXTURE CONSTANTS + event.target = this; - MultiplyOperation: 0, - MixOperation: 1, - AddOperation: 2, + var array = [], i = 0; + var length = listenerArray.length; - // Tone Mapping modes + for ( i = 0; i < length; i ++ ) { - NoToneMapping: 0, // do not do any tone mapping, not even exposure (required for special purpose passes.) - LinearToneMapping: 1, // only apply exposure. - ReinhardToneMapping: 2, - Uncharted2ToneMapping: 3, // John Hable - CineonToneMapping: 4, // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson + array[ i ] = listenerArray[ i ]; - // Mapping modes + } - UVMapping: 300, + for ( i = 0; i < length; i ++ ) { - CubeReflectionMapping: 301, - CubeRefractionMapping: 302, + array[ i ].call( this, event ); - EquirectangularReflectionMapping: 303, - EquirectangularRefractionMapping: 304, + } - SphericalReflectionMapping: 305, - CubeUVReflectionMapping: 306, - CubeUVRefractionMapping: 307, + } - // Wrapping modes + } + + } ); + + var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; + var CullFaceNone = 0; + var CullFaceBack = 1; + var CullFaceFront = 2; + var CullFaceFrontBack = 3; + var FrontFaceDirectionCW = 0; + var FrontFaceDirectionCCW = 1; + var BasicShadowMap = 0; + var PCFShadowMap = 1; + var PCFSoftShadowMap = 2; + var FrontSide = 0; + var BackSide = 1; + var DoubleSide = 2; + var FlatShading = 1; + var SmoothShading = 2; + var NoColors = 0; + var FaceColors = 1; + var VertexColors = 2; + var NoBlending = 0; + var NormalBlending = 1; + var AdditiveBlending = 2; + var SubtractiveBlending = 3; + var MultiplyBlending = 4; + var CustomBlending = 5; + var AddEquation = 100; + var SubtractEquation = 101; + var ReverseSubtractEquation = 102; + var MinEquation = 103; + var MaxEquation = 104; + var ZeroFactor = 200; + var OneFactor = 201; + var SrcColorFactor = 202; + var OneMinusSrcColorFactor = 203; + var SrcAlphaFactor = 204; + var OneMinusSrcAlphaFactor = 205; + var DstAlphaFactor = 206; + var OneMinusDstAlphaFactor = 207; + var DstColorFactor = 208; + var OneMinusDstColorFactor = 209; + var SrcAlphaSaturateFactor = 210; + var NeverDepth = 0; + var AlwaysDepth = 1; + var LessDepth = 2; + var LessEqualDepth = 3; + var EqualDepth = 4; + var GreaterEqualDepth = 5; + var GreaterDepth = 6; + var NotEqualDepth = 7; + var MultiplyOperation = 0; + var MixOperation = 1; + var AddOperation = 2; + var NoToneMapping = 0; + var LinearToneMapping = 1; + var ReinhardToneMapping = 2; + var Uncharted2ToneMapping = 3; + var CineonToneMapping = 4; + var UVMapping = 300; + var CubeReflectionMapping = 301; + var CubeRefractionMapping = 302; + var EquirectangularReflectionMapping = 303; + var EquirectangularRefractionMapping = 304; + var SphericalReflectionMapping = 305; + var CubeUVReflectionMapping = 306; + var CubeUVRefractionMapping = 307; + var RepeatWrapping = 1000; + var ClampToEdgeWrapping = 1001; + var MirroredRepeatWrapping = 1002; + var NearestFilter = 1003; + var NearestMipMapNearestFilter = 1004; + var NearestMipMapLinearFilter = 1005; + var LinearFilter = 1006; + var LinearMipMapNearestFilter = 1007; + var LinearMipMapLinearFilter = 1008; + var UnsignedByteType = 1009; + var ByteType = 1010; + var ShortType = 1011; + var UnsignedShortType = 1012; + var IntType = 1013; + var UnsignedIntType = 1014; + var FloatType = 1015; + var HalfFloatType = 1025; + var UnsignedShort4444Type = 1016; + var UnsignedShort5551Type = 1017; + var UnsignedShort565Type = 1018; + var AlphaFormat = 1019; + var RGBFormat = 1020; + var RGBAFormat = 1021; + var LuminanceFormat = 1022; + var LuminanceAlphaFormat = 1023; + var RGBEFormat = RGBAFormat; + var DepthFormat = 1026; + var RGB_S3TC_DXT1_Format = 2001; + var RGBA_S3TC_DXT1_Format = 2002; + var RGBA_S3TC_DXT3_Format = 2003; + var RGBA_S3TC_DXT5_Format = 2004; + var RGB_PVRTC_4BPPV1_Format = 2100; + var RGB_PVRTC_2BPPV1_Format = 2101; + var RGBA_PVRTC_4BPPV1_Format = 2102; + var RGBA_PVRTC_2BPPV1_Format = 2103; + var RGB_ETC1_Format = 2151; + var LoopOnce = 2200; + var LoopRepeat = 2201; + var LoopPingPong = 2202; + var InterpolateDiscrete = 2300; + var InterpolateLinear = 2301; + var InterpolateSmooth = 2302; + var ZeroCurvatureEnding = 2400; + var ZeroSlopeEnding = 2401; + var WrapAroundEnding = 2402; + var TrianglesDrawMode = 0; + var TriangleStripDrawMode = 1; + var TriangleFanDrawMode = 2; + var LinearEncoding = 3000; + var sRGBEncoding = 3001; + var GammaEncoding = 3007; + var RGBEEncoding = 3002; + var LogLuvEncoding = 3003; + var RGBM7Encoding = 3004; + var RGBM16Encoding = 3005; + var RGBDEncoding = 3006; + var BasicDepthPacking = 3200; + var RGBADepthPacking = 3201; + + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ + + exports.Math = { + + DEG2RAD: Math.PI / 180, + RAD2DEG: 180 / Math.PI, + + generateUUID: function () { - RepeatWrapping: 1000, - ClampToEdgeWrapping: 1001, - MirroredRepeatWrapping: 1002, + // http://www.broofa.com/Tools/Math.uuid.htm - // Filters + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); + var rnd = 0, r; - NearestFilter: 1003, - NearestMipMapNearestFilter: 1004, - NearestMipMapLinearFilter: 1005, - LinearFilter: 1006, - LinearMipMapNearestFilter: 1007, - LinearMipMapLinearFilter: 1008, + return function generateUUID() { - // Data types + for ( var i = 0; i < 36; i ++ ) { - UnsignedByteType: 1009, - ByteType: 1010, - ShortType: 1011, - UnsignedShortType: 1012, - IntType: 1013, - UnsignedIntType: 1014, - FloatType: 1015, - HalfFloatType: 1025, + if ( i === 8 || i === 13 || i === 18 || i === 23 ) { - // Pixel types + uuid[ i ] = '-'; - //UnsignedByteType: 1009, - UnsignedShort4444Type: 1016, - UnsignedShort5551Type: 1017, - UnsignedShort565Type: 1018, + } else if ( i === 14 ) { - // Pixel formats + uuid[ i ] = '4'; - AlphaFormat: 1019, - RGBFormat: 1020, - RGBAFormat: 1021, - LuminanceFormat: 1022, - LuminanceAlphaFormat: 1023, - // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders - RGBEFormat: THREE.RGBAFormat, //1024; - DepthFormat: 1026, + } else { - // DDS / ST3C Compressed texture formats + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; + r = rnd & 0xf; + rnd = rnd >> 4; + uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; - RGB_S3TC_DXT1_Format: 2001, - RGBA_S3TC_DXT1_Format: 2002, - RGBA_S3TC_DXT3_Format: 2003, - RGBA_S3TC_DXT5_Format: 2004, + } - // PVRTC compressed texture formats + } - RGB_PVRTC_4BPPV1_Format: 2100, - RGB_PVRTC_2BPPV1_Format: 2101, - RGBA_PVRTC_4BPPV1_Format: 2102, - RGBA_PVRTC_2BPPV1_Format: 2103, + return uuid.join( '' ); - // ETC compressed texture formats + }; - RGB_ETC1_Format: 2151, + }(), - // Loop styles for AnimationAction + clamp: function ( value, min, max ) { - LoopOnce: 2200, - LoopRepeat: 2201, - LoopPingPong: 2202, + return Math.max( min, Math.min( max, value ) ); - // Interpolation + }, - InterpolateDiscrete: 2300, - InterpolateLinear: 2301, - InterpolateSmooth: 2302, + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation - // Interpolant ending modes + euclideanModulo: function ( n, m ) { - ZeroCurvatureEnding: 2400, - ZeroSlopeEnding: 2401, - WrapAroundEnding: 2402, + return ( ( n % m ) + m ) % m; - // Triangle Draw modes + }, - TrianglesDrawMode: 0, - TriangleStripDrawMode: 1, - TriangleFanDrawMode: 2, + // Linear mapping from range to range - // Texture Encodings + mapLinear: function ( x, a1, a2, b1, b2 ) { - LinearEncoding: 3000, // No encoding at all. - sRGBEncoding: 3001, - GammaEncoding: 3007, // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources. - // These encodings should not specified as output encodings except in rare situations. - RGBEEncoding: 3002, // AKA Radiance. - LogLuvEncoding: 3003, - RGBM7Encoding: 3004, - RGBM16Encoding: 3005, - RGBDEncoding: 3006, // MaxRange is 256. + }, - // Depth packing strategies + // http://en.wikipedia.org/wiki/Smoothstep - BasicDepthPacking: 3200, // for writing to float textures for high precision or for visualizing results in RGB buffers - RGBADepthPacking: 3201 // for packing into RGBA buffers. + smoothstep: function ( x, min, max ) { -} ); + if ( x <= min ) return 0; + if ( x >= max ) return 1; -// File:src/math/Color.js + x = ( x - min ) / ( max - min ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + return x * x * ( 3 - 2 * x ); -THREE.Color = function ( r, g, b ) { + }, - if ( g === undefined && b === undefined ) { + smootherstep: function ( x, min, max ) { - // r is THREE.Color, hex or string - return this.set( r ); + if ( x <= min ) return 0; + if ( x >= max ) return 1; - } + x = ( x - min ) / ( max - min ); - return this.setRGB( r, g, b ); + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); -}; + }, -THREE.Color.prototype = { + random16: function () { - constructor: THREE.Color, + console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - r: 1, g: 1, b: 1, + }, - set: function ( value ) { + // Random integer from interval - if ( value instanceof THREE.Color ) { + randInt: function ( low, high ) { - this.copy( value ); + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - } else if ( typeof value === 'number' ) { + }, - this.setHex( value ); + // Random float from interval - } else if ( typeof value === 'string' ) { + randFloat: function ( low, high ) { - this.setStyle( value ); + return low + Math.random() * ( high - low ); - } + }, - return this; + // Random float from <-range/2, range/2> interval - }, + randFloatSpread: function ( range ) { - setScalar: function ( scalar ) { + return range * ( 0.5 - Math.random() ); - this.r = scalar; - this.g = scalar; - this.b = scalar; + }, - }, + degToRad: function ( degrees ) { - setHex: function ( hex ) { + return degrees * exports.Math.DEG2RAD; - hex = Math.floor( hex ); + }, - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + radToDeg: function ( radians ) { - return this; + return radians * exports.Math.RAD2DEG; - }, + }, - setRGB: function ( r, g, b ) { + isPowerOfTwo: function ( value ) { - this.r = r; - this.g = g; - this.b = b; + return ( value & ( value - 1 ) ) === 0 && value !== 0; - return this; + }, - }, + nearestPowerOfTwo: function ( value ) { - setHSL: function () { + return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); - function hue2rgb( 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; + nextPowerOfTwo: function ( value ) { - } + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - return function setHSL( h, s, l ) { + return value; - // h,s,l ranges are in 0.0 - 1.0 - h = THREE.Math.euclideanModulo( h, 1 ); - s = THREE.Math.clamp( s, 0, 1 ); - l = THREE.Math.clamp( l, 0, 1 ); + } - if ( s === 0 ) { + }; - this.r = this.g = this.b = l; + /** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - } else { + function Vector2 ( x, y ) { + this.isVector2 = true; - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + this.x = x || 0; + this.y = y || 0; - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + }; - } + Vector2.prototype = { - return this; + constructor: Vector2, - }; + get width() { - }(), + return this.x; - setStyle: function ( style ) { + }, - function handleAlpha( string ) { + set width( value ) { - if ( string === undefined ) return; + this.x = value; - if ( parseFloat( string ) < 1 ) { + }, - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + get height() { - } + return this.y; - } + }, + set height( value ) { - var m; + this.y = value; - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + }, - // rgb / hsl + // - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + set: function ( x, y ) { - switch ( name ) { + this.x = x; + this.y = y; - case 'rgb': - case 'rgba': + return this; - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + }, - // rgb(255,0,0) rgba(255,0,0,0.5) - 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; + setScalar: function ( scalar ) { - handleAlpha( color[ 5 ] ); + this.x = scalar; + this.y = scalar; - return this; + return this; - } + }, - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + setX: function ( x ) { - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - 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; + this.x = x; - handleAlpha( color[ 5 ] ); + return this; - return this; + }, - } + setY: function ( y ) { - break; + this.y = y; - case 'hsl': - case 'hsla': + return this; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + }, - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ) / 360; - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + setComponent: function ( index, value ) { - handleAlpha( color[ 5 ] ); + switch ( index ) { - return this.setHSL( h, s, l ); + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - } + } - break; + }, - } + getComponent: function ( index ) { - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + switch ( index ) { - // hex color + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - var hex = m[ 1 ]; - var size = hex.length; + } - if ( size === 3 ) { + }, - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; + clone: function () { - return this; + return new this.constructor( this.x, this.y ); - } else if ( size === 6 ) { + }, - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; + copy: function ( v ) { - return this; + this.x = v.x; + this.y = v.y; - } + return this; - } + }, - if ( style && style.length > 0 ) { + add: function ( v, w ) { - // color keywords - var hex = THREE.ColorKeywords[ style ]; + if ( w !== undefined ) { - if ( hex !== undefined ) { + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - // red - this.setHex( hex ); + } - } else { + this.x += v.x; + this.y += v.y; - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + return this; - } + }, - } + addScalar: function ( s ) { - return this; + this.x += s; + this.y += s; - }, + return this; - clone: function () { + }, - return new this.constructor( this.r, this.g, this.b ); + addVectors: function ( a, b ) { - }, + this.x = a.x + b.x; + this.y = a.y + b.y; - copy: function ( color ) { + return this; - this.r = color.r; - this.g = color.g; - this.b = color.b; + }, - return this; + addScaledVector: function ( v, s ) { - }, + this.x += v.x * s; + this.y += v.y * s; - copyGammaToLinear: function ( color, gammaFactor ) { + return this; - 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 ); + sub: function ( v, w ) { - return this; + if ( w !== undefined ) { - }, + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - copyLinearToGamma: function ( color, gammaFactor ) { + } - if ( gammaFactor === undefined ) gammaFactor = 2.0; + this.x -= v.x; + this.y -= v.y; - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + return this; - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + }, - return this; + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; - convertGammaToLinear: function () { + return this; - var r = this.r, g = this.g, b = this.b; + }, - this.r = r * r; - this.g = g * g; - this.b = b * b; + subVectors: function ( a, b ) { - return this; + this.x = a.x - b.x; + this.y = a.y - b.y; - }, + return this; - convertLinearToGamma: function () { + }, - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + multiply: function ( v ) { - return this; + this.x *= v.x; + this.y *= v.y; - }, + return this; - getHex: function () { + }, - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + multiplyScalar: function ( scalar ) { - }, + if ( isFinite( scalar ) ) { - getHexString: function () { + this.x *= scalar; + this.y *= scalar; - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + } else { - }, + this.x = 0; + this.y = 0; - getHSL: function ( optionalTarget ) { + } - // h,s,l ranges are in 0.0 - 1.0 + return this; - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + }, - var r = this.r, g = this.g, b = this.b; + divide: function ( v ) { - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + this.x /= v.x; + this.y /= v.y; - var hue, saturation; - var lightness = ( min + max ) / 2.0; + return this; - if ( min === max ) { + }, - hue = 0; - saturation = 0; + divideScalar: function ( scalar ) { - } else { + return this.multiplyScalar( 1 / scalar ); - var delta = max - min; + }, - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + min: function ( v ) { - switch ( max ) { + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - 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; + return this; - } + }, - hue /= 6; + max: function ( v ) { - } + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + return this; - return hsl; + }, - }, + clamp: function ( min, max ) { - getStyle: function () { + // This function assumes min < max, if this assumption isn't true it will not operate correctly - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - }, + return this; - offsetHSL: function ( h, s, l ) { + }, - var hsl = this.getHSL(); + clampScalar: function () { - hsl.h += h; hsl.s += s; hsl.l += l; + var min, max; - this.setHSL( hsl.h, hsl.s, hsl.l ); + return function clampScalar( minVal, maxVal ) { - return this; + if ( min === undefined ) { - }, + min = new Vector2(); + max = new Vector2(); - add: function ( color ) { + } - this.r += color.r; - this.g += color.g; - this.b += color.b; + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - addColors: function ( color1, color2 ) { + }(), - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - addScalar: function ( s ) { + }, - this.r += s; - this.g += s; - this.b += s; + floor: function () { - return this; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - }, + return this; - sub: function( color ) { + }, - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); + ceil: function () { - return this; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - }, + return this; - multiply: function ( color ) { + }, - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + round: function () { - return this; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - }, + return this; - multiplyScalar: function ( s ) { + }, - this.r *= s; - this.g *= s; - this.b *= s; + roundToZero: function () { - return this; + 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 ); - }, + return this; - lerp: function ( color, alpha ) { + }, - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + negate: function () { - return this; + this.x = - this.x; + this.y = - this.y; - }, + return this; - equals: function ( c ) { + }, - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + dot: function ( v ) { - }, + return this.x * v.x + this.y * v.y; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + lengthSq: function () { - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + return this.x * this.x + this.y * this.y; - return this; + }, - }, + length: function () { - toArray: function ( array, offset ) { + return Math.sqrt( this.x * this.x + this.y * this.y ); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + }, - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + lengthManhattan: function() { - return array; + return Math.abs( this.x ) + Math.abs( this.y ); - } + }, -}; + normalize: function () { -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 + return this.divideScalar( this.length() ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + }, -THREE.Quaternion = function ( x, y, z, w ) { + angle: function () { - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + // computes the angle in radians with respect to the positive x-axis -}; + var angle = Math.atan2( this.y, this.x ); -THREE.Quaternion.prototype = { + if ( angle < 0 ) angle += 2 * Math.PI; - constructor: THREE.Quaternion, + return angle; - get x () { + }, - return this._x; + distanceTo: function ( v ) { - }, + return Math.sqrt( this.distanceToSquared( v ) ); - set x ( value ) { + }, - this._x = value; - this.onChangeCallback(); + distanceToSquared: function ( v ) { - }, + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - get y () { + }, - return this._y; + distanceToManhattan: function ( v ) { - }, + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - set y ( value ) { + }, - this._y = value; - this.onChangeCallback(); + setLength: function ( length ) { - }, + return this.multiplyScalar( length / this.length() ); - get z () { + }, - return this._z; + lerp: function ( v, alpha ) { - }, + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - set z ( value ) { + return this; - this._z = value; - this.onChangeCallback(); + }, - }, + lerpVectors: function ( v1, v2, alpha ) { - get w () { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this._w; + }, - }, + equals: function ( v ) { - set w ( value ) { + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - this._w = value; - this.onChangeCallback(); + }, - }, + fromArray: function ( array, offset ) { - set: function ( x, y, z, w ) { + if ( offset === undefined ) offset = 0; - this._x = x; - this._y = y; - this._z = z; - this._w = w; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - this.onChangeCallback(); + return this; - return this; + }, - }, + toArray: function ( array, offset ) { - clone: function () { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return new this.constructor( this._x, this._y, this._z, this._w ); + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - }, + return array; - copy: function ( quaternion ) { + }, - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + fromAttribute: function ( attribute, index, offset ) { - this.onChangeCallback(); + if ( offset === undefined ) offset = 0; - return this; + index = index * attribute.itemSize + offset; - }, + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - setFromEuler: function ( euler, update ) { + return this; - if ( euler instanceof THREE.Euler === false ) { + }, - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + rotateAround: function ( center, angle ) { - } + var c = Math.cos( angle ), s = Math.sin( angle ); - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + var x = this.x - center.x; + var y = this.y - center.y; - 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.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - var order = euler.order; + return this; - if ( order === 'XYZ' ) { + } - 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 ( order === 'YXZ' ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - 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 Texture ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isTexture = true; - } else if ( order === 'ZXY' ) { + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - 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.uuid = exports.Math.generateUUID(); - } else if ( order === 'ZYX' ) { + this.name = ''; + this.sourceFile = ''; - 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.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - } else if ( order === 'YZX' ) { + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - 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.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - } else if ( order === 'XZY' ) { + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - 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.anisotropy = anisotropy !== undefined ? anisotropy : 1; - } + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - if ( update !== false ) this.onChangeCallback(); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); - return this; + 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) - }, - setFromAxisAngle: function ( axis, angle ) { + // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. + // + // Also changing the encoding after already used by a Material will not automatically make the Material + // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. + this.encoding = encoding !== undefined ? encoding : LinearEncoding; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + this.version = 0; + this.onUpdate = null; - // assumes axis is normalized + }; - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + Texture.prototype = { - this.onChangeCallback(); + constructor: Texture, - return this; + set needsUpdate( value ) { - }, + if ( value === true ) this.version ++; - setFromRotationMatrix: function ( m ) { + }, - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + clone: function () { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return new this.constructor().copy( this ); - var te = m.elements, + }, - 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 ], + copy: function ( source ) { - trace = m11 + m22 + m33, - s; + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - if ( trace > 0 ) { + this.mapping = source.mapping; - s = 0.5 / Math.sqrt( trace + 1.0 ); + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - } else if ( m11 > m22 && m11 > m33 ) { + this.anisotropy = source.anisotropy; - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + this.format = source.format; + this.type = source.type; - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); - } else if ( m22 > m33 ) { + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + return this; - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + }, - } else { + toJSON: function ( meta ) { - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + if ( meta.textures[ this.uuid ] !== undefined ) { - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + return meta.textures[ this.uuid ]; - } + } - this.onChangeCallback(); + function getDataURL( image ) { - return this; + var canvas; - }, + if ( image.toDataURL !== undefined ) { - setFromUnitVectors: function () { + canvas = image; - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + } else { - // assumes direction vectors vFrom and vTo are normalized + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - var v1, r; + canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); - var EPS = 0.000001; + } - return function setFromUnitVectors( vFrom, vTo ) { + if ( canvas.width > 2048 || canvas.height > 2048 ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + return canvas.toDataURL( 'image/jpeg', 0.6 ); - r = vFrom.dot( vTo ) + 1; + } else { - if ( r < EPS ) { + return canvas.toDataURL( 'image/png' ); - r = 0; + } - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + } - v1.set( - vFrom.y, vFrom.x, 0 ); + var output = { + metadata: { + version: 4.4, + type: 'Texture', + generator: 'Texture.toJSON' + }, - } else { + uuid: this.uuid, + name: this.name, - v1.set( 0, - vFrom.z, vFrom.y ); + mapping: this.mapping, - } + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + wrap: [ this.wrapS, this.wrapT ], - } else { + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - v1.crossVectors( vFrom, vTo ); + flipY: this.flipY + }; - } + if ( this.image !== undefined ) { - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + // TODO: Move to THREE.Image - return this.normalize(); + var image = this.image; - }; + if ( image.uuid === undefined ) { - }(), + image.uuid = exports.Math.generateUUID(); // UGH - inverse: function () { + } - return this.conjugate().normalize(); + if ( meta.images[ image.uuid ] === undefined ) { - }, + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - conjugate: function () { + } - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + output.image = image.uuid; - this.onChangeCallback(); + } - return this; + meta.textures[ this.uuid ] = output; - }, + return output; - dot: function ( v ) { + }, - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + dispose: function () { - }, + this.dispatchEvent( { type: 'dispose' } ); - lengthSq: function () { + }, - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + transformUv: function ( uv ) { - }, + if ( this.mapping !== UVMapping ) return; - length: function () { + uv.multiply( this.repeat ); + uv.add( this.offset ); - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + if ( uv.x < 0 || uv.x > 1 ) { - }, + switch ( this.wrapS ) { - normalize: function () { + case RepeatWrapping: - var l = this.length(); + uv.x = uv.x - Math.floor( uv.x ); + break; - if ( l === 0 ) { + case ClampToEdgeWrapping: - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + uv.x = uv.x < 0 ? 0 : 1; + break; - } else { + case MirroredRepeatWrapping: - l = 1 / l; + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + uv.x = Math.ceil( uv.x ) - uv.x; - } + } else { - this.onChangeCallback(); + uv.x = uv.x - Math.floor( uv.x ); - return this; + } + break; - }, + } - multiply: function ( q, p ) { + } - if ( p !== undefined ) { + if ( uv.y < 0 || uv.y > 1 ) { - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + switch ( this.wrapT ) { - } + case RepeatWrapping: - return this.multiplyQuaternions( this, q ); + uv.y = uv.y - Math.floor( uv.y ); + break; - }, + case ClampToEdgeWrapping: - premultiply: function ( q ) { + uv.y = uv.y < 0 ? 0 : 1; + break; - return this.multiplyQuaternions( q, this ); + case MirroredRepeatWrapping: - }, + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - multiplyQuaternions: function ( a, b ) { + uv.y = Math.ceil( uv.y ) - uv.y; - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + } else { - 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; + uv.y = uv.y - Math.floor( uv.y ); - 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; + } + break; - this.onChangeCallback(); + } - return this; + } - }, + if ( this.flipY ) { - slerp: function ( qb, t ) { + uv.y = 1 - uv.y; - 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; + } - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + }; - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + Object.assign( Texture.prototype, EventDispatcher.prototype ); - if ( cosHalfTheta < 0 ) { + var count = 0; + function TextureIdCount () { return count++; }; - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + /** + * @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://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - cosHalfTheta = - cosHalfTheta; + function Matrix4 () { + this.isMatrix4 = true; - } else { + this.elements = new Float32Array( [ - this.copy( qb ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - } + ] ); - if ( cosHalfTheta >= 1.0 ) { + if ( arguments.length > 0 ) { - this._w = w; - this._x = x; - this._y = y; - this._z = z; + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - return this; + } - } + }; - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + Matrix4.prototype = { - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + constructor: Matrix4, - 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 ); + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - return this; + var te = this.elements; - } + 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; - var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + return this; - 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 ); + }, - this.onChangeCallback(); + identity: function () { - return this; + this.set( - }, + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - equals: function ( quaternion ) { + ); - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + return this; - }, + }, - fromArray: function ( array, offset ) { + clone: function () { - if ( offset === undefined ) offset = 0; + return new Matrix4().fromArray( this.elements ); - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + }, - this.onChangeCallback(); + copy: function ( m ) { - return this; + this.elements.set( m.elements ); - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + copyPosition: function ( m ) { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + var te = this.elements; + var me = m.elements; - return array; + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - }, + return this; - onChange: function ( callback ) { + }, - this.onChangeCallback = callback; + extractBasis: function ( xAxis, yAxis, zAxis ) { - return this; + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - }, + return this; - onChangeCallback: function () {} + }, -}; + makeBasis: function ( xAxis, yAxis, zAxis ) { -Object.assign( THREE.Quaternion, { + 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 + ); - slerp: function( qa, qb, qm, t ) { + return this; - return qm.copy( qa ).slerp( qb, t ); + }, - }, + extractRotation: function () { - slerpFlat: function( - dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + var v1; - // fuzz-free, array-based Quaternion SLERP operation + return function extractRotation( m ) { - var x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ], + if ( v1 === undefined ) v1 = new Vector3(); - x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + var te = this.elements; + var me = m.elements; - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - var s = 1 - t, + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + return this; - var sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + }; - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + }(), - } + makeRotationFromEuler: function ( euler ) { - var tDir = t * dir; + if ( (euler && euler.isEuler) === false ) { - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + } - var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + var te = this.elements; - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + 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 ); - } + if ( euler.order === 'XYZ' ) { - } + var ae = a * e, af = a * f, be = b * e, bf = b * f; - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - } + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; -} ); + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; -// File:src/math/Vector2.js + } else if ( euler.order === 'YXZ' ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + var ce = c * e, cf = c * f, de = d * e, df = d * f; -THREE.Vector2 = function ( x, y ) { + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - this.x = x || 0; - this.y = y || 0; + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; -}; + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; -THREE.Vector2.prototype = { + } else if ( euler.order === 'ZXY' ) { - constructor: THREE.Vector2, + var ce = c * e, cf = c * f, de = d * e, df = d * f; - get width() { + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - return this.x; + 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; - set width( value ) { + } else if ( euler.order === 'ZYX' ) { - this.x = value; + 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; - get height() { + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - return this.y; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'YZX' ) { - set height( value ) { + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - this.y = value; + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - }, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - // + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - set: function ( x, y ) { + } else if ( euler.order === 'XZY' ) { - this.x = x; - this.y = y; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - return this; + 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; - setScalar: function ( scalar ) { + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - this.x = scalar; - this.y = scalar; + } - return this; + // 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; - setX: function ( x ) { + return this; - this.x = x; + }, - return this; + makeRotationFromQuaternion: function ( q ) { - }, + var te = this.elements; - setY: function ( y ) { + 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; - this.y = y; + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - return this; + 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 ); - setComponent: function ( index, value ) { + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - switch ( index ) { + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + return this; - } + }, - }, + lookAt: function () { - getComponent: function ( index ) { + var x, y, z; - switch ( index ) { + return function lookAt( eye, target, up ) { - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + if ( x === undefined ) { - } + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); - }, + } - clone: function () { + var te = this.elements; - return new this.constructor( this.x, this.y ); + z.subVectors( eye, target ).normalize(); - }, + if ( z.lengthSq() === 0 ) { - copy: function ( v ) { + z.z = 1; - this.x = v.x; - this.y = v.y; + } - return this; + x.crossVectors( up, z ).normalize(); - }, + if ( x.lengthSq() === 0 ) { - add: function ( v, w ) { + z.z += 0.0001; + x.crossVectors( up, z ).normalize(); - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + y.crossVectors( z, x ); - } - this.x += v.x; - this.y += v.y; + 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; - return this; + return this; - }, + }; - addScalar: function ( s ) { + }(), - this.x += s; - this.y += s; + multiply: function ( m, n ) { - return this; + if ( n !== undefined ) { - }, + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - addVectors: function ( a, b ) { + } - this.x = a.x + b.x; - this.y = a.y + b.y; + return this.multiplyMatrices( this, m ); - return this; + }, - }, + premultiply: function ( m ) { - addScaledVector: function ( v, s ) { + return this.multiplyMatrices( m, this ); - this.x += v.x * s; - this.y += v.y * s; + }, - return this; + multiplyMatrices: function ( a, b ) { - }, + var ae = a.elements; + var be = b.elements; + var te = this.elements; - sub: function ( v, w ) { + 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 ]; - if ( w !== undefined ) { + 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 ]; - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + 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; - } + 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; - this.x -= v.x; - this.y -= v.y; + 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; - return this; + 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; - }, + return this; - subScalar: function ( s ) { + }, - this.x -= s; - this.y -= s; + multiplyToArray: function ( a, b, r ) { - return this; + var te = this.elements; - }, + this.multiplyMatrices( a, b ); - subVectors: function ( a, b ) { + 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 ]; - this.x = a.x - b.x; - this.y = a.y - b.y; + return this; - return this; + }, - }, + multiplyScalar: function ( s ) { - multiply: function ( v ) { + var te = this.elements; - this.x *= v.x; - this.y *= v.y; + 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; - return this; + return this; - }, + }, - multiplyScalar: function ( scalar ) { + applyToVector3Array: function () { - if ( isFinite( scalar ) ) { + var v1; - this.x *= scalar; - this.y *= scalar; + return function applyToVector3Array( array, offset, length ) { - } else { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - this.x = 0; - this.y = 0; + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - } + v1.fromArray( array, j ); + v1.applyMatrix4( this ); + v1.toArray( array, j ); - return this; + } - }, + return array; - divide: function ( v ) { + }; - this.x /= v.x; - this.y /= v.y; + }(), - return this; + applyToBuffer: function () { - }, + var v1; - divideScalar: function ( scalar ) { + return function applyToBuffer( buffer, offset, length ) { - return this.multiplyScalar( 1 / scalar ); + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - }, + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - min: function ( v ) { + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); + v1.applyMatrix4( this ); - return this; + buffer.setXYZ( v1.x, v1.y, v1.z ); - }, + } - max: function ( v ) { + return buffer; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); + }; - return this; + }(), - }, + determinant: function () { - clamp: function ( min, max ) { + var te = this.elements; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + 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 ]; - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - return this; + 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 + ) - }, + ); - clampScalar: function () { + }, - var min, max; + transpose: function () { - return function clampScalar( minVal, maxVal ) { + var te = this.elements; + var tmp; - if ( min === undefined ) { + 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; - min = new THREE.Vector2(); - max = new THREE.Vector2(); + 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; - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + }, - return this.clamp( min, max ); + flattenToArrayOffset: function ( array, offset ) { - }; + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - }(), + return this.toArray( array, offset ); - clampLength: function ( min, max ) { + }, - var length = this.length(); + getPosition: function () { - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + var v1; - }, + return function getPosition() { - floor: function () { + if ( v1 === undefined ) v1 = new Vector3(); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + return v1.setFromMatrixColumn( this, 3 ); - return this; + }; - }, + }(), - ceil: function () { + setPosition: function ( v ) { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + var te = this.elements; - return this; + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - }, + return this; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + getInverse: function ( m, throwOnDegenerate ) { - return this; + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - }, + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - roundToZero: function () { + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - 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 ); + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - return this; + if ( det === 0 ) { - }, + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - negate: function () { + if ( throwOnDegenerate || false ) {} else { - this.x = - this.x; - this.y = - this.y; + console.warn( msg ); - return this; + } - }, + return this.identity(); - dot: function ( v ) { + } + + var detInv = 1 / det; - return this.x * v.x + this.y * v.y; + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - }, + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - lengthSq: function () { + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - return this.x * this.x + this.y * this.y; + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - }, + return this; - length: function () { + }, - return Math.sqrt( this.x * this.x + this.y * this.y ); + scale: function ( v ) { - }, + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - lengthManhattan: function() { + 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 Math.abs( this.x ) + Math.abs( this.y ); + return this; - }, + }, - normalize: function () { + getMaxScaleOnAxis: function () { - return this.divideScalar( this.length() ); + var te = this.elements; - }, + 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 ]; - angle: function () { + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - // computes the angle in radians with respect to the positive x-axis + }, - var angle = Math.atan2( this.y, this.x ); + makeTranslation: function ( x, y, z ) { - if ( angle < 0 ) angle += 2 * Math.PI; + this.set( - return angle; + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - }, + ); - distanceTo: function ( v ) { + return this; - return Math.sqrt( this.distanceToSquared( v ) ); + }, - }, + makeRotationX: function ( theta ) { - distanceToSquared: function ( v ) { + var c = Math.cos( theta ), s = Math.sin( theta ); - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + this.set( - }, + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - distanceToManhattan: function ( v ) { + ); - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + return this; - }, + }, - setLength: function ( length ) { + makeRotationY: function ( theta ) { - return this.multiplyScalar( length / this.length() ); + var c = Math.cos( theta ), s = Math.sin( theta ); - }, + this.set( - lerp: function ( v, alpha ) { + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + ); - return this; + return this; - }, + }, - lerpVectors: function ( v1, v2, alpha ) { + makeRotationZ: function ( theta ) { - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + var c = Math.cos( theta ), s = Math.sin( theta ); - }, + this.set( - equals: function ( v ) { + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + ); - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + makeRotationAxis: function ( axis, angle ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + // Based on http://www.gamedev.net/reference/articles/article1199.asp - return this; + 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( - toArray: function ( array, offset ) { + 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 - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + return this; - return array; + }, - }, + makeScale: function ( x, y, z ) { - fromAttribute: function ( attribute, index, offset ) { + this.set( - if ( offset === undefined ) offset = 0; + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - index = index * attribute.itemSize + offset; + ); - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + return this; - return this; + }, - }, + compose: function ( position, quaternion, scale ) { - rotateAround: function ( center, angle ) { + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - var c = Math.cos( angle ), s = Math.sin( angle ); + return this; - var x = this.x - center.x; - var y = this.y - center.y; + }, - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; + decompose: function () { - return this; + var vector, matrix; - } + return function decompose( position, quaternion, scale ) { -}; + if ( vector === undefined ) { -// File:src/math/Vector3.js + vector = new Vector3(); + matrix = new Matrix4(); -/** - * @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 - */ + } -THREE.Vector3 = function ( x, y, z ) { + var te = this.elements; - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + 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 ) { -THREE.Vector3.prototype = { + sx = - sx; - constructor: THREE.Vector3, + } - set: function ( x, y, z ) { + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - this.x = x; - this.y = y; - this.z = z; + // scale the rotation part - return this; + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - }, + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - setScalar: function ( scalar ) { + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - this.x = scalar; - this.y = scalar; - this.z = scalar; + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - return this; + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - }, + quaternion.setFromRotationMatrix( matrix ); - setX: function ( x ) { + scale.x = sx; + scale.y = sy; + scale.z = sz; - this.x = x; + return this; - return this; + }; - }, + }(), - setY: function ( y ) { + makeFrustum: function ( left, right, bottom, top, near, far ) { - this.y = y; + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - return this; + 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; - setZ: function ( z ) { + return this; - this.z = z; + }, - return this; + makePerspective: function ( fov, aspect, near, far ) { - }, + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - setComponent: function ( index, value ) { + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - switch ( index ) { + }, - 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 ); + makeOrthographic: function ( left, right, top, bottom, near, far ) { - } + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - }, + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; - getComponent: function ( index ) { + 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; - switch ( index ) { + return this; - 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 ); + }, - } + equals: function ( matrix ) { - }, + var te = this.elements; + var me = matrix.elements; - clone: function () { + for ( var i = 0; i < 16; i ++ ) { - return new this.constructor( this.x, this.y, this.z ); + if ( te[ i ] !== me[ i ] ) return false; - }, + } - copy: function ( v ) { + return true; - this.x = v.x; - this.y = v.y; - this.z = v.z; + }, - return this; + fromArray: function ( array ) { - }, + this.elements.set( array ); - add: function ( v, w ) { + return this; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.x += v.x; - this.y += v.y; - this.z += v.z; + var te = this.elements; - return this; + 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 ]; - addScalar: function ( s ) { + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - this.x += s; - this.y += s; - this.z += s; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - return this; + return array; - }, + } - addVectors: function ( a, b ) { + }; - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - return this; + function Quaternion ( x, y, z, w ) { + this.isQuaternion = true; - }, + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - addScaledVector: function ( v, s ) { + }; - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + Quaternion.prototype = { - return this; + constructor: Quaternion, - }, + get x () { - sub: function ( v, w ) { + return this._x; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + set x ( value ) { - } + this._x = value; + this.onChangeCallback(); - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + }, - return this; + get y () { - }, + return this._y; - subScalar: function ( s ) { + }, - this.x -= s; - this.y -= s; - this.z -= s; + set y ( value ) { - return this; + this._y = value; + this.onChangeCallback(); - }, + }, - subVectors: function ( a, b ) { + get z () { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + return this._z; - return this; + }, - }, + set z ( value ) { - multiply: function ( v, w ) { + this._z = value; + this.onChangeCallback(); - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + get w () { - } + return this._w; - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + }, - return this; + set w ( value ) { - }, + this._w = value; + this.onChangeCallback(); - multiplyScalar: function ( scalar ) { + }, - if ( isFinite( scalar ) ) { + set: function ( x, y, z, w ) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + this._x = x; + this._y = y; + this._z = z; + this._w = w; - } else { + this.onChangeCallback(); - this.x = 0; - this.y = 0; - this.z = 0; + return this; - } + }, - return this; + clone: function () { - }, + return new this.constructor( this._x, this._y, this._z, this._w ); - multiplyVectors: function ( a, b ) { + }, - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + copy: function ( quaternion ) { - return this; + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - }, + this.onChangeCallback(); - applyEuler: function () { + return this; - var quaternion; + }, - return function applyEuler( euler ) { + setFromEuler: function ( euler, update ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - } + } - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - return this.applyQuaternion( quaternion.setFromEuler( euler ) ); + 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 ); - }; + var order = euler.order; - }(), + if ( order === 'XYZ' ) { - applyAxisAngle: 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; - var quaternion; + } else if ( order === 'YXZ' ) { - return function applyAxisAngle( axis, angle ) { + 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 ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + } else if ( order === 'ZXY' ) { - return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + 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 ( order === 'ZYX' ) { - }(), + 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; - applyMatrix3: function ( m ) { + } else if ( order === 'YZX' ) { - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + 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.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; + } else if ( order === 'XZY' ) { - return this; + 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; - }, + } - applyMatrix4: function ( m ) { + if ( update !== false ) this.onChangeCallback(); - // input: THREE.Matrix4 affine matrix + return this; - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + }, - 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 ]; + setFromAxisAngle: function ( axis, angle ) { - return this; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - }, + // assumes axis is normalized - applyProjection: function ( m ) { + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - // input: THREE.Matrix4 projection matrix + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - 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 + this.onChangeCallback(); - 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; - return this; + }, - }, + setFromRotationMatrix: function ( m ) { - applyQuaternion: function ( q ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - var x = this.x, y = this.y, z = this.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - // calculate quat * vector + var te = m.elements, - 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; + 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 ], - // calculate result * inverse quat + trace = m11 + m22 + m33, + s; - 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; + if ( trace > 0 ) { - return this; + s = 0.5 / Math.sqrt( trace + 1.0 ); - }, + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - project: function () { + } else if ( m11 > m22 && m11 > m33 ) { - var matrix; + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - return function project( camera ) { + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + } else if ( m22 > m33 ) { - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - }; + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - }(), + } else { - unproject: function () { + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - var matrix; + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - return function unproject( camera ) { + } - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + this.onChangeCallback(); - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + return this; - }; + }, - }(), + setFromUnitVectors: function () { - transformDirection: function ( m ) { + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + // assumes direction vectors vFrom and vTo are normalized - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + var v1, r; - 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; + var EPS = 0.000001; - return this.normalize(); + return function setFromUnitVectors( vFrom, vTo ) { - }, + if ( v1 === undefined ) v1 = new Vector3(); - divide: function ( v ) { + r = vFrom.dot( vTo ) + 1; - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; + if ( r < EPS ) { - return this; + r = 0; - }, + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - divideScalar: function ( scalar ) { + v1.set( - vFrom.y, vFrom.x, 0 ); - return this.multiplyScalar( 1 / scalar ); + } else { - }, + v1.set( 0, - vFrom.z, vFrom.y ); - min: function ( v ) { + } - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); + } else { - return this; + v1.crossVectors( vFrom, vTo ); - }, + } - max: function ( v ) { + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); + return this.normalize(); - return this; + }; - }, + }(), - clamp: function ( min, max ) { + inverse: function () { - // This function assumes min < max, if this assumption isn't true it will not operate correctly + return this.conjugate().normalize(); - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + }, - return this; + conjugate: function () { - }, + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - clampScalar: function () { + this.onChangeCallback(); - var min, max; + return this; - return function clampScalar( minVal, maxVal ) { + }, - if ( min === undefined ) { + dot: function ( v ) { - min = new THREE.Vector3(); - max = new THREE.Vector3(); + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - } + }, - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); + lengthSq: function () { - return this.clamp( min, max ); + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - }; + }, - }(), + length: function () { - clampLength: function ( min, max ) { + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - var length = this.length(); + }, - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + normalize: function () { - }, + var l = this.length(); - floor: function () { + if ( l === 0 ) { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - return this; + } else { - }, + l = 1 / l; - ceil: function () { + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + } - return this; + this.onChangeCallback(); - }, + return this; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + multiply: function ( q, p ) { - return this; + if ( p !== undefined ) { - }, + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - 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.multiplyQuaternions( this, q ); - return this; + }, - }, + premultiply: function ( q ) { - negate: function () { + return this.multiplyQuaternions( q, this ); - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + }, - return this; + multiplyQuaternions: function ( a, b ) { - }, + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - dot: function ( v ) { + 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; - return this.x * v.x + this.y * v.y + this.z * v.z; + 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(); - lengthSq: function () { + return this; - return this.x * this.x + this.y * this.y + this.z * this.z; + }, - }, + slerp: function ( qb, t ) { - length: function () { + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + var x = this._x, y = this._y, z = this._z, w = this._w; - }, + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - lengthManhattan: function () { + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + if ( cosHalfTheta < 0 ) { - }, + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - normalize: function () { + cosHalfTheta = - cosHalfTheta; - return this.divideScalar( this.length() ); + } else { - }, + this.copy( qb ); - setLength: function ( length ) { + } - return this.multiplyScalar( length / this.length() ); + if ( cosHalfTheta >= 1.0 ) { - }, + this._w = w; + this._x = x; + this._y = y; + this._z = z; - lerp: function ( v, alpha ) { + return this; - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + } - return this; + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - }, + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - lerpVectors: function ( v1, v2, alpha ) { + 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 ); - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + return this; - }, + } - cross: function ( v, w ) { + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - if ( w !== undefined ) { + 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 ); - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + this.onChangeCallback(); - } + return this; - var x = this.x, y = this.y, z = this.z; + }, - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + equals: function ( quaternion ) { - return this; + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - }, + }, - crossVectors: function ( a, b ) { + fromArray: function ( array, offset ) { - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + if ( offset === undefined ) offset = 0; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - return this; + this.onChangeCallback(); - }, + return this; - projectOnVector: function ( vector ) { + }, - var scalar = vector.dot( this ) / vector.lengthSq(); - - return this.copy( vector ).multiplyScalar( scalar ); - - }, + toArray: function ( array, offset ) { - projectOnPlane: function () { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - var v1; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - return function projectOnPlane( planeNormal ) { + return array; - if ( v1 === undefined ) v1 = new THREE.Vector3(); + }, - v1.copy( this ).projectOnVector( planeNormal ); + onChange: function ( callback ) { - return this.sub( v1 ); + this.onChangeCallback = callback; - }; + return this; - }(), + }, - reflect: function () { + onChangeCallback: function () {} - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + }; - var v1; + Object.assign( Quaternion, { - return function reflect( normal ) { + slerp: function( qa, qb, qm, t ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + return qm.copy( qa ).slerp( qb, t ); - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + }, - }; + slerpFlat: function( + dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - }(), + // fuzz-free, array-based Quaternion SLERP operation - angleTo: function ( v ) { + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - // clamp, to handle numerical problems + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + var s = 1 - t, - }, + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - distanceTo: function ( v ) { + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - return Math.sqrt( this.distanceToSquared( v ) ); + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - }, + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - distanceToSquared: function ( v ) { + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + } - return dx * dx + dy * dy + dz * dz; + var tDir = t * dir; - }, + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - distanceToManhattan: function ( v ) { + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - }, + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - setFromSpherical: function( s ) { + } - var sinPhiRadius = Math.sin( s.phi ) * s.radius; + } - this.x = sinPhiRadius * Math.sin( s.theta ); - this.y = Math.cos( s.phi ) * s.radius; - this.z = sinPhiRadius * Math.cos( s.theta ); + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - return this; + } - }, + } ); - setFromMatrixPosition: function ( m ) { + /** + * @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 + */ - return this.setFromMatrixColumn( m, 3 ); + function Vector3 ( x, y, z ) { + this.isVector3 = true; - }, + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - setFromMatrixScale: function ( m ) { + }; - var sx = this.setFromMatrixColumn( m, 0 ).length(); - var sy = this.setFromMatrixColumn( m, 1 ).length(); - var sz = this.setFromMatrixColumn( m, 2 ).length(); + Vector3.prototype = { - this.x = sx; - this.y = sy; - this.z = sz; + constructor: Vector3, - return this; + set: function ( x, y, z ) { - }, + this.x = x; + this.y = y; + this.z = z; - setFromMatrixColumn: function ( m, index ) { + return this; - if ( typeof m === 'number' ) { + }, - console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); - var temp = m - m = index; - index = temp; + setScalar: function ( scalar ) { - } + this.x = scalar; + this.y = scalar; + this.z = scalar; - return this.fromArray( m.elements, index * 4 ); + return this; - }, + }, - equals: function ( v ) { + setX: function ( x ) { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + this.x = x; - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + setY: function ( y ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + this.y = y; - return this; + return this; - }, + }, - toArray: function ( array, offset ) { + setZ: function ( z ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + this.z = z; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + return this; - return array; + }, - }, + setComponent: function ( index, value ) { - fromAttribute: function ( attribute, index, offset ) { + switch ( index ) { - if ( offset === undefined ) offset = 0; + 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 ); - index = index * attribute.itemSize + offset; + } - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + }, - return this; + 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 ); -// File:src/math/Vector4.js + } -/** - * @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 - */ + }, -THREE.Vector4 = function ( x, y, z, w ) { + clone: function () { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + return new this.constructor( this.x, this.y, this.z ); -}; + }, -THREE.Vector4.prototype = { + copy: function ( v ) { - constructor: THREE.Vector4, + this.x = v.x; + this.y = v.y; + this.z = v.z; - set: function ( x, y, z, w ) { + return this; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + }, - return this; + add: function ( v, w ) { - }, + if ( w !== undefined ) { - setScalar: function ( scalar ) { + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + } - return this; + this.x += v.x; + this.y += v.y; + this.z += v.z; - }, + return this; - setX: function ( x ) { + }, - this.x = x; + addScalar: function ( s ) { - return this; + this.x += s; + this.y += s; + this.z += s; - }, + return this; - setY: function ( y ) { + }, - this.y = y; + addVectors: function ( a, b ) { - return this; + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - }, + return this; - setZ: function ( z ) { + }, - this.z = z; + addScaledVector: function ( v, s ) { - return this; + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - }, + return this; - setW: function ( w ) { + }, - this.w = w; + sub: function ( v, w ) { - return this; + if ( w !== undefined ) { - }, + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - setComponent: function ( index, value ) { + } - switch ( index ) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - 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 ); + return this; - } + }, - }, + subScalar: function ( s ) { - getComponent: function ( index ) { + this.x -= s; + this.y -= s; + this.z -= s; - switch ( index ) { + return this; - 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 ); + }, - } + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - clone: function () { + return this; - return new this.constructor( this.x, this.y, this.z, this.w ); + }, - }, + multiply: function ( v, w ) { - copy: function ( v ) { + if ( w !== undefined ) { - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - return this; + } - }, + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - add: function ( v, w ) { + return this; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + multiplyScalar: function ( scalar ) { - } + if ( isFinite( scalar ) ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - return this; + } else { - }, + this.x = 0; + this.y = 0; + this.z = 0; - addScalar: function ( s ) { + } - this.x += s; - this.y += s; - this.z += s; - this.w += s; + return this; - return this; + }, - }, + multiplyVectors: function ( a, b ) { - addVectors: function ( a, b ) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + return this; - return this; + }, - }, + applyEuler: function () { - addScaledVector: function ( v, s ) { + var quaternion; - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + return function applyEuler( euler ) { - return this; + if ( (euler && euler.isEuler) === false ) { - }, + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - sub: function ( v, w ) { + } - if ( w !== undefined ) { + if ( quaternion === undefined ) quaternion = new Quaternion(); - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + return this.applyQuaternion( quaternion.setFromEuler( euler ) ); - } + }; - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + }(), - return this; + applyAxisAngle: function () { - }, + var quaternion; - subScalar: function ( s ) { + return function applyAxisAngle( axis, angle ) { - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + if ( quaternion === undefined ) quaternion = new Quaternion(); - return this; + return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - }, + }; - subVectors: function ( a, b ) { + }(), - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + applyMatrix3: function ( m ) { - return this; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - }, + 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; - multiplyScalar: function ( scalar ) { + return this; - if ( isFinite( scalar ) ) { + }, - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + applyMatrix4: function ( m ) { - } else { + // input: THREE.Matrix4 affine matrix - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - } + 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 ]; - return this; + return this; - }, + }, - applyMatrix4: function ( m ) { + applyProjection: function ( m ) { - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + // input: THREE.Matrix4 projection matrix - 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 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 this; + 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; - divideScalar: function ( scalar ) { + }, - return this.multiplyScalar( 1 / scalar ); + applyQuaternion: function ( q ) { - }, + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - setAxisAngleFromQuaternion: function ( q ) { + // calculate quat * vector - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + 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; - // q is assumed to be normalized + // calculate result * inverse quat - this.w = 2 * Math.acos( q.w ); + 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; - var s = Math.sqrt( 1 - q.w * q.w ); + return this; - if ( s < 0.0001 ) { + }, - this.x = 1; - this.y = 0; - this.z = 0; + project: function () { - } else { + var matrix; - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + return function project( camera ) { - } + if ( matrix === undefined ) matrix = new Matrix4(); - return this; + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - }, + }; - setAxisAngleFromRotationMatrix: function ( m ) { + }(), - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + unproject: function () { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + var matrix; - 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 + return function unproject( camera ) { - te = m.elements, + if ( matrix === undefined ) matrix = new Matrix4(); - 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 ]; + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + }; - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + }(), - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + transformDirection: function ( m ) { - // this singularity is identity matrix so angle = 0 + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - this.set( 1, 0, 0, 0 ); + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - return this; // zero angle, arbitrary axis + 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; - } + return this.normalize(); - // otherwise this singularity is angle = 180 + }, - angle = Math.PI; + divide: function ( v ) { - 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; + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - if ( ( xx > yy ) && ( xx > zz ) ) { + return this; - // m11 is the largest diagonal term + }, - if ( xx < epsilon ) { + divideScalar: function ( scalar ) { - x = 0; - y = 0.707106781; - z = 0.707106781; + return this.multiplyScalar( 1 / scalar ); - } else { + }, - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + min: function ( v ) { - } + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - } else if ( yy > zz ) { + return this; - // m22 is the largest diagonal term + }, - if ( yy < epsilon ) { + max: function ( v ) { - x = 0.707106781; - y = 0; - z = 0.707106781; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - } else { + return this; - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + }, - } + clamp: function ( min, max ) { - } else { + // This function assumes min < max, if this assumption isn't true it will not operate correctly - // m33 is the largest diagonal term so base result on this + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - if ( zz < epsilon ) { + return this; - x = 0.707106781; - y = 0.707106781; - z = 0; + }, - } else { + clampScalar: function () { - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + var min, max; - } + return function clampScalar( minVal, maxVal ) { - } + if ( min === undefined ) { - this.set( x, y, z, angle ); + min = new Vector3(); + max = new Vector3(); - return this; // return 180 deg rotation + } - } + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - // as we have reached here there are no singularities so we can handle normally + return this.clamp( min, max ); - 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; + }(), - // 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 + clampLength: function ( min, max ) { - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + var length = this.length(); - return this; + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - }, + }, - min: function ( v ) { + floor: function () { - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - return this; + return this; - }, + }, - max: function ( v ) { + ceil: function () { - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - return this; + return this; - }, + }, - clamp: function ( min, max ) { + round: function () { - // This function assumes min < max, if this assumption isn't true it will not operate correctly + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + return this; - return this; + }, - }, + roundToZero: function () { - clampScalar: 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 ); - var min, max; + return this; - return function clampScalar( minVal, maxVal ) { + }, - if ( min === undefined ) { + negate: function () { - min = new THREE.Vector4(); - max = new THREE.Vector4(); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - } + return this; - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + }, - return this.clamp( min, max ); + dot: function ( v ) { - }; + return this.x * v.x + this.y * v.y + this.z * v.z; - }(), + }, - floor: function () { + lengthSq: function () { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + return this.x * this.x + this.y * this.y + this.z * this.z; - return this; + }, - }, + length: function () { - ceil: function () { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + }, - return this; + lengthManhattan: function () { - }, + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + normalize: function () { - return this; + return this.divideScalar( this.length() ); - }, + }, - roundToZero: function () { + setLength: function ( length ) { - 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 ); + return this.multiplyScalar( length / this.length() ); - return this; + }, - }, + lerp: function ( v, alpha ) { - negate: function () { + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + return this; - return this; + }, - }, + lerpVectors: function ( v1, v2, alpha ) { - dot: function ( v ) { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + }, - }, + cross: function ( v, w ) { - lengthSq: function () { + if ( w !== undefined ) { - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - }, + } - length: function () { + var x = this.x, y = this.y, z = this.z; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - }, + return this; - lengthManhattan: function () { + }, - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + crossVectors: function ( a, b ) { - }, + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - normalize: function () { + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - return this.divideScalar( this.length() ); + return this; - }, + }, - setLength: function ( length ) { + projectOnVector: function ( vector ) { - return this.multiplyScalar( length / this.length() ); + var scalar = vector.dot( this ) / vector.lengthSq(); + + return this.copy( vector ).multiplyScalar( scalar ); + + }, - }, + projectOnPlane: function () { - lerp: function ( v, alpha ) { + var v1; - 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; + return function projectOnPlane( planeNormal ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); - }, + v1.copy( this ).projectOnVector( planeNormal ); - lerpVectors: function ( v1, v2, alpha ) { + return this.sub( v1 ); - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + }; - }, + }(), - equals: function ( v ) { + reflect: function () { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - }, + var v1; - fromArray: function ( array, offset ) { + return function reflect( normal ) { - if ( offset === undefined ) offset = 0; + if ( v1 === undefined ) v1 = new Vector3(); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - return this; + }; - }, + }(), - toArray: function ( array, offset ) { + angleTo: function ( v ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + // clamp, to handle numerical problems - return array; + return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); - }, + }, - fromAttribute: function ( attribute, index, offset ) { + distanceTo: function ( v ) { - if ( offset === undefined ) offset = 0; + return Math.sqrt( this.distanceToSquared( v ) ); - index = index * attribute.itemSize + offset; + }, - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + distanceToSquared: function ( v ) { - return this; + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - } + return dx * dx + dy * dy + dz * dz; -}; + }, -// File:src/math/Euler.js + distanceToManhattan: function ( v ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); -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; + setFromSpherical: function( s ) { -}; + var sinPhiRadius = Math.sin( s.phi ) * s.radius; -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + this.x = sinPhiRadius * Math.sin( s.theta ); + this.y = Math.cos( s.phi ) * s.radius; + this.z = sinPhiRadius * Math.cos( s.theta ); -THREE.Euler.DefaultOrder = 'XYZ'; + return this; -THREE.Euler.prototype = { + }, - constructor: THREE.Euler, + setFromMatrixPosition: function ( m ) { - get x () { + return this.setFromMatrixColumn( m, 3 ); - return this._x; + }, - }, + setFromMatrixScale: function ( m ) { - set x ( value ) { + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - this._x = value; - this.onChangeCallback(); + this.x = sx; + this.y = sy; + this.z = sz; - }, + return this; - get y () { + }, - return this._y; + setFromMatrixColumn: function ( m, index ) { - }, + if ( typeof m === 'number' ) { - set y ( value ) { + console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); + var temp = m + m = index; + index = temp; - this._y = value; - this.onChangeCallback(); + } - }, + return this.fromArray( m.elements, index * 4 ); - get z () { + }, - return this._z; + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - set z ( value ) { + }, - this._z = value; - this.onChangeCallback(); + fromArray: function ( array, offset ) { - }, + if ( offset === undefined ) offset = 0; - get order () { + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - return this._order; + return this; - }, + }, - set order ( value ) { + toArray: function ( array, offset ) { - this._order = value; - this.onChangeCallback(); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - }, + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - set: function ( x, y, z, order ) { + return array; - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + }, - this.onChangeCallback(); + fromAttribute: function ( attribute, index, offset ) { - return this; + if ( offset === undefined ) offset = 0; - }, + index = index * attribute.itemSize + offset; - clone: function () { + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - return new this.constructor( this._x, this._y, this._z, this._order ); + return this; - }, + } - copy: function ( euler ) { + }; - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - this.onChangeCallback(); + function SpritePlugin ( renderer, sprites ) { + this.isSpritePlugin = true; - return this; + var gl = renderer.context; + var state = renderer.state; - }, + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; - setFromRotationMatrix: function ( m, order, update ) { + var texture; - var clamp = THREE.Math.clamp; + // decompose matrixWorld - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); - 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 ]; + function init() { - order = order || this._order; + 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 ( order === 'XYZ' ) { + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - if ( Math.abs( m13 ) < 0.99999 ) { + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - } else { + program = createProgram(); - this._x = Math.atan2( m32, m22 ); - this._z = 0; + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - } + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - } else if ( order === 'YXZ' ) { + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - if ( Math.abs( m23 ) < 0.99999 ) { + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + 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' ), - } else { + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; - } + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); - } else if ( order === 'ZXY' ) { + texture = new Texture( canvas ); + texture.needsUpdate = true; - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + } - if ( Math.abs( m32 ) < 0.99999 ) { + this.render = function ( scene, camera ) { - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + if ( sprites.length === 0 ) return; - } else { + // setup gl - this._y = 0; - this._z = Math.atan2( m21, m11 ); + if ( program === undefined ) { - } + init(); - } else if ( order === 'ZYX' ) { + } - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + gl.useProgram( program ); - if ( Math.abs( m31 ) < 0.99999 ) { + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); - } else { + 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 ); - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - } + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - } else if ( order === 'YZX' ) { + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - if ( Math.abs( m21 ) < 0.99999 ) { + if ( fog ) { - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - } else { + if ( (fog && fog.isFog) ) { - this._x = 0; - this._y = Math.atan2( m13, m33 ); + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); - } + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; - } else if ( order === 'XZY' ) { + } else if ( (fog && fog.isFogExp2) ) { - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + gl.uniform1f( uniforms.fogDensity, fog.density ); - if ( Math.abs( m12 ) < 0.99999 ) { + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + } - } else { + } else { - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - } + } - } else { - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + // update positions and sort - } + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - this._order = order; + var sprite = sprites[ i ]; - if ( update !== false ) this.onChangeCallback(); + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; - return this; + } - }, + sprites.sort( painterSortStable ); - setFromQuaternion: function () { + // render all sprites - var matrix; + var scale = []; - return function setFromQuaternion( q, order, update ) { + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + var sprite = sprites[ i ]; + var material = sprite.material; - matrix.makeRotationFromQuaternion( q ); + if ( material.visible === false ) continue; - return this.setFromRotationMatrix( matrix, order, update ); + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); - }; + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - }(), + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - setFromVector3: function ( v, order ) { + var fogType = 0; - return this.set( v.x, v.y, v.z, order || this._order ); + if ( scene.fog && material.fog ) { - }, + fogType = sceneFogType; - reorder: function () { + } - // WARNING: this discards revolution information -bhouston + if ( oldFogType !== fogType ) { - var q = new THREE.Quaternion(); + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; - return function reorder( newOrder ) { + } - q.setFromEuler( this ); - - return this.setFromQuaternion( q, newOrder ); + if ( material.map !== null ) { - }; + 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 { - equals: function ( euler ) { + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + } - }, + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - fromArray: function ( array ) { + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); - this.onChangeCallback(); + if ( material.map ) { - return this; + renderer.setTexture2D( material.map, 0 ); - }, + } else { - toArray: function ( array, offset ) { + renderer.setTexture2D( texture, 0 ); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + } - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - return array; + } - }, + // restore gl - toVector3: function ( optionalResult ) { + state.enable( gl.CULL_FACE ); - if ( optionalResult ) { + renderer.resetGLState(); - return optionalResult.set( this._x, this._y, this._z ); + }; - } else { + function createProgram () { - return new THREE.Vector3( this._x, this._y, this._z ); + var program = gl.createProgram(); - } + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - }, + gl.shaderSource( vertexShader, [ - onChange: function ( callback ) { + 'precision ' + renderer.getPrecision() + ' float;', - this.onChangeCallback = callback; + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - return this; + 'attribute vec2 position;', + 'attribute vec2 uv;', - }, + 'varying vec2 vUV;', - onChangeCallback: function () {} + 'void main() {', -}; + 'vUV = uvOffset + uv * uvScale;', -// File:src/math/Line3.js + 'vec2 alignedPosition = position * scale;', -/** - * @author bhouston / http://clara.io - */ + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', -THREE.Line3 = function ( start, end ) { + 'vec4 finalPosition;', - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', -}; + 'gl_Position = finalPosition;', -THREE.Line3.prototype = { + '}' - constructor: THREE.Line3, + ].join( '\n' ) ); - set: function ( start, end ) { + gl.shaderSource( fragmentShader, [ - this.start.copy( start ); - this.end.copy( end ); + 'precision ' + renderer.getPrecision() + ' float;', - return this; + '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;', - clone: function () { + 'varying vec2 vUV;', - return new this.constructor().copy( this ); + 'void main() {', - }, + 'vec4 texture = texture2D( map, vUV );', - copy: function ( line ) { + 'if ( texture.a < alphaTest ) discard;', - this.start.copy( line.start ); - this.end.copy( line.end ); + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - return this; + 'if ( fogType > 0 ) {', - }, + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - center: function ( optionalTarget ) { + 'if ( fogType == 1 ) {', - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - }, + '} else {', - delta: function ( optionalTarget ) { + 'const float LOG2 = 1.442695;', + 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.end, this.start ); + '}', - }, + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - distanceSq: function () { + '}', - return this.start.distanceToSquared( this.end ); + '}' - }, + ].join( '\n' ) ); - distance: function () { + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - return this.start.distanceTo( this.end ); + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - }, + gl.linkProgram( program ); - at: function ( t, optionalTarget ) { + return program; - var result = optionalTarget || new THREE.Vector3(); + } - return this.delta( result ).multiplyScalar( t ).add( this.start ); + function painterSortStable ( a, b ) { - }, + if ( a.renderOrder !== b.renderOrder ) { - closestPointToPointParameter: function () { + return a.renderOrder - b.renderOrder; - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + } else if ( a.z !== b.z ) { - return function closestPointToPointParameter( point, clampToLine ) { + return b.z - a.z; - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + } else { - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + return b.id - a.id; - var t = startEnd_startP / startEnd2; + } - if ( clampToLine ) { + } - t = THREE.Math.clamp( t, 0, 1 ); + }; - } + /** + * @author bhouston / http://clara.io + */ - return t; + function Box2 ( min, max ) { + this.isBox2 = true; - }; + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - }(), + }; - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + Box2.prototype = { - var t = this.closestPointToPointParameter( point, clampToLine ); + constructor: Box2, - var result = optionalTarget || new THREE.Vector3(); + set: function ( min, max ) { - return this.delta( result ).multiplyScalar( t ).add( this.start ); + this.min.copy( min ); + this.max.copy( max ); - }, + return this; - applyMatrix4: function ( matrix ) { + }, - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + setFromPoints: function ( points ) { - return this; + this.makeEmpty(); - }, + for ( var i = 0, il = points.length; i < il; i ++ ) { - equals: function ( line ) { + this.expandByPoint( points[ i ] ); - return line.start.equals( this.start ) && line.end.equals( this.end ); + } - } + return this; -}; + }, -// File:src/math/Box2.js + setFromCenterAndSize: function () { -/** - * @author bhouston / http://clara.io - */ + var v1 = new Vector2(); -THREE.Box2 = function ( min, max ) { + return function setFromCenterAndSize( center, size ) { - this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); -}; + return this; -THREE.Box2.prototype = { + }; - constructor: THREE.Box2, + }(), - set: function ( min, max ) { + clone: function () { - this.min.copy( min ); - this.max.copy( max ); + return new this.constructor().copy( this ); - return this; + }, - }, + copy: function ( box ) { - setFromPoints: function ( points ) { + this.min.copy( box.min ); + this.max.copy( box.max ); - this.makeEmpty(); + return this; - for ( var i = 0, il = points.length; i < il; i ++ ) { + }, - this.expandByPoint( points[ i ] ); + makeEmpty: function () { - } + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - return this; + return this; - }, + }, - setFromCenterAndSize: function () { + isEmpty: function () { - var v1 = new THREE.Vector2(); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return function setFromCenterAndSize( center, size ) { + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + }, - return this; + center: function ( optionalTarget ) { - }; + var result = optionalTarget || new Vector2(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - }(), + }, - clone: function () { + size: function ( optionalTarget ) { - return new this.constructor().copy( this ); + var result = optionalTarget || new Vector2(); + return result.subVectors( this.max, this.min ); - }, + }, - copy: function ( box ) { + expandByPoint: function ( point ) { - this.min.copy( box.min ); - this.max.copy( box.max ); + this.min.min( point ); + this.max.max( point ); - return this; + return this; - }, + }, - makeEmpty: function () { + expandByVector: function ( vector ) { - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + this.min.sub( vector ); + this.max.add( vector ); - return this; + return this; - }, + }, - isEmpty: function () { + expandByScalar: function ( scalar ) { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + return this; - }, + }, - center: function ( optionalTarget ) { + containsPoint: function ( point ) { - var result = optionalTarget || new THREE.Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - }, + return false; - size: function ( optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector2(); - return result.subVectors( this.max, this.min ); + return true; - }, + }, - expandByPoint: function ( point ) { + containsBox: function ( box ) { - this.min.min( point ); - this.max.max( point ); + 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 this; + return true; - }, + } - expandByVector: function ( vector ) { + return false; - this.min.sub( vector ); - this.max.add( vector ); + }, - return this; + getParameter: function ( point, optionalTarget ) { - }, + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - expandByScalar: function ( scalar ) { + var result = optionalTarget || new Vector2(); - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + 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 ) + ); - return this; + }, - }, + intersectsBox: function ( box ) { - containsPoint: function ( point ) { + // using 6 splitting planes to rule out intersections. - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ) { - return false; + return false; - } + } - return true; + return true; - }, + }, - containsBox: function ( box ) { + clampPoint: function ( point, optionalTarget ) { - 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 ) ) { + var result = optionalTarget || new Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - return true; + }, - } + distanceToPoint: function () { - return false; + var v1 = new Vector2(); - }, + return function distanceToPoint( point ) { - getParameter: function ( point, optionalTarget ) { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + }; - var result = optionalTarget || new THREE.Vector2(); + }(), - 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 ) - ); + intersect: function ( box ) { - }, + this.min.max( box.min ); + this.max.min( box.max ); - intersectsBox: function ( box ) { + return this; - // using 6 splitting planes to rule out intersections. + }, - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ) { + union: function ( box ) { - return false; + this.min.min( box.min ); + this.max.max( box.max ); - } + return this; - return true; + }, - }, + translate: function ( offset ) { - clampPoint: function ( point, optionalTarget ) { + this.min.add( offset ); + this.max.add( offset ); - var result = optionalTarget || new THREE.Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + return this; - }, + }, - distanceToPoint: function () { + equals: function ( box ) { - var v1 = new THREE.Vector2(); + return box.min.equals( this.min ) && box.max.equals( this.max ); - return function distanceToPoint( point ) { + } - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + }; - }; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - }(), + function LensFlarePlugin ( renderer, flares ) { + this.isLensFlarePlugin = true; - intersect: function ( box ) { + var gl = renderer.context; + var state = renderer.state; - this.min.max( box.min ); - this.max.min( box.max ); + var vertexBuffer, elementBuffer; + var shader, program, attributes, uniforms; - return this; + var tempTexture, occlusionTexture; - }, + function init() { - union: function ( box ) { + var vertices = new Float32Array( [ + - 1, - 1, 0, 0, + 1, - 1, 1, 0, + 1, 1, 1, 1, + - 1, 1, 0, 1 + ] ); - this.min.min( box.min ); - this.max.max( box.max ); + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - return this; + // buffers - }, + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - translate: function ( offset ) { + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - this.min.add( offset ); - this.max.add( offset ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - return this; + // textures - }, + tempTexture = gl.createTexture(); + occlusionTexture = gl.createTexture(); - equals: function ( box ) { + state.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 ); - return box.min.equals( this.min ) && box.max.equals( this.max ); + state.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 ); - } + shader = { -}; + vertexShader: [ -// File:src/math/Box3.js + "uniform lowp int renderType;", -/** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", -THREE.Box3 = function ( min, max ) { + "uniform sampler2D occlusionMap;", - this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + "attribute vec2 position;", + "attribute vec2 uv;", -}; + "varying vec2 vUV;", + "varying float vVisibility;", -THREE.Box3.prototype = { + "void main() {", - constructor: THREE.Box3, + "vUV = uv;", - set: function ( min, max ) { + "vec2 pos = position;", - this.min.copy( min ); - this.max.copy( max ); + "if ( renderType == 2 ) {", - return this; + "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 ) );", - }, + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - setFromArray: function ( array ) { + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + "}", - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - for ( var i = 0, l = array.length; i < l; i += 3 ) { + "}" - var x = array[ i ]; - var y = array[ i + 1 ]; - var z = array[ i + 2 ]; + ].join( "\n" ), - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + fragmentShader: [ - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + "uniform lowp int renderType;", - } + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + "varying vec2 vUV;", + "varying float vVisibility;", - }, + "void main() {", - setFromPoints: function ( points ) { + // pink square - this.makeEmpty(); + "if ( renderType == 0 ) {", - for ( var i = 0, il = points.length; i < il; i ++ ) { + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - this.expandByPoint( points[ i ] ); + // restore - } + "} else if ( renderType == 1 ) {", - return this; + "gl_FragColor = texture2D( map, vUV );", - }, + // flare - setFromCenterAndSize: function () { + "} else {", - var v1 = new THREE.Vector3(); + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - return function setFromCenterAndSize( center, size ) { + "}", - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + "}" - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + ].join( "\n" ) - return this; + }; - }; + program = createProgram( shader ); - }(), + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + }; - setFromObject: function () { + 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" ) + }; - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + } - var v1 = new THREE.Vector3(); + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - return function setFromObject( object ) { + this.render = function ( scene, camera, viewport ) { - var scope = this; + if ( flares.length === 0 ) return; - object.updateMatrixWorld( true ); + var tempPosition = new Vector3(); - this.makeEmpty(); + var invAspect = viewport.w / viewport.z, + halfViewportWidth = viewport.z * 0.5, + halfViewportHeight = viewport.w * 0.5; - object.traverse( function ( node ) { + var size = 16 / viewport.w, + scale = new Vector2( size * invAspect, size ); - var geometry = node.geometry; + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - if ( geometry !== undefined ) { + var validArea = new Box2(); - if ( geometry instanceof THREE.Geometry ) { + validArea.min.set( 0, 0 ); + validArea.max.set( viewport.z - 16, viewport.w - 16 ); - var vertices = geometry.vertices; + if ( program === undefined ) { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + init(); - v1.copy( vertices[ i ] ); - v1.applyMatrix4( node.matrixWorld ); + } - scope.expandByPoint( v1 ); + gl.useProgram( program ); - } + state.initAttributes(); + state.enableAttribute( attributes.vertex ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - } else if ( geometry instanceof THREE.BufferGeometry ) { + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/uniforms - var attribute = geometry.attributes.position; + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); - if ( attribute !== undefined ) { + 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 ); - var array, offset, stride; + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + state.disable( gl.CULL_FACE ); + state.setDepthWrite( false ); - array = attribute.data.array; - offset = attribute.offset; - stride = attribute.data.stride; + for ( var i = 0, l = flares.length; i < l; i ++ ) { - } else { + size = 16 / viewport.w; + scale.set( size * invAspect, size ); - array = attribute.array; - offset = 0; - stride = 3; + // calc object screen position - } + var flare = flares[ i ]; - for ( var i = offset, il = array.length; i < il; i += stride ) { + tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); - v1.fromArray( array, i ); - v1.applyMatrix4( node.matrixWorld ); + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - scope.expandByPoint( v1 ); + // setup arrays for gl programs - } + screenPosition.copy( tempPosition ); - } + // horizontal and vertical coordinate of the lower left corner of the pixels to copy - } + screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; - } + // screen cull - } ); + if ( validArea.containsPoint( screenPositionPixels ) === true ) { - return this; + // save current RGB to temp texture - }; + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, null ); + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - }(), - clone: function () { + // render pink quad - return new this.constructor().copy( this ); + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - }, + state.disable( gl.BLEND ); + state.enable( gl.DEPTH_TEST ); - copy: function ( box ) { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - this.min.copy( box.min ); - this.max.copy( box.max ); - return this; + // copy result to occlusionMap - }, + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - makeEmpty: function () { - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + // restore graphics - return this; + gl.uniform1i( uniforms.renderType, 1 ); + state.disable( gl.DEPTH_TEST ); - }, + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - isEmpty: function () { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + // update object positions - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + flare.positionScreen.copy( screenPosition ); - }, + if ( flare.customUpdateCallback ) { - center: function ( optionalTarget ) { + flare.customUpdateCallback( flare ); - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + } else { - }, + flare.updateLensFlares(); - size: function ( optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.max, this.min ); + // render flares - }, + gl.uniform1i( uniforms.renderType, 2 ); + state.enable( gl.BLEND ); - expandByPoint: function ( point ) { + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - this.min.min( point ); - this.max.max( point ); + var sprite = flare.lensFlares[ j ]; - return this; + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - }, + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - expandByVector: function ( vector ) { + size = sprite.size * sprite.scale / viewport.w; - this.min.sub( vector ); - this.max.add( vector ); + scale.x = size * invAspect; + scale.y = size; - return this; + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform1f( uniforms.rotation, sprite.rotation ); - }, + gl.uniform1f( uniforms.opacity, sprite.opacity ); + gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - expandByScalar: function ( scalar ) { + state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); + renderer.setTexture2D( sprite.texture, 1 ); - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - return this; + } - }, + } - containsPoint: function ( point ) { + } - 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 ) { + } - return false; + // restore gl - } + state.enable( gl.CULL_FACE ); + state.enable( gl.DEPTH_TEST ); + state.setDepthWrite( true ); - return true; + renderer.resetGLState(); - }, + }; - containsBox: function ( box ) { + function createProgram ( shader ) { - 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 ) ) { + var program = gl.createProgram(); - return true; + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - } + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - return false; + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - }, + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - getParameter: function ( point, optionalTarget ) { + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + gl.linkProgram( program ); - var result = optionalTarget || new THREE.Vector3(); + return program; - 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 ) - ); + } - }, + }; - intersectsBox: function ( box ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - // using 6 splitting planes to rule out intersections. + function CubeTexture ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isCubeTexture = this.isTexture = true; - 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 ) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - return false; + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - } + this.flipY = false; - return true; + }; - }, + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - intersectsSphere: ( function () { + Object.defineProperty( CubeTexture.prototype, 'images', { - var closestPoint; + get: function () { - return function intersectsSphere( sphere ) { + return this.image; - if ( closestPoint === undefined ) closestPoint = new THREE.Vector3(); + }, - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, closestPoint ); + set: function ( value ) { - // If that point is inside the sphere, the AABB and sphere intersect. - return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + this.image = value; - }; + } - } )(), + } ); - intersectsPlane: function ( plane ) { + /** + * + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [renderer] ) + * + * uploads a uniform value(s) + * the 'renderer' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (renderer factorizations): + * + * .upload( gl, seq, values, renderer ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * .splitDynamic( seq, values ) : filteredSeq + * + * filters 'seq' entries with dynamic entry and removes them from 'seq' + * + * + * Methods of the top-level container (renderer factorizations): + * + * .setValue( gl, name, value ) + * + * sets uniform with name 'name' to 'value' + * + * .set( gl, obj, prop ) + * + * sets uniform from object and property with same name than uniform + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + * + * @author tschw + * + */ - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. + exports.WebGLUniforms = ( function() { // scope - var min, max; + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - if ( plane.normal.x > 0 ) { + // --- Base for inner nodes (including the root) --- - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + var UniformContainer = function() { - } else { + this.seq = []; + this.map = {}; - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + }, - } + // --- Utilities --- - if ( plane.normal.y > 0 ) { + // Array Caches (provide typed arrays for temporary by size) - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + arrayCacheF32 = [], + arrayCacheI32 = [], - } else { + uncacheTemporaryArrays = function() { - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + arrayCacheF32.length = 0; + arrayCacheI32.length = 0; - } + }, - if ( plane.normal.z > 0 ) { + // Flattening for arrays of vectors and matrices - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + flatten = function( array, nBlocks, blockSize ) { - } else { + var firstElem = array[ 0 ]; - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - } + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - return ( min <= plane.constant && max >= plane.constant ); + if ( r === undefined ) { - }, + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - clampPoint: function ( point, optionalTarget ) { + } - var result = optionalTarget || new THREE.Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + if ( nBlocks !== 0 ) { - }, + firstElem.toArray( r, 0 ); - distanceToPoint: function () { + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - var v1 = new THREE.Vector3(); + offset += blockSize; + array[ i ].toArray( r, offset ); - return function distanceToPoint( point ) { + } - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + } - }; + return r; - }(), + }, - getBoundingSphere: function () { + // Texture unit allocation - var v1 = new THREE.Vector3(); + allocTexUnits = function( renderer, n ) { - return function getBoundingSphere( optionalTarget ) { + var r = arrayCacheI32[ n ]; - var result = optionalTarget || new THREE.Sphere(); + if ( r === undefined ) { - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - return result; + } - }; + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - }(), + return r; - intersect: function ( box ) { + }, - this.min.max( box.min ); - this.max.min( box.max ); + // --- Setters --- - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if( this.isEmpty() ) this.makeEmpty(); + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - return this; + // Single scalar - }, + setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, + setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, - union: function ( box ) { + // Single float vector (from flat array or THREE.VectorN) - this.min.min( box.min ); - this.max.max( box.max ); + setValue2fv = function( gl, v ) { - return this; + if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); + else gl.uniform2f( this.addr, v.x, v.y ); - }, + }, - applyMatrix4: function () { + setValue3fv = function( gl, v ) { - 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() - ]; + if ( v.x !== undefined ) + gl.uniform3f( this.addr, v.x, v.y, v.z ); + else if ( v.r !== undefined ) + gl.uniform3f( this.addr, v.r, v.g, v.b ); + else + gl.uniform3fv( this.addr, v ); - return function applyMatrix4( matrix ) { + }, - // transform of empty box is an empty box. - if( this.isEmpty() ) return this; + setValue4fv = function( gl, v ) { - // 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 + if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); + else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - this.setFromPoints( points ); + }, - return this; + // Single matrix (from flat array or MatrixN) - }; + setValue2fm = function( gl, v ) { - }(), + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - translate: function ( offset ) { + }, - this.min.add( offset ); - this.max.add( offset ); + setValue3fm = function( gl, v ) { - return this; + gl.uniformMatrix3fv( this.addr, false, v.elements || v ); - }, + }, - equals: function ( box ) { + setValue4fm = function( gl, v ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + gl.uniformMatrix4fv( this.addr, false, v.elements || v ); - } + }, -}; + // Single texture (2D / Cube) -// File:src/math/Matrix3.js + setValueT1 = function( gl, v, renderer ) { -/** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw - */ + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); -THREE.Matrix3 = function () { + }, - this.elements = new Float32Array( [ + setValueT6 = function( gl, v, renderer ) { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - ] ); + }, - if ( arguments.length > 0 ) { + // Integer / Boolean vectors or arrays thereof (always flat arrays) - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, + setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, + setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, - } + // Helper to pick the right setter for the singular case -}; + getSingularSetter = function( type ) { -THREE.Matrix3.prototype = { + switch ( type ) { - constructor: THREE.Matrix3, + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - var te = this.elements; + case 0x8b5e: return setValueT1; // SAMPLER_2D + case 0x8b60: return setValueT6; // SAMPLER_CUBE - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - return this; + } - }, + }, - identity: function () { + // Array of scalars - this.set( + setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, + setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + // Array of vectors (flat or from THREE classes) - ); + setValueV2a = function( gl, v ) { - return this; + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - }, + }, - clone: function () { + setValueV3a = function( gl, v ) { - return new this.constructor().fromArray( this.elements ); + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - }, + }, - copy: function ( m ) { + setValueV4a = function( gl, v ) { - var me = m.elements; + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - this.set( + }, - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] + // Array of matrices (flat or from THREE clases) - ); + setValueM2a = function( gl, v ) { - return this; + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - }, + }, - setFromMatrix4: function( m ) { + setValueM3a = function( gl, v ) { - var me = m.elements; + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - this.set( + }, - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + setValueM4a = function( gl, v ) { - ); + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - return this; + }, - }, + // Array of textures (2D / Cube) - applyToVector3Array: function () { + setValueT1a = function( gl, v, renderer ) { - var v1; + var n = v.length, + units = allocTexUnits( renderer, n ); - return function applyToVector3Array( array, offset, length ) { + gl.uniform1iv( this.addr, units ); - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + for ( var i = 0; i !== n; ++ i ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - v1.fromArray( array, j ); - v1.applyMatrix3( this ); - v1.toArray( array, j ); + } - } + }, - return array; + setValueT6a = function( gl, v, renderer ) { - }; + var n = v.length, + units = allocTexUnits( renderer, n ); - }(), + gl.uniform1iv( this.addr, units ); - applyToBuffer: function () { + for ( var i = 0; i !== n; ++ i ) { - var v1; + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - return function applyToBuffer( buffer, offset, length ) { + } - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + }, - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + // Helper to pick the right setter for a pure (bottom-level) array - v1.applyMatrix3( this ); + getPureArraySetter = function( type ) { - buffer.setXYZ( v1.x, v1.y, v1.z ); + switch ( type ) { - } + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - return buffer; + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - }; + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - }(), + case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - multiplyScalar: function ( s ) { + } - var te = this.elements; + }, - 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; + // --- Uniform Classes --- - return this; + SingleUniform = function SingleUniform( id, activeInfo, addr ) { - }, + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - determinant: function () { + // this.path = activeInfo.name; // DEBUG - var te = this.elements; + }, - 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 ]; + PureArrayUniform = function( id, activeInfo, addr ) { - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - }, + // this.path = activeInfo.name; // DEBUG - getInverse: function ( matrix, throwOnDegenerate ) { + }, - if ( matrix instanceof THREE.Matrix4 ) { + StructuredUniform = function( id ) { - console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); + this.id = id; - } + UniformContainer.call( this ); // mix-in - var me = matrix.elements, - te = this.elements, + }; - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], - n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], - n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], + StructuredUniform.prototype.setValue = function( gl, value ) { - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - det = n11 * t11 + n21 * t12 + n31 * t13; + var seq = this.seq; - if ( det === 0 ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - if ( throwOnDegenerate || false ) { + } - throw new Error( msg ); + }; - } else { + // --- Top-level --- - console.warn( msg ); + // Parser - builds up the property tree from the path strings - } + var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, + // extracts + // - the identifier (member name or array index) + // - followed by an optional right bracket (found when array index) + // - followed by an optional left bracket or dot (type of subscript) + // + // Note: These portions can be read in a non-overlapping fashion and + // allow straightforward parsing of the hierarchy that WebGL encodes + // in the uniform names. - return this.identity(); - } - - var detInv = 1 / det; + addUniform = function( container, uniformObject ) { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + }, - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + parseUniform = function( activeInfo, addr, container ) { - return this; + var path = activeInfo.name, + pathLength = path.length; - }, + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - transpose: function () { + for (; ;) { - var tmp, m = this.elements; + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - 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 = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - return this; + if ( idIsIndex ) id = id | 0; // convert to integer - }, + if ( subscript === undefined || + subscript === '[' && matchEnd + 2 === pathLength ) { + // bare name or "pure" bottom-level array "[0]" suffix - flattenToArrayOffset: function ( array, offset ) { + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + break; - return this.toArray( array, offset ); + } else { + // step into inner node / create it in case it doesn't exist - }, + var map = container.map, + next = map[ id ]; - getNormalMatrix: function ( matrix4 ) { + if ( next === undefined ) { - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + next = new StructuredUniform( id ); + addUniform( container, next ); - }, + } - transposeIntoArray: function ( r ) { + container = next; - var m = this.elements; + } - 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 ]; + } - return this; + }, - }, + // Root Container - fromArray: function ( array ) { + WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { - this.elements.set( array ); + UniformContainer.call( this ); - return this; + this.renderer = renderer; - }, + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); - toArray: function ( array, offset ) { + for ( var i = 0; i !== n; ++ i ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); - var te = this.elements; + parseUniform( info, addr, this ); - 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 ]; - array[ offset + 8 ] = te[ 8 ]; - return array; + WebGLUniforms.prototype.setValue = function( gl, name, value ) { - } + var u = this.map[ name ]; -}; + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); -// File:src/math/Matrix4.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 alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + WebGLUniforms.prototype.set = function( gl, object, name ) { -THREE.Matrix4 = function () { + var u = this.map[ name ]; - this.elements = new Float32Array( [ + if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + }; - ] ); + WebGLUniforms.prototype.setOptional = function( gl, object, name ) { - if ( arguments.length > 0 ) { + var v = object[ name ]; - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + if ( v !== undefined ) this.setValue( gl, name, v ); - } + }; -}; -THREE.Matrix4.prototype = { + // Static interface - constructor: THREE.Matrix4, + WebGLUniforms.upload = function( gl, seq, values, renderer ) { - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - var te = this.elements; + var u = seq[ i ], + v = values[ u.id ]; - 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; + if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined - return this; + u.setValue( gl, v.value, renderer ); - }, + } - identity: function () { + } - this.set( + }; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + WebGLUniforms.seqWithValue = function( seq, values ) { - ); + var r = []; - return this; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - }, + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - clone: function () { + } - return new THREE.Matrix4().fromArray( this.elements ); + return r; - }, + }; - copy: function ( m ) { + WebGLUniforms.splitDynamic = function( seq, values ) { - this.elements.set( m.elements ); + var r = null, + n = seq.length, + w = 0; - return this; + for ( var i = 0; i !== n; ++ i ) { - }, + var u = seq[ i ], + v = values[ u.id ]; - copyPosition: function ( m ) { + if ( v && v.dynamic === true ) { - var te = this.elements; - var me = m.elements; + if ( r === null ) r = []; + r.push( u ); - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + } else { - return this; + // in-place compact 'seq', removing the matches + if ( w < i ) seq[ w ] = u; + ++ w; - }, + } - extractBasis: function ( xAxis, yAxis, zAxis ) { + } - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + if ( w < n ) seq.length = w; - return this; + return r; - }, + }; - makeBasis: function ( xAxis, yAxis, zAxis ) { + WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { - 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 - ); + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - return this; + var v = values[ seq[ i ].id ], + f = v.onUpdateCallback; - }, + if ( f !== undefined ) f.call( v, object, camera ); - extractRotation: function () { + } - var v1; + }; - return function extractRotation( m ) { + return WebGLUniforms; - if ( v1 === undefined ) v1 = new THREE.Vector3(); + } )(); - var te = this.elements; - var me = m.elements; + /** + * @author mrdoob / http://mrdoob.com/ + */ - var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); + function WebGLTextures ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + this.isWebGLTextures = true; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + var _infoMemory = info.memory; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); - 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; + function clampToMaxSize ( image, maxSize ) { - return this; + if ( image.width > maxSize || image.height > maxSize ) { - }; + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - }(), + var scale = maxSize / Math.max( image.width, image.height ); - makeRotationFromEuler: function ( euler ) { + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = Math.floor( image.width * scale ); + canvas.height = Math.floor( image.height * scale ); - if ( euler instanceof THREE.Euler === false ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - } + return canvas; - 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 ); + return image; - if ( euler.order === 'XYZ' ) { + } - var ae = a * e, af = a * f, be = b * e, bf = b * f; + function isPowerOfTwo( image ) { - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + } - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + function makePowerOfTwo( image ) { - } else if ( euler.order === 'YXZ' ) { + if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { - var ce = c * e, cf = c * f, de = d * e, df = d * f; + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = exports.Math.nearestPowerOfTwo( image.width ); + canvas.height = exports.Math.nearestPowerOfTwo( image.height ); - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + return canvas; - } else if ( euler.order === 'ZXY' ) { + } - var ce = c * e, cf = c * f, de = d * e, df = d * f; + return image; - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + } - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + function textureNeedsPowerOfTwo( texture ) { - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; - } else if ( euler.order === 'ZYX' ) { + return 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; + // Fallback filters for non-power-of-2 textures - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + function filterFallback ( f ) { - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - } else if ( euler.order === 'YZX' ) { + return _gl.NEAREST; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + return _gl.LINEAR; - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + } - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + // - } else if ( euler.order === 'XZY' ) { + function onTextureDispose( event ) { - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + var texture = event.target; - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + texture.removeEventListener( 'dispose', onTextureDispose ); - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + deallocateTexture( texture ); - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + _infoMemory.textures --; - } - // 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; + function onRenderTargetDispose( event ) { - return this; + var renderTarget = event.target; - }, + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - makeRotationFromQuaternion: function ( q ) { + deallocateRenderTarget( renderTarget ); - var te = this.elements; + _infoMemory.textures --; - 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; + // - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + function deallocateTexture( texture ) { - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + var textureProperties = properties.get( texture ); - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + if ( texture.image && textureProperties.__image__webglTextureCube ) { - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + // cube texture - return this; + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - }, + } else { - lookAt: function () { + // 2D texture - var x, y, z; + if ( textureProperties.__webglInit === undefined ) return; - return function lookAt( eye, target, up ) { + _gl.deleteTexture( textureProperties.__webglTexture ); - if ( x === undefined ) { + } - x = new THREE.Vector3(); - y = new THREE.Vector3(); - z = new THREE.Vector3(); + // remove all webgl properties + properties.delete( texture ); - } + } - var te = this.elements; + function deallocateRenderTarget( renderTarget ) { - z.subVectors( eye, target ).normalize(); + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - if ( z.lengthSq() === 0 ) { + if ( ! renderTarget ) return; - z.z = 1; + if ( textureProperties.__webglTexture !== undefined ) { - } + _gl.deleteTexture( textureProperties.__webglTexture ); - x.crossVectors( up, z ).normalize(); + } - if ( x.lengthSq() === 0 ) { + if ( renderTarget.depthTexture ) { - z.z += 0.0001; - x.crossVectors( up, z ).normalize(); + renderTarget.depthTexture.dispose(); - } + } - y.crossVectors( z, x ); + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { + for ( var i = 0; i < 6; i ++ ) { - 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; + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - return this; + } - }; + } else { - }(), + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - multiply: function ( m, n ) { + } - if ( n !== undefined ) { + properties.delete( renderTarget.texture ); + properties.delete( renderTarget ); - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + } - } + // - return this.multiplyMatrices( this, m ); - }, - premultiply: function ( m ) { + function setTexture2D( texture, slot ) { - return this.multiplyMatrices( m, this ); + var textureProperties = properties.get( texture ); - }, + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - multiplyMatrices: function ( a, b ) { + var image = texture.image; - var ae = a.elements; - var be = b.elements; - var te = this.elements; + if ( image === undefined ) { - 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 ]; + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - 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 ]; + } else if ( image.complete === false ) { - 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; + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - 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; + } else { - 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; + uploadTexture( textureProperties, texture, slot ); + return; - 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; + } - return this; + } - }, + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - multiplyToArray: function ( a, b, r ) { + } - var te = this.elements; + function setTextureCube ( texture, slot ) { - this.multiplyMatrices( a, b ); + var textureProperties = properties.get( texture ); - 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 ( texture.image.length === 6 ) { - return this; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - }, + if ( ! textureProperties.__image__webglTextureCube ) { - multiplyScalar: function ( s ) { + texture.addEventListener( 'dispose', onTextureDispose ); - var te = this.elements; + textureProperties.__image__webglTextureCube = _gl.createTexture(); - 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; + _infoMemory.textures ++; - return this; + } - }, + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - applyToVector3Array: function () { + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - var v1; + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); - return function applyToVector3Array( array, offset, length ) { + var cubeImage = []; - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + for ( var i = 0; i < 6; i ++ ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + if ( ! isCompressed && ! isDataTexture ) { - v1.fromArray( array, j ); - v1.applyMatrix4( this ); - v1.toArray( array, j ); + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - } + } else { - return array; + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - }; + } - }(), + } - applyToBuffer: function () { + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - var v1; + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); - return function applyToBuffer( buffer, offset, length ) { + for ( var i = 0; i < 6; i ++ ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + if ( ! isCompressed ) { - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + if ( isDataTexture ) { - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - v1.applyMatrix4( this ); + } else { - buffer.setXYZ( v1.x, v1.y, v1.z ); + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - } + } - return buffer; + } else { - }; + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - }(), + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - determinant: function () { + mipmap = mipmaps[ j ]; - var te = this.elements; + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - 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 ]; + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - 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 - ) + } else { - ); + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); - }, + } - transpose: function () { + } else { - var te = this.elements; - var tmp; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - 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 ) { + if ( texture.generateMipmaps && isPowerOfTwoImage ) { - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - return this.toArray( array, offset ); + } - }, + textureProperties.__version = texture.version; - getPosition: function () { + if ( texture.onUpdate ) texture.onUpdate( texture ); - var v1; + } else { - return function getPosition() { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - if ( v1 === undefined ) v1 = new THREE.Vector3(); - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + } - return v1.setFromMatrixColumn( this, 3 ); + } - }; + } - }(), + function setTextureCubeDynamic ( texture, slot ) { - setPosition: function ( v ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - var te = this.elements; + } - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) { - return this; + var extension; - }, + if ( isPowerOfTwoImage ) { - getInverse: function ( m, throwOnDegenerate ) { + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], - n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], - n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], - n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], + } else { - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - if ( det === 0 ) { + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + } - if ( throwOnDegenerate || false ) { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - throw new Error( msg ); + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - } else { + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); - console.warn( msg ); + } - } + } - return this.identity(); + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - } - - var detInv = 1 / det; + if ( extension ) { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + } - return this; + } - }, + } - scale: function ( v ) { + function uploadTexture( textureProperties, texture, slot ) { - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + if ( textureProperties.__webglInit === undefined ) { - 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; + textureProperties.__webglInit = true; - return this; + texture.addEventListener( 'dispose', onTextureDispose ); - }, + textureProperties.__webglTexture = _gl.createTexture(); - getMaxScaleOnAxis: function () { + _infoMemory.textures ++; - var te = this.elements; + } - 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 ]; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + _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 image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - makeTranslation: function ( x, y, z ) { + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - this.set( + image = makePowerOfTwo( image ); - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + } - ); + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - return this; + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - }, + var mipmap, mipmaps = texture.mipmaps; - makeRotationX: function ( theta ) { + if ( (texture && texture.isDepthTexture) ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + // populate depth texture with dummy data - this.set( + var internalFormat = _gl.DEPTH_COMPONENT; - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + if ( texture.type === FloatType ) { - ); + if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); + internalFormat = _gl.DEPTH_COMPONENT32F; - return this; + } else if ( _isWebGL2 ) { - }, + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - makeRotationY: function ( theta ) { + } - var c = Math.cos( theta ), s = Math.sin( theta ); + state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - this.set( + } else if ( (texture && texture.isDataTexture) ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + // 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 && isPowerOfTwoImage ) { - return this; + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - }, + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - makeRotationZ: function ( theta ) { + } - var c = Math.cos( theta ), s = Math.sin( theta ); + texture.generateMipmaps = false; - this.set( + } else { - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - ); + } - return this; + } else if ( (texture && texture.isCompressedTexture) ) { - }, + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - makeRotationAxis: function ( axis, angle ) { + mipmap = mipmaps[ i ]; - // Based on http://www.gamedev.net/reference/articles/article1199.asp + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - 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; + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - this.set( + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - 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 + } else { - ); + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - return this; + } - }, + } else { - makeScale: function ( x, y, z ) { + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - this.set( + } - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + } - ); + } else { - return this; + // regular Texture (image, video, canvas) - }, + // 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 - compose: function ( position, quaternion, scale ) { + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - return this; + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - }, + } - decompose: function () { + texture.generateMipmaps = false; - var vector, matrix; + } else { - return function decompose( position, quaternion, scale ) { + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); - if ( vector === undefined ) { + } - vector = new THREE.Vector3(); - matrix = new THREE.Matrix4(); + } - } + if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); - var te = this.elements; + textureProperties.__version = texture.version; - 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 ( texture.onUpdate ) texture.onUpdate( texture ); - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { + } - sx = - sx; + // Render targets - } + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) { - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + var glFormat = paramThreeToGL( renderTarget.texture.format ); + var glType = paramThreeToGL( renderTarget.texture.type ); + state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - // scale the rotation part + } - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage ( renderbuffer, renderTarget ) { - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - quaternion.setFromRotationMatrix( matrix ); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - scale.x = sx; - scale.y = sy; - scale.z = sz; + } else { - return this; + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - }; + } - }(), + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - makeFrustum: function ( left, right, bottom, top, near, far ) { + } - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture ( framebuffer, renderTarget ) { - 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 ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); - 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; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - return this; + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { - }, + throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); - makePerspective: function ( fov, aspect, near, far ) { + } - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + // upload an empty depth texture with framebuffer size + if ( !properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + setTexture2D( renderTarget.depthTexture, 0 ); - }, + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - makeOrthographic: function ( left, right, top, bottom, near, far ) { + } - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + var renderTargetProperties = properties.get( renderTarget ); - 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; + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - return this; + if ( renderTarget.depthTexture ) { - }, + if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); - equals: function ( matrix ) { + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - var te = this.elements; - var me = matrix.elements; + } else { - for ( var i = 0; i < 16; i ++ ) { + if ( isCube ) { - if ( te[ i ] !== me[ i ] ) return false; + renderTargetProperties.__webglDepthbuffer = []; - } + for ( var i = 0; i < 6; i ++ ) { - return true; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); - }, + } - fromArray: function ( array ) { + } else { - this.elements.set( array ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - return this; + } - }, + } - toArray: function ( array, offset ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + } - var te = this.elements; + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + textureProperties.__webglTexture = _gl.createTexture(); - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + _infoMemory.textures ++; - return array; + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - } + // Setup framebuffer -}; + if ( isCube ) { -// File:src/math/Ray.js + renderTargetProperties.__webglFramebuffer = []; -/** - * @author bhouston / http://clara.io - */ + for ( var i = 0; i < 6; i ++ ) { -THREE.Ray = function ( origin, direction ) { + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + } -}; + } else { -THREE.Ray.prototype = { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - constructor: THREE.Ray, + } - set: function ( origin, direction ) { + // Setup color buffer - this.origin.copy( origin ); - this.direction.copy( direction ); + if ( isCube ) { - return this; + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); - }, + for ( var i = 0; i < 6; i ++ ) { - clone: function () { + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - return new this.constructor().copy( this ); + } - }, + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - copy: function ( ray ) { + } else { - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); - return this; + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + state.bindTexture( _gl.TEXTURE_2D, null ); - }, + } - at: function ( t, optionalTarget ) { + // Setup depth and stencil buffers - var result = optionalTarget || new THREE.Vector3(); + if ( renderTarget.depthBuffer ) { - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + setupDepthRenderbuffer( renderTarget ); - }, + } - lookAt: function ( v ) { + } - this.direction.copy( v ).sub( this.origin ).normalize(); + function updateRenderTargetMipmap( renderTarget ) { - return this; + var texture = renderTarget.texture; - }, + if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - recast: function () { + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; - var v1 = new THREE.Vector3(); + state.bindTexture( target, webglTexture ); + _gl.generateMipmap( target ); + state.bindTexture( target, null ); - return function recast( t ) { + } - this.origin.copy( this.at( t, v1 ) ); + } - return this; + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - }; + }; - }(), + /** + * @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 + */ - closestPointToPoint: function ( point, optionalTarget ) { + function Vector4 ( x, y, z, w ) { + this.isVector4 = true; - var result = optionalTarget || new THREE.Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - if ( directionDistance < 0 ) { + }; - return result.copy( this.origin ); + Vector4.prototype = { - } + constructor: Vector4, - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + set: function ( x, y, z, w ) { - }, + this.x = x; + this.y = y; + this.z = z; + this.w = w; - distanceToPoint: function ( point ) { + return this; - return Math.sqrt( this.distanceSqToPoint( point ) ); + }, - }, + setScalar: function ( scalar ) { - distanceSqToPoint: function () { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - var v1 = new THREE.Vector3(); + return this; - return function distanceSqToPoint( point ) { + }, - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + setX: function ( x ) { - // point behind the ray + this.x = x; - if ( directionDistance < 0 ) { + return this; - return this.origin.distanceToSquared( point ); + }, - } + setY: function ( y ) { - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + this.y = y; - return v1.distanceToSquared( point ); + return this; - }; + }, - }(), + setZ: function ( z ) { - distanceSqToSegment: function () { + this.z = z; - var segCenter = new THREE.Vector3(); - var segDir = new THREE.Vector3(); - var diff = new THREE.Vector3(); + return this; - return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + }, - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // 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 + setW: function ( w ) { - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + this.w = w; - var segExtent = v0.distanceTo( v1 ) * 0.5; - 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; + return this; - if ( det > 0 ) { + }, - // The ray and segment are not parallel. + setComponent: function ( index, value ) { - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + switch ( index ) { - if ( s0 >= 0 ) { + 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 ); - if ( s1 >= - extDet ) { + } - if ( s1 <= extDet ) { + }, - // region 0 - // Minimum at interior points of ray and segment. + getComponent: function ( index ) { - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + 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 ); - // region 1 + } - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + }, - } + clone: function () { - } else { + return new this.constructor( this.x, this.y, this.z, this.w ); - // region 5 + }, - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + copy: function ( v ) { - } + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - } else { + return this; - if ( s1 <= - extDet ) { + }, - // region 4 + add: function ( v, w ) { - 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; + if ( w !== undefined ) { - } else if ( s1 <= extDet ) { + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - // region 3 + } - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - } else { + return this; - // 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; + addScalar: function ( s ) { - } + this.x += s; + this.y += s; + this.z += s; + this.w += s; - } + return this; - } else { + }, - // Ray and segment are parallel. + addVectors: function ( a, b ) { - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - } + return this; - if ( optionalPointOnRay ) { + }, - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + addScaledVector: function ( v, s ) { - } + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - if ( optionalPointOnSegment ) { + return this; - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + }, - } + sub: function ( v, w ) { - return sqrDist; + if ( w !== undefined ) { - }; + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - }(), + } - intersectSphere: function () { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - var v1 = new THREE.Vector3(); + return this; - return function intersectSphere( sphere, optionalTarget ) { + }, - v1.subVectors( sphere.center, this.origin ); - var tca = v1.dot( this.direction ); - var d2 = v1.dot( v1 ) - tca * tca; - var radius2 = sphere.radius * sphere.radius; + subScalar: function ( s ) { - if ( d2 > radius2 ) return null; + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - var thc = Math.sqrt( radius2 - d2 ); + return this; - // 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; + subVectors: function ( a, b ) { - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - // 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 ); + return this; - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + }, - }; + multiplyScalar: function ( scalar ) { - }(), + if ( isFinite( scalar ) ) { - intersectsSphere: function ( sphere ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - return this.distanceToPoint( sphere.center ) <= sphere.radius; + } else { - }, + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; - distanceToPlane: function ( plane ) { + } - var denominator = plane.normal.dot( this.direction ); + return this; - if ( denominator === 0 ) { + }, - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + applyMatrix4: function ( m ) { - return 0; + var x = this.x, y = this.y, z = this.z, w = this.w; + 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; - // Null is preferable to undefined since undefined means.... it is undefined + return this; - return null; + }, - } + divideScalar: function ( scalar ) { - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + return this.multiplyScalar( 1 / scalar ); - // Return if the ray never intersects the plane + }, - return t >= 0 ? t : null; + setAxisAngleFromQuaternion: function ( q ) { - }, + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - intersectPlane: function ( plane, optionalTarget ) { + // q is assumed to be normalized - var t = this.distanceToPlane( plane ); + this.w = 2 * Math.acos( q.w ); - if ( t === null ) { + var s = Math.sqrt( 1 - q.w * q.w ); - return null; + if ( s < 0.0001 ) { - } + this.x = 1; + this.y = 0; + this.z = 0; - return this.at( t, optionalTarget ); + } else { - }, + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; - intersectsPlane: function ( plane ) { + }, - // check if the ray lies on the plane first + setAxisAngleFromRotationMatrix: function ( m ) { - var distToPoint = plane.distanceToPoint( this.origin ); + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - if ( distToPoint === 0 ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return true; + 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 - } + te = m.elements, - var denominator = plane.normal.dot( this.direction ); + 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 ( denominator * distToPoint < 0 ) { + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - return true; + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - } + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - // ray origin is behind the plane (and is pointing behind it) + // this singularity is identity matrix so angle = 0 - return false; + this.set( 1, 0, 0, 0 ); - }, + return this; // zero angle, arbitrary axis - intersectBox: function ( box, optionalTarget ) { + } - var tmin, tmax, tymin, tymax, tzmin, tzmax; + // otherwise this singularity is angle = 180 - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + angle = Math.PI; - var origin = this.origin; + 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; - if ( invdirx >= 0 ) { + if ( ( xx > yy ) && ( xx > zz ) ) { - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + // m11 is the largest diagonal term - } else { + if ( xx < epsilon ) { - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + x = 0; + y = 0.707106781; + z = 0.707106781; - } + } else { - if ( invdiry >= 0 ) { + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + } - } else { + } else if ( yy > zz ) { - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + // m22 is the largest diagonal term - } + if ( yy < epsilon ) { - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + x = 0.707106781; + y = 0; + z = 0.707106781; - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + } else { - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + } - if ( invdirz >= 0 ) { + } else { - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + // m33 is the largest diagonal term so base result on this - } else { + if ( zz < epsilon ) { - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + x = 0.707106781; + y = 0.707106781; + z = 0; - } + } else { - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + } - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + } - //return point closest to the ray (positive side) + this.set( x, y, z, angle ); - if ( tmax < 0 ) return null; + return this; // return 180 deg rotation - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + } - }, + // as we have reached here there are no singularities so we can handle normally - intersectsBox: ( function () { + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - var v = new THREE.Vector3(); + if ( Math.abs( s ) < 0.001 ) s = 1; - return function intersectsBox( box ) { + // 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 - return this.intersectBox( box, v ) !== null; + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - }; + return this; - } )(), + }, - intersectTriangle: function () { + min: function ( v ) { - // 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(); + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { + return this; - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + }, - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + max: function ( v ) { - // 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; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - if ( DdN > 0 ) { + return this; - if ( backfaceCulling ) return null; - sign = 1; + }, - } else if ( DdN < 0 ) { + clamp: function ( min, max ) { - sign = - 1; - DdN = - DdN; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - } else { + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - return null; + return this; - } + }, - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + clampScalar: function () { - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + var min, max; - return null; + return function clampScalar( minVal, maxVal ) { - } + if ( min === undefined ) { - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + min = new Vector4(); + max = new Vector4(); - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + } - return null; + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - } + return this.clamp( min, max ); - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + }; - return null; + }(), - } + floor: function () { - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - // t < 0, no intersection - if ( QdN < 0 ) { + return this; - return null; + }, - } + ceil: function () { - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - }; + return this; - }(), + }, - applyMatrix4: function ( matrix4 ) { + round: function () { - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); + 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; + return this; - }, + }, - equals: function ( ray ) { + roundToZero: function () { - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + 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 ); - } + return this; -}; + }, -// File:src/math/Sphere.js + negate: function () { -/** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; -THREE.Sphere = function ( center, radius ) { + return this; - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + }, -}; + dot: function ( v ) { -THREE.Sphere.prototype = { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - constructor: THREE.Sphere, + }, - set: function ( center, radius ) { + lengthSq: function () { - this.center.copy( center ); - this.radius = radius; + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - return this; + }, - }, + length: function () { - setFromPoints: function () { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - var box = new THREE.Box3(); + }, - return function setFromPoints( points, optionalCenter ) { + lengthManhattan: function () { - var center = this.center; + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - if ( optionalCenter !== undefined ) { + }, - center.copy( optionalCenter ); + normalize: function () { - } else { + return this.divideScalar( this.length() ); - box.setFromPoints( points ).center( center ); + }, - } + setLength: function ( length ) { - var maxRadiusSq = 0; + return this.multiplyScalar( length / this.length() ); - for ( var i = 0, il = points.length; i < il; i ++ ) { + }, - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + lerp: function ( v, alpha ) { - } + 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.radius = Math.sqrt( maxRadiusSq ); + return this; - return this; + }, - }; + lerpVectors: function ( v1, v2, alpha ) { - }(), + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - clone: function () { + }, - return new this.constructor().copy( this ); + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - copy: function ( sphere ) { + }, - this.center.copy( sphere.center ); - this.radius = sphere.radius; + fromArray: function ( array, offset ) { - return this; + if ( offset === undefined ) offset = 0; - }, + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - empty: function () { + return this; - return ( this.radius <= 0 ); + }, - }, + toArray: function ( array, offset ) { - containsPoint: function ( point ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - }, + return array; - distanceToPoint: function ( point ) { + }, - return ( point.distanceTo( this.center ) - this.radius ); + fromAttribute: function ( attribute, index, offset ) { - }, + if ( offset === undefined ) offset = 0; - intersectsSphere: function ( sphere ) { + index = index * attribute.itemSize + offset; - var radiusSum = this.radius + sphere.radius; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + return this; - }, + } - intersectsBox: function ( box ) { + }; - return box.intersectsSphere( this ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function WebGLState ( gl, extensions, paramThreeToGL ) { + this.isWebGLState = true; - intersectsPlane: function ( plane ) { + var _this = this; - // We use the following equation to compute the signed distance from - // the center of the sphere to the plane. - // - // distance = q * n - d - // - // If this distance is greater than the radius of the sphere, - // then there is no intersection. + this.buffers = { + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) + }; - return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; + var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - }, + var capabilities = {}; - clampPoint: function ( point, optionalTarget ) { + var compressedTextureFormats = null; - var deltaLengthSq = this.center.distanceToSquared( point ); + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; + var currentPremultipledAlpha = false; - var result = optionalTarget || new THREE.Vector3(); + var currentFlipSided = null; + var currentCullFace = null; - result.copy( point ); + var currentLineWidth = null; - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + var currentScissorTest = null; - } + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - return result; + var currentTextureSlot = null; + var currentBoundTextures = {}; - }, + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); - getBoundingBox: function ( optionalTarget ) { + function createTexture( type, target, count ) { - var box = optionalTarget || new THREE.Box3(); + var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + var texture = gl.createTexture(); - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - return box; + for ( var i = 0; i < count; i ++ ) { - }, + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); - applyMatrix4: function ( matrix ) { + } - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return texture; - return this; + } - }, + var emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); - translate: function ( offset ) { + // - this.center.add( offset ); + this.init = function () { - return this; + this.clearColor( 0, 0, 0, 1 ); + this.clearDepth( 1 ); + this.clearStencil( 0 ); - }, + this.enable( gl.DEPTH_TEST ); + this.setDepthFunc( LessEqualDepth ); - equals: function ( sphere ) { + this.setFlipSided( false ); + this.setCullFace( CullFaceBack ); + this.enable( gl.CULL_FACE ); - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + this.enable( gl.BLEND ); + this.setBlending( NormalBlending ); - } + }; -}; + this.initAttributes = function () { -// File:src/math/Frustum.js + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + newAttributes[ i ] = 0; -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() + this.enableAttribute = function ( attribute ) { - ]; + newAttributes[ attribute ] = 1; -}; + if ( enabledAttributes[ attribute ] === 0 ) { -THREE.Frustum.prototype = { + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - constructor: THREE.Frustum, + } - set: function ( p0, p1, p2, p3, p4, p5 ) { + if ( attributeDivisors[ attribute ] !== 0 ) { - var planes = this.planes; + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + extension.vertexAttribDivisorANGLE( attribute, 0 ); + attributeDivisors[ attribute ] = 0; - return this; + } - }, + }; - clone: function () { + this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { - return new this.constructor().copy( this ); + newAttributes[ attribute ] = 1; - }, + if ( enabledAttributes[ attribute ] === 0 ) { - copy: function ( frustum ) { + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - var planes = this.planes; + } - for ( var i = 0; i < 6; i ++ ) { + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { - planes[ i ].copy( frustum.planes[ i ] ); + extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; - } + } - return this; + }; - }, + this.disableUnusedAttributes = function () { - setFromMatrix: function ( m ) { + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - 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 ]; + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - 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(); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - return this; + } - }, + } - intersectsObject: function () { + }; - var sphere = new THREE.Sphere(); + this.enable = function ( id ) { - return function intersectsObject( object ) { + if ( capabilities[ id ] !== true ) { - var geometry = object.geometry; + gl.enable( id ); + capabilities[ id ] = true; - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + } - sphere.copy( geometry.boundingSphere ) - .applyMatrix4( object.matrixWorld ); + }; - return this.intersectsSphere( sphere ); + this.disable = function ( id ) { - }; + if ( capabilities[ id ] !== false ) { - }(), + gl.disable( id ); + capabilities[ id ] = false; - intersectsSprite: function () { + } - var sphere = new THREE.Sphere(); + }; - return function intersectsSprite( sprite ) { + this.getCompressedTextureFormats = function () { - sphere.center.set( 0, 0, 0 ); - sphere.radius = 0.7071067811865476; - sphere.applyMatrix4( sprite.matrixWorld ); + if ( compressedTextureFormats === null ) { - return this.intersectsSphere( sphere ); + compressedTextureFormats = []; - }; + if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || + extensions.get( 'WEBGL_compressed_texture_s3tc' ) || + extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { - }(), + var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); - intersectsSphere: function ( sphere ) { + for ( var i = 0; i < formats.length; i ++ ) { - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + compressedTextureFormats.push( formats[ i ] ); - for ( var i = 0; i < 6; i ++ ) { + } - var distance = planes[ i ].distanceToPoint( center ); + } - if ( distance < negRadius ) { + } - return false; + return compressedTextureFormats; - } + }; - } + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - return true; + if ( blending !== NoBlending ) { - }, + this.enable( gl.BLEND ); - intersectsBox: function () { + } else { - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + this.disable( gl.BLEND ); + currentBlending = blending; // no blending, that is + return; - return function intersectsBox( box ) { + } - var planes = this.planes; + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - for ( var i = 0; i < 6 ; i ++ ) { + if ( blending === AdditiveBlending ) { - var plane = planes[ i ]; + if ( premultipliedAlpha ) { - 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; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + } else { - // if both outside plane, no intersection + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - if ( d1 < 0 && d2 < 0 ) { + } - return false; + } else if ( blending === SubtractiveBlending ) { - } + if ( premultipliedAlpha ) { - } + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); - return true; + } else { - }; + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - }(), + } + } else if ( blending === MultiplyBlending ) { - containsPoint: function ( point ) { + if ( premultipliedAlpha ) { - var planes = this.planes; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - for ( var i = 0; i < 6; i ++ ) { + } else { - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - return false; + } - } + } else { - } + if ( premultipliedAlpha ) { - return true; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - } + } else { -}; + 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 ); -// File:src/math/Plane.js + } -/** - * @author bhouston / http://clara.io - */ + } -THREE.Plane = function ( normal, constant ) { + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + } -}; + if ( blending === CustomBlending ) { -THREE.Plane.prototype = { + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - constructor: THREE.Plane, + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - set: function ( normal, constant ) { + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); - this.normal.copy( normal ); - this.constant = constant; + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - return this; + } - }, + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - setComponents: function ( x, y, z, w ) { + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - this.normal.set( x, y, z ); - this.constant = w; + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - return this; + } - }, + } else { - setFromNormalAndCoplanarPoint: function ( normal, point ) { + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + } - return this; + }; - }, + // TODO Deprecate - setFromCoplanarPoints: function () { + this.setColorWrite = function ( colorWrite ) { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + this.buffers.color.setMask( colorWrite ); - return function setFromCoplanarPoints( a, b, c ) { + }; - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); + this.setDepthTest = function ( depthTest ) { - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + this.buffers.depth.setTest( depthTest ); - this.setFromNormalAndCoplanarPoint( normal, a ); + }; - return this; + this.setDepthWrite = function ( depthWrite ) { - }; + this.buffers.depth.setMask( depthWrite ); - }(), + }; - clone: function () { + this.setDepthFunc = function ( depthFunc ) { - return new this.constructor().copy( this ); + this.buffers.depth.setFunc( depthFunc ); - }, + }; - copy: function ( plane ) { + this.setStencilTest = function ( stencilTest ) { - this.normal.copy( plane.normal ); - this.constant = plane.constant; + this.buffers.stencil.setTest( stencilTest ); - return this; + }; - }, + this.setStencilWrite = function ( stencilWrite ) { - normalize: function () { + this.buffers.stencil.setMask( stencilWrite ); - // Note: will lead to a divide by zero if the plane is invalid. + }; - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { - return this; + this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); - }, + }; - negate: function () { + this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { - this.constant *= - 1; - this.normal.negate(); + this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); - return this; + }; - }, + // - distanceToPoint: function ( point ) { + this.setFlipSided = function ( flipSided ) { - return this.normal.dot( point ) + this.constant; + if ( currentFlipSided !== flipSided ) { - }, + if ( flipSided ) { - distanceToSphere: function ( sphere ) { + gl.frontFace( gl.CW ); - return this.distanceToPoint( sphere.center ) - sphere.radius; + } else { - }, + gl.frontFace( gl.CCW ); - projectPoint: function ( point, optionalTarget ) { + } - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + currentFlipSided = flipSided; - }, + } - orthoPoint: function ( point, optionalTarget ) { + }; - var perpendicularMagnitude = this.distanceToPoint( point ); + this.setCullFace = function ( cullFace ) { - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + if ( cullFace !== CullFaceNone ) { - }, + this.enable( gl.CULL_FACE ); - intersectLine: function () { + if ( cullFace !== currentCullFace ) { - var v1 = new THREE.Vector3(); + if ( cullFace === CullFaceBack ) { - return function intersectLine( line, optionalTarget ) { + gl.cullFace( gl.BACK ); - var result = optionalTarget || new THREE.Vector3(); + } else if ( cullFace === CullFaceFront ) { - var direction = line.delta( v1 ); + gl.cullFace( gl.FRONT ); - var denominator = this.normal.dot( direction ); + } else { - if ( denominator === 0 ) { + gl.cullFace( gl.FRONT_AND_BACK ); - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + } - return result.copy( line.start ); + } - } + } else { - // Unsure if this is the correct method to handle this case. - return undefined; + this.disable( gl.CULL_FACE ); - } + } - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + currentCullFace = cullFace; - if ( t < 0 || t > 1 ) { + }; - return undefined; + this.setLineWidth = function ( width ) { - } + if ( width !== currentLineWidth ) { - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + gl.lineWidth( width ); - }; + currentLineWidth = width; - }(), + } - intersectsLine: function ( line ) { + }; - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + this.setPolygonOffset = function ( polygonOffset, factor, units ) { - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + if ( polygonOffset ) { - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + this.enable( gl.POLYGON_OFFSET_FILL ); - }, + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - intersectsBox: function ( box ) { + gl.polygonOffset( factor, units ); - return box.intersectsPlane( this ); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - }, + } - intersectsSphere: function ( sphere ) { + } else { - return sphere.intersectsPlane( this ); + this.disable( gl.POLYGON_OFFSET_FILL ); - }, + } - coplanarPoint: function ( optionalTarget ) { + }; - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + this.getScissorTest = function () { - }, + return currentScissorTest; - applyMatrix4: function () { + }; - var v1 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + this.setScissorTest = function ( scissorTest ) { - return function applyMatrix4( matrix, optionalNormalMatrix ) { + currentScissorTest = scissorTest; - var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); + if ( scissorTest ) { - // transform normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + this.enable( gl.SCISSOR_TEST ); - // recalculate constant (like in setFromNormalAndCoplanarPoint) - this.constant = - referencePoint.dot( normal ); + } else { - return this; + this.disable( gl.SCISSOR_TEST ); - }; + } - }(), + }; - translate: function ( offset ) { + // texture - this.constant = this.constant - offset.dot( this.normal ); + this.activeTexture = function ( webglSlot ) { - return this; + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; - }, + if ( currentTextureSlot !== webglSlot ) { - equals: function ( plane ) { + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + } - } + }; -}; + this.bindTexture = function ( webglType, webglTexture ) { -// File:src/math/Spherical.js + if ( currentTextureSlot === null ) { -/** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The poles (phi) are at the positive and negative y axis. - * The equator starts at positive z. - */ + _this.activeTexture(); -THREE.Spherical = function ( radius, phi, theta ) { + } - this.radius = ( radius !== undefined ) ? radius : 1.0; - this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole - this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - return this; + if ( boundTexture === undefined ) { -}; + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; -THREE.Spherical.prototype = { + } - constructor: THREE.Spherical, + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - set: function ( radius, phi, theta ) { + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - this.radius = radius; - this.phi = phi; - this.theta = theta; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - return this; + } - }, + }; - clone: function () { + this.compressedTexImage2D = function () { - return new this.constructor().copy( this ); + try { - }, + gl.compressedTexImage2D.apply( gl, arguments ); - copy: function ( other ) { + } catch ( error ) { - this.radius.copy( other.radius ); - this.phi.copy( other.phi ); - this.theta.copy( other.theta ); + console.error( error ); - return this; + } - }, + }; - // restrict phi to be betwee EPS and PI-EPS - makeSafe: function() { + this.texImage2D = function () { - var EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + try { - return this; + gl.texImage2D.apply( gl, arguments ); - }, + } catch ( error ) { - setFromVector3: function( vec3 ) { + console.error( error ); - this.radius = vec3.length(); + } - if ( this.radius === 0 ) { + }; - this.theta = 0; - this.phi = 0; + // TODO Deprecate - } else { + this.clearColor = function ( r, g, b, a ) { - this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis - this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + this.buffers.color.setClear( r, g, b, a ); - } + }; - return this; + this.clearDepth = function ( depth ) { - }, + this.buffers.depth.setClear( depth ); -}; + }; -// File:src/math/Math.js + this.clearStencil = function ( stencil ) { -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.buffers.stencil.setClear( stencil ); -THREE.Math = { + }; - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, + // - generateUUID: function () { + this.scissor = function ( scissor ) { - // http://www.broofa.com/Tools/Math.uuid.htm + if ( currentScissor.equals( scissor ) === false ) { - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - return function generateUUID() { + } - for ( var i = 0; i < 36; i ++ ) { + }; - if ( i === 8 || i === 13 || i === 18 || i === 23 ) { + this.viewport = function ( viewport ) { - uuid[ i ] = '-'; + if ( currentViewport.equals( viewport ) === false ) { - } else if ( i === 14 ) { + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - uuid[ i ] = '4'; + } - } else { + }; - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + // - } + this.reset = function () { - } + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - return uuid.join( '' ); + if ( enabledAttributes[ i ] === 1 ) { - }; + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - }(), + } - clamp: function ( value, min, max ) { + } - return Math.max( min, Math.min( max, value ) ); + capabilities = {}; - }, + compressedTextureFormats = null; - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + currentTextureSlot = null; + currentBoundTextures = {}; - euclideanModulo: function ( n, m ) { + currentBlending = null; - return ( ( n % m ) + m ) % m; + currentFlipSided = null; + currentCullFace = null; - }, + this.buffers.color.reset(); + this.buffers.depth.reset(); + this.buffers.stencil.reset(); - // Linear mapping from range to range + }; - mapLinear: function ( x, a1, a2, b1, b2 ) { + }; - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + function WebGLColorBuffer ( gl, state ) { + this.isWebGLColorBuffer = true; - }, + var locked = false; - // http://en.wikipedia.org/wiki/Smoothstep + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4(); - smoothstep: function ( x, min, max ) { + this.setMask = function ( colorMask ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + if ( currentColorMask !== colorMask && ! locked ) { - x = ( x - min ) / ( max - min ); + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - return x * x * ( 3 - 2 * x ); + } - }, + }; - smootherstep: function ( x, min, max ) { + this.setLocked = function ( lock ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + locked = lock; - x = ( x - min ) / ( max - min ); + }; - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + this.setClear = function ( r, g, b, a ) { - }, + color.set( r, g, b, a ); - random16: function () { + if ( currentColorClear.equals( color ) === false ) { - console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - }, + } - // Random integer from interval + }; - randInt: function ( low, high ) { + this.reset = function () { - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + locked = false; - }, + currentColorMask = null; + currentColorClear = new Vector4(); - // Random float from interval + }; - randFloat: function ( low, high ) { + }; - return low + Math.random() * ( high - low ); + function WebGLDepthBuffer( gl, state ) { + this.isWebGLDepthBuffer = true; - }, + var locked = false; - // Random float from <-range/2, range/2> interval + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - randFloatSpread: function ( range ) { + this.setTest = function ( depthTest ) { - return range * ( 0.5 - Math.random() ); + if ( depthTest ) { - }, + state.enable( gl.DEPTH_TEST ); - degToRad: function ( degrees ) { + } else { - return degrees * THREE.Math.DEG2RAD; + state.disable( gl.DEPTH_TEST ); - }, + } - radToDeg: function ( radians ) { + }; - return radians * THREE.Math.RAD2DEG; + this.setMask = function( depthMask ){ - }, + if ( currentDepthMask !== depthMask && ! locked ) { - isPowerOfTwo: function ( value ) { + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - return ( value & ( value - 1 ) ) === 0 && value !== 0; + } - }, + }; - nearestPowerOfTwo: function ( value ) { + this.setFunc = function ( depthFunc ) { - return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); + if ( currentDepthFunc !== depthFunc ) { - }, + if ( depthFunc ) { - nextPowerOfTwo: function ( value ) { + switch ( depthFunc ) { - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + case NeverDepth: - return value; + gl.depthFunc( gl.NEVER ); + break; - } + case AlwaysDepth: -}; + gl.depthFunc( gl.ALWAYS ); + break; -// File:src/math/Spline.js + case LessDepth: -/** - * 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/ - */ + gl.depthFunc( gl.LESS ); + break; -THREE.Spline = function ( points ) { + case LessEqualDepth: - this.points = points; + gl.depthFunc( gl.LEQUAL ); + break; - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + case EqualDepth: - this.initFromArray = function ( a ) { + gl.depthFunc( gl.EQUAL ); + break; - this.points = []; + case GreaterEqualDepth: - for ( var i = 0; i < a.length; i ++ ) { + gl.depthFunc( gl.GEQUAL ); + break; - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; + case GreaterDepth: - } + gl.depthFunc( gl.GREATER ); + break; - }; + case NotEqualDepth: - this.getPoint = function ( k ) { + gl.depthFunc( gl.NOTEQUAL ); + break; - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; + default: - 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; + gl.depthFunc( gl.LEQUAL ); - 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; + } else { - 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 ); + gl.depthFunc( gl.LEQUAL ); - return v3; + } - }; + currentDepthFunc = depthFunc; - this.getControlPointsArray = function () { + } - var i, p, l = this.points.length, - coords = []; + }; - for ( i = 0; i < l; i ++ ) { + this.setLocked = function ( lock ) { - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; + locked = lock; - } + }; - return coords; + this.setClear = function ( depth ) { - }; + if ( currentDepthClear !== depth ) { - // approximate length by summing linear segments + gl.clearDepth( depth ); + currentDepthClear = depth; - 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; + }; - // first point has 0 length + this.reset = function () { - chunkLengths[ 0 ] = 0; + locked = false; - if ( ! nSubDivisions ) nSubDivisions = 100; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - nSamples = this.points.length * nSubDivisions; + }; - oldPosition.copy( this.points[ 0 ] ); + }; - for ( i = 1; i < nSamples; i ++ ) { + function WebGLStencilBuffer ( gl, state ) { + this.isWebGLStencilBuffer = true; - index = i / nSamples; + var locked = false; - position = this.getPoint( index ); - tmpVec.copy( position ); + var currentStencilMask = null; + var currentStencilFunc = null; + var currentStencilRef = null; + var currentStencilFuncMask = null; + var currentStencilFail = null; + var currentStencilZFail = null; + var currentStencilZPass = null; + var currentStencilClear = null; - totalLength += tmpVec.distanceTo( oldPosition ); + this.setTest = function ( stencilTest ) { - oldPosition.copy( position ); + if ( stencilTest ) { - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); + state.enable( gl.STENCIL_TEST ); - if ( intPoint !== oldIntPoint ) { + } else { - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; + state.disable( gl.STENCIL_TEST ); - } + } - } + }; - // last point ends with total length + this.setMask = function ( stencilMask ) { - chunkLengths[ chunkLengths.length ] = totalLength; + if ( currentStencilMask !== stencilMask && ! locked ) { - return { chunks: chunkLengths, total: totalLength }; + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; - }; + } - this.reparametrizeByArcLength = function ( samplingCoef ) { + }; - var i, j, - index, indexCurrent, indexNext, - realDistance, - sampling, position, - newpoints = [], - tmpVec = new THREE.Vector3(), - sl = this.getLength(); + this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - for ( i = 1; i < this.points.length; i ++ ) { + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; + } - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); + }; - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); + this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { - for ( j = 1; j < sampling - 1; j ++ ) { + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - } + } - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); + }; - } + this.setLocked = function ( lock ) { - this.points = newpoints; + locked = lock; - }; + }; - // Catmull-Rom + this.setClear = function ( stencil ) { - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { + if ( currentStencilClear !== stencil ) { - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + gl.clearStencil( stencil ); + currentStencilClear = stencil; - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + } - } + }; -}; + this.reset = function () { -// File:src/math/Triangle.js + locked = false; -/** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; -THREE.Triangle = function ( a, b, c ) { + }; - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); + }; -}; + /** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ -THREE.Triangle.normal = function () { + /* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers + */ + function WebGLRenderTarget ( width, height, options ) { + this.isWebGLRenderTarget = true; - var v0 = new THREE.Vector3(); + this.uuid = exports.Math.generateUUID(); - return function normal( a, b, c, optionalTarget ) { + this.width = width; + this.height = height; - var result = optionalTarget || new THREE.Vector3(); + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + this.viewport = new Vector4( 0, 0, width, height ); - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + options = options || {}; - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - } + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - return result.set( 0, 0, 0 ); + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = null; - }; + }; -}(); + Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { -// static/instance method to calculate barycentric coordinates -// based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { + setSize: function ( width, height ) { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + if ( this.width !== width || this.height !== height ) { - return function barycoordFromPoint( point, a, b, c, optionalTarget ) { + this.width = width; + this.height = height; - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + this.dispose(); - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); + } - var denom = ( dot00 * dot11 - dot01 * dot01 ); + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - var result = optionalTarget || new THREE.Vector3(); + }, - // collinear or singular triangle - if ( denom === 0 ) { + clone: function () { - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + return new this.constructor().copy( this ); - } + }, - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + copy: function ( source ) { - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + this.width = source.width; + this.height = source.height; - }; + this.viewport.copy( source.viewport ); -}(); + this.texture = source.texture.clone(); -THREE.Triangle.containsPoint = function () { + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - var v1 = new THREE.Vector3(); + return this; - return function containsPoint( point, a, b, c ) { + }, - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + dispose: function () { - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + this.dispatchEvent( { type: 'dispose' } ); - }; + } -}(); + } ); -THREE.Triangle.prototype = { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - constructor: THREE.Triangle, + function Material () { + this.isMaterial = true; - set: function ( a, b, c ) { + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + this.uuid = exports.Math.generateUUID(); - return this; + this.name = ''; + this.type = 'Material'; - }, + this.fog = true; + this.lights = true; - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + this.opacity = 1; + this.transparent = false; - return this; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - }, + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - clone: function () { + this.clippingPlanes = null; + this.clipShadows = false; - return new this.constructor().copy( this ); + this.colorWrite = true; - }, + this.precision = null; // override the renderer's default precision for this material - copy: function ( triangle ) { + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + this.alphaTest = 0; + this.premultipliedAlpha = false; - return this; + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - }, + this.visible = true; - area: function () { + this._needsUpdate = true; - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + }; - return function area() { + Material.prototype = { - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + constructor: Material, - return v0.cross( v1 ).length() * 0.5; + get needsUpdate() { - }; + return this._needsUpdate; - }(), + }, - midpoint: function ( optionalTarget ) { + set needsUpdate( value ) { - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + if ( value === true ) this.update(); + this._needsUpdate = value; - }, + }, - normal: function ( optionalTarget ) { + setValues: function ( values ) { - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); + if ( values === undefined ) return; - }, + for ( var key in values ) { - plane: function ( optionalTarget ) { + var newValue = values[ key ]; - var result = optionalTarget || new THREE.Plane(); + if ( newValue === undefined ) { - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - }, + } - barycoordFromPoint: function ( point, optionalTarget ) { + var currentValue = this[ key ]; - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + if ( currentValue === undefined ) { - }, + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - containsPoint: function ( point ) { + } - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + if ( (currentValue && currentValue.isColor) ) { - }, + currentValue.set( newValue ); - closestPointToPoint: function () { + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { - var plane, edgeList, projectedPoint, closestPoint; + currentValue.copy( newValue ); - return function closestPointToPoint( point, optionalTarget ) { + } else if ( key === 'overdraw' ) { - if ( plane === undefined ) { + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - plane = new THREE.Plane(); - edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ]; - projectedPoint = new THREE.Vector3(); - closestPoint = new THREE.Vector3(); + } else { - } + this[ key ] = newValue; - var result = optionalTarget || new THREE.Vector3(); - var minDistance = Infinity; + } - // project the point onto the plane of the triangle + } - plane.setFromCoplanarPoints( this.a, this.b, this.c ); - plane.projectPoint( point, projectedPoint ); + }, - // check if the projection lies within the triangle + toJSON: function ( meta ) { - if( this.containsPoint( projectedPoint ) === true ) { + var isRoot = meta === undefined; - // if so, this is the closest point + if ( isRoot ) { - result.copy( projectedPoint ); + meta = { + textures: {}, + images: {} + }; - } else { + } - // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices + var data = { + metadata: { + version: 4.4, + type: 'Material', + generator: 'Material.toJSON' + } + }; - edgeList[ 0 ].set( this.a, this.b ); - edgeList[ 1 ].set( this.b, this.c ); - edgeList[ 2 ].set( this.c, this.a ); + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - for( var i = 0; i < edgeList.length; i ++ ) { + if ( this.name !== '' ) data.name = this.name; - edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); - var distance = projectedPoint.distanceToSquared( closestPoint ); + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - if( distance < minDistance ) { + if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); + if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; - minDistance = distance; + if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; + if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( (this.bumpMap && this.bumpMap.isTexture) ) { - result.copy( closestPoint ); + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - } + } + if ( (this.normalMap && this.normalMap.isTexture) ) { - } + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - } + } + if ( (this.displacementMap && this.displacementMap.isTexture) ) { - return result; + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - }; + } + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - }(), + if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - equals: function ( triangle ) { + if ( (this.envMap && this.envMap.isTexture) ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - } + } -}; + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; -// File:src/math/Interpolant.js + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.shading !== SmoothShading ) data.shading = this.shading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; -/** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - * @author tschw - */ + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; -THREE.Interpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // TODO: Copied from Object3D.toJSON - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + function extractFromCache ( cache ) { - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + var values = []; -}; + for ( var key in cache ) { -THREE.Interpolant.prototype = { + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - constructor: THREE.Interpolant, + } - evaluate: function( t ) { + return values; - var pp = this.parameterPositions, - i1 = this._cachedIndex, + } - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + if ( isRoot ) { - validate_interval: { + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - seek: { + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - var right; + } - linear_scan: { -//- See http://jsperf.com/comparison-to-undefined/3 -//- slower code: -//- -//- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + return data; - for ( var giveUpAt = i1 + 2; ;) { + }, - if ( t1 === undefined ) { + clone: function () { - if ( t < t0 ) break forward_scan; + return new this.constructor().copy( this ); - // after end + }, - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + copy: function ( source ) { - } + this.name = source.name; - if ( i1 === giveUpAt ) break; // this loop + this.fog = source.fog; + this.lights = source.lights; - t0 = t1; - t1 = pp[ ++ i1 ]; + this.blending = source.blending; + this.side = source.side; + this.shading = source.shading; + this.vertexColors = source.vertexColors; - if ( t < t1 ) { + this.opacity = source.opacity; + this.transparent = source.transparent; - // we have arrived at the sought interval - break seek; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - } + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - } + this.colorWrite = source.colorWrite; - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + this.precision = source.precision; - } + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; -//- slower code: -//- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + this.alphaTest = source.alphaTest; - // looping? + this.premultipliedAlpha = source.premultipliedAlpha; - var t1global = pp[ 1 ]; + this.overdraw = source.overdraw; - if ( t < t1global ) { + this.visible = source.visible; + this.clipShadows = source.clipShadows; - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - } + if ( srcPlanes !== null ) { - // linear reverse scan + var n = srcPlanes.length; + dstPlanes = new Array( n ); - for ( var giveUpAt = i1 - 2; ;) { + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - if ( t0 === undefined ) { + } - // before start + this.clippingPlanes = dstPlanes; - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this; - } + }, - if ( i1 === giveUpAt ) break; // this loop + update: function () { - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + this.dispatchEvent( { type: 'update' } ); - if ( t >= t0 ) { + }, - // we have arrived at the sought interval - break seek; + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); - } + } - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + }; - } + Object.assign( Material.prototype, EventDispatcher.prototype ); - // the interval is valid + var count$1 = 0; + function MaterialIdCount () { return count$1++; }; - break validate_interval; + /** + * Uniform Utilities + */ - } // linear scan + exports.UniformsUtils = { - // binary search + merge: function ( uniforms ) { - while ( i1 < right ) { + var merged = {}; - var mid = ( i1 + right ) >>> 1; + for ( var u = 0; u < uniforms.length; u ++ ) { - if ( t < pp[ mid ] ) { + var tmp = this.clone( uniforms[ u ] ); - right = mid; + for ( var p in tmp ) { - } else { + merged[ p ] = tmp[ p ]; - i1 = mid + 1; + } - } + } - } + return merged; - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + }, - // check boundary cases, again + clone: function ( uniforms_src ) { - if ( t0 === undefined ) { + var uniforms_dst = {}; - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + for ( var u in uniforms_src ) { - } + uniforms_dst[ u ] = {}; - if ( t1 === undefined ) { + for ( var p in uniforms_src[ u ] ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + var parameter_src = uniforms_src[ u ][ p ]; - } + if ( (parameter_src && parameter_src.isColor) || + (parameter_src && parameter_src.isVector2) || + (parameter_src && parameter_src.isVector3) || + (parameter_src && parameter_src.isVector4) || + (parameter_src && parameter_src.isMatrix3) || + (parameter_src && parameter_src.isMatrix4) || + (parameter_src && parameter_src.isTexture) ) { - } // seek + uniforms_dst[ u ][ p ] = parameter_src.clone(); - this._cachedIndex = i1; + } else if ( Array.isArray( parameter_src ) ) { - this.intervalChanged_( i1, t0, t1 ); + uniforms_dst[ u ][ p ] = parameter_src.slice(); - } // validate_interval + } else { - return this.interpolate_( i1, t0, t, t1 ); + uniforms_dst[ u ][ p ] = parameter_src; - }, + } - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + } - // --- Protected interface + } - DefaultSettings_: {}, + return uniforms_dst; - getSettings_: function() { + } - return this.settings || this.DefaultSettings_; + }; - }, + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, + * + * fragmentShader: , + * vertexShader: , + * + * wireframe: , + * wireframeLinewidth: , + * + * lights: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - copySampleValue_: function( index ) { + function ShaderMaterial ( parameters ) { + this.isShaderMaterial = this.isMaterial = true; - // copies a sample value to the result buffer + Material.call( this ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + this.type = 'ShaderMaterial'; - for ( var i = 0; i !== stride; ++ i ) { + this.defines = {}; + this.uniforms = {}; - result[ i ] = values[ offset + i ]; + 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}'; - } + this.linewidth = 1; - return result; + this.wireframe = false; + this.wireframeLinewidth = 1; - }, + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes - // Template methods for derived classes: + this.skinning = false; // set to use skinning attribute streams + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - interpolate_: function( i1, t0, t, t1 ) { + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; - throw new Error( "call to abstract method" ); - // implementations shall return this.resultBuffer + // 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; - intervalChanged_: function( i1, t0, t1 ) { + if ( parameters !== undefined ) { - // empty + if ( parameters.attributes !== undefined ) { - } + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); -}; + } -Object.assign( THREE.Interpolant.prototype, { + this.setValues( parameters ); - beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_, + } - afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_ + }; -} ); + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; -// File:src/math/interpolants/CubicInterpolant.js + ShaderMaterial.prototype.copy = function ( source ) { -/** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - * - * @author tschw - */ + Material.prototype.copy.call( this, source ); -THREE.CubicInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + this.uniforms = exports.UniformsUtils.clone( source.uniforms ); - this._weightPrev = -0; - this._offsetPrev = -0; - this._weightNext = -0; - this._offsetNext = -0; + this.defines = source.defines; -}; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; -THREE.CubicInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + this.lights = source.lights; + this.clipping = source.clipping; - constructor: THREE.CubicInterpolant, + this.skinning = source.skinning; - DefaultSettings_: { + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + this.extensions = source.extensions; - }, + return this; - intervalChanged_: function( i1, t0, t1 ) { + }; - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + ShaderMaterial.prototype.toJSON = function ( meta ) { - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + var data = Material.prototype.toJSON.call( this, meta ); - if ( tPrev === undefined ) { + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - switch ( this.getSettings_().endingStart ) { + return data; - case THREE.ZeroSlopeEnding: + }; - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; - break; + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n"; - case THREE.WrapAroundEnding: + var alphatest_fragment = "#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + var ambient_pars = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n"; - break; + var aomap_fragment = "#ifdef USE_AOMAP\n\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n"; - default: // ZeroCurvatureEnding + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif"; - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + var begin_vertex = "\nvec3 transformed = vec3( position );\n"; - } + var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; - } + var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n\t\tif( decayExponent > 0.0 ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t\t\t// page 32, equation 26: E[window1]\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n\n#else\n\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n#endif\n\n\t\t}\n\n\t\treturn 1.0;\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\n\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n\treturn specularColor * AB.x + AB.y;\n\n} // validated\n\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; - if ( tNext === undefined ) { + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n"; - switch ( this.getSettings_().endingEnd ) { + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\n#endif\n"; - case THREE.ZeroSlopeEnding: + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n"; - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - break; + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n\n"; - case THREE.WrapAroundEnding: + var color_fragment = "#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif"; - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + var color_pars_fragment = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n"; - break; + var color_pars_vertex = "#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif"; - default: // ZeroCurvatureEnding + var color_vertex = "#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif"; - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n"; - } + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_textureSize (1024.0)\n\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\n\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\n\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\t// float powScale = exp2(roughnessLevel + mipLevel);\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\n\tfloat rcpPowScale = 1.0 / powScale;\n\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\n\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\n\t// round to nearest mipmap if we are not interpolating.\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\n\t// Tri linear interpolation.\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\n\tvec4 result = mix(color10, color20, t);\n\n\treturn vec4(result.rgb, 1.0);\n}\n\n#endif\n"; - } + var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\n\tobjectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n"; - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; - }, + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n"; - interpolate_: function( i1, t0, t, t1 ) { + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n"; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + var encodings_pars_fragment = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + var envmap_fragment = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\n\t#endif\n\n\tenvColor = envMapTexelToLinear( envColor );\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n"; - // evaluate polynomials + var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n\n#ifdef USE_ENVMAP\n\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n"; - var sP = - wP * ppp + 2 * wP * pp - wP * p; - var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; - var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - var sN = wN * ppp - wN * pp; + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n"; - // combine data linearly + var envmap_vertex = "#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n"; - for ( var i = 0; i !== stride; ++ i ) { + var fog_fragment = "#ifdef USE_FOG\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n\t#else\n\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\n\t#endif\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n"; - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + var fog_pars_fragment = "#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n\n#endif"; - } + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n"; - return result; + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif"; - } + var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\n#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\n#endif\n\n#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; -} ); + var lights_pars = "uniform vec3 ambientLightColor;\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\n\t}\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n\n\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\t#include \n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\n\t\t#endif\n\n\t\t#include \n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n"; -// File:src/math/interpolants/DiscreteInterpolant.js + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n"; -THREE.DiscreteInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\n\t#ifndef STANDARD\n\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\n\t#endif\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\n\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n"; -}; + var lights_template = "//\n// This is a template that can be used to light a material, it uses pluggable RenderEquations (RE)\n// for specific lighting scenarios.\n//\n// Instructions for use:\n// - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n// - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n// - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n//\n// TODO:\n// - Add area light support.\n// - Add sphere light support.\n// - Add diffuse light probe (irradiance cubemap) support.\n//\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t// TODO, replace 8 with the real maxMIPLevel\n\t \tirradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, 8 );\n\n\t#endif\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\t// TODO, replace 8 with the real maxMIPLevel\n\tvec3 radiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_BlinnShininessExponent( material ), 8 );\n\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n\n#endif\n"; -THREE.DiscreteInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; - constructor: THREE.DiscreteInterpolant, + var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\n\tuniform float logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n#endif\n"; - interpolate_: function( i1, t0, t, t1 ) { + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\n\t#endif\n\n\tuniform float logDepthBufFC;\n\n#endif"; - return this.copySampleValue_( i1 - 1 ); + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\n\t#else\n\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n\t#endif\n\n#endif\n"; - } + var map_fragment = "#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n"; -} ); + var map_pars_fragment = "#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n"; -// File:src/math/interpolants/LinearInterpolant.js + var map_particle_fragment = "#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n"; -/** - * @author tschw - */ + var map_particle_pars_fragment = "#ifdef USE_MAP\n\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n\n#endif\n"; -THREE.LinearInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + var metalnessmap_fragment = "float metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n\n#endif\n"; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif"; -}; + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; -THREE.LinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\n\t#ifndef USE_MORPHNORMALS\n\n\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif"; - constructor: THREE.LinearInterpolant, + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n"; - interpolate_: function( i1, t0, t, t1 ) { + var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + var normal_fragment = "#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n"; - offset1 = i1 * stride, - offset0 = offset1 - stride, + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n"; - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\n\treturn dot( v, UnpackFactors );\n\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; - for ( var i = 0; i !== stride; ++ i ) { + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n"; - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + var project_vertex = "#ifdef USE_SKINNING\n\n\tvec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; - } + var roughnessmap_fragment = "float roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n\n#endif\n"; - return result; + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif"; - } + var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\n\t\tvec2 f = fract( uv * size + 0.5 );\n\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\n\t\treturn c;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn 1.0;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the distance from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t// dp = distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n"; -} ); + var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\n\t#endif\n\n#endif\n"; -// File:src/math/interpolants/QuaternionLinearInterpolant.js + var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\n\t}\n\n\t#endif\n\n#endif\n"; -/** - * Spherical linear unit quaternion interpolant. - * - * @author tschw - */ + var shadowmask_pars_fragment = "float getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHTS > 0\n\n\tDirectionalLight directionalLight;\n\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHTS > 0\n\n\tSpotLight spotLight;\n\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#if NUM_POINT_LIGHTS > 0\n\n\tPointLight pointLight;\n\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\n\t}\n\n\t#endif\n\n\t#endif\n\n\treturn shadow;\n\n}\n"; -THREE.QuaternionLinearInterpolant = function( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + var skinbase_vertex = "#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; - THREE.Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + var skinning_pars_vertex = "#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n"; -}; + var skinning_vertex = "#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n\n#endif\n"; -THREE.QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { + var skinnormal_vertex = "#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; - constructor: THREE.QuaternionLinearInterpolant, + var specularmap_fragment = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif"; - interpolate_: function( i1, t0, t, t1 ) { + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif"; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n"; - offset = i1 * stride, + var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\n\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n return toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\n // John Hable's filmic operator from Uncharted 2 video game\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n\n}\n\n// source: http://filmicgames.com/archives/75\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n"; - alpha = ( t - t0 ) / ( t1 - t0 ); + var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\n#endif"; - for ( var end = offset + stride; offset !== end; offset += 4 ) { + var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n\n#endif\n"; - THREE.Quaternion.slerpFlat( result, 0, - values, offset - stride, values, offset, alpha ); + var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; - } + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif"; - return result; + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n#endif"; - } + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = uv2;\n\n#endif"; -} ); + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n\t#ifdef USE_SKINNING\n\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\n\t#else\n\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n\t#endif\n\n#endif\n"; -// File:src/core/Clock.js + var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n\n}\n"; -/** - * @author alteredq / http://alteredqualia.com/ - */ + var cube_vert = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; -THREE.Clock = function ( autoStart ) { + var depth_frag = "#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\n\t#endif\n\n}\n"; - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n\n#include \n#include \n#include \n\nvoid main () {\n\n\t#include \n\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n\n}\n"; - this.running = false; + var distanceRGBA_vert = "varying vec4 vWorldPosition;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvWorldPosition = worldPosition;\n\n}\n"; -}; + var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\n\nvarying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n}\n"; -THREE.Clock.prototype = { + var equirect_vert = "varying vec3 vWorldPosition;\n\n#include \n\nvoid main() {\n\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\n\t#include \n\t#include \n\n}\n"; - constructor: THREE.Clock, + var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - start: function () { + var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvLineDistance = scale * lineDistance;\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include \n\t#include \n\n}\n"; - this.startTime = ( performance || Date ).now(); + var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - this.oldTime = this.startTime; - this.running = true; + var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_ENVMAP\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\n}\n"; - }, + var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\n\t#include \n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - stop: function () { + var meshlambert_vert = "#define LAMBERT\n\nvarying vec3 vLightFront;\n\n#ifdef DOUBLE_SIDED\n\n\tvarying vec3 vLightBack;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - this.getElapsedTime(); - this.running = false; + var meshphong_frag = "#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include \n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - }, + var meshphong_vert = "#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\n}\n"; - getElapsedTime: function () { + var meshphysical_frag = "#define PHYSICAL\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\n\nuniform float envMapIntensity; // temporary\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - this.getDelta(); - return this.elapsedTime; + var meshphysical_vert = "#define PHYSICAL\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\n}\n"; - }, + var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\n\t#include \n\n}\n"; - getDelta: function () { + var normal_vert = "varying vec3 vNormal;\n\n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tvNormal = normalize( normalMatrix * normal );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - var diff = 0; + var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - if ( this.autoStart && ! this.running ) { + var points_vert = "uniform float size;\nuniform float scale;\n\n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - this.start(); + var shadow_frag = "uniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid main() {\n\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n\n}\n"; - } + var shadow_vert = "#include \n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n"; - if ( this.running ) { + var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + ambient_pars: ambient_pars, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_vertex: envmap_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars: lights_pars, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_template: lights_template, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_flip: normal_flip, + normal_fragment: normal_fragment, + normalmap_pars_fragment: normalmap_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, + + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert + }; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function Color ( r, g, b ) { + this.isColor = true; + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + return this.set( r ); + + } + + return this.setRGB( r, g, b ); + + }; - var newTime = ( performance || Date ).now(); + Color.prototype = { - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + constructor: Color, - this.elapsedTime += diff; + r: 1, g: 1, b: 1, - } + set: function ( value ) { - return diff; + if ( (value && value.isColor) ) { - } + this.copy( value ); -}; + } else if ( typeof value === 'number' ) { -// File:src/core/EventDispatcher.js + this.setHex( value ); -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ + } else if ( typeof value === 'string' ) { -THREE.EventDispatcher = function () {}; + this.setStyle( value ); -Object.assign( THREE.EventDispatcher.prototype, { + } - addEventListener: function ( type, listener ) { + return this; - if ( this._listeners === undefined ) this._listeners = {}; + }, - var listeners = this._listeners; + setScalar: function ( scalar ) { - if ( listeners[ type ] === undefined ) { + this.r = scalar; + this.g = scalar; + this.b = scalar; - listeners[ type ] = []; + }, - } + setHex: function ( hex ) { - if ( listeners[ type ].indexOf( listener ) === - 1 ) { + hex = Math.floor( hex ); - listeners[ type ].push( listener ); + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - } + return this; - }, + }, - hasEventListener: function ( type, listener ) { + setRGB: function ( r, g, b ) { - if ( this._listeners === undefined ) return false; + this.r = r; + this.g = g; + this.b = b; - var listeners = this._listeners; + return this; - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + }, - return true; + setHSL: function () { - } + function hue2rgb( p, q, t ) { - return false; + 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; - }, + } - removeEventListener: function ( type, listener ) { + return function setHSL( h, s, l ) { - if ( this._listeners === undefined ) return; + // h,s,l ranges are in 0.0 - 1.0 + h = exports.Math.euclideanModulo( h, 1 ); + s = exports.Math.clamp( s, 0, 1 ); + l = exports.Math.clamp( l, 0, 1 ); - var listeners = this._listeners; - var listenerArray = listeners[ type ]; + if ( s === 0 ) { - if ( listenerArray !== undefined ) { + this.r = this.g = this.b = l; - var index = listenerArray.indexOf( listener ); + } else { - if ( index !== - 1 ) { + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - listenerArray.splice( index, 1 ); + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - } + } - } + return this; - }, + }; - dispatchEvent: function ( event ) { + }(), - if ( this._listeners === undefined ) return; + setStyle: function ( style ) { - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; + function handleAlpha( string ) { - if ( listenerArray !== undefined ) { + if ( string === undefined ) return; - event.target = this; + if ( parseFloat( string ) < 1 ) { - var array = [], i = 0; - var length = listenerArray.length; + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - for ( i = 0; i < length; i ++ ) { + } - array[ i ] = listenerArray[ i ]; + } - } - for ( i = 0; i < length; i ++ ) { + var m; - array[ i ].call( this, event ); + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - } + // rgb / hsl - } + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - } + switch ( name ) { -} ); + case 'rgb': + case 'rgba': -// File:src/core/Layers.js + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + // rgb(255,0,0) rgba(255,0,0,0.5) + 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; -THREE.Layers = function () { + handleAlpha( color[ 5 ] ); - this.mask = 1; + return this; -}; + } -THREE.Layers.prototype = { + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - constructor: THREE.Layers, + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + 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; - set: function ( channel ) { + handleAlpha( color[ 5 ] ); - this.mask = 1 << channel; + return this; - }, + } - enable: function ( channel ) { + break; - this.mask |= 1 << channel; + case 'hsl': + case 'hsla': - }, + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - toggle: function ( channel ) { + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + var h = parseFloat( color[ 1 ] ) / 360; + var s = parseInt( color[ 2 ], 10 ) / 100; + var l = parseInt( color[ 3 ], 10 ) / 100; - this.mask ^= 1 << channel; + handleAlpha( color[ 5 ] ); - }, + return this.setHSL( h, s, l ); - disable: function ( channel ) { + } - this.mask &= ~ ( 1 << channel ); + break; - }, + } - test: function ( layers ) { + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - return ( this.mask & layers.mask ) !== 0; + // hex color - } + var hex = m[ 1 ]; + var size = hex.length; -}; + if ( size === 3 ) { -// File:src/core/Raycaster.js + // #ff0 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; -/** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://clara.io/ - * @author stephomi / http://stephaneginier.com/ - */ + return this; -( function ( THREE ) { + } else if ( size === 6 ) { - THREE.Raycaster = function ( origin, direction, near, far ) { + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + return this; - this.near = near || 0; - this.far = far || Infinity; + } - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + } - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + if ( style && style.length > 0 ) { - }; + // color keywords + var hex = exports.ColorKeywords[ style ]; - function ascSort( a, b ) { + if ( hex !== undefined ) { - return a.distance - b.distance; + // red + this.setHex( hex ); - } + } else { - function intersectObject( object, raycaster, intersects, recursive ) { + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - if ( object.visible === false ) return; + } - object.raycast( raycaster, intersects ); + } - if ( recursive === true ) { + return this; - var children = object.children; + }, - for ( var i = 0, l = children.length; i < l; i ++ ) { + clone: function () { - intersectObject( children[ i ], raycaster, intersects, true ); + return new this.constructor( this.r, this.g, this.b ); - } + }, - } + copy: function ( color ) { - } + this.r = color.r; + this.g = color.g; + this.b = color.b; - // + return this; - THREE.Raycaster.prototype = { + }, - constructor: THREE.Raycaster, + copyGammaToLinear: function ( color, gammaFactor ) { - linePrecision: 1, + if ( gammaFactor === undefined ) gammaFactor = 2.0; - set: function ( origin, direction ) { + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - // direction is assumed to be normalized (for accurate distance calculations) + return this; - this.ray.set( origin, direction ); + }, - }, + copyLinearToGamma: function ( color, gammaFactor ) { - setFromCamera: function ( coords, camera ) { + if ( gammaFactor === undefined ) gammaFactor = 2.0; - if ( camera instanceof THREE.PerspectiveCamera ) { + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - } else if ( camera instanceof THREE.OrthographicCamera ) { + return this; - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + }, - } else { + convertGammaToLinear: function () { - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + var r = this.r, g = this.g, b = this.b; - } + this.r = r * r; + this.g = g * g; + this.b = b * b; - }, + return this; - intersectObject: function ( object, recursive ) { + }, - var intersects = []; + convertLinearToGamma: function () { - intersectObject( object, this, intersects, recursive ); + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - intersects.sort( ascSort ); + return this; - return intersects; + }, - }, + getHex: function () { - intersectObjects: function ( objects, recursive ) { + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - var intersects = []; + }, - if ( Array.isArray( objects ) === false ) { + getHexString: function () { - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - } + }, - for ( var i = 0, l = objects.length; i < l; i ++ ) { + getHSL: function ( optionalTarget ) { - intersectObject( objects[ i ], this, intersects, recursive ); + // h,s,l ranges are in 0.0 - 1.0 - } + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - intersects.sort( ascSort ); + var r = this.r, g = this.g, b = this.b; - return intersects; + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - } + var hue, saturation; + var lightness = ( min + max ) / 2.0; - }; + if ( min === max ) { -}( THREE ) ); + hue = 0; + saturation = 0; -// File:src/core/Object3D.js + } else { -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author elephantatwork / www.elephantatwork.ch - */ + var delta = max - min; -THREE.Object3D = function () { + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + switch ( max ) { - this.uuid = THREE.Math.generateUUID(); + 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.name = ''; - this.type = 'Object3D'; + } - this.parent = null; - this.children = []; + hue /= 6; - this.up = THREE.Object3D.DefaultUp.clone(); + } - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - function onRotationChange() { + return hsl; - quaternion.setFromEuler( rotation, false ); + }, - } + getStyle: function () { - function onQuaternionChange() { + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - rotation.setFromQuaternion( quaternion, undefined, false ); + }, - } + offsetHSL: function ( h, s, l ) { - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); + var hsl = this.getHSL(); - Object.defineProperties( this, { - position: { - enumerable: true, - value: position - }, - rotation: { - enumerable: true, - value: rotation - }, - quaternion: { - enumerable: true, - value: quaternion - }, - scale: { - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new THREE.Matrix4() - }, - normalMatrix: { - value: new THREE.Matrix3() - } - } ); + hsl.h += h; hsl.s += s; hsl.l += l; - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + this.setHSL( hsl.h, hsl.s, hsl.l ); - this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + return this; - this.layers = new THREE.Layers(); - this.visible = true; + }, - this.castShadow = false; - this.receiveShadow = false; + add: function ( color ) { - this.frustumCulled = true; - this.renderOrder = 0; + this.r += color.r; + this.g += color.g; + this.b += color.b; - this.userData = {}; + return this; -}; + }, -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); -THREE.Object3D.DefaultMatrixAutoUpdate = true; + addColors: function ( color1, color2 ) { -Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - applyMatrix: function ( matrix ) { + return this; - this.matrix.multiplyMatrices( matrix, this.matrix ); + }, - this.matrix.decompose( this.position, this.quaternion, this.scale ); + addScalar: function ( s ) { - }, + this.r += s; + this.g += s; + this.b += s; - setRotationFromAxisAngle: function ( axis, angle ) { + return this; - // assumes axis is normalized + }, - this.quaternion.setFromAxisAngle( axis, angle ); + sub: function( color ) { - }, + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); - setRotationFromEuler: function ( euler ) { + return this; - this.quaternion.setFromEuler( euler, true ); + }, - }, + multiply: function ( color ) { - setRotationFromMatrix: function ( m ) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return this; - this.quaternion.setFromRotationMatrix( m ); + }, - }, + multiplyScalar: function ( s ) { - setRotationFromQuaternion: function ( q ) { + this.r *= s; + this.g *= s; + this.b *= s; - // assumes q is normalized + return this; - this.quaternion.copy( q ); + }, - }, + lerp: function ( color, alpha ) { - rotateOnAxis: function () { + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - // rotate object on axis in object space - // axis is assumed to be normalized + return this; - var q1 = new THREE.Quaternion(); + }, - return function rotateOnAxis( axis, angle ) { + equals: function ( c ) { - q1.setFromAxisAngle( axis, angle ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - this.quaternion.multiply( q1 ); + }, - return this; + fromArray: function ( array, offset ) { - }; + if ( offset === undefined ) offset = 0; - }(), + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - rotateX: function () { + return this; - var v1 = new THREE.Vector3( 1, 0, 0 ); + }, - return function rotateX( angle ) { + toArray: function ( array, offset ) { - return this.rotateOnAxis( v1, angle ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - }; + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - }(), + return array; - rotateY: function () { + } - var v1 = new THREE.Vector3( 0, 1, 0 ); + }; - return function rotateY( angle ) { + exports.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 }; - return this.rotateOnAxis( v1, angle ); + /** + * Uniforms library for shared webgl shaders + */ - }; + exports.UniformsLib = { - }(), + common: { - rotateZ: function () { + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, - var v1 = new THREE.Vector3( 0, 0, 1 ); + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, - return function rotateZ( angle ) { + "specularMap": { value: null }, + "alphaMap": { value: null }, - return this.rotateOnAxis( v1, angle ); + "envMap": { value: null }, + "flipEnvMap": { value: - 1 }, + "reflectivity": { value: 1.0 }, + "refractionRatio": { value: 0.98 } - }; + }, - }(), + aomap: { - translateOnAxis: function () { + "aoMap": { value: null }, + "aoMapIntensity": { value: 1 } - // translate object by distance along axis in object space - // axis is assumed to be normalized + }, - var v1 = new THREE.Vector3(); + lightmap: { - return function translateOnAxis( axis, distance ) { + "lightMap": { value: null }, + "lightMapIntensity": { value: 1 } - v1.copy( axis ).applyQuaternion( this.quaternion ); + }, - this.position.add( v1.multiplyScalar( distance ) ); + emissivemap: { - return this; + "emissiveMap": { value: null } - }; + }, - }(), + bumpmap: { - translateX: function () { + "bumpMap": { value: null }, + "bumpScale": { value: 1 } - var v1 = new THREE.Vector3( 1, 0, 0 ); + }, - return function translateX( distance ) { + normalmap: { - return this.translateOnAxis( v1, distance ); + "normalMap": { value: null }, + "normalScale": { value: new Vector2( 1, 1 ) } - }; + }, - }(), + displacementmap: { - translateY: function () { + "displacementMap": { value: null }, + "displacementScale": { value: 1 }, + "displacementBias": { value: 0 } - var v1 = new THREE.Vector3( 0, 1, 0 ); + }, - return function translateY( distance ) { + roughnessmap: { - return this.translateOnAxis( v1, distance ); + "roughnessMap": { value: null } - }; + }, - }(), + metalnessmap: { - translateZ: function () { + "metalnessMap": { value: null } - var v1 = new THREE.Vector3( 0, 0, 1 ); + }, - return function translateZ( distance ) { + fog: { - return this.translateOnAxis( v1, distance ); + "fogDensity": { value: 0.00025 }, + "fogNear": { value: 1 }, + "fogFar": { value: 2000 }, + "fogColor": { value: new Color( 0xffffff ) } - }; + }, - }(), + lights: { - localToWorld: function ( vector ) { + "ambientLightColor": { value: [] }, - return vector.applyMatrix4( this.matrixWorld ); + "directionalLights": { value: [], properties: { + "direction": {}, + "color": {}, - }, + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - worldToLocal: function () { + "directionalShadowMap": { value: [] }, + "directionalShadowMatrix": { value: [] }, - var m1 = new THREE.Matrix4(); + "spotLights": { value: [], properties: { + "color": {}, + "position": {}, + "direction": {}, + "distance": {}, + "coneCos": {}, + "penumbraCos": {}, + "decay": {}, - return function worldToLocal( vector ) { + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + "spotShadowMap": { value: [] }, + "spotShadowMatrix": { value: [] }, - }; + "pointLights": { value: [], properties: { + "color": {}, + "position": {}, + "decay": {}, + "distance": {}, - }(), + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, - lookAt: function () { + "pointShadowMap": { value: [] }, + "pointShadowMatrix": { value: [] }, - // This routine does not support objects with rotated and/or translated parent(s) + "hemisphereLights": { value: [], properties: { + "direction": {}, + "skyColor": {}, + "groundColor": {} + } } - var m1 = new THREE.Matrix4(); + }, - return function lookAt( vector ) { + points: { - m1.lookAt( vector, this.position, this.up ); + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, + "size": { value: 1.0 }, + "scale": { value: 1.0 }, + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } - this.quaternion.setFromRotationMatrix( m1 ); + } - }; + }; - }(), + /** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ - add: function ( object ) { - if ( arguments.length > 1 ) { + exports.ShaderLib = { - for ( var i = 0; i < arguments.length; i ++ ) { + 'basic': { - this.add( arguments[ i ] ); + uniforms: exports.UniformsUtils.merge( [ - } + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'fog' ] - return this; + ] ), - } + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] - if ( object === this ) { + }, - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + 'lambert': { - } + uniforms: exports.UniformsUtils.merge( [ - if ( object instanceof THREE.Object3D ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - if ( object.parent !== null ) { + { + "emissive" : { value: new Color( 0x000000 ) } + } - object.parent.remove( object ); + ] ), - } + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + }, - this.children.push( object ); + 'phong': { - } else { + uniforms: exports.UniformsUtils.merge( [ - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - } + { + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, + "shininess": { value: 30 } + } - return this; + ] ), - }, + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] - remove: function ( object ) { + }, - if ( arguments.length > 1 ) { + 'standard': { - for ( var i = 0; i < arguments.length; i ++ ) { + uniforms: exports.UniformsUtils.merge( [ - this.remove( arguments[ i ] ); + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'roughnessmap' ], + exports.UniformsLib[ 'metalnessmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - } + { + "emissive" : { value: new Color( 0x000000 ) }, + "roughness": { value: 0.5 }, + "metalness": { value: 0 }, + "envMapIntensity" : { value: 1 }, // temporary + } - } + ] ), - var index = this.children.indexOf( object ); + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - if ( index !== - 1 ) { + }, - object.parent = null; + 'points': { - object.dispatchEvent( { type: 'removed' } ); + uniforms: exports.UniformsUtils.merge( [ - this.children.splice( index, 1 ); + exports.UniformsLib[ 'points' ], + exports.UniformsLib[ 'fog' ] - } + ] ), - }, + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] - getObjectById: function ( id ) { + }, - return this.getObjectByProperty( 'id', id ); + 'dashed': { - }, + uniforms: exports.UniformsUtils.merge( [ - getObjectByName: function ( name ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'fog' ], - return this.getObjectByProperty( 'name', name ); + { + "scale" : { value: 1 }, + "dashSize" : { value: 1 }, + "totalSize": { value: 2 } + } - }, + ] ), - getObjectByProperty: function ( name, value ) { + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] - if ( this[ name ] === value ) return this; + }, - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + 'depth': { - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + uniforms: exports.UniformsUtils.merge( [ - if ( object !== undefined ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'displacementmap' ] - return object; + ] ), - } + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] - } + }, - return undefined; + 'normal': { - }, + uniforms: { - getWorldPosition: function ( optionalTarget ) { + "opacity" : { value: 1.0 } - var result = optionalTarget || new THREE.Vector3(); + }, - this.updateMatrixWorld( true ); + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] - return result.setFromMatrixPosition( this.matrixWorld ); + }, - }, + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - getWorldQuaternion: function () { + 'cube': { - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + uniforms: { + "tCube": { value: null }, + "tFlip": { value: - 1 }, + "opacity": { value: 1.0 } + }, - return function getWorldQuaternion( optionalTarget ) { + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] - var result = optionalTarget || new THREE.Quaternion(); + }, - this.updateMatrixWorld( true ); + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - this.matrixWorld.decompose( position, result, scale ); + 'equirect': { - return result; + uniforms: { + "tEquirect": { value: null }, + "tFlip": { value: - 1 } + }, - }; + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] - }(), + }, - getWorldRotation: function () { + 'distanceRGBA': { - var quaternion = new THREE.Quaternion(); + uniforms: { - return function getWorldRotation( optionalTarget ) { + "lightPos": { value: new Vector3() } - var result = optionalTarget || new THREE.Euler(); + }, - this.getWorldQuaternion( quaternion ); + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + } - }; + }; - }(), + exports.ShaderLib[ 'physical' ] = { - getWorldScale: function () { + uniforms: exports.UniformsUtils.merge( [ - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + exports.ShaderLib[ 'standard' ].uniforms, - return function getWorldScale( optionalTarget ) { + { + "clearCoat": { value: 0 }, + "clearCoatRoughness": { value: 0 } + } - var result = optionalTarget || new THREE.Vector3(); + ] ), - this.updateMatrixWorld( true ); + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - this.matrixWorld.decompose( position, quaternion, result ); + }; - return result; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / https://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * opacity: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - }; + function MeshDepthMaterial ( parameters ) { + this.isMeshDepthMaterial = this.isMaterial = true; - }(), + Material.call( this ); - getWorldDirection: function () { + this.type = 'MeshDepthMaterial'; - var quaternion = new THREE.Quaternion(); + this.depthPacking = BasicDepthPacking; - return function getWorldDirection( optionalTarget ) { + this.skinning = false; + this.morphTargets = false; - var result = optionalTarget || new THREE.Vector3(); + this.map = null; - this.getWorldQuaternion( quaternion ); + this.alphaMap = null; - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - }; + this.wireframe = false; + this.wireframeLinewidth = 1; - }(), + this.fog = false; + this.lights = false; - raycast: function () {}, + this.setValues( parameters ); - traverse: function ( callback ) { + }; - callback( this ); + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - var children = this.children; + MeshDepthMaterial.prototype.copy = function ( source ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + Material.prototype.copy.call( this, source ); - children[ i ].traverse( callback ); + this.depthPacking = source.depthPacking; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - }, + this.map = source.map; - traverseVisible: function ( callback ) { + this.alphaMap = source.alphaMap; - if ( this.visible === false ) return; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - callback( this ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - var children = this.children; + return this; - for ( var i = 0, l = children.length; i < l; i ++ ) { + }; - children[ i ].traverseVisible( callback ); + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - } + function Box3 ( min, max ) { + this.isBox3 = true; - }, + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - traverseAncestors: function ( callback ) { + }; - var parent = this.parent; + Box3.prototype = { - if ( parent !== null ) { + constructor: Box3, - callback( parent ); + set: function ( min, max ) { - parent.traverseAncestors( callback ); + this.min.copy( min ); + this.max.copy( max ); - } + return this; - }, + }, - updateMatrix: function () { + setFromArray: function ( array ) { - this.matrix.compose( this.position, this.quaternion, this.scale ); + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - this.matrixWorldNeedsUpdate = true; + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - }, + for ( var i = 0, l = array.length; i < l; i += 3 ) { - updateMatrixWorld: function ( force ) { + var x = array[ i ]; + var y = array[ i + 1 ]; + var z = array[ i + 2 ]; - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - if ( this.matrixWorldNeedsUpdate === true || force === true ) { + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - if ( this.parent === null ) { + } - this.matrixWorld.copy( this.matrix ); + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - } else { + }, - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + setFromPoints: function ( points ) { - } + this.makeEmpty(); - this.matrixWorldNeedsUpdate = false; + for ( var i = 0, il = points.length; i < il; i ++ ) { - force = true; + this.expandByPoint( points[ i ] ); - } + } - // update children + return this; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + }, - this.children[ i ].updateMatrixWorld( force ); + setFromCenterAndSize: function () { - } + var v1 = new Vector3(); - }, + return function setFromCenterAndSize( center, size ) { - toJSON: function ( meta ) { + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - // meta is '' when called from JSON.stringify - var isRootObject = ( meta === undefined || meta === '' ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - var output = {}; + return this; - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + }; - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + }(), - output.metadata = { - version: 4.4, - type: 'Object', - generator: 'Object3D.toJSON' - }; + setFromObject: function () { - } + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - // standard Object3D serialization + var v1 = new Vector3(); - var object = {}; + return function setFromObject( object ) { - object.uuid = this.uuid; - object.type = this.type; + var scope = this; - if ( this.name !== '' ) object.name = this.name; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; + object.updateMatrixWorld( true ); - object.matrix = this.matrix.toArray(); + this.makeEmpty(); - // + object.traverse( function ( node ) { - if ( this.geometry !== undefined ) { + var geometry = node.geometry; - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + if ( geometry !== undefined ) { - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); + if ( (geometry && geometry.isGeometry) ) { - } + var vertices = geometry.vertices; - object.geometry = this.geometry.uuid; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - } + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - if ( this.material !== undefined ) { + scope.expandByPoint( v1 ); - if ( meta.materials[ this.material.uuid ] === undefined ) { + } - meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); + } else if ( (geometry && geometry.isBufferGeometry) ) { - } + var attribute = geometry.attributes.position; - object.material = this.material.uuid; + if ( attribute !== undefined ) { - } + var array, offset, stride; - // + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - if ( this.children.length > 0 ) { + array = attribute.data.array; + offset = attribute.offset; + stride = attribute.data.stride; - object.children = []; + } else { - for ( var i = 0; i < this.children.length; i ++ ) { + array = attribute.array; + offset = 0; + stride = 3; - object.children.push( this.children[ i ].toJSON( meta ).object ); + } - } + for ( var i = offset, il = array.length; i < il; i += stride ) { - } + v1.fromArray( array, i ); + v1.applyMatrix4( node.matrixWorld ); - if ( isRootObject ) { + scope.expandByPoint( v1 ); - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + } - if ( geometries.length > 0 ) output.geometries = geometries; - if ( materials.length > 0 ) output.materials = materials; - if ( textures.length > 0 ) output.textures = textures; - if ( images.length > 0 ) output.images = images; + } - } + } - output.object = object; + } - return output; + } ); - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache ( cache ) { + return this; - var values = []; - for ( var key in cache ) { + }; - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + }(), - } - return values; + clone: function () { - } + return new this.constructor().copy( this ); - }, + }, - clone: function ( recursive ) { + copy: function ( box ) { - return new this.constructor().copy( this, recursive ); + this.min.copy( box.min ); + this.max.copy( box.max ); - }, + return this; - copy: function ( source, recursive ) { + }, - if ( recursive === undefined ) recursive = true; + makeEmpty: function () { - this.name = source.name; + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - this.up.copy( source.up ); + return this; - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + }, - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + isEmpty: function () { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - this.visible = source.visible; + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + }, - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + center: function ( optionalTarget ) { - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - if ( recursive === true ) { + }, - for ( var i = 0; i < source.children.length; i ++ ) { + size: function ( optionalTarget ) { - var child = source.children[ i ]; - this.add( child.clone() ); + var result = optionalTarget || new Vector3(); + return result.subVectors( this.max, this.min ); - } + }, - } + expandByPoint: function ( point ) { - return this; + this.min.min( point ); + this.max.max( point ); - } + return this; -} ); + }, -THREE.Object3DIdCount = 0; + expandByVector: function ( vector ) { -// File:src/core/Face3.js + this.min.sub( vector ); + this.max.add( vector ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + return this; -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { + }, - this.a = a; - this.b = b; - this.c = c; + expandByScalar: function ( scalar ) { - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - this.color = color instanceof THREE.Color ? color : new THREE.Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + return this; - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + }, -}; + containsPoint: function ( point ) { -THREE.Face3.prototype = { + 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 ) { - constructor: THREE.Face3, + return false; - clone: function () { + } - return new this.constructor().copy( this ); + return true; - }, + }, - copy: function ( source ) { + containsBox: function ( box ) { - this.a = source.a; - this.b = source.b; - this.c = source.c; + 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 ) ) { - this.normal.copy( source.normal ); - this.color.copy( source.color ); + return true; - this.materialIndex = source.materialIndex; + } - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + return false; - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + }, - } + getParameter: function ( point, optionalTarget ) { - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + var result = optionalTarget || new 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 ) + ); - return this; + }, - } + intersectsBox: function ( box ) { -}; + // using 6 splitting planes to rule out intersections. -// File:src/core/BufferAttribute.js + 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 ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return false; -THREE.BufferAttribute = function ( array, itemSize, normalized ) { + } - this.uuid = THREE.Math.generateUUID(); + return true; - this.array = array; - this.itemSize = itemSize; + }, - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + intersectsSphere: ( function () { - this.version = 0; - this.normalized = normalized === true; + var closestPoint; -}; + return function intersectsSphere( sphere ) { -THREE.BufferAttribute.prototype = { + if ( closestPoint === undefined ) closestPoint = new Vector3(); - constructor: THREE.BufferAttribute, + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - get count() { + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - return this.array.length / this.itemSize; + }; - }, + } )(), - set needsUpdate( value ) { + intersectsPlane: function ( plane ) { - if ( value === true ) this.version ++; + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. - }, + var min, max; - setDynamic: function ( value ) { + if ( plane.normal.x > 0 ) { - this.dynamic = value; + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - return this; + } else { - }, + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - copy: function ( source ) { + } - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; + if ( plane.normal.y > 0 ) { - this.dynamic = source.dynamic; + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - return this; + } else { - }, + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - copyAt: function ( index1, attribute, index2 ) { + } - index1 *= this.itemSize; - index2 *= attribute.itemSize; + if ( plane.normal.z > 0 ) { - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + } else { - } + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - return this; + } - }, + return ( min <= plane.constant && max >= plane.constant ); - copyArray: function ( array ) { + }, - this.array.set( array ); + clampPoint: function ( point, optionalTarget ) { - return this; + var result = optionalTarget || new Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - }, + }, - copyColorsArray: function ( colors ) { + distanceToPoint: function () { - var array = this.array, offset = 0; + var v1 = new Vector3(); - for ( var i = 0, l = colors.length; i < l; i ++ ) { + return function distanceToPoint( point ) { - var color = colors[ i ]; + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - if ( color === undefined ) { + }; - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new THREE.Color(); + }(), - } + getBoundingSphere: function () { - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + var v1 = new Vector3(); - } + return function getBoundingSphere( optionalTarget ) { - return this; + var result = optionalTarget || new Sphere(); - }, + result.center = this.center(); + result.radius = this.size( v1 ).length() * 0.5; - copyIndicesArray: function ( indices ) { + return result; - var array = this.array, offset = 0; + }; - for ( var i = 0, l = indices.length; i < l; i ++ ) { + }(), - var index = indices[ i ]; + intersect: function ( box ) { - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + this.min.max( box.min ); + this.max.min( box.max ); - } + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if( this.isEmpty() ) this.makeEmpty(); - return this; + return this; - }, + }, - copyVector2sArray: function ( vectors ) { + union: function ( box ) { - var array = this.array, offset = 0; + this.min.min( box.min ); + this.max.max( box.max ); - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + return this; - var vector = vectors[ i ]; + }, - if ( vector === undefined ) { + applyMatrix4: function () { - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new THREE.Vector2(); + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - } + return function applyMatrix4( matrix ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + // transform of empty box is an empty box. + if( this.isEmpty() ) return this; - } + // 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 - return this; + this.setFromPoints( points ); - }, + return this; - copyVector3sArray: function ( vectors ) { + }; - var array = this.array, offset = 0; + }(), - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + translate: function ( offset ) { - var vector = vectors[ i ]; + this.min.add( offset ); + this.max.add( offset ); - if ( vector === undefined ) { + return this; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new THREE.Vector3(); + }, - } + equals: function ( box ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + return box.min.equals( this.min ) && box.max.equals( this.max ); - } + } - return this; + }; - }, + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - copyVector4sArray: function ( vectors ) { + function Sphere ( center, radius ) { + this.isSphere = true; - var array = this.array, offset = 0; + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + }; - var vector = vectors[ i ]; + Sphere.prototype = { - if ( vector === undefined ) { + constructor: Sphere, - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new THREE.Vector4(); + set: function ( center, radius ) { - } + this.center.copy( center ); + this.radius = radius; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + return this; - } + }, - return this; + setFromPoints: function () { - }, + var box = new Box3(); - set: function ( value, offset ) { + return function setFromPoints( points, optionalCenter ) { - if ( offset === undefined ) offset = 0; + var center = this.center; - this.array.set( value, offset ); + if ( optionalCenter !== undefined ) { - return this; + center.copy( optionalCenter ); - }, + } else { - getX: function ( index ) { + box.setFromPoints( points ).center( center ); - return this.array[ index * this.itemSize ]; + } - }, + var maxRadiusSq = 0; - setX: function ( index, x ) { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.array[ index * this.itemSize ] = x; + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - return this; + } - }, + this.radius = Math.sqrt( maxRadiusSq ); - getY: function ( index ) { + return this; - return this.array[ index * this.itemSize + 1 ]; + }; - }, + }(), - setY: function ( index, y ) { + clone: function () { - this.array[ index * this.itemSize + 1 ] = y; + return new this.constructor().copy( this ); - return this; + }, - }, + copy: function ( sphere ) { - getZ: function ( index ) { + this.center.copy( sphere.center ); + this.radius = sphere.radius; - return this.array[ index * this.itemSize + 2 ]; + return this; - }, + }, - setZ: function ( index, z ) { + empty: function () { - this.array[ index * this.itemSize + 2 ] = z; + return ( this.radius <= 0 ); - return this; + }, - }, + containsPoint: function ( point ) { - getW: function ( index ) { + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - return this.array[ index * this.itemSize + 3 ]; + }, - }, + distanceToPoint: function ( point ) { - setW: function ( index, w ) { + return ( point.distanceTo( this.center ) - this.radius ); - this.array[ index * this.itemSize + 3 ] = w; + }, - return this; + intersectsSphere: function ( sphere ) { - }, + var radiusSum = this.radius + sphere.radius; - setXY: function ( index, x, y ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - index *= this.itemSize; + }, - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + intersectsBox: function ( box ) { - return this; + return box.intersectsSphere( this ); - }, + }, - setXYZ: function ( index, x, y, z ) { + intersectsPlane: function ( plane ) { - index *= this.itemSize; + // We use the following equation to compute the signed distance from + // the center of the sphere to the plane. + // + // distance = q * n - d + // + // If this distance is greater than the radius of the sphere, + // then there is no intersection. - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; - return this; + }, - }, + clampPoint: function ( point, optionalTarget ) { - setXYZW: function ( index, x, y, z, w ) { + var deltaLengthSq = this.center.distanceToSquared( point ); - index *= this.itemSize; + var result = optionalTarget || new Vector3(); - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + result.copy( point ); - return this; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - }, + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); - clone: function () { + } - return new this.constructor().copy( this ); + return result; - } + }, -}; + getBoundingBox: function ( optionalTarget ) { -// + var box = optionalTarget || new Box3(); -THREE.Int8Attribute = function ( array, itemSize ) { + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - return new THREE.BufferAttribute( new Int8Array( array ), itemSize ); + return box; -}; + }, -THREE.Uint8Attribute = function ( array, itemSize ) { + applyMatrix4: function ( matrix ) { - return new THREE.BufferAttribute( new Uint8Array( array ), itemSize ); + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); -}; + return this; -THREE.Uint8ClampedAttribute = function ( array, itemSize ) { + }, - return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + translate: function ( offset ) { -}; + this.center.add( offset ); -THREE.Int16Attribute = function ( array, itemSize ) { + return this; - return new THREE.BufferAttribute( new Int16Array( array ), itemSize ); + }, -}; + equals: function ( sphere ) { -THREE.Uint16Attribute = function ( array, itemSize ) { + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - return new THREE.BufferAttribute( new Uint16Array( array ), itemSize ); + } -}; + }; -THREE.Int32Attribute = function ( array, itemSize ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - return new THREE.BufferAttribute( new Int32Array( array ), itemSize ); + function Matrix3 () { + this.isMatrix3 = true; -}; + this.elements = new Float32Array( [ -THREE.Uint32Attribute = function ( array, itemSize ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - return new THREE.BufferAttribute( new Uint32Array( array ), itemSize ); + ] ); -}; + if ( arguments.length > 0 ) { -THREE.Float32Attribute = function ( array, itemSize ) { + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - return new THREE.BufferAttribute( new Float32Array( array ), itemSize ); + } -}; + }; -THREE.Float64Attribute = function ( array, itemSize ) { + Matrix3.prototype = { - return new THREE.BufferAttribute( new Float64Array( array ), itemSize ); + constructor: Matrix3, -}; + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + var te = this.elements; -// Deprecated + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; -THREE.DynamicBufferAttribute = function ( array, itemSize ) { + return this; - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new THREE.BufferAttribute( array, itemSize ).setDynamic( true ); + }, -}; + identity: function () { -// File:src/core/InstancedBufferAttribute.js + this.set( -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 -THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) { + ); - THREE.BufferAttribute.call( this, array, itemSize ); + return this; - this.meshPerAttribute = meshPerAttribute || 1; + }, -}; + clone: function () { -THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute; + return new this.constructor().fromArray( this.elements ); -THREE.InstancedBufferAttribute.prototype.copy = function ( source ) { + }, - THREE.BufferAttribute.prototype.copy.call( this, source ); + copy: function ( m ) { - this.meshPerAttribute = source.meshPerAttribute; + var me = m.elements; - return this; + this.set( -}; + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] -// File:src/core/InterleavedBuffer.js + ); -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + return this; -THREE.InterleavedBuffer = function ( array, stride ) { + }, - this.uuid = THREE.Math.generateUUID(); + setFromMatrix4: function( m ) { - this.array = array; - this.stride = stride; + var me = m.elements; - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + this.set( - this.version = 0; + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] -}; + ); -THREE.InterleavedBuffer.prototype = { + return this; - constructor: THREE.InterleavedBuffer, + }, - get length () { + applyToVector3Array: function () { - return this.array.length; + var v1; - }, + return function applyToVector3Array( array, offset, length ) { - get count () { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - return this.array.length / this.stride; + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - }, + v1.fromArray( array, j ); + v1.applyMatrix3( this ); + v1.toArray( array, j ); - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + return array; - }, + }; - setDynamic: function ( value ) { + }(), - this.dynamic = value; + applyToBuffer: function () { - return this; + var v1; - }, + return function applyToBuffer( buffer, offset, length ) { - copy: function ( source ) { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - this.array = new source.array.constructor( source.array ); - this.stride = source.stride; - this.dynamic = source.dynamic; + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - return this; + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - }, + v1.applyMatrix3( this ); - copyAt: function ( index1, attribute, index2 ) { + buffer.setXYZ( v1.x, v1.y, v1.z ); - index1 *= this.stride; - index2 *= attribute.stride; + } - for ( var i = 0, l = this.stride; i < l; i ++ ) { + return buffer; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + }; - } + }(), - return this; + multiplyScalar: function ( s ) { - }, + var te = this.elements; - set: function ( value, offset ) { + 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; - if ( offset === undefined ) offset = 0; + return this; - this.array.set( value, offset ); + }, - return this; + determinant: function () { - }, + var te = this.elements; - clone: function () { + 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 ]; - return new this.constructor().copy( this ); + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - } + }, -}; + getInverse: function ( matrix, throwOnDegenerate ) { -// File:src/core/InstancedInterleavedBuffer.js + if ( (matrix && matrix.isMatrix4) ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); -THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) { + } - THREE.InterleavedBuffer.call( this, array, stride ); + var me = matrix.elements, + te = this.elements, - this.meshPerAttribute = meshPerAttribute || 1; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], -}; + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, -THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype ); -THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer; + det = n11 * t11 + n21 * t12 + n31 * t13; -THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) { + if ( det === 0 ) { - THREE.InterleavedBuffer.prototype.copy.call( this, source ); + var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; - this.meshPerAttribute = source.meshPerAttribute; + if ( throwOnDegenerate || false ) {} else { - return this; + console.warn( msg ); -}; + } -// File:src/core/InterleavedBufferAttribute.js + return this.identity(); + } + + var detInv = 1 / det; -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; -THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset, normalized ) { + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - this.uuid = THREE.Math.generateUUID(); + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + return this; - this.normalized = normalized === true; + }, -}; + transpose: function () { + var tmp, m = this.elements; -THREE.InterleavedBufferAttribute.prototype = { + 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; - constructor: THREE.InterleavedBufferAttribute, + return this; - get length() { + }, - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; + flattenToArrayOffset: function ( array, offset ) { - }, + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - get count() { + return this.toArray( array, offset ); - return this.data.count; + }, - }, + getNormalMatrix: function ( matrix4 ) { - get array() { + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - return this.data.array; + }, - }, + transposeIntoArray: function ( r ) { - setX: function ( index, x ) { + var m = this.elements; - this.data.array[ index * this.data.stride + this.offset ] = x; + 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 ]; - return this; + return this; - }, + }, - setY: function ( index, y ) { + fromArray: function ( array ) { - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + this.elements.set( array ); - return this; + return this; - }, + }, - setZ: function ( index, z ) { + toArray: function ( array, offset ) { - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return this; + var te = this.elements; - }, + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - setW: function ( index, w ) { + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - return this; + return array; - }, + } - getX: function ( index ) { + }; - return this.data.array[ index * this.data.stride + this.offset ]; + /** + * @author bhouston / http://clara.io + */ - }, + function Plane ( normal, constant ) { + this.isPlane = true; - getY: function ( index ) { + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + }; - }, + Plane.prototype = { - getZ: function ( index ) { + constructor: Plane, - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + set: function ( normal, constant ) { - }, + this.normal.copy( normal ); + this.constant = constant; - getW: function ( index ) { + return this; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + }, - }, + setComponents: function ( x, y, z, w ) { - setXY: function ( index, x, y ) { + this.normal.set( x, y, z ); + this.constant = w; - index = index * this.data.stride + this.offset; + return this; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + }, - return this; + 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 - setXYZ: function ( index, x, y, z ) { + return this; - index = index * this.data.stride + this.offset; + }, - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + setFromCoplanarPoints: function () { - return this; + var v1 = new Vector3(); + var v2 = new Vector3(); - }, + return function setFromCoplanarPoints( a, b, c ) { - setXYZW: function ( index, x, y, z, w ) { + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - index = index * this.data.stride + this.offset; + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; - this.data.array[ index + 3 ] = w; + this.setFromNormalAndCoplanarPoint( normal, a ); - return this; + return this; - } + }; -}; + }(), -// File:src/core/Geometry.js + clone: function () { -/** - * @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://clara.io - */ + return new this.constructor().copy( this ); -THREE.Geometry = function () { + }, - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + copy: function ( plane ) { - this.uuid = THREE.Math.generateUUID(); + this.normal.copy( plane.normal ); + this.constant = plane.constant; - this.name = ''; - this.type = 'Geometry'; + return this; - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + }, - this.morphTargets = []; - this.morphNormals = []; + normalize: function () { - this.skinWeights = []; - this.skinIndices = []; + // Note: will lead to a divide by zero if the plane is invalid. - this.lineDistances = []; + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - this.boundingBox = null; - this.boundingSphere = null; + return this; - // update flags + }, - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + negate: function () { -}; + this.constant *= - 1; + this.normal.negate(); -Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { + return this; - applyMatrix: function ( matrix ) { + }, - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + distanceToPoint: function ( point ) { - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + return this.normal.dot( point ) + this.constant; - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + }, - } + distanceToSphere: function ( sphere ) { - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + return this.distanceToPoint( sphere.center ) - sphere.radius; - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + }, - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + projectPoint: function ( point, optionalTarget ) { - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - } + }, - } + orthoPoint: function ( point, optionalTarget ) { - if ( this.boundingBox !== null ) { + var perpendicularMagnitude = this.distanceToPoint( point ); - this.computeBoundingBox(); + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - } + }, - if ( this.boundingSphere !== null ) { + intersectLine: function () { - this.computeBoundingSphere(); + var v1 = new Vector3(); - } + return function intersectLine( line, optionalTarget ) { - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + var result = optionalTarget || new Vector3(); - return this; + var direction = line.delta( v1 ); - }, + var denominator = this.normal.dot( direction ); - rotateX: function () { + if ( denominator === 0 ) { - // rotate geometry around world x-axis + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - var m1; + return result.copy( line.start ); - return function rotateX( angle ) { + } - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + // Unsure if this is the correct method to handle this case. + return undefined; - m1.makeRotationX( angle ); + } - this.applyMatrix( m1 ); + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - return this; + if ( t < 0 || t > 1 ) { - }; + return undefined; - }(), + } - rotateY: function () { + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - // rotate geometry around world y-axis + }; - var m1; + }(), - return function rotateY( angle ) { + intersectsLine: function ( line ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - m1.makeRotationY( angle ); + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - this.applyMatrix( m1 ); + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - return this; + }, - }; + intersectsBox: function ( box ) { - }(), + return box.intersectsPlane( this ); - rotateZ: function () { + }, - // rotate geometry around world z-axis + intersectsSphere: function ( sphere ) { - var m1; + return sphere.intersectsPlane( this ); - return function rotateZ( angle ) { + }, - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + coplanarPoint: function ( optionalTarget ) { - m1.makeRotationZ( angle ); + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); - this.applyMatrix( m1 ); + }, - return this; + applyMatrix4: function () { - }; + var v1 = new Vector3(); + var m1 = new Matrix3(); - }(), + return function applyMatrix4( matrix, optionalNormalMatrix ) { - translate: function () { + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - // translate geometry + // transform normal based on theory here: + // http://www.songho.ca/opengl/gl_normaltransform.html + var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); + var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - var m1; + // recalculate constant (like in setFromNormalAndCoplanarPoint) + this.constant = - referencePoint.dot( normal ); - return function translate( x, y, z ) { + return this; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + }; - m1.makeTranslation( x, y, z ); + }(), - this.applyMatrix( m1 ); + translate: function ( offset ) { - return this; + this.constant = this.constant - offset.dot( this.normal ); - }; + return this; - }(), + }, - scale: function () { + equals: function ( plane ) { - // scale geometry + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - var m1; + } - return function scale( x, y, z ) { + }; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - m1.makeScale( x, y, z ); + function Frustum ( p0, p1, p2, p3, p4, p5 ) { + this.isFrustum = true; - this.applyMatrix( m1 ); + this.planes = [ - return this; + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - }; + ]; - }(), + }; - lookAt: function () { + Frustum.prototype = { - var obj; + constructor: Frustum, - return function lookAt( vector ) { + set: function ( p0, p1, p2, p3, p4, p5 ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + var planes = this.planes; - obj.lookAt( vector ); + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - obj.updateMatrix(); + return this; - this.applyMatrix( obj.matrix ); + }, - }; + clone: function () { - }(), + return new this.constructor().copy( this ); - fromBufferGeometry: function ( geometry ) { + }, - var scope = this; + copy: function ( frustum ) { - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + var planes = this.planes; - var positions = attributes.position.array; - 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; - var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; + for ( var i = 0; i < 6; i ++ ) { - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + planes[ i ].copy( frustum.planes[ i ] ); - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + } - for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + return this; - scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + }, - if ( normals !== undefined ) { + setFromMatrix: function ( m ) { - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + 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 ]; - } + 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(); - if ( colors !== undefined ) { + return this; - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + }, - } + intersectsObject: function () { - if ( uvs !== undefined ) { + var sphere = new Sphere(); - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + return function intersectsObject( object ) { - } + var geometry = object.geometry; - if ( uvs2 !== undefined ) { + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - } + return this.intersectsSphere( sphere ); - } + }; - function addFace( a, b, c, materialIndex ) { + }(), - 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() ] : []; + intersectsSprite: function () { - var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + var sphere = new Sphere(); - scope.faces.push( face ); + return function intersectsSprite( sprite ) { - if ( uvs !== undefined ) { + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + return this.intersectsSphere( sphere ); - } + }; - if ( uvs2 !== undefined ) { + }(), - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + intersectsSphere: function ( sphere ) { - } + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - } + for ( var i = 0; i < 6; i ++ ) { - if ( indices !== undefined ) { + var distance = planes[ i ].distanceToPoint( center ); - var groups = geometry.groups; + if ( distance < negRadius ) { - if ( groups.length > 0 ) { + return false; - for ( var i = 0; i < groups.length; i ++ ) { + } - var group = groups[ i ]; + } - var start = group.start; - var count = group.count; + return true; - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + }, - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + intersectsBox: function () { - } + var p1 = new Vector3(), + p2 = new Vector3(); - } + return function intersectsBox( box ) { - } else { + var planes = this.planes; - for ( var i = 0; i < indices.length; i += 3 ) { + for ( var i = 0; i < 6 ; i ++ ) { - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + 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 d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); - } else { + // if both outside plane, no intersection - for ( var i = 0; i < positions.length / 3; i += 3 ) { + if ( d1 < 0 && d2 < 0 ) { - addFace( i, i + 1, i + 2 ); + return false; - } + } - } + } - this.computeFaceNormals(); + return true; - if ( geometry.boundingBox !== null ) { + }; - this.boundingBox = geometry.boundingBox.clone(); + }(), - } - if ( geometry.boundingSphere !== null ) { + containsPoint: function ( point ) { - this.boundingSphere = geometry.boundingSphere.clone(); + var planes = this.planes; - } + for ( var i = 0; i < 6; i ++ ) { - return this; + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - }, + return false; - center: function () { + } - this.computeBoundingBox(); + } - var offset = this.boundingBox.center().negate(); + return true; - this.translate( offset.x, offset.y, offset.z ); + } - return offset; + }; - }, + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - normalize: function () { + function WebGLShadowMap ( _renderer, _lights, _objects, capabilities ) { + this.isWebGLShadowMap = true; - this.computeBoundingSphere(); + var _gl = _renderer.context, + _state = _renderer.state, + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + _lightShadows = _lights.shadows, - var s = radius === 0 ? 1 : 1.0 / radius; + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - var matrix = new THREE.Matrix4(); - matrix.set( - s, 0, 0, - s * center.x, - 0, s, 0, - s * center.y, - 0, 0, s, - s * center.z, - 0, 0, 0, 1 - ); + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), - this.applyMatrix( matrix ); + _renderList = [], - return this; + _MorphingFlag = 1, + _SkinningFlag = 2, - }, + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - computeFaceNormals: function () { + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + _materialCache = {}; - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + var cubeDirections = [ + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) + ]; - var face = this.faces[ f ]; + var cubeUps = [ + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) + ]; - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + // init - cb.normalize(); + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; + depthMaterialTemplate.clipping = true; - face.normal.copy( cb ); + var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); - } + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { - }, + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; - computeVertexNormals: function ( areaWeighted ) { + var depthMaterial = depthMaterialTemplate.clone(); + depthMaterial.morphTargets = useMorphing; + depthMaterial.skinning = useSkinning; - if ( areaWeighted === undefined ) areaWeighted = true; + _depthMaterials[ i ] = depthMaterial; - var v, vl, f, fl, face, vertices; + var distanceMaterial = new ShaderMaterial( { + defines: { + 'USE_SHADOWMAP': '' + }, + uniforms: distanceUniforms, + vertexShader: distanceShader.vertexShader, + fragmentShader: distanceShader.fragmentShader, + morphTargets: useMorphing, + skinning: useSkinning, + clipping: true + } ); - vertices = new Array( this.vertices.length ); + _distanceMaterials[ i ] = distanceMaterial; - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + } - vertices[ v ] = new THREE.Vector3(); + // - } + var scope = this; - if ( areaWeighted ) { + this.enabled = false; - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + this.autoUpdate = true; + this.needsUpdate = false; - var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + this.type = PCFShadowMap; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + this.renderReverseSided = true; + this.renderSingleSided = true; - face = this.faces[ f ]; + this.render = function ( scene, camera ) { - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + if ( _lightShadows.length === 0 ) return; - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + // Set GL state for depth map. + _state.clearColor( 1, 1, 1, 1 ); + _state.disable( _gl.BLEND ); + _state.setDepthTest( true ); + _state.setScissorTest( false ); - } + // render depth map - } else { + var faceCount, isPointLight; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { - face = this.faces[ f ]; + var light = _lightShadows[ i ]; + var shadow = light.shadow; - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + if ( shadow === undefined ) { - } + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - } + } - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + var shadowCamera = shadow.camera; - vertices[ v ].normalize(); + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - } + if ( (light && light.isPointLight) ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + faceCount = 6; + isPointLight = true; - face = this.faces[ f ]; + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - var vertexNormals = face.vertexNormals; + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction - if ( vertexNormals.length === 3 ) { + // positive X + cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); + // negative X + cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); + // positive Z + cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); + // negative Z + cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); + // positive Y + cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); + // negative Y + cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - } else { + } else { - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + faceCount = 1; + isPointLight = false; - } + } - } + if ( shadow.map === null ) { - if ( this.faces.length > 0 ) { + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - this.normalsNeedUpdate = true; + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - } + shadowCamera.updateProjectionMatrix(); - }, + } - computeMorphNormals: function () { + if ( (shadow && shadow.isSpotLightShadow) ) { - var i, il, f, fl, face; + shadow.update( light ); - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - face = this.faces[ f ]; + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - if ( ! face.__originalFaceNormal ) { + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - face.__originalFaceNormal = face.normal.clone(); + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - } else { + for ( var face = 0; face < faceCount; face ++ ) { - face.__originalFaceNormal.copy( face.normal ); + if ( isPointLight ) { - } + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + } else { - if ( ! face.__originalVertexNormals[ i ] ) { + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + } - } else { + shadowCamera.updateMatrixWorld(); + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + // compute shadow matrix - } + 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 + ); - } + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - } + // update camera matrices and frustum - // use temp geometry to compute face and vertex normals for each morph + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - var tmpGeo = new THREE.Geometry(); - tmpGeo.faces = this.faces; + // set object matrices & frustum culling - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + _renderList.length = 0; - // create on first access + projectObject( scene, camera, shadowCamera ); - if ( ! this.morphNormals[ i ] ) { + // render shadow map + // render regular objects - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + var object = _renderList[ j ]; + var geometry = _objects.update( object ); + var material = object.material; - var faceNormal, vertexNormals; + if ( (material && material.isMultiMaterial) ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var groups = geometry.groups; + var materials = material.materials; - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + var group = groups[ k ]; + var groupMaterial = materials[ group.materialIndex ]; - } + if ( groupMaterial.visible === true ) { - } + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - var morphNormals = this.morphNormals[ i ]; + } - // set vertices to morph target + } - tmpGeo.vertices = this.morphTargets[ i ].vertices; + } else { - // compute morph normals + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + } - // store morph normals + } - var faceNormal, vertexNormals; + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + // Restore GL state. + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); + _renderer.setClearColor( clearColor, clearAlpha ); - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + scope.needsUpdate = false; - faceNormal.copy( face.normal ); + }; - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { - } + var geometry = object.geometry; - } + var result = null; - // restore original normals + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( isPointLight ) { - face = this.faces[ f ]; + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + } - } + if ( ! customMaterial ) { - }, + var useMorphing = false; - computeTangents: function () { + if ( material.morphTargets ) { - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + if ( (geometry && geometry.isBufferGeometry) ) { - }, + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - computeLineDistances: function () { + } else if ( (geometry && geometry.isGeometry) ) { - var d = 0; - var vertices = this.vertices; + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + } - if ( i > 0 ) { + } - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + var useSkinning = (object && object.isSkinnedMesh) && material.skinning; - } + var variantIndex = 0; - this.lineDistances[ i ] = d; + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - } + result = materialVariants[ variantIndex ]; - }, + } else { - computeBoundingBox: function () { + result = customMaterial; - if ( this.boundingBox === null ) { + } - this.boundingBox = new THREE.Box3(); + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - } + // in this case we need a unique material instance reflecting the + // appropriate state - this.boundingBox.setFromPoints( this.vertices ); + var keyA = result.uuid, keyB = material.uuid; - }, + var materialsForVariant = _materialCache[ keyA ]; - computeBoundingSphere: function () { + if ( materialsForVariant === undefined ) { - if ( this.boundingSphere === null ) { + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - this.boundingSphere = new THREE.Sphere(); + } - } + var cachedMaterial = materialsForVariant[ keyB ]; - this.boundingSphere.setFromPoints( this.vertices ); + if ( cachedMaterial === undefined ) { - }, + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - merge: function ( geometry, matrix, materialIndexOffset ) { + } - if ( geometry instanceof THREE.Geometry === false ) { + result = cachedMaterial; - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + } - } + result.visible = material.visible; + result.wireframe = material.wireframe; - 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 ]; + var side = material.side; - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + if ( scope.renderSingleSided && side == DoubleSide ) { - if ( matrix !== undefined ) { + side = FrontSide; - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + } - } + if ( scope.renderReverseSided ) { - // vertices + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + } - var vertex = vertices2[ i ]; + result.side = side; - var vertexCopy = vertex.clone(); + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - vertices1.push( vertexCopy ); + if ( isPointLight && result.uniforms.lightPos !== undefined ) { - } + result.uniforms.lightPos.value.copy( lightPositionWorld ); - // faces + } - for ( i = 0, il = faces2.length; i < il; i ++ ) { + return result; - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + } - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + function projectObject( object, camera, shadowCamera ) { - if ( normalMatrix !== undefined ) { + if ( object.visible === false ) return; - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { - } + if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + var material = object.material; - normal = faceVertexNormals[ j ].clone(); + if ( material.visible === true ) { - if ( normalMatrix !== undefined ) { + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( object ); - normal.applyMatrix3( normalMatrix ).normalize(); + } - } + } - faceCopy.vertexNormals.push( normal ); + } - } + var children = object.children; - faceCopy.color.copy( face.color ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + projectObject( children[ i ], camera, shadowCamera ); - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + } - } + } - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + }; - faces1.push( faceCopy ); + exports.WebGLShader = ( function () { - } + function addLineNumbers( string ) { - // uvs + var lines = string.split( '\n' ); - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + for ( var i = 0; i < lines.length; i ++ ) { - var uv = uvs2[ i ], uvCopy = []; + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - if ( uv === undefined ) { + } - continue; + return lines.join( '\n' ); - } + } - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + return function WebGLShader( gl, type, string ) { - uvCopy.push( uv[ j ].clone() ); + var shader = gl.createShader( type ); - } + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - uvs1.push( uvCopy ); + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - } + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - }, + } - mergeMesh: function ( mesh ) { + if ( gl.getShaderInfoLog( shader ) !== '' ) { - if ( mesh instanceof THREE.Mesh === false ) { + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + } - } + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - mesh.matrixAutoUpdate && mesh.updateMatrix(); + return shader; - this.merge( mesh.geometry, mesh.matrix ); + }; - }, + } )(); - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + /** + * @author fordacious / fordacious.github.io + */ - mergeVertices: function () { + function WebGLProperties () { + this.isWebGLProperties = true; - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + var properties = {}; - var v, key; - var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; + this.get = function ( object ) { - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + var uuid = object.uuid; + var map = properties[ uuid ]; - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + if ( map === undefined ) { - if ( verticesMap[ key ] === undefined ) { + map = {}; + properties[ uuid ] = map; - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + } - } else { + return map; - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + }; - } + this.delete = function ( object ) { - } + delete properties[ object.uuid ]; + }; - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + this.clear = function () { - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + properties = {}; - 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 ]; + exports.WebGLProgram = ( function () { - var dupIndex = - 1; + var programIdCount = 0; - // 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 ++ ) { + function getEncodingComponents( encoding ) { - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + switch ( encoding ) { - dupIndex = n; - faceIndicesToRemove.push( i ); - break; + case LinearEncoding: + return [ 'Linear','( value )' ]; + case sRGBEncoding: + return [ 'sRGB','( value )' ]; + case RGBEEncoding: + return [ 'RGBE','( value )' ]; + case RGBM7Encoding: + return [ 'RGBM','( value, 7.0 )' ]; + case RGBM16Encoding: + return [ 'RGBM','( value, 16.0 )' ]; + case RGBDEncoding: + return [ 'RGBD','( value, 256.0 )' ]; + case GammaEncoding: + return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; + default: + throw new Error( 'unsupported encoding: ' + encoding ); - } + } - } + } - } + function getTexelDecodingFunction( functionName, encoding ) { - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - var idx = faceIndicesToRemove[ i ]; + } - this.faces.splice( idx, 1 ); + function getTexelEncodingFunction( functionName, encoding ) { - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - this.faceVertexUvs[ j ].splice( idx, 1 ); + } - } + function getToneMappingFunction( functionName, toneMapping ) { - } + var toneMappingName; - // Use unique set of vertices + switch ( toneMapping ) { - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + case LinearToneMapping: + toneMappingName = "Linear"; + break; - }, + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; - sortFacesByMaterialIndex: function () { + case Uncharted2ToneMapping: + toneMappingName = "Uncharted2"; + break; - var faces = this.faces; - var length = faces.length; + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; - // tag faces + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - for ( var i = 0; i < length; i ++ ) { + } - faces[ i ]._id = i; + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - } + } - // sort faces + function generateExtensions( extensions, parameters, rendererExtensions ) { - function materialIndexSort( a, b ) { + extensions = extensions || {}; - return a.materialIndex - b.materialIndex; + var chunks = [ + ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', + ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', + ]; - } + return chunks.filter( filterEmptyLine ).join( '\n' ); - faces.sort( materialIndexSort ); + } - // sort uvs + function generateDefines( defines ) { - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + var chunks = []; - var newUvs1, newUvs2; + for ( var name in defines ) { - if ( uvs1 && uvs1.length === length ) newUvs1 = []; - if ( uvs2 && uvs2.length === length ) newUvs2 = []; + var value = defines[ name ]; - for ( var i = 0; i < length; i ++ ) { + if ( value === false ) continue; - var id = faces[ i ]._id; + chunks.push( '#define ' + name + ' ' + value ); - if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); - if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); + } - } + return chunks.join( '\n' ); - if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; - if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; + } - }, + function fetchAttributeLocations( gl, program, identifiers ) { - toJSON: function () { + var attributes = {}; - var data = { - metadata: { - version: 4.4, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - // standard Geometry serialization + for ( var i = 0; i < n; i ++ ) { - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - if ( this.parameters !== undefined ) { + // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); - var parameters = this.parameters; + attributes[ name ] = gl.getAttribLocation( program, name ); - for ( var key in parameters ) { + } - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + return attributes; - } + } - return data; + function filterEmptyLine( string ) { - } + return string !== ''; - var vertices = []; + } - for ( var i = 0; i < this.vertices.length; i ++ ) { + function replaceLightNums( string, parameters ) { - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); - } + } - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + function parseIncludes( string ) { - for ( var i = 0; i < this.faces.length; i ++ ) { + var pattern = /#include +<([\w\d.]+)>/g; - var face = this.faces[ i ]; + function replace( match, include ) { - var hasMaterial = true; - 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; + var replace = ShaderChunk[ include ]; - var faceType = 0; + if ( replace === undefined ) { - faceType = setBit( faceType, 0, 0 ); // isQuad - 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 ); + throw new Error( 'Can not resolve #include <' + include + '>' ); - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + } - if ( hasFaceVertexUv ) { + return parseIncludes( replace ); - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + } - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + return string.replace( pattern, replace ); - } + } - if ( hasFaceNormal ) { + function unrollLoops( string ) { - faces.push( getNormalIndex( face.normal ) ); + var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - } + function replace( match, start, end, snippet ) { - if ( hasFaceVertexNormal ) { + var unroll = ''; - var vertexNormals = face.vertexNormals; + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - } + } - if ( hasFaceColor ) { + return unroll; - faces.push( getColorIndex( face.color ) ); + } - } + return string.replace( pattern, replace ); - if ( hasFaceVertexColor ) { + } - var vertexColors = face.vertexColors; + return function WebGLProgram( renderer, code, material, parameters ) { - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + var gl = renderer.context; - } + var extensions = material.extensions; + var defines = material.defines; - } + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - function setBit( value, position, enabled ) { + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + if ( parameters.shadowMapType === PCFShadowMap ) { - } + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - function getNormalIndex( normal ) { + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - if ( normalsHash[ hash ] !== undefined ) { + } - return normalsHash[ hash ]; + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - } + if ( parameters.envMap ) { - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + switch ( material.envMap.mapping ) { - return normalsHash[ hash ]; + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - } + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - function getColorIndex( color ) { + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - if ( colorsHash[ hash ] !== undefined ) { + } - return colorsHash[ hash ]; + switch ( material.envMap.mapping ) { - } + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + } - return colorsHash[ hash ]; + switch ( material.combine ) { - } + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - function getUvIndex( uv ) { + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - var hash = uv.x.toString() + uv.y.toString(); + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - if ( uvsHash[ hash ] !== undefined ) { + } - return uvsHash[ hash ]; + } - } + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + // console.log( 'building new program ' ); - return uvsHash[ hash ]; + // - } + var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); - data.data = {}; + var customDefines = generateDefines( defines ); - data.data.vertices = vertices; - data.data.normals = normals; - if ( colors.length > 0 ) data.data.colors = colors; - if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility - data.data.faces = faces; + // - return data; + var program = gl.createProgram(); - }, + var prefixVertex, prefixFragment; - clone: function () { + if ( (material && material.isRawShaderMaterial) ) { - /* - // Handle primitives + prefixVertex = [ - var parameters = this.parameters; + customDefines - if ( parameters !== undefined ) { + ].filter( filterEmptyLine ).join( '\n' ); - var values = []; + prefixFragment = [ - for ( var key in parameters ) { + customDefines - values.push( parameters[ key ] ); + ].filter( filterEmptyLine ).join( '\n' ); - } + } else { - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + prefixVertex = [ - } + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - return new this.constructor().copy( this ); - */ + '#define SHADER_NAME ' + material.__webglShader.name, - return new THREE.Geometry().copy( this ); + customDefines, - }, + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - copy: function ( source ) { + '#define GAMMA_FACTOR ' + gammaFactorDefine, - this.vertices = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + '#define MAX_BONES ' + parameters.maxBones, - var vertices = source.vertices; + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + parameters.flatShading ? '#define FLAT_SHADED' : '', - this.vertices.push( vertices[ i ].clone() ); + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - } + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - var faces = source.faces; + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - for ( var i = 0, il = faces.length; i < il; i ++ ) { + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - this.faces.push( faces[ i ].clone() ); + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - } + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', - var faceVertexUvs = source.faceVertexUvs[ i ]; + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - if ( this.faceVertexUvs[ i ] === undefined ) { + '#ifdef USE_COLOR', - this.faceVertexUvs[ i ] = []; + ' attribute vec3 color;', - } + '#endif', - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + '#ifdef USE_MORPHTARGETS', - var uvs = faceVertexUvs[ j ], uvsCopy = []; + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + ' #ifdef USE_MORPHNORMALS', - var uv = uvs[ k ]; + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - uvsCopy.push( uv.clone() ); + ' #else', - } + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - this.faceVertexUvs[ i ].push( uvsCopy ); + ' #endif', - } + '#endif', - } + '#ifdef USE_SKINNING', - return this; + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - }, + '#endif', - dispose: function () { + '\n' - this.dispatchEvent( { type: 'dispose' } ); + ].filter( filterEmptyLine ).join( '\n' ); - } + prefixFragment = [ -} ); + customExtensions, -THREE.GeometryIdCount = 0; + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', -// File:src/core/DirectGeometry.js + '#define SHADER_NAME ' + material.__webglShader.name, -/** - * @author mrdoob / http://mrdoob.com/ - */ + customDefines, -THREE.DirectGeometry = function () { + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + '#define GAMMA_FACTOR ' + gammaFactorDefine, - this.uuid = THREE.Math.generateUUID(); + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - this.name = ''; - this.type = 'DirectGeometry'; + 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.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + parameters.flatShading ? '#define FLAT_SHADED' : '', - this.groups = []; + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - this.morphTargets = {}; + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - this.skinWeights = []; - this.skinIndices = []; + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - // this.lineDistances = []; + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', - this.boundingBox = null; - this.boundingSphere = null; + parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', - // update flags + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', -}; + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', -Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, { + ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox, - computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere, + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', + parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', + parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', + parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', - computeFaceNormals: function () { + parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', - console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); + '\n' - }, + ].filter( filterEmptyLine ).join( '\n' ); - computeVertexNormals: function () { + } - console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); + vertexShader = parseIncludes( vertexShader, parameters ); + vertexShader = replaceLightNums( vertexShader, parameters ); - }, + fragmentShader = parseIncludes( fragmentShader, parameters ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); - computeGroups: function ( geometry ) { + if ( (material && material.isShaderMaterial) === false ) { - var group; - var groups = []; - var materialIndex; + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); - var faces = geometry.faces; + } - for ( var i = 0; i < faces.length; i ++ ) { + var vertexGlsl = prefixVertex + vertexShader; + var fragmentGlsl = prefixFragment + fragmentShader; - var face = faces[ i ]; + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); - // materials + var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); - if ( face.materialIndex !== materialIndex ) { + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - materialIndex = face.materialIndex; + // Force a particular attribute to index 0. - if ( group !== undefined ) { + if ( material.index0AttributeName !== undefined ) { - group.count = ( i * 3 ) - group.start; - groups.push( group ); + gl.bindAttribLocation( program, 0, material.index0AttributeName ); - } + } else if ( parameters.morphTargets === true ) { - group = { - start: i * 3, - materialIndex: materialIndex - }; + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - } + } - } + gl.linkProgram( program ); - if ( group !== undefined ) { + var programLog = gl.getProgramInfoLog( program ); + var vertexLog = gl.getShaderInfoLog( glVertexShader ); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); - group.count = ( i * 3 ) - group.start; - groups.push( group ); + var runnable = true; + var haveDiagnostics = true; - } + // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); - this.groups = groups; + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { - }, + runnable = false; - fromGeometry: function ( geometry ) { + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; + } else if ( programLog !== '' ) { - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - // morphs + } else if ( vertexLog === '' || fragmentLog === '' ) { - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + haveDiagnostics = false; - var morphTargetsPosition; + } - if ( morphTargetsLength > 0 ) { + if ( haveDiagnostics ) { - morphTargetsPosition = []; + this.diagnostics = { - for ( var i = 0; i < morphTargetsLength; i ++ ) { + runnable: runnable, + material: material, - morphTargetsPosition[ i ] = []; + programLog: programLog, - } + vertexShader: { - this.morphTargets.position = morphTargetsPosition; + log: vertexLog, + prefix: prefixVertex - } + }, - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + fragmentShader: { - var morphTargetsNormal; + log: fragmentLog, + prefix: prefixFragment - if ( morphNormalsLength > 0 ) { + } - morphTargetsNormal = []; + }; - for ( var i = 0; i < morphNormalsLength; i ++ ) { + } - morphTargetsNormal[ i ] = []; + // clean up - } + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - this.morphTargets.normal = morphTargetsNormal; + // set up caching for uniform locations - } + var cachedUniforms; - // skins + this.getUniforms = function() { - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + if ( cachedUniforms === undefined ) { - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + cachedUniforms = + new exports.WebGLUniforms( gl, program, renderer ); - // + } - for ( var i = 0; i < faces.length; i ++ ) { + return cachedUniforms; - var face = faces[ i ]; + }; - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + // set up caching for attribute locations - var vertexNormals = face.vertexNormals; + var cachedAttributes; - if ( vertexNormals.length === 3 ) { + this.getAttributes = function() { - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + if ( cachedAttributes === undefined ) { - } else { + cachedAttributes = fetchAttributeLocations( gl, program ); - var normal = face.normal; + } - this.normals.push( normal, normal, normal ); + return cachedAttributes; - } + }; - var vertexColors = face.vertexColors; + // free resource - if ( vertexColors.length === 3 ) { + this.destroy = function() { - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + gl.deleteProgram( program ); + this.program = undefined; - } else { + }; - var color = face.color; + // DEPRECATED - this.colors.push( color, color, color ); + Object.defineProperties( this, { - } + uniforms: { + get: function() { - if ( hasFaceVertexUv === true ) { + console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); + return this.getUniforms(); - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + } + }, - if ( vertexUvs !== undefined ) { + attributes: { + get: function() { - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); + return this.getAttributes(); - } else { + } + } - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + } ); - this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); - } + // - } + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - if ( hasFaceVertexUv2 === true ) { + return this; - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + }; - if ( vertexUvs !== undefined ) { + } )(); - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + function WebGLPrograms ( renderer, capabilities ) { + this.isWebGLPrograms = true; - } else { + var programs = []; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points' + }; - this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + var parameterNames = [ + "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", + "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", + "roughnessMap", "metalnessMap", + "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", + "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", + "maxBones", "useVertexTexture", "morphTargets", "morphNormals", + "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", + "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", + "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', + "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" + ]; - } - } + function allocateBones ( object ) { - // morphs + if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - for ( var j = 0; j < morphTargetsLength; j ++ ) { + return 1024; - var morphTarget = morphTargets[ j ].vertices; + } else { - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + // 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 = capabilities.maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - for ( var j = 0; j < morphNormalsLength; j ++ ) { + var maxBones = nVertexMatrices; - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + if ( object !== undefined && (object && object.isSkinnedMesh) ) { - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - } + if ( maxBones < object.skeleton.bones.length ) { - // skins + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - if ( hasSkinIndices ) { + } - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + } - } + return maxBones; - if ( hasSkinWeights ) { + } - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + } - } + function getTextureEncodingFromMap( map, gammaOverrideLinear ) { - } + var encoding; - this.computeGroups( geometry ); + if ( ! map ) { - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + encoding = LinearEncoding; - return this; + } else if ( (map && map.isTexture) ) { - }, + encoding = map.encoding; - dispose: function () { + } else if ( (map && map.isWebGLRenderTarget) ) { - this.dispatchEvent( { type: 'dispose' } ); + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; - } + } -} ); + // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. + if ( encoding === LinearEncoding && gammaOverrideLinear ) { -// File:src/core/BufferGeometry.js + encoding = GammaEncoding; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.BufferGeometry = function () { + return encoding; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + } - this.uuid = THREE.Math.generateUUID(); + this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { - this.name = ''; - this.type = 'BufferGeometry'; + var shaderID = shaderIDs[ material.type ]; - this.index = null; - this.attributes = {}; + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - this.morphAttributes = {}; + var maxBones = allocateBones( object ); + var precision = renderer.getPrecision(); - this.groups = []; + if ( material.precision !== null ) { - this.boundingBox = null; - this.boundingSphere = null; + precision = capabilities.getMaxPrecision( material.precision ); - this.drawRange = { start: 0, count: Infinity }; + if ( precision !== material.precision ) { -}; + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); -Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, { + } - getIndex: function () { + } - return this.index; + var currentRenderTarget = renderer.getCurrentRenderTarget(); - }, + var parameters = { - setIndex: function ( index ) { + shaderID: shaderID, - this.index = index; + precision: precision, + supportsVertexTextures: capabilities.vertexTextures, + outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), + map: !! material.map, + mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), + envMap: !! material.envMap, + envMapMode: material.envMap && material.envMap.mapping, + envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), + envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, - }, + combine: material.combine, - addAttribute: function ( name, attribute ) { + vertexColors: material.vertexColors, - if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) { + fog: !! fog, + useFog: material.fog, + fogExp: (fog && fog.isFogExp2), - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + flatShading: material.shading === FlatShading, - this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, - return; + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, - } + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: renderer.maxMorphTargets, + maxMorphNormals: renderer.maxMorphNormals, - if ( name === 'index' ) { + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numHemiLights: lights.hemi.length, - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + numClippingPlanes: nClipPlanes, - return; + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapType: renderer.shadowMap.type, - } + toneMapping: renderer.toneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - this.attributes[ name ] = attribute; + premultipliedAlpha: material.premultipliedAlpha, - return this; + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - }, + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false - getAttribute: function ( name ) { + }; - return this.attributes[ name ]; + return parameters; - }, + }; - removeAttribute: function ( name ) { + this.getProgramCode = function ( material, parameters ) { - delete this.attributes[ name ]; + var array = []; - return this; + if ( parameters.shaderID ) { - }, + array.push( parameters.shaderID ); - addGroup: function ( start, count, materialIndex ) { + } else { - this.groups.push( { + array.push( material.fragmentShader ); + array.push( material.vertexShader ); - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + } - } ); + if ( material.defines !== undefined ) { - }, + for ( var name in material.defines ) { - clearGroups: function () { + array.push( name ); + array.push( material.defines[ name ] ); - this.groups = []; + } - }, + } - setDrawRange: function ( start, count ) { + for ( var i = 0; i < parameterNames.length; i ++ ) { - this.drawRange.start = start; - this.drawRange.count = count; + array.push( parameters[ parameterNames[ i ] ] ); - }, + } - applyMatrix: function ( matrix ) { + return array.join(); - var position = this.attributes.position; + }; - if ( position !== undefined ) { + this.acquireProgram = function ( material, parameters, code ) { - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + var program; - } + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { - var normal = this.attributes.normal; + var programInfo = programs[ p ]; - if ( normal !== undefined ) { + if ( programInfo.code === code ) { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + program = programInfo; + ++ program.usedTimes; - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + break; - } + } - if ( this.boundingBox !== null ) { + } - this.computeBoundingBox(); + if ( program === undefined ) { - } + program = new exports.WebGLProgram( renderer, code, material, parameters ); + programs.push( program ); - if ( this.boundingSphere !== null ) { + } - this.computeBoundingSphere(); + return program; - } + }; - return this; + this.releaseProgram = function( program ) { - }, + if ( -- program.usedTimes === 0 ) { - rotateX: function () { + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); - // rotate geometry around world x-axis + // Free WebGL resources + program.destroy(); - var m1; + } - return function rotateX( angle ) { + }; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - m1.makeRotationX( angle ); + }; - this.applyMatrix( m1 ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - return this; + function BufferAttribute ( array, itemSize, normalized ) { + this.isBufferAttribute = true; - }; + this.uuid = exports.Math.generateUUID(); - }(), + this.array = array; + this.itemSize = itemSize; - rotateY: function () { + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - // rotate geometry around world y-axis + this.version = 0; + this.normalized = normalized === true; - var m1; + }; - return function rotateY( angle ) { + BufferAttribute.prototype = { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + constructor: BufferAttribute, - m1.makeRotationY( angle ); + get count() { - this.applyMatrix( m1 ); + return this.array.length / this.itemSize; - return this; + }, - }; + set needsUpdate( value ) { - }(), + if ( value === true ) this.version ++; - rotateZ: function () { + }, - // rotate geometry around world z-axis + setDynamic: function ( value ) { - var m1; + this.dynamic = value; - return function rotateZ( angle ) { + return this; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + }, - m1.makeRotationZ( angle ); + copy: function ( source ) { - this.applyMatrix( m1 ); + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; - return this; + this.dynamic = source.dynamic; - }; + return this; - }(), + }, - translate: function () { + copyAt: function ( index1, attribute, index2 ) { - // translate geometry + index1 *= this.itemSize; + index2 *= attribute.itemSize; - var m1; + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - return function translate( x, y, z ) { + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + } - m1.makeTranslation( x, y, z ); + return this; - this.applyMatrix( m1 ); + }, - return this; + copyArray: function ( array ) { - }; + this.array.set( array ); - }(), + return this; - scale: function () { + }, - // scale geometry + copyColorsArray: function ( colors ) { - var m1; + var array = this.array, offset = 0; - return function scale( x, y, z ) { + for ( var i = 0, l = colors.length; i < l; i ++ ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + var color = colors[ i ]; - m1.makeScale( x, y, z ); + if ( color === undefined ) { - this.applyMatrix( m1 ); + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - return this; + } - }; + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - }(), + } - lookAt: function () { + return this; - var obj; + }, - return function lookAt( vector ) { + copyIndicesArray: function ( indices ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + var array = this.array, offset = 0; - obj.lookAt( vector ); + for ( var i = 0, l = indices.length; i < l; i ++ ) { - obj.updateMatrix(); + var index = indices[ i ]; - this.applyMatrix( obj.matrix ); + array[ offset ++ ] = index.a; + array[ offset ++ ] = index.b; + array[ offset ++ ] = index.c; - }; + } - }(), + return this; - center: function () { + }, - this.computeBoundingBox(); + copyVector2sArray: function ( vectors ) { - var offset = this.boundingBox.center().negate(); + var array = this.array, offset = 0; - this.translate( offset.x, offset.y, offset.z ); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - return offset; + var vector = vectors[ i ]; - }, + if ( vector === undefined ) { - setFromObject: function ( object ) { + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + } - var geometry = object.geometry; + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - if ( object instanceof THREE.Points || object instanceof THREE.Line ) { + } - var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 ); + return this; - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + }, - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + copyVector3sArray: function ( vectors ) { - var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 ); + var array = this.array, offset = 0; - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } + var vector = vectors[ i ]; - if ( geometry.boundingSphere !== null ) { + if ( vector === undefined ) { - this.boundingSphere = geometry.boundingSphere.clone(); + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - } + } - if ( geometry.boundingBox !== null ) { + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - this.boundingBox = geometry.boundingBox.clone(); + } - } + return this; - } else if ( object instanceof THREE.Mesh ) { + }, - if ( geometry instanceof THREE.Geometry ) { + copyVector4sArray: function ( vectors ) { - this.fromGeometry( geometry ); + var array = this.array, offset = 0; - } + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } + var vector = vectors[ i ]; - return this; + if ( vector === undefined ) { - }, + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - updateFromObject: function ( object ) { + } - var geometry = object.geometry; + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - if ( object instanceof THREE.Mesh ) { + } - var direct = geometry.__directGeometry; + return this; - if ( direct === undefined || geometry.elementsNeedUpdate === true ) { + }, - return this.fromGeometry( geometry ); + set: function ( value, offset ) { - } + if ( offset === undefined ) offset = 0; - direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; + this.array.set( value, offset ); - geometry.elementsNeedUpdate = false; - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + return this; - geometry = direct; + }, - } + getX: function ( index ) { - var attribute; + return this.array[ index * this.itemSize ]; - if ( geometry.verticesNeedUpdate === true ) { + }, - attribute = this.attributes.position; + setX: function ( index, x ) { - if ( attribute !== undefined ) { + this.array[ index * this.itemSize ] = x; - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.verticesNeedUpdate = false; + getY: function ( index ) { - } + return this.array[ index * this.itemSize + 1 ]; - if ( geometry.normalsNeedUpdate === true ) { + }, - attribute = this.attributes.normal; + setY: function ( index, y ) { - if ( attribute !== undefined ) { + this.array[ index * this.itemSize + 1 ] = y; - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.normalsNeedUpdate = false; + getZ: function ( index ) { - } + return this.array[ index * this.itemSize + 2 ]; - if ( geometry.colorsNeedUpdate === true ) { + }, - attribute = this.attributes.color; + setZ: function ( index, z ) { - if ( attribute !== undefined ) { + this.array[ index * this.itemSize + 2 ] = z; - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.colorsNeedUpdate = false; + getW: function ( index ) { - } + return this.array[ index * this.itemSize + 3 ]; - if ( geometry.uvsNeedUpdate ) { + }, - attribute = this.attributes.uv; + setW: function ( index, w ) { - if ( attribute !== undefined ) { + this.array[ index * this.itemSize + 3 ] = w; - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.uvsNeedUpdate = false; + setXY: function ( index, x, y ) { - } + index *= this.itemSize; - if ( geometry.lineDistancesNeedUpdate ) { + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - attribute = this.attributes.lineDistance; + return this; - if ( attribute !== undefined ) { + }, - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + setXYZ: function ( index, x, y, z ) { - } + index *= this.itemSize; - geometry.lineDistancesNeedUpdate = false; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - } + return this; - if ( geometry.groupsNeedUpdate ) { + }, - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + setXYZW: function ( index, x, y, z, w ) { - geometry.groupsNeedUpdate = false; + index *= this.itemSize; - } + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - return this; + return this; - }, + }, - fromGeometry: function ( geometry ) { + clone: function () { - geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry ); + return new this.constructor().copy( this ); - return this.fromDirectGeometry( geometry.__directGeometry ); + } - }, + }; - fromDirectGeometry: function ( geometry ) { + // - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + function Int8Attribute ( array, itemSize ) { + this.isInt8Attribute = true; - if ( geometry.normals.length > 0 ) { + return new BufferAttribute( new Int8Array( array ), itemSize ); - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + }; - } + function Uint8Attribute ( array, itemSize ) { + this.isUint8Attribute = true; - if ( geometry.colors.length > 0 ) { + return new BufferAttribute( new Uint8Array( array ), itemSize ); - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + }; - } + function Uint8ClampedAttribute ( array, itemSize ) { + this.isUint8ClampedAttribute = true; - if ( geometry.uvs.length > 0 ) { + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + }; - } + function Int16Attribute ( array, itemSize ) { + this.isInt16Attribute = true; - if ( geometry.uvs2.length > 0 ) { + return new BufferAttribute( new Int16Array( array ), itemSize ); - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + }; - } + function Uint16Attribute ( array, itemSize ) { + this.isUint16Attribute = true; - if ( geometry.indices.length > 0 ) { + return new BufferAttribute( new Uint16Array( array ), itemSize ); - var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; - var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + }; - } + function Int32Attribute ( array, itemSize ) { + this.isInt32Attribute = true; - // groups + return new BufferAttribute( new Int32Array( array ), itemSize ); - this.groups = geometry.groups; + }; - // morphs + function Uint32Attribute ( array, itemSize ) { + this.isUint32Attribute = true; - for ( var name in geometry.morphTargets ) { + return new BufferAttribute( new Uint32Array( array ), itemSize ); - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + }; - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + function Float32Attribute ( array, itemSize ) { + this.isFloat32Attribute = true; - var morphTarget = morphTargets[ i ]; + return new BufferAttribute( new Float32Array( array ), itemSize ); - var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 ); + }; - array.push( attribute.copyVector3sArray( morphTarget ) ); + function Float64Attribute ( array, itemSize ) { + this.isFloat64Attribute = true; - } + return new BufferAttribute( new Float64Array( array ), itemSize ); - this.morphAttributes[ name ] = array; + }; - } - // skinning + // Deprecated - if ( geometry.skinIndices.length > 0 ) { + function DynamicBufferAttribute ( array, itemSize ) { + this.isDynamicBufferAttribute = true; - var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); - } + }; - if ( geometry.skinWeights.length > 0 ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + function Face3 ( a, b, c, normal, color, materialIndex ) { + this.isFace3 = true; - } + this.a = a; + this.b = b; + this.c = c; - // + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - if ( geometry.boundingSphere !== null ) { + this.color = (color && color.isColor) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - this.boundingSphere = geometry.boundingSphere.clone(); + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - } + }; - if ( geometry.boundingBox !== null ) { + Face3.prototype = { - this.boundingBox = geometry.boundingBox.clone(); + constructor: Face3, - } + clone: function () { - return this; + return new this.constructor().copy( this ); - }, + }, - computeBoundingBox: function () { + copy: function ( source ) { - if ( this.boundingBox === null ) { + this.a = source.a; + this.b = source.b; + this.c = source.c; - this.boundingBox = new THREE.Box3(); + this.normal.copy( source.normal ); + this.color.copy( source.color ); - } + this.materialIndex = source.materialIndex; - var positions = this.attributes.position.array; + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - if ( positions !== undefined ) { + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - this.boundingBox.setFromArray( positions ); + } - } else { + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - this.boundingBox.makeEmpty(); + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - } + } - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + return this; - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + } - } + }; - }, + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - computeBoundingSphere: function () { + function Euler ( x, y, z, order ) { + this.isEuler = true; - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - return function computeBoundingSphere() { + }; - if ( this.boundingSphere === null ) { + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - this.boundingSphere = new THREE.Sphere(); + Euler.DefaultOrder = 'XYZ'; - } + Euler.prototype = { - var positions = this.attributes.position; + constructor: Euler, - if ( positions ) { + get x () { - var array = positions.array; - var center = this.boundingSphere.center; + return this._x; - box.setFromArray( array ); - 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 + set x ( value ) { - var maxRadiusSq = 0; + this._x = value; + this.onChangeCallback(); - for ( var i = 0, il = array.length; i < il; i += 3 ) { + }, - vector.fromArray( array, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + get y () { - } + return this._y; - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + }, - if ( isNaN( this.boundingSphere.radius ) ) { + set y ( value ) { - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + this._y = value; + this.onChangeCallback(); - } + }, - } + get z () { - }; + return this._z; - }(), + }, - computeFaceNormals: function () { + set z ( value ) { - // backwards compatibility + this._z = value; + this.onChangeCallback(); - }, + }, - computeVertexNormals: function () { + get order () { - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + return this._order; - if ( attributes.position ) { + }, - var positions = attributes.position.array; + set order ( value ) { - if ( attributes.normal === undefined ) { + this._order = value; + this.onChangeCallback(); - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + }, - } else { + set: function ( x, y, z, order ) { - // reset existing normals to zero + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - var array = attributes.normal.array; + this.onChangeCallback(); - for ( var i = 0, il = array.length; i < il; i ++ ) { + return this; - array[ i ] = 0; + }, - } + clone: function () { - } + return new this.constructor( this._x, this._y, this._z, this._order ); - var normals = attributes.normal.array; + }, - var vA, vB, vC, + copy: function ( euler ) { - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + this.onChangeCallback(); - // indexed elements + return this; - if ( index ) { + }, - var indices = index.array; + setFromRotationMatrix: function ( m, order, update ) { - if ( groups.length === 0 ) { + var clamp = exports.Math.clamp; - this.addGroup( 0, indices.length ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - } + 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 ]; - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + order = order || this._order; - var group = groups[ j ]; + if ( order === 'XYZ' ) { - var start = group.start; - var count = group.count; + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - for ( var i = start, il = start + count; i < il; i += 3 ) { + if ( Math.abs( m13 ) < 0.99999 ) { - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + } else { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + this._x = Math.atan2( m32, m22 ); + this._z = 0; - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + } - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + } else if ( order === 'YXZ' ) { - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - } + if ( Math.abs( m23 ) < 0.99999 ) { - } + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - } else { + } else { - // non-indexed elements (unconnected triangle soup) + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + } - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + } else if ( order === 'ZXY' ) { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + if ( Math.abs( m32 ) < 0.99999 ) { - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + } else { - } + this._y = 0; + this._z = Math.atan2( m21, m11 ); - } + } - this.normalizeNormals(); + } else if ( order === 'ZYX' ) { - attributes.normal.needsUpdate = true; + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - } + if ( Math.abs( m31 ) < 0.99999 ) { - }, + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - merge: function ( geometry, offset ) { + } else { - if ( geometry instanceof THREE.BufferGeometry === false ) { + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + } - } + } else if ( order === 'YZX' ) { - if ( offset === undefined ) offset = 0; + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - var attributes = this.attributes; + if ( Math.abs( m21 ) < 0.99999 ) { - for ( var key in attributes ) { + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - if ( geometry.attributes[ key ] === undefined ) continue; + } else { - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + this._x = 0; + this._y = Math.atan2( m13, m33 ); - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + } - var attributeSize = attribute2.itemSize; + } else if ( order === 'XZY' ) { - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - attributeArray1[ j ] = attributeArray2[ i ]; + if ( Math.abs( m12 ) < 0.99999 ) { - } + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - } + } else { - return this; + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - }, + } - normalizeNormals: function () { + } else { - var normals = this.attributes.normal.array; + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); - var x, y, z, n; + } - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + this._order = order; - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; + if ( update !== false ) this.onChangeCallback(); - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + return this; - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; + }, - } + setFromQuaternion: function () { - }, + var matrix; - toNonIndexed: function () { + return function setFromQuaternion( q, order, update ) { - if ( this.index === null ) { + if ( matrix === undefined ) matrix = new Matrix4(); - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + matrix.makeRotationFromQuaternion( q ); - } + return this.setFromRotationMatrix( matrix, order, update ); - var geometry2 = new THREE.BufferGeometry(); + }; - var indices = this.index.array; - var attributes = this.attributes; + }(), - for ( var name in attributes ) { + setFromVector3: function ( v, order ) { - var attribute = attributes[ name ]; + return this.set( v.x, v.y, v.z, order || this._order ); - var array = attribute.array; - var itemSize = attribute.itemSize; + }, - var array2 = new array.constructor( indices.length * itemSize ); + reorder: function () { - var index = 0, index2 = 0; + // WARNING: this discards revolution information -bhouston - for ( var i = 0, l = indices.length; i < l; i ++ ) { + var q = new Quaternion(); - index = indices[ i ] * itemSize; + return function reorder( newOrder ) { - for ( var j = 0; j < itemSize; j ++ ) { + q.setFromEuler( this ); + + return this.setFromQuaternion( q, newOrder ); - array2[ index2 ++ ] = array[ index ++ ]; + }; - } + }(), - } + equals: function ( euler ) { - geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) ); + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - } + }, - return geometry2; + fromArray: function ( array ) { - }, + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - toJSON: function () { + this.onChangeCallback(); - var data = { - metadata: { - version: 4.4, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + return this; - // standard BufferGeometry serialization + }, - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + toArray: function ( array, offset ) { - if ( this.parameters !== undefined ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - var parameters = this.parameters; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - for ( var key in parameters ) { + return array; - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + }, - } + toVector3: function ( optionalResult ) { - return data; + if ( optionalResult ) { - } + return optionalResult.set( this._x, this._y, this._z ); - data.data = { attributes: {} }; + } else { - var index = this.index; + return new Vector3( this._x, this._y, this._z ); - if ( index !== null ) { + } - var array = Array.prototype.slice.call( index.array ); + }, - data.data.index = { - type: index.array.constructor.name, - array: array - }; + onChange: function ( callback ) { - } + this.onChangeCallback = callback; - var attributes = this.attributes; + return this; - for ( var key in attributes ) { + }, - var attribute = attributes[ key ]; + onChangeCallback: function () {} - var array = Array.prototype.slice.call( attribute.array ); + }; - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array, - normalized: attribute.normalized - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function Layers () { + this.isLayers = true; - var groups = this.groups; + this.mask = 1; - if ( groups.length > 0 ) { + }; - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + Layers.prototype = { - } + constructor: Layers, - var boundingSphere = this.boundingSphere; + set: function ( channel ) { - if ( boundingSphere !== null ) { + this.mask = 1 << channel; - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + }, - } + enable: function ( channel ) { - return data; + this.mask |= 1 << channel; - }, + }, - clone: function () { + toggle: function ( channel ) { - /* - // Handle primitives + this.mask ^= 1 << channel; - var parameters = this.parameters; + }, - if ( parameters !== undefined ) { + disable: function ( channel ) { - var values = []; + this.mask &= ~ ( 1 << channel ); - for ( var key in parameters ) { + }, - values.push( parameters[ key ] ); + test: function ( layers ) { - } + return ( this.mask & layers.mask ) !== 0; - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + } - } + }; - return new this.constructor().copy( this ); - */ + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author elephantatwork / www.elephantatwork.ch + */ - return new THREE.BufferGeometry().copy( this ); + function Object3D () { + this.isObject3D = true; - }, + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - copy: function ( source ) { + this.uuid = exports.Math.generateUUID(); - var index = source.index; + this.name = ''; + this.type = 'Object3D'; - if ( index !== null ) { + this.parent = null; + this.children = []; - this.setIndex( index.clone() ); + this.up = Object3D.DefaultUp.clone(); - } + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - var attributes = source.attributes; + function onRotationChange() { - for ( var name in attributes ) { + quaternion.setFromEuler( rotation, false ); - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + } - } + function onQuaternionChange() { - var groups = source.groups; + rotation.setFromQuaternion( quaternion, undefined, false ); - for ( var i = 0, l = groups.length; i < l; i ++ ) { + } - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); - } + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - return this; + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - }, + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - dispose: function () { + this.layers = new Layers(); + this.visible = true; - this.dispatchEvent( { type: 'dispose' } ); + this.castShadow = false; + this.receiveShadow = false; - } + this.frustumCulled = true; + this.renderOrder = 0; -} ); + this.userData = {}; -THREE.BufferGeometry.MaxIndex = 65535; + }; -// File:src/core/InstancedBufferGeometry.js + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + Object.assign( Object3D.prototype, EventDispatcher.prototype, { -THREE.InstancedBufferGeometry = function () { + applyMatrix: function ( matrix ) { - THREE.BufferGeometry.call( this ); + this.matrix.multiplyMatrices( matrix, this.matrix ); - this.type = 'InstancedBufferGeometry'; - this.maxInstancedCount = undefined; + this.matrix.decompose( this.position, this.quaternion, this.scale ); -}; + }, -THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry; + setRotationFromAxisAngle: function ( axis, angle ) { -THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { + // assumes axis is normalized - this.groups.push( { + this.quaternion.setFromAxisAngle( axis, angle ); - start: start, - count: count, - instances: instances + }, - } ); + setRotationFromEuler: function ( euler ) { -}; + this.quaternion.setFromEuler( euler, true ); -THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { + }, - var index = source.index; + setRotationFromMatrix: function ( m ) { - if ( index !== null ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - this.setIndex( index.clone() ); + this.quaternion.setFromRotationMatrix( m ); - } + }, - var attributes = source.attributes; + setRotationFromQuaternion: function ( q ) { - for ( var name in attributes ) { + // assumes q is normalized - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + this.quaternion.copy( q ); - } + }, - var groups = source.groups; + rotateOnAxis: function () { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + // rotate object on axis in object space + // axis is assumed to be normalized - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.instances ); + var q1 = new Quaternion(); - } + return function rotateOnAxis( axis, angle ) { - return this; + q1.setFromAxisAngle( axis, angle ); -}; + this.quaternion.multiply( q1 ); -// File:src/core/Uniform.js + return this; -/** - * @author mrdoob / http://mrdoob.com/ - */ + }; -THREE.Uniform = function ( value ) { + }(), - if ( typeof value === 'string' ) { + rotateX: function () { - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + var v1 = new Vector3( 1, 0, 0 ); - } + return function rotateX( angle ) { - this.value = value; + return this.rotateOnAxis( v1, angle ); - this.dynamic = false; + }; -}; + }(), -THREE.Uniform.prototype = { + rotateY: function () { - constructor: THREE.Uniform, + var v1 = new Vector3( 0, 1, 0 ); - onUpdate: function ( callback ) { + return function rotateY( angle ) { - this.dynamic = true; - this.onUpdateCallback = callback; + return this.rotateOnAxis( v1, angle ); - return this; + }; - } + }(), -}; + rotateZ: function () { -// File:src/animation/AnimationAction.js + var v1 = new Vector3( 0, 0, 1 ); -/** - * - * Action provided by AnimationMixer for scheduling clip playback on specific - * objects. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - * - */ + return function rotateZ( angle ) { -THREE.AnimationAction = function() { + return this.rotateOnAxis( v1, angle ); - throw new Error( "THREE.AnimationAction: " + - "Use mixer.clipAction for construction." ); + }; -}; + }(), -THREE.AnimationAction._new = - function AnimationAction( mixer, clip, localRoot ) { + translateOnAxis: function () { - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot || null; + // translate object by distance along axis in object space + // axis is assumed to be normalized - var tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + var v1 = new Vector3(); - var interpolantSettings = { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding - }; + return function translateOnAxis( axis, distance ) { - for ( var i = 0; i !== nTracks; ++ i ) { + v1.copy( axis ).applyQuaternion( this.quaternion ); - var interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + this.position.add( v1.multiplyScalar( distance ) ); - } + return this; - this._interpolantSettings = interpolantSettings; + }; - this._interpolants = interpolants; // bound by the mixer + }(), - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + translateX: function () { - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + var v1 = new Vector3( 1, 0, 0 ); - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + return function translateX( distance ) { - this.loop = THREE.LoopRepeat; - this._loopCount = -1; + return this.translateOnAxis( v1, distance ); - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + }; - // scaled local time of the action - // gets clamped or wrapped to 0..clip.duration according to loop - this.time = 0; + }(), - this.timeScale = 1; - this._effectiveTimeScale = 1; + translateY: function () { - this.weight = 1; - this._effectiveWeight = 1; + var v1 = new Vector3( 0, 1, 0 ); - this.repetitions = Infinity; // no. of repetitions when looping + return function translateY( distance ) { - this.paused = false; // false -> zero effective time scale - this.enabled = true; // true -> zero effective weight + return this.translateOnAxis( v1, distance ); - this.clampWhenFinished = false; // keep feeding the last frame? + }; - this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true; // clips for start, loop and end + }(), -}; + translateZ: function () { -THREE.AnimationAction._new.prototype = { + var v1 = new Vector3( 0, 0, 1 ); - constructor: THREE.AnimationAction._new, + return function translateZ( distance ) { - // State & Scheduling + return this.translateOnAxis( v1, distance ); - play: function() { + }; - this._mixer._activateAction( this ); + }(), - return this; + localToWorld: function ( vector ) { - }, + return vector.applyMatrix4( this.matrixWorld ); - stop: function() { + }, - this._mixer._deactivateAction( this ); + worldToLocal: function () { - return this.reset(); + var m1 = new Matrix4(); - }, + return function worldToLocal( vector ) { - reset: function() { + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - this.paused = false; - this.enabled = true; + }; - this.time = 0; // restart clip - this._loopCount = -1; // forget previous loops - this._startTime = null; // forget scheduling + }(), - return this.stopFading().stopWarping(); + lookAt: function () { - }, + // This routine does not support objects with rotated and/or translated parent(s) - isRunning: function() { + var m1 = new Matrix4(); - var start = this._startTime; + return function lookAt( vector ) { - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + m1.lookAt( vector, this.position, this.up ); - }, + this.quaternion.setFromRotationMatrix( m1 ); - // return true when play has been called - isScheduled: function() { + }; - return this._mixer._isActiveAction( this ); + }(), - }, + add: function ( object ) { - startAt: function( time ) { + if ( arguments.length > 1 ) { - this._startTime = time; + for ( var i = 0; i < arguments.length; i ++ ) { - return this; + this.add( arguments[ i ] ); - }, + } - setLoop: function( mode, repetitions ) { + return this; - this.loop = mode; - this.repetitions = repetitions; + } - return this; + if ( object === this ) { - }, + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - // Weight + } - // set the weight stopping any scheduled fading - // although .enabled = false yields an effective weight of zero, this - // method does *not* change .enabled, because it would be confusing - setEffectiveWeight: function( weight ) { + if ( (object && object.isObject3D) ) { - this.weight = weight; + if ( object.parent !== null ) { - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + object.parent.remove( object ); - return this.stopFading(); + } - }, + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - // return the weight considering fading and .enabled - getEffectiveWeight: function() { + this.children.push( object ); - return this._effectiveWeight; + } else { - }, + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - fadeIn: function( duration ) { + } - return this._scheduleFading( duration, 0, 1 ); + return this; - }, + }, - fadeOut: function( duration ) { + remove: function ( object ) { - return this._scheduleFading( duration, 1, 0 ); + if ( arguments.length > 1 ) { - }, + for ( var i = 0; i < arguments.length; i ++ ) { - crossFadeFrom: function( fadeOutAction, duration, warp ) { + this.remove( arguments[ i ] ); - var mixer = this._mixer; + } - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + } - if( warp ) { + var index = this.children.indexOf( object ); - var fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + if ( index !== - 1 ) { - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + object.parent = null; - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + object.dispatchEvent( { type: 'removed' } ); - } + this.children.splice( index, 1 ); - return this; + } - }, + }, - crossFadeTo: function( fadeInAction, duration, warp ) { + getObjectById: function ( id ) { - return fadeInAction.crossFadeFrom( this, duration, warp ); + return this.getObjectByProperty( 'id', id ); - }, + }, - stopFading: function() { + getObjectByName: function ( name ) { - var weightInterpolant = this._weightInterpolant; + return this.getObjectByProperty( 'name', name ); - if ( weightInterpolant !== null ) { + }, - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + getObjectByProperty: function ( name, value ) { - } + 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 ); - // Time Scale Control + if ( object !== undefined ) { - // set the weight stopping any scheduled warping - // although .paused = true yields an effective time scale of zero, this - // method does *not* change .paused, because it would be confusing - setEffectiveTimeScale: function( timeScale ) { + return object; - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 :timeScale; + } - return this.stopWarping(); + } - }, + return undefined; - // return the time scale considering warping and .paused - getEffectiveTimeScale: function() { + }, - return this._effectiveTimeScale; + getWorldPosition: function ( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); - setDuration: function( duration ) { + this.updateMatrixWorld( true ); - this.timeScale = this._clip.duration / duration; + return result.setFromMatrixPosition( this.matrixWorld ); - return this.stopWarping(); + }, - }, + getWorldQuaternion: function () { - syncWith: function( action ) { + var position = new Vector3(); + var scale = new Vector3(); - this.time = action.time; - this.timeScale = action.timeScale; + return function getWorldQuaternion( optionalTarget ) { - return this.stopWarping(); + var result = optionalTarget || new Quaternion(); - }, + this.updateMatrixWorld( true ); - halt: function( duration ) { + this.matrixWorld.decompose( position, result, scale ); - return this.warp( this._effectiveTimeScale, 0, duration ); + return result; - }, + }; - warp: function( startTimeScale, endTimeScale, duration ) { + }(), - var mixer = this._mixer, now = mixer.time, - interpolant = this._timeScaleInterpolant, + getWorldRotation: function () { - timeScale = this.timeScale; + var quaternion = new Quaternion(); - if ( interpolant === null ) { + return function getWorldRotation( optionalTarget ) { - interpolant = mixer._lendControlInterpolant(), - this._timeScaleInterpolant = interpolant; + var result = optionalTarget || new Euler(); - } + this.getWorldQuaternion( quaternion ); - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - times[ 0 ] = now; - times[ 1 ] = now + duration; + }; - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + }(), - return this; + getWorldScale: function () { - }, + var position = new Vector3(); + var quaternion = new Quaternion(); - stopWarping: function() { + return function getWorldScale( optionalTarget ) { - var timeScaleInterpolant = this._timeScaleInterpolant; + var result = optionalTarget || new Vector3(); - if ( timeScaleInterpolant !== null ) { + this.updateMatrixWorld( true ); - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + this.matrixWorld.decompose( position, quaternion, result ); - } + return result; - return this; + }; - }, + }(), - // Object Accessors + getWorldDirection: function () { - getMixer: function() { + var quaternion = new Quaternion(); - return this._mixer; + return function getWorldDirection( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); - getClip: function() { + this.getWorldQuaternion( quaternion ); - return this._clip; + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); - }, + }; - getRoot: function() { + }(), - return this._localRoot || this._mixer._root; + raycast: function () {}, - }, + traverse: function ( callback ) { - // Interna + callback( this ); - _update: function( time, deltaTime, timeDirection, accuIndex ) { - // called by the mixer + var children = this.children; - var startTime = this._startTime; + for ( var i = 0, l = children.length; i < l; i ++ ) { - if ( startTime !== null ) { + children[ i ].traverse( callback ); - // check for scheduled start of action + } - var timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + }, - return; // yet to come / don't decide when delta = 0 + traverseVisible: function ( callback ) { - } + if ( this.visible === false ) return; - // start + callback( this ); - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + var children = this.children; - } + for ( var i = 0, l = children.length; i < l; i ++ ) { - // apply time scale and advance time + children[ i ].traverseVisible( callback ); - deltaTime *= this._updateTimeScale( time ); - var clipTime = this._updateTime( deltaTime ); + } - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + }, - var weight = this._updateWeight( time ); + traverseAncestors: function ( callback ) { - if ( weight > 0 ) { + var parent = this.parent; - var interpolants = this._interpolants; - var propertyMixers = this._propertyBindings; + if ( parent !== null ) { - for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { + callback( parent ); - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + parent.traverseAncestors( callback ); - } + } - } + }, - }, + updateMatrix: function () { - _updateWeight: function( time ) { + this.matrix.compose( this.position, this.quaternion, this.scale ); - var weight = 0; + this.matrixWorldNeedsUpdate = true; - if ( this.enabled ) { + }, - weight = this.weight; - var interpolant = this._weightInterpolant; + updateMatrixWorld: function ( force ) { - if ( interpolant !== null ) { + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + if ( this.matrixWorldNeedsUpdate === true || force === true ) { - weight *= interpolantValue; + if ( this.parent === null ) { - if ( time > interpolant.parameterPositions[ 1 ] ) { + this.matrixWorld.copy( this.matrix ); - this.stopFading(); + } else { - if ( interpolantValue === 0 ) { + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - // faded out, disable - this.enabled = false; + } - } + this.matrixWorldNeedsUpdate = false; - } + force = true; - } + } - } + // update children - this._effectiveWeight = weight; - return weight; + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - }, + this.children[ i ].updateMatrixWorld( force ); - _updateTimeScale: function( time ) { + } - var timeScale = 0; + }, - if ( ! this.paused ) { + toJSON: function ( meta ) { - timeScale = this.timeScale; + // meta is '' when called from JSON.stringify + var isRootObject = ( meta === undefined || meta === '' ); - var interpolant = this._timeScaleInterpolant; + var output = {}; - if ( interpolant !== null ) { + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {} + }; - timeScale *= interpolantValue; + output.metadata = { + version: 4.4, + type: 'Object', + generator: 'Object3D.toJSON' + }; - if ( time > interpolant.parameterPositions[ 1 ] ) { + } - this.stopWarping(); + // standard Object3D serialization - if ( timeScale === 0 ) { + var object = {}; - // motion has halted, pause - this.paused = true; + object.uuid = this.uuid; + object.type = this.type; - } else { + if ( this.name !== '' ) object.name = this.name; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; - // warp done - apply final time scale - this.timeScale = timeScale; + object.matrix = this.matrix.toArray(); - } + // - } + if ( this.geometry !== undefined ) { - } + if ( meta.geometries[ this.geometry.uuid ] === undefined ) { - } + meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); - this._effectiveTimeScale = timeScale; - return timeScale; + } - }, + object.geometry = this.geometry.uuid; - _updateTime: function( deltaTime ) { + } - var time = this.time + deltaTime; + if ( this.material !== undefined ) { - if ( deltaTime === 0 ) return time; + if ( meta.materials[ this.material.uuid ] === undefined ) { - var duration = this._clip.duration, + meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); - loop = this.loop, - loopCount = this._loopCount; + } - if ( loop === THREE.LoopOnce ) { + object.material = this.material.uuid; - if ( loopCount === -1 ) { - // just started + } - this.loopCount = 0; - this._setEndings( true, true, false ); + // - } + if ( this.children.length > 0 ) { - handle_stop: { + object.children = []; - if ( time >= duration ) { + for ( var i = 0; i < this.children.length; i ++ ) { - time = duration; + object.children.push( this.children[ i ].toJSON( meta ).object ); - } else if ( time < 0 ) { + } - time = 0; + } - } else break handle_stop; + if ( isRootObject ) { - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? -1 : 1 - } ); + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; - } + } - } else { // repetitive Repeat or PingPong + output.object = object; - var pingPong = ( loop === THREE.LoopPingPong ); + return output; - if ( loopCount === -1 ) { - // just started + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache ( cache ) { - if ( deltaTime >= 0 ) { + var values = []; + for ( var key in cache ) { - loopCount = 0; + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - this._setEndings( - true, this.repetitions === 0, pingPong ); + } + return values; - } else { + } - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + }, - this._setEndings( - this.repetitions === 0, true, pingPong ); + clone: function ( recursive ) { - } + return new this.constructor().copy( this, recursive ); - } + }, - if ( time >= duration || time < 0 ) { - // wrap around + copy: function ( source, recursive ) { - var loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + if ( recursive === undefined ) recursive = true; - loopCount += Math.abs( loopDelta ); + this.name = source.name; - var pending = this.repetitions - loopCount; + this.up.copy( source.up ); - if ( pending < 0 ) { - // have to stop (switch state, clamp time, fire event) + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - time = deltaTime > 0 ? duration : 0; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : -1 - } ); + this.visible = source.visible; - } else { - // keep running + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - if ( pending === 0 ) { - // entering the last round + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - var atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - } else { + if ( recursive === true ) { - this._setEndings( false, false, pingPong ); + for ( var i = 0; i < source.children.length; i ++ ) { - } + var child = source.children[ i ]; + this.add( child.clone() ); - this._loopCount = loopCount; + } - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + } - } + return this; - } + } - if ( pingPong && ( loopCount & 1 ) === 1 ) { - // invert time for the "pong round" + } ); - this.time = time; - return duration - time; + var count$3 = 0; + function Object3DIdCount () { return count$3++; }; - } + /** + * @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://clara.io + */ - } + function Geometry () { + this.isGeometry = true; - this.time = time; - return time; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - }, + this.uuid = exports.Math.generateUUID(); - _setEndings: function( atStart, atEnd, pingPong ) { + this.name = ''; + this.type = 'Geometry'; - var settings = this._interpolantSettings; + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - if ( pingPong ) { + this.morphTargets = []; + this.morphNormals = []; - settings.endingStart = THREE.ZeroSlopeEnding; - settings.endingEnd = THREE.ZeroSlopeEnding; + this.skinWeights = []; + this.skinIndices = []; - } else { + this.lineDistances = []; - // assuming for LoopOnce atStart == atEnd == true + this.boundingBox = null; + this.boundingSphere = null; - if ( atStart ) { + // update flags - settings.endingStart = this.zeroSlopeAtStart ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - } else { + }; - settings.endingStart = THREE.WrapAroundEnding; + Object.assign( Geometry.prototype, EventDispatcher.prototype, { - } + applyMatrix: function ( matrix ) { - if ( atEnd ) { + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - settings.endingEnd = this.zeroSlopeAtEnd ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - } else { + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - settings.endingEnd = THREE.WrapAroundEnding; + } - } + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - } + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - }, + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - _scheduleFading: function( duration, weightNow, weightThen ) { + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - var mixer = this._mixer, now = mixer.time, - interpolant = this._weightInterpolant; + } - if ( interpolant === null ) { + } - interpolant = mixer._lendControlInterpolant(), - this._weightInterpolant = interpolant; + if ( this.boundingBox !== null ) { - } + this.computeBoundingBox(); - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + } - times[ 0 ] = now; values[ 0 ] = weightNow; - times[ 1 ] = now + duration; values[ 1 ] = weightThen; + if ( this.boundingSphere !== null ) { - return this; + this.computeBoundingSphere(); - } + } -}; + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; + return this; -// File:src/animation/AnimationClip.js + }, -/** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + rotateX: function () { -THREE.AnimationClip = function ( name, duration, tracks ) { + // rotate geometry around world x-axis - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : -1; + var m1; - this.uuid = THREE.Math.generateUUID(); + return function rotateX( angle ) { - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + if ( m1 === undefined ) m1 = new Matrix4(); - this.resetDuration(); + m1.makeRotationX( angle ); - } + this.applyMatrix( m1 ); - // maybe only do these on demand, as doing them here could potentially slow down loading - // but leaving these here during development as this ensures a lot of testing of these functions - this.trim(); - this.optimize(); + return this; -}; + }; -THREE.AnimationClip.prototype = { + }(), - constructor: THREE.AnimationClip, + rotateY: function () { - resetDuration: function() { + // rotate geometry around world y-axis - var tracks = this.tracks, - duration = 0; + var m1; - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + return function rotateY( angle ) { - var track = this.tracks[ i ]; + if ( m1 === undefined ) m1 = new Matrix4(); - duration = Math.max( - duration, track.times[ track.times.length - 1 ] ); + m1.makeRotationY( angle ); - } + this.applyMatrix( m1 ); - this.duration = duration; + return this; - }, + }; - trim: function() { + }(), - for ( var i = 0; i < this.tracks.length; i ++ ) { + rotateZ: function () { - this.tracks[ i ].trim( 0, this.duration ); + // rotate geometry around world z-axis - } + var m1; - return this; + return function rotateZ( angle ) { - }, + if ( m1 === undefined ) m1 = new Matrix4(); - optimize: function() { + m1.makeRotationZ( angle ); - for ( var i = 0; i < this.tracks.length; i ++ ) { + this.applyMatrix( m1 ); - this.tracks[ i ].optimize(); + return this; - } + }; - return this; + }(), - } + translate: function () { -}; + // translate geometry -// Static methods: + var m1; -Object.assign( THREE.AnimationClip, { + return function translate( x, y, z ) { - parse: function( json ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + m1.makeTranslation( x, y, z ); - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { + this.applyMatrix( m1 ); - tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + return this; - } + }; - return new THREE.AnimationClip( json.name, json.duration, tracks ); + }(), - }, + scale: function () { + // scale geometry - toJSON: function( clip ) { + var m1; - var tracks = [], - clipTracks = clip.tracks; + return function scale( x, y, z ) { - var json = { + if ( m1 === undefined ) m1 = new Matrix4(); - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks + m1.makeScale( x, y, z ); - }; + this.applyMatrix( m1 ); - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { + return this; - tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) ); + }; - } + }(), - return json; + lookAt: function () { - }, + var obj; + return function lookAt( vector ) { - CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { + if ( obj === undefined ) obj = new Object3D(); - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + obj.lookAt( vector ); - for ( var i = 0; i < numMorphTargets; i ++ ) { + obj.updateMatrix(); - var times = []; - var values = []; + this.applyMatrix( obj.matrix ); - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + }; - values.push( 0, 1, 0 ); + }(), - var order = THREE.AnimationUtils.getKeyframeOrder( times ); - times = THREE.AnimationUtils.sortedArray( times, 1, order ); - values = THREE.AnimationUtils.sortedArray( values, 1, order ); + fromBufferGeometry: function ( geometry ) { - // if there is a key at the first frame, duplicate it as the - // last frame as well for perfect loop. - if ( ! noLoop && times[ 0 ] === 0 ) { + var scope = this; - times.push( numMorphTargets ); - values.push( values[ 0 ] ); + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - } + var positions = attributes.position.array; + 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; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - tracks.push( - new THREE.NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); - } + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - return new THREE.AnimationClip( name, -1, tracks ); + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - }, + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - findByName: function( objectOrClipArray, name ) { + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - var clipArray = objectOrClipArray; + if ( normals !== undefined ) { - if ( ! Array.isArray( objectOrClipArray ) ) { + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + } - } + if ( colors !== undefined ) { - for ( var i = 0; i < clipArray.length; i ++ ) { + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - if ( clipArray[ i ].name === name ) { + } - return clipArray[ i ]; + if ( uvs !== undefined ) { - } - } + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - return null; + } - }, + if ( uvs2 !== undefined ) { - CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); - var animationToMorphTargets = {}; + } - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; + } - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { + function addFace( a, b, c, materialIndex ) { - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + 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() ] : []; - if ( parts && parts.length > 1 ) { + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - var name = parts[ 1 ]; + scope.faces.push( face ); - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + if ( uvs !== undefined ) { - animationToMorphTargets[ name ] = animationMorphTargets = []; + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - } + } - animationMorphTargets.push( morphTarget ); + if ( uvs2 !== undefined ) { - } + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); - } + } - var clips = []; + } - for ( var name in animationToMorphTargets ) { + if ( indices !== undefined ) { - clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + var groups = geometry.groups; - } + if ( groups.length > 0 ) { - return clips; + for ( var i = 0; i < groups.length; i ++ ) { - }, + var group = groups[ i ]; - // parse the animation.hierarchy format - parseAnimation: function( animation, bones, nodeName ) { + var start = group.start; + var count = group.count; - if ( ! animation ) { + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - console.error( " no animation in JSONLoader data" ); - return null; + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - } + } - var addNonemptyTrack = function( - trackType, trackName, animationKeys, propertyName, destTracks ) { + } - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { + } else { - var times = []; - var values = []; + for ( var i = 0; i < indices.length; i += 3 ) { - THREE.AnimationUtils.flattenJSON( - animationKeys, times, values, propertyName ); + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + } - destTracks.push( new trackType( trackName, times, values ) ); + } - } + } else { - } + for ( var i = 0; i < positions.length / 3; i += 3 ) { - }; + addFace( i, i + 1, i + 2 ); - var tracks = []; + } - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || -1; - var fps = animation.fps || 30; + } - var hierarchyTracks = animation.hierarchy || []; + this.computeFaceNormals(); - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + if ( geometry.boundingBox !== null ) { - var animationKeys = hierarchyTracks[ h ].keys; + this.boundingBox = geometry.boundingBox.clone(); - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; + } - // process morph targets in a way exactly compatible - // with AnimationHandler.init( animation ) - if ( animationKeys[0].morphTargets ) { + if ( geometry.boundingSphere !== null ) { - // figure out all morph targets used in this track - var morphTargetNames = {}; - for ( var k = 0; k < animationKeys.length; k ++ ) { + this.boundingSphere = geometry.boundingSphere.clone(); - if ( animationKeys[k].morphTargets ) { + } - for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { + return this; - morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; - } + }, - } + center: function () { - } + this.computeBoundingBox(); - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( var morphTargetName in morphTargetNames ) { + var offset = this.boundingBox.center().negate(); - var times = []; - var values = []; + this.translate( offset.x, offset.y, offset.z ); - for ( var m = 0; - m !== animationKeys[k].morphTargets.length; ++ m ) { + return offset; - var animationKey = animationKeys[k]; + }, - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + normalize: function () { - } + this.computeBoundingSphere(); - tracks.push( new THREE.NumberKeyframeTrack( - '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - } + var s = radius === 0 ? 1 : 1.0 / radius; - duration = morphTargetNames.length * ( fps || 1.0 ); + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - } else { - // ...assume skeletal animation + this.applyMatrix( matrix ); - var boneName = '.bones[' + bones[ h ].name + ']'; + return this; - addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + }, - addNonemptyTrack( - THREE.QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + computeFaceNormals: function () { - addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + var cb = new Vector3(), ab = new Vector3(); - } + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + var face = this.faces[ f ]; - if ( tracks.length === 0 ) { + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - return null; + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - } + cb.normalize(); - var clip = new THREE.AnimationClip( clipName, duration, tracks ); + face.normal.copy( cb ); - return clip; + } - } + }, -} ); + computeVertexNormals: function ( areaWeighted ) { -// File:src/animation/AnimationMixer.js + if ( areaWeighted === undefined ) areaWeighted = true; -/** - * - * Player for AnimationClips. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var v, vl, f, fl, face, vertices; -THREE.AnimationMixer = function( root ) { + vertices = new Array( this.vertices.length ); - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - this.time = 0; + vertices[ v ] = new Vector3(); - this.timeScale = 1.0; + } -}; + if ( areaWeighted ) { -Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, { + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - // return an action for a clip optionally using a custom root target - // object (this method allocates a lot of dynamic memory in case a - // previously unknown clip/root combination is specified) - clipAction: function( clip, optionalRoot ) { + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - var root = optionalRoot || this._root, - rootUuid = root.uuid, + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + face = this.faces[ f ]; - clipUuid = clipObject !== null ? clipObject.uuid : clip, + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - actionsForClip = this._actionsByClip[ clipUuid ], - prototypeAction = null; + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - if ( actionsForClip !== undefined ) { + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - var existingAction = - actionsForClip.actionByRoot[ rootUuid ]; + } - if ( existingAction !== undefined ) { + } else { - return existingAction; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - // also, take the clip from the prototype action - if ( clipObject === null ) - clipObject = prototypeAction._clip; + } - } + } - // clip must be known when specified via string - if ( clipObject === null ) return null; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - // allocate all resources required to run it - var newAction = new THREE. - AnimationMixer._Action( this, clipObject, optionalRoot ); + vertices[ v ].normalize(); - this._bindAction( newAction, prototypeAction ); + } - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - return newAction; + face = this.faces[ f ]; - }, + var vertexNormals = face.vertexNormals; - // get an existing action - existingAction: function( clip, optionalRoot ) { + if ( vertexNormals.length === 3 ) { - var root = optionalRoot || this._root, - rootUuid = root.uuid, + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + } else { - clipUuid = clipObject ? clipObject.uuid : clip, + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); - actionsForClip = this._actionsByClip[ clipUuid ]; + } - if ( actionsForClip !== undefined ) { + } - return actionsForClip.actionByRoot[ rootUuid ] || null; + if ( this.faces.length > 0 ) { - } + this.normalsNeedUpdate = true; - return null; + } - }, + }, - // deactivates all previously scheduled actions - stopAllAction: function() { + computeMorphNormals: function () { - var actions = this._actions, - nActions = this._nActiveActions, - bindings = this._bindings, - nBindings = this._nActiveBindings; + var i, il, f, fl, face; - this._nActiveActions = 0; - this._nActiveBindings = 0; + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - for ( var i = 0; i !== nActions; ++ i ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - actions[ i ].reset(); + face = this.faces[ f ]; - } + if ( ! face.__originalFaceNormal ) { - for ( var i = 0; i !== nBindings; ++ i ) { + face.__originalFaceNormal = face.normal.clone(); - bindings[ i ].useCount = 0; + } else { - } + face.__originalFaceNormal.copy( face.normal ); - return this; + } - }, + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - // advance the time and update apply the animation - update: function( deltaTime ) { + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - deltaTime *= this.timeScale; + if ( ! face.__originalVertexNormals[ i ] ) { - var actions = this._actions, - nActions = this._nActiveActions, + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + } else { - accuIndex = this._accuIndex ^= 1; + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - // run active actions + } - for ( var i = 0; i !== nActions; ++ i ) { + } - var action = actions[ i ]; + } - if ( action.enabled ) { + // use temp geometry to compute face and vertex normals for each morph - action._update( time, deltaTime, timeDirection, accuIndex ); + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - } + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - } + // create on first access - // update scene graph + if ( ! this.morphNormals[ i ] ) { - var bindings = this._bindings, - nBindings = this._nActiveBindings; + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - for ( var i = 0; i !== nBindings; ++ i ) { + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - bindings[ i ].apply( accuIndex ); + var faceNormal, vertexNormals; - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - return this; + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - }, + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - // return this mixer's root target object - getRoot: function() { + } - return this._root; + } - }, + var morphNormals = this.morphNormals[ i ]; - // free all resources specific to a particular clip - uncacheClip: function( clip ) { + // set vertices to morph target - var actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + tmpGeo.vertices = this.morphTargets[ i ].vertices; - if ( actionsForClip !== undefined ) { + // compute morph normals - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - var actionsToRemove = actionsForClip.knownActions; + // store morph normals - for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + var faceNormal, vertexNormals; - var action = actionsToRemove[ i ]; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this._deactivateAction( action ); + face = this.faces[ f ]; - var cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - action._cacheIndex = null; - action._byClipCacheIndex = null; + faceNormal.copy( face.normal ); - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - this._removeInactiveBindingsForAction( action ); + } - } + } - delete actionsByClip[ clipUuid ]; + // restore original normals - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + face = this.faces[ f ]; - // free all resources specific to a particular root target object - uncacheRoot: function( root ) { + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - var rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + } - for ( var clipUuid in actionsByClip ) { + }, - var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + computeTangents: function () { - if ( action !== undefined ) { + console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); - this._deactivateAction( action ); - this._removeInactiveAction( action ); + }, - } + computeLineDistances: function () { - } + var d = 0; + var vertices = this.vertices; - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - if ( bindingByName !== undefined ) { + if ( i > 0 ) { - for ( var trackName in bindingByName ) { + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - var binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); + } - } + this.lineDistances[ i ] = d; - } + } - }, + }, - // remove a targeted clip from the cache - uncacheAction: function( clip, optionalRoot ) { + computeBoundingBox: function () { - var action = this.existingAction( clip, optionalRoot ); + if ( this.boundingBox === null ) { - if ( action !== null ) { + this.boundingBox = new Box3(); - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } - } + this.boundingBox.setFromPoints( this.vertices ); - } + }, -} ); + computeBoundingSphere: function () { -THREE.AnimationMixer._Action = THREE.AnimationAction._new; + if ( this.boundingSphere === null ) { -// Implementation details: + this.boundingSphere = new Sphere(); -Object.assign( THREE.AnimationMixer.prototype, { + } - _bindAction: function( action, prototypeAction ) { + this.boundingSphere.setFromPoints( this.vertices ); - var root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName, - bindingsByName = bindingsByRoot[ rootUuid ]; + }, - if ( bindingsByName === undefined ) { + merge: function ( geometry, matrix, materialIndexOffset ) { - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + if ( (geometry && geometry.isGeometry) === false ) { - } + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - for ( var i = 0; i !== nTracks; ++ i ) { + } - var track = tracks[ i ], - trackName = track.name, - binding = bindingsByName[ trackName ]; + 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 ]; - if ( binding !== undefined ) { + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - bindings[ i ] = binding; + if ( matrix !== undefined ) { - } else { + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - binding = bindings[ i ]; + } - if ( binding !== undefined ) { + // vertices - // existing binding, make sure the cache knows + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - if ( binding._cacheIndex === null ) { + var vertex = vertices2[ i ]; - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + var vertexCopy = vertex.clone(); - } + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - continue; + vertices1.push( vertexCopy ); - } + } - var path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + // faces - binding = new THREE.PropertyMixer( - THREE.PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + for ( i = 0, il = faces2.length; i < il; i ++ ) { - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - bindings[ i ] = binding; + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - } + if ( normalMatrix !== undefined ) { - interpolants[ i ].resultBuffer = binding.buffer; + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - } + } - }, + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - _activateAction: function( action ) { + normal = faceVertexNormals[ j ].clone(); - if ( ! this._isActiveAction( action ) ) { + if ( normalMatrix !== undefined ) { - if ( action._cacheIndex === null ) { + normal.applyMatrix3( normalMatrix ).normalize(); - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind + } - var rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; + faceCopy.vertexNormals.push( normal ); - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); + } - this._addInactiveAction( action, clipUuid, rootUuid ); + faceCopy.color.copy( face.color ); - } + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - var bindings = action._propertyBindings; + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - // increment reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + } - var binding = bindings[ i ]; + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - if ( binding.useCount ++ === 0 ) { + faces1.push( faceCopy ); - this._lendBinding( binding ); - binding.saveOriginalState(); + } - } + // uvs - } + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - this._lendAction( action ); + var uv = uvs2[ i ], uvCopy = []; - } + if ( uv === undefined ) { - }, + continue; - _deactivateAction: function( action ) { + } - if ( this._isActiveAction( action ) ) { + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - var bindings = action._propertyBindings; + uvCopy.push( uv[ j ].clone() ); - // decrement reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + } - var binding = bindings[ i ]; + uvs1.push( uvCopy ); - if ( -- binding.useCount === 0 ) { + } - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + }, - } + mergeMesh: function ( mesh ) { - } + if ( (mesh && mesh.isMesh) === false ) { - this._takeBackAction( action ); + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - } + } - }, + mesh.matrixAutoUpdate && mesh.updateMatrix(); - // Memory manager + this.merge( mesh.geometry, mesh.matrix ); - _initMemoryManager: function() { + }, - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< _Action > - used as prototypes - // actionByRoot: _Action - lookup - // } + mergeVertices: function () { + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + var v, key; + var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + 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 ); - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; + if ( verticesMap[ key ] === undefined ) { - var scope = this; + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - this.stats = { + } else { - actions: { - get total() { return scope._actions.length; }, - get inUse() { return scope._nActiveActions; } - }, - bindings: { - get total() { return scope._bindings.length; }, - get inUse() { return scope._nActiveBindings; } - }, - controlInterpolants: { - get total() { return scope._controlInterpolants.length; }, - get inUse() { return scope._nActiveControlInterpolants; } - } + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - }; + } - }, + } - // Memory management for _Action objects - _isActiveAction: function( action ) { + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - var index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - }, + face = this.faces[ i ]; - _addInactiveAction: function( action, clipUuid, rootUuid ) { + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - var actions = this._actions, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + indices = [ face.a, face.b, face.c ]; - if ( actionsForClip === undefined ) { + var dupIndex = - 1; - actionsForClip = { + // 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 ++ ) { - knownActions: [ action ], - actionByRoot: {} + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - }; + dupIndex = n; + faceIndicesToRemove.push( i ); + break; - action._byClipCacheIndex = 0; + } - actionsByClip[ clipUuid ] = actionsForClip; + } - } else { + } - var knownActions = actionsForClip.knownActions; + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + var idx = faceIndicesToRemove[ i ]; - } + this.faces.splice( idx, 1 ); - action._cacheIndex = actions.length; - actions.push( action ); + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - actionsForClip.actionByRoot[ rootUuid ] = action; + this.faceVertexUvs[ j ].splice( idx, 1 ); - }, + } - _removeInactiveAction: function( action ) { + } - var actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + // Use unique set of vertices - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - action._cacheIndex = null; + }, + sortFacesByMaterialIndex: function () { - var clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + var faces = this.faces; + var length = faces.length; - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + // tag faces - byClipCacheIndex = action._byClipCacheIndex; + for ( var i = 0; i < length; i ++ ) { - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + faces[ i ]._id = i; - action._byClipCacheIndex = null; + } + // sort faces - var actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( actions._localRoot || this._root ).uuid; + function materialIndexSort( a, b ) { - delete actionByRoot[ rootUuid ]; + return a.materialIndex - b.materialIndex; - if ( knownActionsForClip.length === 0 ) { + } - delete actionsByClip[ clipUuid ]; + faces.sort( materialIndexSort ); - } + // sort uvs - this._removeInactiveBindingsForAction( action ); + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - }, + var newUvs1, newUvs2; - _removeInactiveBindingsForAction: function( action ) { + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - var bindings = action._propertyBindings; - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + for ( var i = 0; i < length; i ++ ) { - var binding = bindings[ i ]; + var id = faces[ i ]._id; - if ( -- binding.referenceCount === 0 ) { + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - this._removeInactiveBinding( binding ); + } - } + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - } + }, - }, + toJSON: function () { - _lendAction: function( action ) { + var data = { + metadata: { + version: 4.4, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + // standard Geometry serialization - var actions = this._actions, - prevIndex = action._cacheIndex, + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - lastActiveIndex = this._nActiveActions ++, + if ( this.parameters !== undefined ) { - firstInactiveAction = actions[ lastActiveIndex ]; + var parameters = this.parameters; - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + for ( var key in parameters ) { - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - }, + } - _takeBackAction: function( action ) { + return data; - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + } - var actions = this._actions, - prevIndex = action._cacheIndex, + var vertices = []; - firstInactiveIndex = -- this._nActiveActions, + for ( var i = 0; i < this.vertices.length; i ++ ) { - lastActiveAction = actions[ firstInactiveIndex ]; + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + } - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - }, + for ( var i = 0; i < this.faces.length; i ++ ) { - // Memory management for PropertyMixer objects + var face = this.faces[ i ]; - _addInactiveBinding: function( binding, rootUuid, trackName ) { + var hasMaterial = true; + 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; - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + var faceType = 0; - bindings = this._bindings; + faceType = setBit( faceType, 0, 0 ); // isQuad + 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 ); - if ( bindingByName === undefined ) { + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + if ( hasFaceVertexUv ) { - } + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - bindingByName[ trackName ] = binding; + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - binding._cacheIndex = bindings.length; - bindings.push( binding ); + } - }, + if ( hasFaceNormal ) { - _removeInactiveBinding: function( binding ) { + faces.push( getNormalIndex( face.normal ) ); - var bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + } - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + if ( hasFaceVertexNormal ) { - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + var vertexNormals = face.vertexNormals; - delete bindingByName[ trackName ]; + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - remove_empty_map: { + } - for ( var _ in bindingByName ) break remove_empty_map; + if ( hasFaceColor ) { - delete bindingsByRoot[ rootUuid ]; + faces.push( getColorIndex( face.color ) ); - } + } - }, + if ( hasFaceVertexColor ) { - _lendBinding: function( binding ) { + var vertexColors = face.vertexColors; - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - lastActiveIndex = this._nActiveBindings ++, + } - firstInactiveBinding = bindings[ lastActiveIndex ]; + } - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + function setBit( value, position, enabled ) { - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - }, + } - _takeBackBinding: function( binding ) { + function getNormalIndex( normal ) { - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - firstInactiveIndex = -- this._nActiveBindings, + if ( normalsHash[ hash ] !== undefined ) { - lastActiveBinding = bindings[ firstInactiveIndex ]; + return normalsHash[ hash ]; - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + } - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - }, + return normalsHash[ hash ]; + } - // Memory management of Interpolants for weight and time scale + function getColorIndex( color ) { - _lendControlInterpolant: function() { + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - var interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++, - interpolant = interpolants[ lastActiveIndex ]; + if ( colorsHash[ hash ] !== undefined ) { - if ( interpolant === undefined ) { + return colorsHash[ hash ]; - interpolant = new THREE.LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + } - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - } + return colorsHash[ hash ]; - return interpolant; + } - }, + function getUvIndex( uv ) { - _takeBackControlInterpolant: function( interpolant ) { + var hash = uv.x.toString() + uv.y.toString(); - var interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + if ( uvsHash[ hash ] !== undefined ) { - firstInactiveIndex = -- this._nActiveControlInterpolants, + return uvsHash[ hash ]; - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + } - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + return uvsHash[ hash ]; - }, + } - _controlInterpolantsResultBuffer: new Float32Array( 1 ) + data.data = {}; -} ); + data.data.vertices = vertices; + data.data.normals = normals; + if ( colors.length > 0 ) data.data.colors = colors; + if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility + data.data.faces = faces; -// File:src/animation/AnimationObjectGroup.js + return data; -/** - * - * A group of objects that receives a shared animation state. - * - * Usage: - * - * - Add objects you would otherwise pass as 'root' to the - * constructor or the .clipAction method of AnimationMixer. - * - * - Instead pass this object as 'root'. - * - * - You can also add and remove objects later when the mixer - * is running. - * - * Note: - * - * Objects of this class appear as one object to the mixer, - * so cache control of the individual objects must be done - * on the group. - * - * Limitation: - * - * - The animated properties must be compatible among the - * all objects in the group. - * - * - A single property can either be controlled through a - * target group or directly, but not both. - * - * @author tschw - */ + }, -THREE.AnimationObjectGroup = function( var_args ) { + clone: function () { - this.uuid = THREE.Math.generateUUID(); + /* + // Handle primitives - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + var parameters = this.parameters; - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + if ( parameters !== undefined ) { - var indices = {}; - this._indicesByUUID = indices; // for bookkeeping + var values = []; - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + for ( var key in parameters ) { - indices[ arguments[ i ].uuid ] = i; + values.push( parameters[ key ] ); - } + } - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - var scope = this; + } - this.stats = { + return new this.constructor().copy( this ); + */ - objects: { - get total() { return scope._objects.length; }, - get inUse() { return this.total - scope.nCachedObjects_; } - }, + return new Geometry().copy( this ); - get bindingsPerObject() { return scope._bindings.length; } + }, - }; + copy: function ( source ) { -}; + this.vertices = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; -THREE.AnimationObjectGroup.prototype = { + var vertices = source.vertices; - constructor: THREE.AnimationObjectGroup, + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - add: function( var_args ) { + this.vertices.push( vertices[ i ].clone() ); - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length; + } - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + var faces = source.faces; - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + for ( var i = 0, il = faces.length; i < il; i ++ ) { - if ( index === undefined ) { + this.faces.push( faces[ i ].clone() ); - // unknown object -> add it to the ACTIVE region + } - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - // accounting is done, now do the same for all bindings + var faceVertexUvs = source.faceVertexUvs[ i ]; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + if ( this.faceVertexUvs[ i ] === undefined ) { - bindings[ j ].push( - new THREE.PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ) ); + this.faceVertexUvs[ i ] = []; - } + } - } else if ( index < nCachedObjects ) { + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - var knownObject = objects[ index ]; + var uvs = faceVertexUvs[ j ], uvsCopy = []; - // move existing object to the ACTIVE region + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + var uv = uvs[ k ]; - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + uvsCopy.push( uv.clone() ); - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + } - // accounting is done, now do the same for all bindings + this.faceVertexUvs[ i ].push( uvsCopy ); - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - binding = bindingsForPath[ index ]; + } - bindingsForPath[ index ] = lastCached; + return this; - if ( binding === undefined ) { + }, - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + dispose: function () { - binding = new THREE.PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ); + this.dispatchEvent( { type: 'dispose' } ); - } + } - bindingsForPath[ firstActiveIndex ] = binding; + } ); - } + var count$2 = 0; + function GeometryIdCount () { return count$2++; }; - } else if ( objects[ index ] !== knownObject) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - console.error( "Different objects with the same UUID " + - "detected. Clean the caches or recreate your " + - "infrastructure when reloading scenes..." ); + function DirectGeometry () { + this.isDirectGeometry = true; - } // else the object is already where we want it to be + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - } // for arguments + this.uuid = exports.Math.generateUUID(); - this.nCachedObjects_ = nCachedObjects; + this.name = ''; + this.type = 'DirectGeometry'; - }, + this.indices = []; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - remove: function( var_args ) { + this.groups = []; - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + this.morphTargets = {}; - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + this.skinWeights = []; + this.skinIndices = []; - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + // this.lineDistances = []; - if ( index !== undefined && index >= nCachedObjects ) { + this.boundingBox = null; + this.boundingSphere = null; - // move existing object into the CACHED region + // update flags - var lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + }; - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - // accounting is done, now do the same for all bindings + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + computeFaceNormals: function () { - var bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + }, - } + computeVertexNormals: function () { - } + console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); - } // for arguments + }, - this.nCachedObjects_ = nCachedObjects; + computeGroups: function ( geometry ) { - }, + var group; + var groups = []; + var materialIndex; - // remove & forget - uncache: function( var_args ) { + var faces = geometry.faces; - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + for ( var i = 0; i < faces.length; i ++ ) { - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + var face = faces[ i ]; - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + // materials - if ( index !== undefined ) { + if ( face.materialIndex !== materialIndex ) { - delete indicesByUUID[ uuid ]; + materialIndex = face.materialIndex; - if ( index < nCachedObjects ) { + if ( group !== undefined ) { - // object is cached, shrink the CACHED region + group.count = ( i * 3 ) - group.start; + groups.push( group ); - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + } - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + group = { + start: i * 3, + materialIndex: materialIndex + }; - // last object goes to the activated slot and pop - indicesByUUID[ lastObject.uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = lastObject; - objects.pop(); + } - // accounting is done, now do the same for all bindings + } - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + if ( group !== undefined ) { - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + group.count = ( i * 3 ) - group.start; + groups.push( group ); - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + } - } + this.groups = groups; - } else { + }, - // object is active, just swap with the last and pop + fromGeometry: function ( geometry ) { - var lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + var faces = geometry.faces; + var vertices = geometry.vertices; + var faceVertexUvs = geometry.faceVertexUvs; - indicesByUUID[ lastObject.uuid ] = index; - objects[ index ] = lastObject; - objects.pop(); + var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; - // accounting is done, now do the same for all bindings + // morphs - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - var bindingsForPath = bindings[ j ]; + var morphTargetsPosition; - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + if ( morphTargetsLength > 0 ) { - } + morphTargetsPosition = []; - } // cached or active + for ( var i = 0; i < morphTargetsLength; i ++ ) { - } // if object is known + morphTargetsPosition[ i ] = []; - } // for arguments + } - this.nCachedObjects_ = nCachedObjects; + this.morphTargets.position = morphTargetsPosition; - }, + } - // Internal interface used by befriended PropertyBinding.Composite: + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - subscribe_: function( path, parsedPath ) { - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + var morphTargetsNormal; - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ], - bindings = this._bindings; + if ( morphNormalsLength > 0 ) { - if ( index !== undefined ) return bindings[ index ]; + morphTargetsNormal = []; - var paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + for ( var i = 0; i < morphNormalsLength; i ++ ) { - index = bindings.length; + morphTargetsNormal[ i ] = []; - indicesByPath[ path ] = index; + } - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + this.morphTargets.normal = morphTargetsNormal; - for ( var i = nCachedObjects, - n = objects.length; i !== n; ++ i ) { + } - var object = objects[ i ]; + // skins - bindingsForPath[ i ] = - new THREE.PropertyBinding( object, path, parsedPath ); + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - } + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - return bindingsForPath; + // - }, + for ( var i = 0; i < faces.length; i ++ ) { - unsubscribe_: function( path ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + var face = faces[ i ]; - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - if ( index !== undefined ) { + var vertexNormals = face.vertexNormals; - var paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + if ( vertexNormals.length === 3 ) { - indicesByPath[ lastBindingsPath ] = index; + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - bindings[ index ] = lastBindings; - bindings.pop(); + } else { - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + var normal = face.normal; - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + this.normals.push( normal, normal, normal ); - } + } - } + var vertexColors = face.vertexColors; -}; + if ( vertexColors.length === 3 ) { + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); -// File:src/animation/AnimationUtils.js + } else { -/** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + var color = face.color; -THREE.AnimationUtils = { + this.colors.push( color, color, color ); - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function( array, from, to ) { + } - if ( THREE.AnimationUtils.isTypedArray( array ) ) { + if ( hasFaceVertexUv === true ) { - return new array.constructor( array.subarray( from, to ) ); + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - } + if ( vertexUvs !== undefined ) { - return array.slice( from, to ); + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - }, + } else { - // converts an array to a specific type - convertArray: function( array, type, forceClone ) { + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + } - return new type( array ); // create typed array + } - } + if ( hasFaceVertexUv2 === true ) { - return Array.prototype.slice.call( array ); // create Array + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - }, + if ( vertexUvs !== undefined ) { - isTypedArray: function( object ) { + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + } else { - }, + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - // returns an array by which times and values can be sorted - getKeyframeOrder: function( times ) { + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - function compareTime( i, j ) { + } - return times[ i ] - times[ j ]; + } - } + // morphs - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) result[ i ] = i; + for ( var j = 0; j < morphTargetsLength; j ++ ) { - result.sort( compareTime ); + var morphTarget = morphTargets[ j ].vertices; - return result; + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); - }, + } - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function( values, stride, order ) { + for ( var j = 0; j < morphNormalsLength; j ++ ) { - var nValues = values.length; - var result = new values.constructor( nValues ); + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); - var srcOffset = order[ i ] * stride; + } - for ( var j = 0; j !== stride; ++ j ) { + // skins - result[ dstOffset ++ ] = values[ srcOffset + j ]; + if ( hasSkinIndices ) { - } + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - } + } - return result; + if ( hasSkinWeights ) { - }, + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - // function for parsing AOS keyframe formats - flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { + } - var i = 1, key = jsonKeys[ 0 ]; + } - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + this.computeGroups( geometry ); - key = jsonKeys[ i ++ ]; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - } + return this; - if ( key === undefined ) return; // no data + }, - var value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data + dispose: function () { - if ( Array.isArray( value ) ) { + this.dispatchEvent( { type: 'dispose' } ); - do { + } - value = key[ valuePropertyName ]; + } ); - if ( value !== undefined ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - times.push( key.time ); - values.push.apply( values, value ); // push all elements + function BufferGeometry () { + this.isBufferGeometry = true; - } + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - key = jsonKeys[ i ++ ]; + this.uuid = exports.Math.generateUUID(); - } while ( key !== undefined ); + this.name = ''; + this.type = 'BufferGeometry'; - } else if ( value.toArray !== undefined ) { - // ...assume THREE.Math-ish + this.index = null; + this.attributes = {}; - do { + this.morphAttributes = {}; - value = key[ valuePropertyName ]; + this.groups = []; - if ( value !== undefined ) { + this.boundingBox = null; + this.boundingSphere = null; - times.push( key.time ); - value.toArray( values, values.length ); + this.drawRange = { start: 0, count: Infinity }; - } + }; - key = jsonKeys[ i ++ ]; + Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { - } while ( key !== undefined ); + getIndex: function () { - } else { - // otherwise push as-is + return this.index; - do { + }, - value = key[ valuePropertyName ]; + setIndex: function ( index ) { - if ( value !== undefined ) { + this.index = index; - times.push( key.time ); - values.push( value ); + }, - } + addAttribute: function ( name, attribute ) { - key = jsonKeys[ i ++ ]; + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { - } while ( key !== undefined ); + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - } + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - } + return; -}; + } -// File:src/animation/KeyframeTrack.js + if ( name === 'index' ) { -/** - * - * A timed sequence of keyframes for a specific property. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); -THREE.KeyframeTrack = function ( name, times, values, interpolation ) { + return; - if( name === undefined ) throw new Error( "track name is undefined" ); + } - if( times === undefined || times.length === 0 ) { + this.attributes[ name ] = attribute; - throw new Error( "no keyframes in track named " + name ); + return this; - } + }, - this.name = name; + getAttribute: function ( name ) { - this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType ); + return this.attributes[ name ]; - this.setInterpolation( interpolation || this.DefaultInterpolation ); + }, - this.validate(); - this.optimize(); + removeAttribute: function ( name ) { -}; + delete this.attributes[ name ]; -THREE.KeyframeTrack.prototype = { + return this; - constructor: THREE.KeyframeTrack, + }, - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, + addGroup: function ( start, count, materialIndex ) { - DefaultInterpolation: THREE.InterpolateLinear, + this.groups.push( { - InterpolantFactoryMethodDiscrete: function( result ) { + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - return new THREE.DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); + } ); - }, + }, - InterpolantFactoryMethodLinear: function( result ) { + clearGroups: function () { - return new THREE.LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + this.groups = []; - }, + }, - InterpolantFactoryMethodSmooth: function( result ) { + setDrawRange: function ( start, count ) { - return new THREE.CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); + this.drawRange.start = start; + this.drawRange.count = count; - }, + }, - setInterpolation: function( interpolation ) { + applyMatrix: function ( matrix ) { - var factoryMethod; + var position = this.attributes.position; - switch ( interpolation ) { + if ( position !== undefined ) { - case THREE.InterpolateDiscrete: + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - factoryMethod = this.InterpolantFactoryMethodDiscrete; + } - break; + var normal = this.attributes.normal; - case THREE.InterpolateLinear: + if ( normal !== undefined ) { - factoryMethod = this.InterpolantFactoryMethodLinear; + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - break; + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - case THREE.InterpolateSmooth: + } - factoryMethod = this.InterpolantFactoryMethodSmooth; + if ( this.boundingBox !== null ) { - break; + this.computeBoundingBox(); - } + } - if ( factoryMethod === undefined ) { + if ( this.boundingSphere !== null ) { - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + this.computeBoundingSphere(); - if ( this.createInterpolant === undefined ) { + } - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + return this; - this.setInterpolation( this.DefaultInterpolation ); + }, - } else { + rotateX: function () { - throw new Error( message ); // fatal, in this case + // rotate geometry around world x-axis - } + var m1; - } + return function rotateX( angle ) { - console.warn( message ); - return; + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeRotationX( angle ); - this.createInterpolant = factoryMethod; + this.applyMatrix( m1 ); - }, + return this; - getInterpolation: function() { + }; - switch ( this.createInterpolant ) { + }(), - case this.InterpolantFactoryMethodDiscrete: + rotateY: function () { - return THREE.InterpolateDiscrete; + // rotate geometry around world y-axis - case this.InterpolantFactoryMethodLinear: + var m1; - return THREE.InterpolateLinear; + return function rotateY( angle ) { - case this.InterpolantFactoryMethodSmooth: + if ( m1 === undefined ) m1 = new Matrix4(); - return THREE.InterpolateSmooth; + m1.makeRotationY( angle ); - } + this.applyMatrix( m1 ); - }, + return this; - getValueSize: function() { + }; - return this.values.length / this.times.length; + }(), - }, + rotateZ: function () { - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { + // rotate geometry around world z-axis - if( timeOffset !== 0.0 ) { + var m1; - var times = this.times; + return function rotateZ( angle ) { - for( var i = 0, n = times.length; i !== n; ++ i ) { + if ( m1 === undefined ) m1 = new Matrix4(); - times[ i ] += timeOffset; + m1.makeRotationZ( angle ); - } + this.applyMatrix( m1 ); - } + return this; - return this; + }; - }, + }(), - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { + translate: function () { - if( timeScale !== 1.0 ) { + // translate geometry - var times = this.times; + var m1; - for( var i = 0, n = times.length; i !== n; ++ i ) { + return function translate( x, y, z ) { - times[ i ] *= timeScale; + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeTranslation( x, y, z ); - } + this.applyMatrix( m1 ); - return this; + return this; - }, + }; - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function( startTime, endTime ) { + }(), - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; + scale: function () { - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== -1 && times[ to ] > endTime ) -- to; + // scale geometry - ++ to; // inclusive -> exclusive bound + var m1; - if( from !== 0 || to !== nKeys ) { + return function scale( x, y, z ) { - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; + if ( m1 === undefined ) m1 = new Matrix4(); - var stride = this.getValueSize(); - this.times = THREE.AnimationUtils.arraySlice( times, from, to ); - this.values = THREE.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); + m1.makeScale( x, y, z ); - } + this.applyMatrix( m1 ); - return this; + return this; - }, + }; - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { + }(), - var valid = true; + lookAt: function () { - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + var obj; - console.error( "invalid value size in track", this ); - valid = false; + return function lookAt( vector ) { - } + if ( obj === undefined ) obj = new Object3D(); - var times = this.times, - values = this.values, + obj.lookAt( vector ); - nKeys = times.length; + obj.updateMatrix(); - if( nKeys === 0 ) { + this.applyMatrix( obj.matrix ); - console.error( "track is empty", this ); - valid = false; + }; - } + }(), - var prevTime = null; + center: function () { - for( var i = 0; i !== nKeys; i ++ ) { + this.computeBoundingBox(); - var currTime = times[ i ]; + var offset = this.boundingBox.center().negate(); - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + this.translate( offset.x, offset.y, offset.z ); - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; + return offset; - } + }, - if( prevTime !== null && prevTime > currTime ) { + setFromObject: function ( object ) { - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - } + var geometry = object.geometry; - prevTime = currTime; + if ( (object && object.isPoints) || (object && object.isLine) ) { - } + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); - if ( values !== undefined ) { + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - if ( THREE.AnimationUtils.isTypedArray( values ) ) { + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - for ( var i = 0, n = values.length; i !== n; ++ i ) { + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); - var value = values[ i ]; + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - if ( isNaN( value ) ) { + } - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; + if ( geometry.boundingSphere !== null ) { - } + this.boundingSphere = geometry.boundingSphere.clone(); - } + } - } + if ( geometry.boundingBox !== null ) { - } + this.boundingBox = geometry.boundingBox.clone(); - return valid; + } - }, + } else if ( (object && object.isMesh) ) { - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function() { + if ( (geometry && geometry.isGeometry) ) { - var times = this.times, - values = this.values, - stride = this.getValueSize(), + this.fromGeometry( geometry ); - writeIndex = 1; + } - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + } - var keep = false; + return this; - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + }, - // remove adjacent keyframes scheduled at the same time + updateFromObject: function ( object ) { - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + var geometry = object.geometry; - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + if ( (object && object.isMesh) ) { - for ( var j = 0; j !== stride; ++ j ) { + var direct = geometry.__directGeometry; - var value = values[ offset + j ]; + if ( direct === undefined || geometry.elementsNeedUpdate === true ) { - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + return this.fromGeometry( geometry ); - keep = true; - break; + } - } + direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; - } + geometry.elementsNeedUpdate = false; + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - } + geometry = direct; - // in-place compaction + } - if ( keep ) { + var attribute; - if ( i !== writeIndex ) { + if ( geometry.verticesNeedUpdate === true ) { - times[ writeIndex ] = times[ i ]; + attribute = this.attributes.position; - var readOffset = i * stride, - writeOffset = writeIndex * stride; + if ( attribute !== undefined ) { - for ( var j = 0; j !== stride; ++ j ) { + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; - values[ writeOffset + j ] = values[ readOffset + j ]; + } - } + geometry.verticesNeedUpdate = false; + } - } + if ( geometry.normalsNeedUpdate === true ) { - ++ writeIndex; + attribute = this.attributes.normal; - } + if ( attribute !== undefined ) { - } + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - if ( writeIndex !== times.length ) { + } - this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + geometry.normalsNeedUpdate = false; - } + } - return this; + if ( geometry.colorsNeedUpdate === true ) { - } + attribute = this.attributes.color; -}; + if ( attribute !== undefined ) { -// Static methods: + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; -Object.assign( THREE.KeyframeTrack, { + } - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + geometry.colorsNeedUpdate = false; - parse: function( json ) { + } - if( json.type === undefined ) { + if ( geometry.uvsNeedUpdate ) { - throw new Error( "track type undefined, can not parse" ); + attribute = this.attributes.uv; - } + if ( attribute !== undefined ) { - var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - if ( json.times === undefined ) { + } - var times = [], values = []; + geometry.uvsNeedUpdate = false; - THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + } - json.times = times; - json.values = values; + if ( geometry.lineDistancesNeedUpdate ) { - } + attribute = this.attributes.lineDistance; - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + if ( attribute !== undefined ) { - return trackType.parse( json ); + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; - } else { + } - // by default, we asssume a constructor compatible with the base - return new trackType( - json.name, json.times, json.values, json.interpolation ); + geometry.lineDistancesNeedUpdate = false; - } + } - }, + if ( geometry.groupsNeedUpdate ) { - toJSON: function( track ) { + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - var trackType = track.constructor; + geometry.groupsNeedUpdate = false; - var json; + } - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + return this; - json = trackType.toJSON( track ); + }, - } else { + fromGeometry: function ( geometry ) { - // by default, we assume the data can be serialized as-is - json = { + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - 'name': track.name, - 'times': THREE.AnimationUtils.convertArray( track.times, Array ), - 'values': THREE.AnimationUtils.convertArray( track.values, Array ) + return this.fromDirectGeometry( geometry.__directGeometry ); - }; + }, - var interpolation = track.getInterpolation(); + fromDirectGeometry: function ( geometry ) { - if ( interpolation !== track.DefaultInterpolation ) { + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - json.interpolation = interpolation; + if ( geometry.normals.length > 0 ) { - } + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - } + } - json.type = track.ValueTypeName; // mandatory + if ( geometry.colors.length > 0 ) { - return json; + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - }, + } - _getTrackTypeForValueTypeName: function( typeName ) { + if ( geometry.uvs.length > 0 ) { - switch( typeName.toLowerCase() ) { + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - case "scalar": - case "double": - case "float": - case "number": - case "integer": + } - return THREE.NumberKeyframeTrack; + if ( geometry.uvs2.length > 0 ) { - case "vector": - case "vector2": - case "vector3": - case "vector4": + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - return THREE.VectorKeyframeTrack; + } - case "color": + if ( geometry.indices.length > 0 ) { - return THREE.ColorKeyframeTrack; + var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; + var indices = new TypeArray( geometry.indices.length * 3 ); + this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); - case "quaternion": + } - return THREE.QuaternionKeyframeTrack; + // groups - case "bool": - case "boolean": + this.groups = geometry.groups; - return THREE.BooleanKeyframeTrack; + // morphs - case "string": + for ( var name in geometry.morphTargets ) { - return THREE.StringKeyframeTrack; + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - } + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - throw new Error( "Unsupported typeName: " + typeName ); + var morphTarget = morphTargets[ i ]; - } + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); -} ); + array.push( attribute.copyVector3sArray( morphTarget ) ); -// File:src/animation/PropertyBinding.js + } -/** - * - * A reference to a real property in the scene graph. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + this.morphAttributes[ name ] = array; -THREE.PropertyBinding = function ( rootNode, path, parsedPath ) { + } - this.path = path; - this.parsedPath = parsedPath || - THREE.PropertyBinding.parseTrackName( path ); + // skinning - this.node = THREE.PropertyBinding.findNode( - rootNode, this.parsedPath.nodeName ) || rootNode; + if ( geometry.skinIndices.length > 0 ) { - this.rootNode = rootNode; + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); -}; + } -THREE.PropertyBinding.prototype = { + if ( geometry.skinWeights.length > 0 ) { - constructor: THREE.PropertyBinding, + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - getValue: function getValue_unbound( targetArray, offset ) { + } - this.bind(); - this.getValue( targetArray, offset ); + // - // Note: This class uses a State pattern on a per-method basis: - // 'bind' sets 'this.getValue' / 'setValue' and shadows the - // prototype version of these methods with one that represents - // the bound state. When the property is not found, the methods - // become no-ops. + if ( geometry.boundingSphere !== null ) { - }, + this.boundingSphere = geometry.boundingSphere.clone(); - setValue: function getValue_unbound( sourceArray, offset ) { + } - this.bind(); - this.setValue( sourceArray, offset ); + if ( geometry.boundingBox !== null ) { - }, + this.boundingBox = geometry.boundingBox.clone(); - // create getter / setter pair for a property in the scene graph - bind: function() { + } - var targetObject = this.node, - parsedPath = this.parsedPath, + return this; - objectName = parsedPath.objectName, - propertyName = parsedPath.propertyName, - propertyIndex = parsedPath.propertyIndex; + }, - if ( ! targetObject ) { + computeBoundingBox: function () { - targetObject = THREE.PropertyBinding.findNode( - this.rootNode, parsedPath.nodeName ) || this.rootNode; + if ( this.boundingBox === null ) { - this.node = targetObject; + this.boundingBox = new Box3(); - } + } - // set fail state so we can just 'return' on error - this.getValue = this._getValue_unavailable; - this.setValue = this._setValue_unavailable; + var positions = this.attributes.position.array; - // ensure there is a value node - if ( ! targetObject ) { + if ( positions !== undefined ) { - console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); - return; + this.boundingBox.setFromArray( positions ); - } + } else { - if ( objectName ) { + this.boundingBox.makeEmpty(); - var objectIndex = parsedPath.objectIndex; + } - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - case 'materials': + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - if ( ! targetObject.material ) { + } - console.error( ' can not bind to material as node does not have a material', this ); - return; + }, - } + computeBoundingSphere: function () { - if ( ! targetObject.material.materials ) { + var box = new Box3(); + var vector = new Vector3(); - console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); - return; + return function computeBoundingSphere() { - } + if ( this.boundingSphere === null ) { - targetObject = targetObject.material.materials; + this.boundingSphere = new Sphere(); - break; + } - case 'bones': + var positions = this.attributes.position; - if ( ! targetObject.skeleton ) { + if ( positions ) { - console.error( ' can not bind to bones as node does not have a skeleton', this ); - return; + var array = positions.array; + var center = this.boundingSphere.center; - } + box.setFromArray( array ); + box.center( center ); - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - targetObject = targetObject.skeleton.bones; + var maxRadiusSq = 0; - // support resolving morphTarget names into indices. - for ( var i = 0; i < targetObject.length; i ++ ) { + for ( var i = 0, il = array.length; i < il; i += 3 ) { - if ( targetObject[ i ].name === objectIndex ) { + vector.fromArray( array, i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - objectIndex = i; - break; + } - } + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - } + if ( isNaN( this.boundingSphere.radius ) ) { - break; + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - default: + } - if ( targetObject[ objectName ] === undefined ) { + } - console.error( ' can not bind to objectName of node, undefined', this ); - return; + }; - } + }(), - targetObject = targetObject[ objectName ]; + computeFaceNormals: function () { - } + // backwards compatibility + }, - if ( objectIndex !== undefined ) { + computeVertexNormals: function () { - if ( targetObject[ objectIndex ] === undefined ) { + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); - return; + if ( attributes.position ) { - } + var positions = attributes.position.array; - targetObject = targetObject[ objectIndex ]; + if ( attributes.normal === undefined ) { - } + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - } + } else { - // resolve property - var nodeProperty = targetObject[ propertyName ]; + // reset existing normals to zero - if ( nodeProperty === undefined ) { + var array = attributes.normal.array; - var nodeName = parsedPath.nodeName; + for ( var i = 0, il = array.length; i < il; i ++ ) { - console.error( " trying to update property for track: " + nodeName + - '.' + propertyName + " but it wasn't found.", targetObject ); - return; + array[ i ] = 0; - } + } - // determine versioning scheme - var versioning = this.Versioning.None; + } - if ( targetObject.needsUpdate !== undefined ) { // material + var normals = attributes.normal.array; - versioning = this.Versioning.NeedsUpdate; - this.targetObject = targetObject; + var vA, vB, vC, - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - versioning = this.Versioning.MatrixWorldNeedsUpdate; - this.targetObject = targetObject; + cb = new Vector3(), + ab = new Vector3(); - } + // indexed elements - // determine how the property gets bound - var bindingType = this.BindingType.Direct; + if ( index ) { - if ( propertyIndex !== undefined ) { - // access a sub element of the property array (only primitives are supported right now) + var indices = index.array; - if ( propertyName === "morphTargetInfluences" ) { - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + if ( groups.length === 0 ) { - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + this.addGroup( 0, indices.length ); - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); - return; + } - } + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - if ( ! targetObject.geometry.morphTargets ) { + var group = groups[ j ]; - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); - return; + var start = group.start; + var count = group.count; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - propertyIndex = i; - break; + 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; - } + 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; - bindingType = this.BindingType.ArrayElement; + } - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + } - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - // must use copy for Object3D.Euler/Quaternion + } else { - bindingType = this.BindingType.HasFromToArray; + // non-indexed elements (unconnected triangle soup) - this.resolvedProperty = nodeProperty; + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - } else if ( nodeProperty.length !== undefined ) { + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - bindingType = this.BindingType.EntireArray; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - this.resolvedProperty = nodeProperty; + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - } else { + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - this.propertyName = propertyName; + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - } + } - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + } - }, + this.normalizeNormals(); - unbind: function() { + attributes.normal.needsUpdate = true; - this.node = null; + } - // back to the prototype version of getValue / setValue - // note: avoiding to mutate the shape of 'this' via 'delete' - this.getValue = this._getValue_unbound; - this.setValue = this._setValue_unbound; + }, - } + merge: function ( geometry, offset ) { -}; + if ( (geometry && geometry.isBufferGeometry) === false ) { -Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - // these are used to "bind" a nonexistent property - _getValue_unavailable: function() {}, - _setValue_unavailable: function() {}, + } - // initial state of these methods that calls 'bind' - _getValue_unbound: THREE.PropertyBinding.prototype.getValue, - _setValue_unbound: THREE.PropertyBinding.prototype.setValue, + if ( offset === undefined ) offset = 0; - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + var attributes = this.attributes; - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + for ( var key in attributes ) { - GetterByBindingType: [ + if ( geometry.attributes[ key ] === undefined ) continue; - function getValue_direct( buffer, offset ) { + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - buffer[ offset ] = this.node[ this.propertyName ]; + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - }, + var attributeSize = attribute2.itemSize; - function getValue_array( buffer, offset ) { + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - var source = this.resolvedProperty; + attributeArray1[ j ] = attributeArray2[ i ]; - for ( var i = 0, n = source.length; i !== n; ++ i ) { + } - buffer[ offset ++ ] = source[ i ]; + } - } + return this; - }, + }, - function getValue_arrayElement( buffer, offset ) { + normalizeNormals: function () { - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + var normals = this.attributes.normal.array; - }, + var x, y, z, n; - function getValue_toArray( buffer, offset ) { + for ( var i = 0, il = normals.length; i < il; i += 3 ) { - this.resolvedProperty.toArray( buffer, offset ); + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; - } + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - ], + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; - SetterByBindingTypeAndVersioning: [ + } - [ - // Direct + }, - function setValue_direct( buffer, offset ) { + toNonIndexed: function () { - this.node[ this.propertyName ] = buffer[ offset ]; + if ( this.index === null ) { - }, + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - function setValue_direct_setNeedsUpdate( buffer, offset ) { + } - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + var geometry2 = new BufferGeometry(); - }, + var indices = this.index.array; + var attributes = this.attributes; - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + for ( var name in attributes ) { - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + var attribute = attributes[ name ]; - } + var array = attribute.array; + var itemSize = attribute.itemSize; - ], [ + var array2 = new array.constructor( indices.length * itemSize ); - // EntireArray + var index = 0, index2 = 0; - function setValue_array( buffer, offset ) { + for ( var i = 0, l = indices.length; i < l; i ++ ) { - var dest = this.resolvedProperty; + index = indices[ i ] * itemSize; - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + for ( var j = 0; j < itemSize; j ++ ) { - dest[ i ] = buffer[ offset ++ ]; + array2[ index2 ++ ] = array[ index ++ ]; - } + } - }, + } - function setValue_array_setNeedsUpdate( buffer, offset ) { + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); - var dest = this.resolvedProperty; + } - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + return geometry2; - dest[ i ] = buffer[ offset ++ ]; + }, - } + toJSON: function () { - this.targetObject.needsUpdate = true; + var data = { + metadata: { + version: 4.4, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - }, + // standard BufferGeometry serialization - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - var dest = this.resolvedProperty; + if ( this.parameters !== undefined ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + var parameters = this.parameters; - dest[ i ] = buffer[ offset ++ ]; + for ( var key in parameters ) { - } + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - this.targetObject.matrixWorldNeedsUpdate = true; + } - } + return data; - ], [ + } - // ArrayElement + data.data = { attributes: {} }; - function setValue_arrayElement( buffer, offset ) { + var index = this.index; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + if ( index !== null ) { - }, + var array = Array.prototype.slice.call( index.array ); - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + data.data.index = { + type: index.array.constructor.name, + array: array + }; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + } - }, + var attributes = this.attributes; - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + for ( var key in attributes ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + var attribute = attributes[ key ]; - } + var array = Array.prototype.slice.call( attribute.array ); - ], [ + data.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array, + normalized: attribute.normalized + }; - // HasToFromArray + } - function setValue_fromArray( buffer, offset ) { + var groups = this.groups; - this.resolvedProperty.fromArray( buffer, offset ); + if ( groups.length > 0 ) { - }, + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + } - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + var boundingSphere = this.boundingSphere; - }, + if ( boundingSphere !== null ) { - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + } - } + return data; - ] + }, - ] + clone: function () { -} ); + /* + // Handle primitives -THREE.PropertyBinding.Composite = - function( targetGroup, path, optionalParsedPath ) { + var parameters = this.parameters; - var parsedPath = optionalParsedPath || - THREE.PropertyBinding.parseTrackName( path ); + if ( parameters !== undefined ) { - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + var values = []; -}; + for ( var key in parameters ) { -THREE.PropertyBinding.Composite.prototype = { + values.push( parameters[ key ] ); - constructor: THREE.PropertyBinding.Composite, + } - getValue: function( array, offset ) { + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - this.bind(); // bind all binding + } - var firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + return new this.constructor().copy( this ); + */ - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + return new BufferGeometry().copy( this ); - }, + }, - setValue: function( array, offset ) { + copy: function ( source ) { - var bindings = this._bindings; + var index = source.index; - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + if ( index !== null ) { - bindings[ i ].setValue( array, offset ); + this.setIndex( index.clone() ); - } + } - }, + var attributes = source.attributes; - bind: function() { + for ( var name in attributes ) { - var bindings = this._bindings; + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + } - bindings[ i ].bind(); + var groups = source.groups; - } + for ( var i = 0, l = groups.length; i < l; i ++ ) { - }, + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - unbind: function() { + } - var bindings = this._bindings; + return this; - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + }, - bindings[ i ].unbind(); + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); - } + } -}; + } ); -THREE.PropertyBinding.create = function( root, path, parsedPath ) { + BufferGeometry.MaxIndex = 65535; - if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - return new THREE.PropertyBinding( root, path, parsedPath ); + function WebGLGeometries ( gl, properties, info ) { + this.isWebGLGeometries = true; - } else { + var geometries = {}; - return new THREE.PropertyBinding.Composite( root, path, parsedPath ); + function get( object ) { - } + var geometry = object.geometry; -}; + if ( geometries[ geometry.id ] !== undefined ) { -THREE.PropertyBinding.parseTrackName = function( trackName ) { + return geometries[ geometry.id ]; - // matches strings in the form of: - // nodeName.property - // nodeName.property[accessor] - // nodeName.material.property[accessor] - // uuid.property[accessor] - // uuid.objectName[objectIndex].propertyName[propertyIndex] - // parentName/nodeName.property - // parentName/parentName/nodeName.property[index] - // .bone[Armature.DEF_cog].position - // created and tested via https://regex101.com/#javascript + } - var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; - var matches = re.exec( trackName ); + geometry.addEventListener( 'dispose', onGeometryDispose ); - if ( ! matches ) { + var buffergeometry; - throw new Error( "cannot parse trackName at all: " + trackName ); + if ( (geometry && geometry.isBufferGeometry) ) { - } + buffergeometry = geometry; - if ( matches.index === re.lastIndex ) { + } else if ( (geometry && geometry.isGeometry) ) { - re.lastIndex++; + if ( geometry._bufferGeometry === undefined ) { - } + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - var results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 3 ], // allowed to be null, specified root node. - objectName: matches[ 5 ], - objectIndex: matches[ 7 ], - propertyName: matches[ 9 ], - propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set. - }; + } - if ( results.propertyName === null || results.propertyName.length === 0 ) { + buffergeometry = geometry._bufferGeometry; - throw new Error( "can not parse propertyName from trackName: " + trackName ); + } - } + geometries[ geometry.id ] = buffergeometry; - return results; + info.memory.geometries ++; -}; + return buffergeometry; -THREE.PropertyBinding.findNode = function( root, nodeName ) { + } - if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { + function onGeometryDispose( event ) { - return root; + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; - } + if ( buffergeometry.index !== null ) { - // search into skeleton bones. - if ( root.skeleton ) { + deleteAttribute( buffergeometry.index ); - var searchSkeleton = function( skeleton ) { + } - for( var i = 0; i < skeleton.bones.length; i ++ ) { + deleteAttributes( buffergeometry.attributes ); - var bone = skeleton.bones[ i ]; + geometry.removeEventListener( 'dispose', onGeometryDispose ); - if ( bone.name === nodeName ) { + delete geometries[ geometry.id ]; - return bone; + // TODO - } - } + var property = properties.get( geometry ); - return null; + if ( property.wireframe ) { - }; + deleteAttribute( property.wireframe ); - var bone = searchSkeleton( root.skeleton ); + } - if ( bone ) { + properties.delete( geometry ); - return bone; + var bufferproperty = properties.get( buffergeometry ); - } - } + if ( bufferproperty.wireframe ) { - // search into node subtree. - if ( root.children ) { + deleteAttribute( bufferproperty.wireframe ); - var searchNodeSubtree = function( children ) { + } - for( var i = 0; i < children.length; i ++ ) { + properties.delete( buffergeometry ); - var childNode = children[ i ]; + // - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + info.memory.geometries --; - return childNode; + } - } + function getAttributeBuffer( attribute ) { - var result = searchNodeSubtree( childNode.children ); + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - if ( result ) return result; + return properties.get( attribute.data ).__webglBuffer; - } + } - return null; + return properties.get( attribute ).__webglBuffer; - }; + } - var subTreeNode = searchNodeSubtree( root.children ); + function deleteAttribute( attribute ) { - if ( subTreeNode ) { + var buffer = getAttributeBuffer( attribute ); - return subTreeNode; + if ( buffer !== undefined ) { - } + gl.deleteBuffer( buffer ); + removeAttributeBuffer( attribute ); - } + } - return null; + } -}; + function deleteAttributes( attributes ) { -// File:src/animation/PropertyMixer.js + for ( var name in attributes ) { -/** - * - * Buffered scene graph property that allows weighted accumulation. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + deleteAttribute( attributes[ name ] ); -THREE.PropertyMixer = function ( binding, typeName, valueSize ) { + } - this.binding = binding; - this.valueSize = valueSize; + } - var bufferType = Float64Array, - mixFunction; + function removeAttributeBuffer( attribute ) { - switch ( typeName ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - case 'quaternion': mixFunction = this._slerp; break; + properties.delete( attribute.data ); - case 'string': - case 'bool': + } else { - bufferType = Array, mixFunction = this._select; break; + properties.delete( attribute ); - default: mixFunction = this._lerp; + } - } + } - this.buffer = new bufferType( valueSize * 4 ); - // layout: [ incoming | accu0 | accu1 | orig ] - // - // interpolators can use .buffer as their .result - // the data then goes to 'incoming' - // - // 'accu0' and 'accu1' are used frame-interleaved for - // the cumulative result and are compared to detect - // changes - // - // 'orig' stores the original state of the property + this.get = get; - this._mixBufferRegion = mixFunction; + }; - this.cumulativeWeight = 0; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.useCount = 0; - this.referenceCount = 0; + function WebGLObjects ( gl, properties, info ) { + this.isWebGLObjects = true; -}; + var geometries = new WebGLGeometries( gl, properties, info ); -THREE.PropertyMixer.prototype = { + // - constructor: THREE.PropertyMixer, + function update( object ) { - // accumulate data in the 'incoming' region into 'accu' - accumulate: function( accuIndex, weight ) { + // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + var geometry = geometries.get( object ); - var buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride, + if ( (object.geometry && object.geometry.isGeometry) ) { - currentWeight = this.cumulativeWeight; + geometry.updateFromObject( object ); - if ( currentWeight === 0 ) { + } - // accuN := incoming * weight + var index = geometry.index; + var attributes = geometry.attributes; - for ( var i = 0; i !== stride; ++ i ) { + if ( index !== null ) { - buffer[ offset + i ] = buffer[ i ]; + updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); - } + } - currentWeight = weight; + for ( var name in attributes ) { - } else { + updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); - // accuN := accuN + incoming * weight + } - currentWeight += weight; - var mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + // morph targets - } + var morphAttributes = geometry.morphAttributes; - this.cumulativeWeight = currentWeight; + for ( var name in morphAttributes ) { - }, + var array = morphAttributes[ name ]; - // apply the state of 'accu' to the binding when accus differ - apply: function( accuIndex ) { + for ( var i = 0, l = array.length; i < l; i ++ ) { - var stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + updateAttribute( array[ i ], gl.ARRAY_BUFFER ); - weight = this.cumulativeWeight, + } - binding = this.binding; + } - this.cumulativeWeight = 0; + return geometry; - if ( weight < 1 ) { + } - // accuN := accuN + original * ( 1 - cumulativeWeight ) + function updateAttribute( attribute, bufferType ) { - var originalValueOffset = stride * 3; + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + var attributeProperties = properties.get( data ); - } + if ( attributeProperties.__webglBuffer === undefined ) { - for ( var i = stride, e = stride + stride; i !== e; ++ i ) { + createBuffer( attributeProperties, data, bufferType ); - if ( buffer[ i ] !== buffer[ i + stride ] ) { + } else if ( attributeProperties.version !== data.version ) { - // value has changed -> update scene graph + updateBuffer( attributeProperties, data, bufferType ); - binding.setValue( buffer, offset ); - break; + } - } + } - } + function createBuffer( attributeProperties, data, bufferType ) { - }, + attributeProperties.__webglBuffer = gl.createBuffer(); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - // remember the state of the bound property and copy it to both accus - saveOriginalState: function() { + var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - var binding = this.binding; + gl.bufferData( bufferType, data.array, usage ); - var buffer = this.buffer, - stride = this.valueSize, + attributeProperties.version = data.version; - originalValueOffset = stride * 3; + } - binding.getValue( buffer, originalValueOffset ); + function updateBuffer( attributeProperties, data, bufferType ) { - // accu[0..1] := orig -- initially detect changes against the original - for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + if ( data.dynamic === false || data.updateRange.count === - 1 ) { - } + // Not using update ranges - this.cumulativeWeight = 0; + gl.bufferSubData( bufferType, 0, data.array ); - }, + } else if ( data.updateRange.count === 0 ) { - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState: function() { + console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); - var originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + } else { - }, + gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, + data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); + data.updateRange.count = 0; // reset range - // mix functions + } - _select: function( buffer, dstOffset, srcOffset, t, stride ) { + attributeProperties.version = data.version; - if ( t >= 0.5 ) { + } - for ( var i = 0; i !== stride; ++ i ) { + function getAttributeBuffer( attribute ) { - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - } + return properties.get( attribute.data ).__webglBuffer; - } + } - }, + return properties.get( attribute ).__webglBuffer; - _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { + } - THREE.Quaternion.slerpFlat( buffer, dstOffset, - buffer, dstOffset, buffer, srcOffset, t ); + function getWireframeAttribute( geometry ) { - }, + var property = properties.get( geometry ); - _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { + if ( property.wireframe !== undefined ) { - var s = 1 - t; + return property.wireframe; - for ( var i = 0; i !== stride; ++ i ) { + } - var j = dstOffset + i; + var indices = []; - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + var index = geometry.index; + var attributes = geometry.attributes; + var position = attributes.position; - } + // console.time( 'wireframe' ); - } + if ( index !== null ) { -}; + var edges = {}; + var array = index.array; -// File:src/animation/tracks/BooleanKeyframeTrack.js + for ( var i = 0, l = array.length; i < l; i += 3 ) { -/** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var a = array[ i + 0 ]; + var b = array[ i + 1 ]; + var c = array[ i + 2 ]; -THREE.BooleanKeyframeTrack = function ( name, times, values ) { + if ( checkEdge( edges, a, b ) ) indices.push( a, b ); + if ( checkEdge( edges, b, c ) ) indices.push( b, c ); + if ( checkEdge( edges, c, a ) ) indices.push( c, a ); - THREE.KeyframeTrack.call( this, name, times, values ); + } -}; + } else { -THREE.BooleanKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + var array = attributes.position.array; - constructor: THREE.BooleanKeyframeTrack, + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - ValueTypeName: 'bool', - ValueBufferType: Array, + var a = i + 0; + var b = i + 1; + var c = i + 2; - DefaultInterpolation: THREE.InterpolateDiscrete, + indices.push( a, b, b, c, c, a ); - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined + } - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + } -} ); + // console.timeEnd( 'wireframe' ); -// File:src/animation/tracks/ColorKeyframeTrack.js + var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); -/** - * - * A Track of keyframe values that represent color. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); -THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) { + property.wireframe = attribute; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + return attribute; -}; + } -THREE.ColorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + function checkEdge( edges, a, b ) { - constructor: THREE.ColorKeyframeTrack, + if ( a > b ) { - ValueTypeName: 'color' + var tmp = a; + a = b; + b = tmp; - // ValueBufferType is inherited + } - // DefaultInterpolation is inherited + var list = edges[ a ]; + if ( list === undefined ) { - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. + edges[ a ] = [ b ]; + return true; -} ); + } else if ( list.indexOf( b ) === -1 ) { -// File:src/animation/tracks/NumberKeyframeTrack.js + list.push( b ); + return true; -/** - * - * A Track of numeric keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } -THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) { + return false; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + } -}; + this.getAttributeBuffer = getAttributeBuffer; + this.getWireframeAttribute = getWireframeAttribute; -THREE.NumberKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + this.update = update; - constructor: THREE.NumberKeyframeTrack, + }; - ValueTypeName: 'number', + /** + * @author mrdoob / http://mrdoob.com/ + */ - // ValueBufferType is inherited + function WebGLLights () { + this.isWebGLLights = true; - // DefaultInterpolation is inherited + var lights = {}; -} ); + this.get = function ( light ) { -// File:src/animation/tracks/QuaternionKeyframeTrack.js + if ( lights[ light.id ] !== undefined ) { -/** - * - * A Track of quaternion keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + return lights[ light.id ]; -THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) { + } - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + var uniforms; -}; + switch ( light.type ) { -THREE.QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - constructor: THREE.QuaternionKeyframeTrack, + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - ValueTypeName: 'quaternion', + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0, - // ValueBufferType is inherited + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - DefaultInterpolation: THREE.InterpolateLinear, + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - InterpolantFactoryMethodLinear: function( result ) { + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - return new THREE.QuaternionLinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - }, + } - InterpolantFactoryMethodSmooth: undefined // not yet implemented + lights[ light.id ] = uniforms; -} ); + return uniforms; -// File:src/animation/tracks/StringKeyframeTrack.js + }; -/** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + }; -THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) { + function WebGLCapabilities ( gl, extensions, parameters ) { + this.isWebGLCapabilities = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + var maxAnisotropy; -}; + function getMaxAnisotropy() { -THREE.StringKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - constructor: THREE.StringKeyframeTrack, + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - ValueTypeName: 'string', - ValueBufferType: Array, + if ( extension !== null ) { - DefaultInterpolation: THREE.InterpolateDiscrete, + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - InterpolantFactoryMethodLinear: undefined, + } else { - InterpolantFactoryMethodSmooth: undefined + maxAnisotropy = 0; -} ); + } -// File:src/animation/tracks/VectorKeyframeTrack.js + return maxAnisotropy; -/** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } -THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) { + function getMaxPrecision( precision ) { - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + if ( precision === 'highp' ) { -}; + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { -THREE.VectorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { + return 'highp'; - constructor: THREE.VectorKeyframeTrack, + } - ValueTypeName: 'vector' + precision = 'mediump'; - // ValueBufferType is inherited + } - // DefaultInterpolation is inherited + if ( precision === 'mediump' ) { -} ); + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { -// File:src/audio/Audio.js + return 'mediump'; -/** - * @author mrdoob / http://mrdoob.com/ - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + } -THREE.Audio = function ( listener ) { + } - THREE.Object3D.call( this ); + return 'lowp'; - this.type = 'Audio'; + } - this.context = listener.context; - this.source = this.context.createBufferSource(); - this.source.onended = this.onEnded.bind( this ); + this.getMaxAnisotropy = getMaxAnisotropy; + this.getMaxPrecision = getMaxPrecision; - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; - this.autoplay = false; + this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - this.startTime = 0; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.sourceType = 'empty'; + this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); - this.filters = []; + this.vertexTextures = this.maxVertexTextures > 0; + this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; -}; + var _maxPrecision = getMaxPrecision( this.precision ); -THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + if ( _maxPrecision !== this.precision ) { - constructor: THREE.Audio, + console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); + this.precision = _maxPrecision; - getOutput: function () { + } - return this.gain; + if ( this.logarithmicDepthBuffer ) { - }, + this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); - setNodeSource: function ( audioNode ) { + } - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + }; - return this; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function WebGLExtensions ( gl ) { + this.isWebGLExtensions = true; - setBuffer: function ( audioBuffer ) { + var extensions = {}; - this.source.buffer = audioBuffer; - this.sourceType = 'buffer'; + this.get = function ( name ) { - if ( this.autoplay ) this.play(); + if ( extensions[ name ] !== undefined ) { - return this; + return extensions[ name ]; - }, + } - play: function () { + var extension; - if ( this.isPlaying === true ) { + switch ( name ) { - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - } + 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; - if ( this.hasPlaybackControl === false ) { + 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; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - } + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - var source = this.context.createBufferSource(); + default: + extension = gl.getExtension( name ); - source.buffer = this.source.buffer; - source.loop = this.source.loop; - source.onended = this.source.onended; - source.start( 0, this.startTime ); - source.playbackRate.value = this.playbackRate; + } - this.isPlaying = true; + if ( extension === null ) { - this.source = source; + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - return this.connect(); + } - }, + extensions[ name ] = extension; - pause: function () { + return extension; - if ( this.hasPlaybackControl === false ) { + }; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.source.stop(); - this.startTime = this.context.currentTime; - this.isPlaying = false; + function WebGLIndexedBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLIndexedBufferRenderer = true; - return this; + var mode; - }, + function setMode( value ) { - stop: function () { + mode = value; - if ( this.hasPlaybackControl === false ) { + } - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + var type, size; - } + function setIndex( index ) { - this.source.stop(); - this.startTime = 0; - this.isPlaying = false; + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { - return this; + type = _gl.UNSIGNED_INT; + size = 4; - }, + } else { - connect: function () { + type = _gl.UNSIGNED_SHORT; + size = 2; - if ( this.filters.length > 0 ) { + } - this.source.connect( this.filters[ 0 ] ); + } - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + function render( start, count ) { - this.filters[ i - 1 ].connect( this.filters[ i ] ); + _gl.drawElements( mode, count, type, start * size ); - } + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + } - } else { + function renderInstances( geometry, start, count ) { - this.source.connect( this.getOutput() ); + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - } + if ( extension === null ) { - return this; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - }, + } - disconnect: function () { + extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); - if ( this.filters.length > 0 ) { + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + } - this.source.disconnect( this.filters[ 0 ] ); + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + }; - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + function WebGLClipping() { + this.isWebGLClipping = true; - } + var scope = this, - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - } else { + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - this.source.disconnect( this.getOutput() ); + uniform = { value: null, needsUpdate: false }; - } + this.uniform = uniform; + this.numPlanes = 0; - return this; + this.init = function( planes, enableLocalClipping, camera ) { - }, + var enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; - getFilters: function () { + localClippingEnabled = enableLocalClipping; - return this.filters; + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - }, + return enabled; - setFilters: function ( value ) { + }; - if ( ! value ) value = []; + this.beginShadows = function() { - if ( this.isPlaying === true ) { + renderingShadows = true; + projectPlanes( null ); - this.disconnect(); - this.filters = value; - this.connect(); + }; - } else { + this.endShadows = function() { - this.filters = value; + renderingShadows = false; + resetGlobalState(); - } + }; - return this; + this.setState = function( planes, clipShadows, camera, cache, fromCache ) { - }, + if ( ! localClippingEnabled || + planes === null || planes.length === 0 || + renderingShadows && ! clipShadows ) { + // there's no local clipping - getFilter: function () { + if ( renderingShadows ) { + // there's no global clipping - return this.getFilters()[ 0 ]; + projectPlanes( null ); - }, + } else { - setFilter: function ( filter ) { + resetGlobalState(); + } - return this.setFilters( filter ? [ filter ] : [] ); + } else { - }, + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - setPlaybackRate: function ( value ) { + dstArray = cache.clippingState || null; - if ( this.hasPlaybackControl === false ) { + uniform.value = dstArray; // ensure unique state - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - } + for ( var i = 0; i !== lGlobal; ++ i ) { - this.playbackRate = value; + dstArray[ i ] = globalState[ i ]; - if ( this.isPlaying === true ) { + } - this.source.playbackRate.value = this.playbackRate; + cache.clippingState = dstArray; + this.numPlanes += nGlobal; - } + } - return this; - }, + }; - getPlaybackRate: function () { + function resetGlobalState() { - return this.playbackRate; + if ( uniform.value !== globalState ) { - }, + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - onEnded: function () { + } - this.isPlaying = false; + scope.numPlanes = numGlobalPlanes; - }, + } - getLoop: function () { + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - if ( this.hasPlaybackControl === false ) { + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + if ( nPlanes !== 0 ) { - } + dstArray = uniform.value; - return this.source.loop; + if ( skipTransform !== true || dstArray === null ) { - }, + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - setLoop: function ( value ) { + viewNormalMatrix.getNormalMatrix( viewMatrix ); - if ( this.hasPlaybackControl === false ) { + if ( dstArray === null || dstArray.length < flatSize ) { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + dstArray = new Float32Array( flatSize ); - } + } - this.source.loop = value; + for ( var i = 0, i4 = dstOffset; + i !== nPlanes; ++ i, i4 += 4 ) { - }, + plane.copy( planes[ i ] ). + applyMatrix4( viewMatrix, viewNormalMatrix ); - getVolume: function () { + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - return this.gain.gain.value; + } - }, + } + uniform.value = dstArray; + uniform.needsUpdate = true; - setVolume: function ( value ) { + } - this.gain.gain.value = value; + scope.numPlanes = nPlanes; + return dstArray; - return this; + } - } + }; -} ); + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/audio/AudioAnalyser.js + function WebGLBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLBufferRenderer = true; -/** - * @author mrdoob / http://mrdoob.com/ - */ + var mode; -THREE.AudioAnalyser = function ( audio, fftSize ) { + function setMode( value ) { - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; + mode = value; - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + } - audio.getOutput().connect( this.analyser ); + function render( start, count ) { -}; + _gl.drawArrays( mode, start, count ); -Object.assign( THREE.AudioAnalyser.prototype, { + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - getFrequencyData: function () { + } - this.analyser.getByteFrequencyData( this.data ); + function renderInstances( geometry ) { - return this.data; + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - }, + if ( extension === null ) { - getAverageFrequency: function () { + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - var value = 0, data = this.getFrequencyData(); + } - for ( var i = 0; i < data.length; i ++ ) { + var position = geometry.attributes.position; - value += data[ i ]; + var count = 0; - } + if ( (position && position.isInterleavedBufferAttribute) ) { - return value / data.length; + count = position.data.count; - } + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); -} ); + } else { -// File:src/audio/AudioContext.js + count = position.count; -/** - * @author mrdoob / http://mrdoob.com/ - */ + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); -Object.defineProperty( THREE, 'AudioContext', { + } - get: ( function () { + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - var context; + } - return function get() { + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - if ( context === undefined ) { + }; - context = new ( window.AudioContext || window.webkitAudioContext )(); + /** + * @author alteredq / http://alteredqualia.com + */ - } + function WebGLRenderTargetCube ( width, height, options ) { + this.isWebGLRenderTargetCube = this.isWebGLRenderTarget = true; - return context; + WebGLRenderTarget.call( this, width, height, options ); - }; + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; - } )() + }; -} ); + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; -// File:src/audio/PositionalAudio.js + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + function BoxBufferGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxBufferGeometry = this.isBufferGeometry = true; -THREE.PositionalAudio = function ( listener ) { + BufferGeometry.call( this ); - THREE.Audio.call( this, listener ); + this.type = 'BoxBufferGeometry'; - this.panner = this.context.createPanner(); - this.panner.connect( this.gain ); + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; -}; + var scope = this; -THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prototype ), { + // segments + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - constructor: THREE.PositionalAudio, + // these are used to calculate buffer length + var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); + var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); - getOutput: function () { + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); - return this.panner; + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; + var numberOfVertices = 0; - }, + // group variables + var groupStart = 0; - getRefDistance: function () { + // build each side of the box geometry + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz - return this.panner.refDistance; + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - }, + // helper functions - setRefDistance: function ( value ) { + function calculateVertexCount ( w, h, d ) { - this.panner.refDistance = value; + var vertices = 0; - }, + // calculate the amount of vertices for each side (plane) + vertices += (w + 1) * (h + 1) * 2; // xy + vertices += (w + 1) * (d + 1) * 2; // xz + vertices += (d + 1) * (h + 1) * 2; // zy - getRolloffFactor: function () { + return vertices; - return this.panner.rolloffFactor; + } - }, + function calculateIndexCount ( w, h, d ) { - setRolloffFactor: function ( value ) { + var index = 0; - this.panner.rolloffFactor = value; + // calculate the amount of squares for each side + index += w * h * 2; // xy + index += w * d * 2; // xz + index += d * h * 2; // zy - }, + return index * 6; // two triangles per square => six vertices per square - getDistanceModel: function () { + } - return this.panner.distanceModel; + function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - }, + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - setDistanceModel: function ( value ) { + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - this.panner.distanceModel = value; + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - }, + var vertexCounter = 0; + var groupCount = 0; - getMaxDistance: function () { + var vector = new Vector3(); - return this.panner.maxDistance; + // generate vertices, normals and uvs - }, + for ( var iy = 0; iy < gridY1; iy ++ ) { - setMaxDistance: function ( value ) { + var y = iy * segmentHeight - heightHalf; - this.panner.maxDistance = value; + for ( var ix = 0; ix < gridX1; ix ++ ) { - }, + var x = ix * segmentWidth - widthHalf; - updateMatrixWorld: ( function () { + // set values to correct vector component + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - var position = new THREE.Vector3(); + // now apply vector to vertex buffer + vertices[ vertexBufferOffset ] = vector.x; + vertices[ vertexBufferOffset + 1 ] = vector.y; + vertices[ vertexBufferOffset + 2 ] = vector.z; - return function updateMatrixWorld( force ) { + // set values to correct vector component + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + // now apply vector to normal buffer + normals[ vertexBufferOffset ] = vector.x; + normals[ vertexBufferOffset + 1 ] = vector.y; + normals[ vertexBufferOffset + 2 ] = vector.z; - position.setFromMatrixPosition( this.matrixWorld ); + // uvs + uvs[ uvBufferOffset ] = ix / gridX; + uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); - this.panner.setPosition( position.x, position.y, position.z ); + // update offsets and counters + vertexBufferOffset += 3; + uvBufferOffset += 2; + vertexCounter += 1; - }; + } - } )() + } + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment -} ); + for ( iy = 0; iy < gridY; iy ++ ) { -// File:src/audio/AudioListener.js + for ( ix = 0; ix < gridX; ix ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + // indices + var a = numberOfVertices + ix + gridX1 * iy; + var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; -THREE.AudioListener = function () { + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - THREE.Object3D.call( this ); + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - this.type = 'AudioListener'; + // update offsets and counters + indexBufferOffset += 6; + groupCount += 6; - this.context = THREE.AudioContext; + } - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + } - this.filter = null; + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, materialIndex ); -}; + // calculate new start value for groups + groupStart += groupCount; -THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + // update total number of vertices + numberOfVertices += vertexCounter; - constructor: THREE.AudioListener, + } - getInput: function () { + }; - return this.gain; + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - }, + /** + * @author bhouston / http://clara.io + */ - removeFilter: function ( ) { + function Ray ( origin, direction ) { + this.isRay = true; - if ( this.filter !== null ) { + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + }; - } + Ray.prototype = { - }, + constructor: Ray, - getFilter: function () { + set: function ( origin, direction ) { - return this.filter; + this.origin.copy( origin ); + this.direction.copy( direction ); - }, + return this; - setFilter: function ( value ) { + }, - if ( this.filter !== null ) { + clone: function () { - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + return new this.constructor().copy( this ); - } else { + }, - this.gain.disconnect( this.context.destination ); + copy: function ( ray ) { - } + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + return this; - }, + }, - getMasterVolume: function () { + at: function ( t, optionalTarget ) { - return this.gain.gain.value; + var result = optionalTarget || new Vector3(); - }, + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - setMasterVolume: function ( value ) { + }, - this.gain.gain.value = value; + lookAt: function ( v ) { - }, + this.direction.copy( v ).sub( this.origin ).normalize(); - updateMatrixWorld: ( function () { + return this; - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3(); + }, - var orientation = new THREE.Vector3(); + recast: function () { - return function updateMatrixWorld( force ) { + var v1 = new Vector3(); - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + return function recast( t ) { - var listener = this.context.listener; - var up = this.up; + this.origin.copy( this.at( t, v1 ) ); - this.matrixWorld.decompose( position, quaternion, scale ); + return this; - orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + }; - listener.setPosition( position.x, position.y, position.z ); - listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); + }(), - }; + closestPointToPoint: function ( point, optionalTarget ) { - } )() + var result = optionalTarget || new Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); -} ); + if ( directionDistance < 0 ) { -// File:src/cameras/Camera.js + return result.copy( this.origin ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley -*/ + } -THREE.Camera = function () { + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - THREE.Object3D.call( this ); + }, - this.type = 'Camera'; + distanceToPoint: function ( point ) { - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + return Math.sqrt( this.distanceSqToPoint( point ) ); -}; + }, -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; + distanceSqToPoint: function () { -THREE.Camera.prototype.getWorldDirection = function () { + var v1 = new Vector3(); - var quaternion = new THREE.Quaternion(); + return function distanceSqToPoint( point ) { - return function getWorldDirection( optionalTarget ) { + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - var result = optionalTarget || new THREE.Vector3(); + // point behind the ray - this.getWorldQuaternion( quaternion ); + if ( directionDistance < 0 ) { - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + return this.origin.distanceToSquared( point ); - }; + } -}(); + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); -THREE.Camera.prototype.lookAt = function () { + return v1.distanceToSquared( point ); - // This routine does not support cameras with rotated and/or translated parent(s) + }; - var m1 = new THREE.Matrix4(); + }(), - return function lookAt( vector ) { + distanceSqToSegment: function () { - m1.lookAt( this.position, vector, this.up ); + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - this.quaternion.setFromRotationMatrix( m1 ); + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - }; + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h + // 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 -}(); + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); -THREE.Camera.prototype.clone = function () { + var segExtent = v0.distanceTo( v1 ) * 0.5; + 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; - return new this.constructor().copy( this ); + if ( det > 0 ) { -}; + // The ray and segment are not parallel. -THREE.Camera.prototype.copy = function ( source ) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - THREE.Object3D.prototype.copy.call( this, source ); + if ( s0 >= 0 ) { - this.matrixWorldInverse.copy( source.matrixWorldInverse ); - this.projectionMatrix.copy( source.projectionMatrix ); + if ( s1 >= - extDet ) { - return this; + if ( s1 <= extDet ) { -}; + // region 0 + // Minimum at interior points of ray and segment. -// File:src/cameras/CubeCamera.js + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.CubeCamera = function ( near, far, cubeResolution ) { + // region 1 - THREE.Object3D.call( this ); + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - this.type = 'CubeCamera'; + } - var fov = 90, aspect = 1; + } else { - 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 ); + // region 5 - 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 ); + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - 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 ); + } else { - 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 ); + if ( s1 <= - extDet ) { - 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 ); + // region 4 - var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter }; + 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; - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + } else if ( s1 <= extDet ) { - this.updateCubeMap = function ( renderer, scene ) { + // region 3 - if ( this.parent === null ) this.updateMatrixWorld(); + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.texture.generateMipmaps; + } else { - renderTarget.texture.generateMipmaps = false; + // region 2 - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + 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; - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + } - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + } - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + } else { - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + // Ray and segment are parallel. - renderTarget.texture.generateMipmaps = generateMipmaps; + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + } - renderer.setRenderTarget( null ); + if ( optionalPointOnRay ) { - }; + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); -}; + } -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; + if ( optionalPointOnSegment ) { -// File:src/cameras/OrthographicCamera.js + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); -/** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + } -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { + return sqrDist; - THREE.Camera.call( this ); + }; - this.type = 'OrthographicCamera'; + }(), - this.zoom = 1; - this.view = null; + intersectSphere: function () { - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + var v1 = new Vector3(); - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + return function intersectSphere( sphere, optionalTarget ) { - this.updateProjectionMatrix(); + v1.subVectors( sphere.center, this.origin ); + var tca = v1.dot( this.direction ); + var d2 = v1.dot( v1 ) - tca * tca; + var radius2 = sphere.radius * sphere.radius; -}; + if ( d2 > radius2 ) return null; -THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { + var thc = Math.sqrt( radius2 - d2 ); - constructor: THREE.OrthographicCamera, + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - copy: function ( source ) { + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - THREE.Camera.prototype.copy.call( this, source ); + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; + // 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 ); - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - return this; + }; - }, + }(), - setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { + intersectsSphere: function ( sphere ) { - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + return this.distanceToPoint( sphere.center ) <= sphere.radius; - this.updateProjectionMatrix(); + }, - }, + distanceToPlane: function ( plane ) { - clearViewOffset: function() { + var denominator = plane.normal.dot( this.direction ); - this.view = null; - this.updateProjectionMatrix(); + if ( denominator === 0 ) { - }, + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - updateProjectionMatrix: function () { + return 0; - 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; + } - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + // Null is preferable to undefined since undefined means.... it is undefined - if ( this.view !== null ) { + return null; - var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); - var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); - var scaleW = ( this.right - this.left ) / this.view.width; - var scaleH = ( this.top - this.bottom ) / this.view.height; + } - left += scaleW * ( this.view.offsetX / zoomW ); - right = left + scaleW * ( this.view.width / zoomW ); - top -= scaleH * ( this.view.offsetY / zoomH ); - bottom = top - scaleH * ( this.view.height / zoomH ); + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - } + // Return if the ray never intersects the plane - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + return t >= 0 ? t : null; - }, + }, - toJSON: function ( meta ) { + intersectPlane: function ( plane, optionalTarget ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var t = this.distanceToPlane( plane ); - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; + if ( t === null ) { - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + return null; - return data; + } - } + return this.at( t, optionalTarget ); -} ); + }, -// File:src/cameras/PerspectiveCamera.js -/** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { + intersectsPlane: function ( plane ) { - THREE.Camera.call( this ); + // check if the ray lies on the plane first - this.type = 'PerspectiveCamera'; + var distToPoint = plane.distanceToPoint( this.origin ); - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; + if ( distToPoint === 0 ) { - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + return true; - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + } - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + var denominator = plane.normal.dot( this.direction ); - this.updateProjectionMatrix(); + if ( denominator * distToPoint < 0 ) { -}; + return true; -THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { + } - constructor: THREE.PerspectiveCamera, + // ray origin is behind the plane (and is pointing behind it) - copy: function ( source ) { + return false; - THREE.Camera.prototype.copy.call( this, source ); + }, - this.fov = source.fov; - this.zoom = source.zoom; + intersectBox: function ( box, optionalTarget ) { - this.near = source.near; - this.far = source.far; - this.focus = source.focus; + var tmin, tmax, tymin, tymax, tzmin, tzmax; - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + var origin = this.origin; - return this; + if ( invdirx >= 0 ) { - }, + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength: function ( focalLength ) { + } else { - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + } - }, + if ( invdiry >= 0 ) { - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - var vExtentSlope = Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ); + } else { - return 0.5 * this.getFilmHeight() / vExtentSlope; + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - }, + } - getEffectiveFOV: function () { + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - return THREE.Math.RAD2DEG * 2 * Math.atan( - Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + // 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 ( tymin > tmin || tmin !== tmin ) tmin = tymin; - getFilmWidth: function () { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + if ( invdirz >= 0 ) { - }, + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - getFilmHeight: function () { + } else { - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - }, + } - /** - * 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. - */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - - this.aspect = fullWidth / fullHeight; - - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; - - this.updateProjectionMatrix(); + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - }, + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - clearViewOffset: function() { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - this.view = null; - this.updateProjectionMatrix(); + //return point closest to the ray (positive side) - }, + if ( tmax < 0 ) return null; - updateProjectionMatrix: function () { + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - var near = this.near, - top = near * Math.tan( - THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, - height = 2 * top, - width = this.aspect * height, - left = - 0.5 * width, - view = this.view; + }, - if ( view !== null ) { + intersectsBox: ( function () { - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; + var v = new Vector3(); - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; + return function intersectsBox( box ) { - } + return this.intersectBox( box, v ) !== null; - var skew = this.filmOffset; - if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + }; - this.projectionMatrix.makeFrustum( - left, left + width, top - height, top, near, this.far ); + } )(), - }, + intersectTriangle: function () { - toJSON: function ( meta ) { + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { - data.object.fov = this.fov; - data.object.zoom = this.zoom; + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - data.object.aspect = this.aspect; + // 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 ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + if ( DdN > 0 ) { - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + if ( backfaceCulling ) return null; + sign = 1; - return data; + } else if ( DdN < 0 ) { - } + sign = - 1; + DdN = - DdN; -} ); + } else { -// File:src/cameras/StereoCamera.js + return null; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.StereoCamera = function () { + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - this.type = 'StereoCamera'; + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - this.aspect = 1; + return null; - this.cameraL = new THREE.PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + } - this.cameraR = new THREE.PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); -}; + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { -Object.assign( THREE.StereoCamera.prototype, { + return null; - update: ( function () { + } - var focus, fov, aspect, near, far; + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - var eyeRight = new THREE.Matrix4(); - var eyeLeft = new THREE.Matrix4(); + return null; - return function update( camera ) { + } - var needsUpdate = focus !== camera.focus || fov !== camera.fov || - aspect !== camera.aspect * this.aspect || near !== camera.near || - far !== camera.far; + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - if ( needsUpdate ) { + // t < 0, no intersection + if ( QdN < 0 ) { - focus = camera.focus; - fov = camera.fov; - aspect = camera.aspect * this.aspect; - near = camera.near; - far = camera.far; + return null; - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + } - var projectionMatrix = camera.projectionMatrix.clone(); - var eyeSep = 0.064 / 2; - var eyeSepOnProjection = eyeSep * near / focus; - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); - var xmin, xmax; + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - // translate xOffset + }; - eyeLeft.elements[ 12 ] = - eyeSep; - eyeRight.elements[ 12 ] = eyeSep; + }(), - // for left eye + applyMatrix4: function ( matrix4 ) { - xmin = - ymax * aspect + eyeSepOnProjection; - xmax = ymax * aspect + eyeSepOnProjection; + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + return this; - this.cameraL.projectionMatrix.copy( projectionMatrix ); + }, - // for right eye + equals: function ( ray ) { - xmin = - ymax * aspect - eyeSepOnProjection; - xmax = ymax * aspect - eyeSepOnProjection; + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + } - this.cameraR.projectionMatrix.copy( projectionMatrix ); + }; - } + /** + * @author bhouston / http://clara.io + */ - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); + function Line3 ( start, end ) { + this.isLine3 = true; - }; + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - } )() + }; -} ); + Line3.prototype = { -// File:src/lights/Light.js + constructor: Line3, -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + set: function ( start, end ) { -THREE.Light = function ( color, intensity ) { + this.start.copy( start ); + this.end.copy( end ); - THREE.Object3D.call( this ); + return this; - this.type = 'Light'; + }, - this.color = new THREE.Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + clone: function () { - this.receiveShadow = undefined; + return new this.constructor().copy( this ); -}; + }, -THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + copy: function ( line ) { - constructor: THREE.Light, + this.start.copy( line.start ); + this.end.copy( line.end ); - copy: function ( source ) { + return this; - THREE.Object3D.prototype.copy.call( this, source ); + }, - this.color.copy( source.color ); - this.intensity = source.intensity; + center: function ( optionalTarget ) { - return this; + var result = optionalTarget || new Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - }, + }, - toJSON: function ( meta ) { + delta: function ( optionalTarget ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var result = optionalTarget || new Vector3(); + return result.subVectors( this.end, this.start ); - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + }, - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + distanceSq: function () { - if ( this.distance !== undefined ) data.object.distance = this.distance; - if ( this.angle !== undefined ) data.object.angle = this.angle; - if ( this.decay !== undefined ) data.object.decay = this.decay; - if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; + return this.start.distanceToSquared( this.end ); - return data; + }, - } + distance: function () { -} ); + return this.start.distanceTo( this.end ); -// File:src/lights/LightShadow.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + at: function ( t, optionalTarget ) { -THREE.LightShadow = function ( camera ) { + var result = optionalTarget || new Vector3(); - this.camera = camera; + return this.delta( result ).multiplyScalar( t ).add( this.start ); - this.bias = 0; - this.radius = 1; + }, - this.mapSize = new THREE.Vector2( 512, 512 ); + closestPointToPointParameter: function () { - this.map = null; - this.matrix = new THREE.Matrix4(); + var startP = new Vector3(); + var startEnd = new Vector3(); -}; + return function closestPointToPointParameter( point, clampToLine ) { -Object.assign( THREE.LightShadow.prototype, { + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - copy: function ( source ) { + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - this.camera = source.camera.clone(); + var t = startEnd_startP / startEnd2; - this.bias = source.bias; - this.radius = source.radius; + if ( clampToLine ) { - this.mapSize.copy( source.mapSize ); + t = exports.Math.clamp( t, 0, 1 ); - return this; + } - }, + return t; - clone: function () { + }; - return new this.constructor().copy( this ); + }(), - } + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { -} ); + var t = this.closestPointToPointParameter( point, clampToLine ); -// File:src/lights/AmbientLight.js + var result = optionalTarget || new Vector3(); -/** - * @author mrdoob / http://mrdoob.com/ - */ + return this.delta( result ).multiplyScalar( t ).add( this.start ); -THREE.AmbientLight = function ( color, intensity ) { + }, - THREE.Light.call( this, color, intensity ); + applyMatrix4: function ( matrix ) { - this.type = 'AmbientLight'; + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - this.castShadow = undefined; + return this; -}; + }, -THREE.AmbientLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + equals: function ( line ) { - constructor: THREE.AmbientLight + return line.start.equals( this.start ) && line.end.equals( this.end ); -} ); + } -// File:src/lights/DirectionalLight.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ -THREE.DirectionalLight = function ( color, intensity ) { + function Triangle ( a, b, c ) { + this.isTriangle = true; - THREE.Light.call( this, color, intensity ); + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - this.type = 'DirectionalLight'; + }; - this.position.copy( THREE.Object3D.DefaultUp ); - this.updateMatrix(); + Triangle.normal = function () { - this.target = new THREE.Object3D(); + var v0 = new Vector3(); - this.shadow = new THREE.DirectionalLightShadow(); + return function normal( a, b, c, optionalTarget ) { -}; + var result = optionalTarget || new Vector3(); -THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - constructor: THREE.DirectionalLight, + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - copy: function ( source ) { + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - THREE.Light.prototype.copy.call( this, source ); + } - this.target = source.target.clone(); + return result.set( 0, 0, 0 ); - this.shadow = source.shadow.clone(); + }; - return this; + }(); - } + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + Triangle.barycoordFromPoint = function () { -} ); + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); -// File:src/lights/DirectionalLightShadow.js + return function barycoordFromPoint( point, a, b, c, optionalTarget ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); -THREE.DirectionalLightShadow = function ( light ) { + 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 ); - THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + var denom = ( dot00 * dot11 - dot01 * dot01 ); -}; + var result = optionalTarget || new Vector3(); -THREE.DirectionalLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { + // collinear or singular triangle + if ( denom === 0 ) { - constructor: THREE.DirectionalLightShadow + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return result.set( - 2, - 1, - 1 ); -} ); + } -// File:src/lights/HemisphereLight.js + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; -/** - * @author alteredq / http://alteredqualia.com/ - */ + // barycentric coordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { + }; - THREE.Light.call( this, skyColor, intensity ); + }(); - this.type = 'HemisphereLight'; + Triangle.containsPoint = function () { - this.castShadow = undefined; + var v1 = new Vector3(); - this.position.copy( THREE.Object3D.DefaultUp ); - this.updateMatrix(); + return function containsPoint( point, a, b, c ) { - this.groundColor = new THREE.Color( groundColor ); + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); -}; + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); -THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + }; - constructor: THREE.HemisphereLight, + }(); - copy: function ( source ) { + Triangle.prototype = { - THREE.Light.prototype.copy.call( this, source ); + constructor: Triangle, - this.groundColor.copy( source.groundColor ); + set: function ( a, b, c ) { - return this; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - } + return this; -} ); + }, -// File:src/lights/PointLight.js + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + return this; -THREE.PointLight = function ( color, intensity, distance, decay ) { + }, - THREE.Light.call( this, color, intensity ); + clone: function () { - this.type = 'PointLight'; + return new this.constructor().copy( this ); - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * 4 * Math.PI; + }, - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / ( 4 * Math.PI ); - } - } ); + copy: function ( triangle ) { - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) ); + return this; -}; + }, -THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + area: function () { - constructor: THREE.PointLight, + var v0 = new Vector3(); + var v1 = new Vector3(); - copy: function ( source ) { + return function area() { - THREE.Light.prototype.copy.call( this, source ); + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - this.distance = source.distance; - this.decay = source.decay; + return v0.cross( v1 ).length() * 0.5; - this.shadow = source.shadow.clone(); + }; - return this; + }(), - } + midpoint: function ( optionalTarget ) { -} ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); -// File:src/lights/SpotLight.js + }, -/** - * @author alteredq / http://alteredqualia.com/ - */ + normal: function ( optionalTarget ) { -THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) { + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); - THREE.Light.call( this, color, intensity ); + }, - this.type = 'SpotLight'; + plane: function ( optionalTarget ) { - this.position.copy( THREE.Object3D.DefaultUp ); - this.updateMatrix(); + var result = optionalTarget || new Plane(); - this.target = new THREE.Object3D(); + return result.setFromCoplanarPoints( this.a, this.b, this.c ); - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * Math.PI; - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / Math.PI; - } - } ); + }, - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + barycoordFromPoint: function ( point, optionalTarget ) { - this.shadow = new THREE.SpotLightShadow(); + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); -}; + }, -THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { + containsPoint: function ( point ) { - constructor: THREE.SpotLight, + return Triangle.containsPoint( point, this.a, this.b, this.c ); - copy: function ( source ) { + }, - THREE.Light.prototype.copy.call( this, source ); + closestPointToPoint: function () { - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + var plane, edgeList, projectedPoint, closestPoint; - this.target = source.target.clone(); + return function closestPointToPoint( point, optionalTarget ) { - this.shadow = source.shadow.clone(); + if ( plane === undefined ) { - return this; + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); - } + } -} ); + var result = optionalTarget || new Vector3(); + var minDistance = Infinity; -// File:src/lights/SpotLightShadow.js + // project the point onto the plane of the triangle -/** - * @author mrdoob / http://mrdoob.com/ - */ + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); -THREE.SpotLightShadow = function () { + // check if the projection lies within the triangle - THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) ); + if( this.containsPoint( projectedPoint ) === true ) { -}; + // if so, this is the closest point -THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { + result.copy( projectedPoint ); - constructor: THREE.SpotLightShadow, + } else { - update: function ( light ) { + // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices - var fov = THREE.Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || 500; + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - var camera = this.camera; + for( var i = 0; i < edgeList.length; i ++ ) { - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + var distance = projectedPoint.distanceToSquared( closestPoint ); - } + if( distance < minDistance ) { - } + minDistance = distance; -} ); + result.copy( closestPoint ); -// File:src/loaders/AudioLoader.js + } -/** - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + } -THREE.AudioLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + return result; -}; + }; -Object.assign( THREE.AudioLoader.prototype, { + }(), - load: function ( url, onLoad, onProgress, onError ) { + equals: function ( triangle ) { - var loader = new THREE.XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( buffer ) { + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - var context = THREE.AudioContext; + } - context.decodeAudioData( buffer, function ( audioBuffer ) { + }; - onLoad( audioBuffer ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * shading: THREE.SmoothShading, + * depthTest: , + * depthWrite: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: + * } + */ - } ); + function MeshBasicMaterial ( parameters ) { + this.isMeshBasicMaterial = this.isMaterial = true; - }, onProgress, onError ); + Material.call( this ); - } + this.type = 'MeshBasicMaterial'; -} ); + this.color = new Color( 0xffffff ); // emissive -// File:src/loaders/Cache.js + this.map = null; -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.aoMap = null; + this.aoMapIntensity = 1.0; -THREE.Cache = { + this.specularMap = null; - enabled: false, + this.alphaMap = null; - files: {}, + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - add: function ( key, file ) { + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - if ( this.enabled === false ) return; + this.skinning = false; + this.morphTargets = false; - // console.log( 'THREE.Cache', 'Adding key:', key ); + this.lights = false; - this.files[ key ] = file; + this.setValues( parameters ); - }, + }; - get: function ( key ) { + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - if ( this.enabled === false ) return; + MeshBasicMaterial.prototype.copy = function ( source ) { - // console.log( 'THREE.Cache', 'Checking key:', key ); + Material.prototype.copy.call( this, source ); - return this.files[ key ]; + this.color.copy( source.color ); - }, + this.map = source.map; - remove: function ( key ) { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - delete this.files[ key ]; + this.specularMap = source.specularMap; - }, + this.alphaMap = source.alphaMap; - clear: function () { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.files = {}; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; -}; + return this; -// File:src/loaders/Loader.js + }; -/** - * @author alteredq / http://alteredqualia.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ -THREE.Loader = function () { + function Mesh ( geometry, material ) { + this.isMesh = true; - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + Object3D.call( this ); -}; + this.type = 'Mesh'; -THREE.Loader.prototype = { + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - constructor: THREE.Loader, + this.drawMode = TrianglesDrawMode; - crossOrigin: undefined, + this.updateMorphTargets(); - extractUrlBase: function ( url ) { + }; - var parts = url.split( '/' ); + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - if ( parts.length === 1 ) return './'; + constructor: Mesh, - parts.pop(); + setDrawMode: function ( value ) { - return parts.join( '/' ) + '/'; + this.drawMode = value; - }, + }, - initMaterials: function ( materials, texturePath, crossOrigin ) { + copy: function ( source ) { - var array = []; + Object3D.prototype.copy.call( this, source ); - for ( var i = 0; i < materials.length; ++ i ) { + this.drawMode = source.drawMode; - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + return this; - } + }, - return array; + updateMorphTargets: function () { - }, + if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - createMaterial: ( function () { + this.morphTargetBase = - 1; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - var color, textureLoader, materialLoader; + for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - return function createMaterial( m, texturePath, crossOrigin ) { + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - if ( color === undefined ) color = new THREE.Color(); - if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader(); + } - // convert from old material format + } - var textures = {}; + }, - function loadTexture( path, repeat, offset, wrap, anisotropy ) { + getMorphTargetIndexByName: function ( name ) { - var fullPath = texturePath + path; - var loader = THREE.Loader.Handlers.get( fullPath ); + if ( this.morphTargetDictionary[ name ] !== undefined ) { - var texture; + return this.morphTargetDictionary[ name ]; - if ( loader !== null ) { + } - texture = loader.load( fullPath ); + console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); - } else { + return 0; - textureLoader.setCrossOrigin( crossOrigin ); - texture = textureLoader.load( fullPath ); + }, - } + raycast: ( function () { - if ( repeat !== undefined ) { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - texture.repeat.fromArray( repeat ); + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - } + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - if ( offset !== undefined ) { + var barycoord = new Vector3(); - texture.offset.fromArray( offset ); + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - } + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - if ( wrap !== undefined ) { + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping; - - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping; - - } - - if ( anisotropy !== undefined ) { - - texture.anisotropy = anisotropy; - - } - - var uuid = THREE.Math.generateUUID(); - - textures[ uuid ] = texture; - - return uuid; - - } - - // - - var json = { - uuid: THREE.Math.generateUUID(), - type: 'MeshLambertMaterial' - }; - - for ( var name in m ) { - - var value = m[ name ]; - - switch ( name ) { - case 'DbgColor': - case 'DbgIndex': - case 'opticalDensity': - case 'illumination': - break; - case 'DbgName': - json.name = value; - break; - case 'blending': - json.blending = THREE[ value ]; - break; - case 'colorAmbient': - case 'mapAmbient': - console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); - break; - case 'colorDiffuse': - json.color = color.fromArray( value ).getHex(); - break; - case 'colorSpecular': - json.specular = color.fromArray( value ).getHex(); - break; - case 'colorEmissive': - json.emissive = color.fromArray( value ).getHex(); - break; - case 'specularCoef': - json.shininess = value; - break; - case 'shading': - if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; - if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; - if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; - break; - case 'mapDiffuse': - json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - break; - case 'mapDiffuseRepeat': - case 'mapDiffuseOffset': - case 'mapDiffuseWrap': - case 'mapDiffuseAnisotropy': - break; - case 'mapEmissive': - json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); - break; - case 'mapEmissiveRepeat': - case 'mapEmissiveOffset': - case 'mapEmissiveWrap': - case 'mapEmissiveAnisotropy': - break; - case 'mapLight': - json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - break; - case 'mapLightRepeat': - case 'mapLightOffset': - case 'mapLightWrap': - case 'mapLightAnisotropy': - break; - case 'mapAO': - json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); - break; - case 'mapAORepeat': - case 'mapAOOffset': - case 'mapAOWrap': - case 'mapAOAnisotropy': - break; - case 'mapBump': - json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - break; - case 'mapBumpScale': - json.bumpScale = value; - break; - case 'mapBumpRepeat': - case 'mapBumpOffset': - case 'mapBumpWrap': - case 'mapBumpAnisotropy': - break; - case 'mapNormal': - json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - break; - case 'mapNormalFactor': - json.normalScale = [ value, value ]; - break; - case 'mapNormalRepeat': - case 'mapNormalOffset': - case 'mapNormalWrap': - case 'mapNormalAnisotropy': - break; - case 'mapSpecular': - json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - break; - case 'mapSpecularRepeat': - case 'mapSpecularOffset': - case 'mapSpecularWrap': - case 'mapSpecularAnisotropy': - break; - case 'mapMetalness': - json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); - break; - case 'mapMetalnessRepeat': - case 'mapMetalnessOffset': - case 'mapMetalnessWrap': - case 'mapMetalnessAnisotropy': - break; - case 'mapRoughness': - json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); - break; - case 'mapRoughnessRepeat': - case 'mapRoughnessOffset': - case 'mapRoughnessWrap': - case 'mapRoughnessAnisotropy': - break; - case 'mapAlpha': - json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - break; - case 'mapAlphaRepeat': - case 'mapAlphaOffset': - case 'mapAlphaWrap': - case 'mapAlphaAnisotropy': - break; - case 'flipSided': - json.side = THREE.BackSide; - break; - case 'doubleSided': - json.side = THREE.DoubleSide; - break; - case 'transparency': - console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); - json.opacity = value; - break; - case 'depthTest': - case 'depthWrite': - case 'colorWrite': - case 'opacity': - case 'reflectivity': - case 'transparent': - case 'visible': - case 'wireframe': - json[ name ] = value; - break; - case 'vertexColors': - if ( value === true ) json.vertexColors = THREE.VertexColors; - if ( value === 'face' ) json.vertexColors = THREE.FaceColors; - break; - default: - console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); - break; - } - - } - - if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; - if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; - - if ( json.opacity < 1 ) json.transparent = true; - - materialLoader.setTextures( textures ); - - return materialLoader.parse( json ); - - }; - - } )() + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); -}; + uv1.add( uv2 ).add( uv3 ); -THREE.Loader.Handlers = { + return uv1.clone(); - handlers: [], + } - add: function ( regex, loader ) { + function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { - this.handlers.push( regex, loader ); + var intersect; + var material = object.material; - }, + if ( material.side === BackSide ) { - get: function ( file ) { + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - var handlers = this.handlers; + } else { - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; + } - if ( regex.test( file ) ) { + if ( intersect === null ) return null; - return loader; + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - } + if ( distance < raycaster.near || distance > raycaster.far ) return null; - return null; + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; - } + } -}; + function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { -// File:src/loaders/XHRLoader.js + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); -THREE.XHRLoader = function ( manager ) { + if ( intersection ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + if ( uvs ) { -}; + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); -Object.assign( THREE.XHRLoader.prototype, { + intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); - load: function ( url, onLoad, onProgress, onError ) { + } - if ( this.path !== undefined ) url = this.path + url; + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); + intersection.faceIndex = a; - var scope = this; + } - var cached = THREE.Cache.get( url ); + return intersection; - if ( cached !== undefined ) { + } - scope.manager.itemStart( url ); + return function raycast( raycaster, intersects ) { - setTimeout( function () { + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - if ( onLoad ) onLoad( cached ); + if ( material === undefined ) return; - scope.manager.itemEnd( url ); + // Checking boundingSphere distance to ray - }, 0 ); + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - return cached; + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - } + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - var request = new XMLHttpRequest(); - request.overrideMimeType( 'text/plain' ); - request.open( 'GET', url, true ); + // - request.addEventListener( 'load', function ( event ) { + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var response = event.target.response; + // Check boundingBox before continuing - THREE.Cache.add( url, response ); + if ( geometry.boundingBox !== null ) { - if ( this.status === 200 ) { + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - if ( onLoad ) onLoad( response ); + } - scope.manager.itemEnd( url ); + var uvs, intersection; - } else if ( this.status === 0 ) { + if ( (geometry && geometry.isBufferGeometry) ) { - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + var a, b, c; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); + if ( attributes.uv !== undefined ) { - if ( onLoad ) onLoad( response ); + uvs = attributes.uv.array; - scope.manager.itemEnd( url ); + } - } else { + if ( index !== null ) { - if ( onError ) onError( event ); + var indices = index.array; - scope.manager.itemError( url ); + for ( var i = 0, l = indices.length; i < l; i += 3 ) { - } + a = indices[ i ]; + b = indices[ i + 1 ]; + c = indices[ i + 2 ]; - }, false ); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - if ( onProgress !== undefined ) { + if ( intersection ) { - request.addEventListener( 'progress', function ( event ) { + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); - onProgress( event ); + } - }, false ); + } - } + } else { - request.addEventListener( 'error', function ( event ) { - if ( onError ) onError( event ); + for ( var i = 0, l = positions.length; i < l; i += 9 ) { - scope.manager.itemError( url ); + a = i / 3; + b = a + 1; + c = a + 2; - }, false ); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + if ( intersection ) { - request.send( null ); + intersection.index = a; // triangle number in positions buffer semantics + intersects.push( intersection ); - scope.manager.itemStart( url ); + } - return request; + } - }, + } - setPath: function ( value ) { + } else if ( (geometry && geometry.isGeometry) ) { - this.path = value; - return this; + var fvA, fvB, fvC; + var isFaceMaterial = (material && material.isMultiMaterial); + var materials = isFaceMaterial === true ? material.materials : null; - }, + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - setResponseType: function ( value ) { + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - this.responseType = value; - return this; + var face = faces[ f ]; + var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; - }, + if ( faceMaterial === undefined ) continue; - setWithCredentials: function ( value ) { + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - this.withCredentials = value; - return this; + if ( faceMaterial.morphTargets === true ) { - } + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; -} ); + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); -// File:src/loaders/FontLoader.js + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var influence = morphInfluences[ t ]; -THREE.FontLoader = function ( manager ) { + if ( influence === 0 ) continue; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + var targets = morphTargets[ t ].vertices; -}; + vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); + vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); + vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); -Object.assign( THREE.FontLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - var scope = this; + fvA = vA; + fvB = vB; + fvC = vC; - var loader = new THREE.XHRLoader( this.manager ); - loader.load( url, function ( text ) { + } - var json; + intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - try { + if ( intersection ) { - json = JSON.parse( text ); + if ( uvs ) { - } catch ( e ) { + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 2 ] ); - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); - } + } - var font = scope.parse( json ); + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - if ( onLoad ) onLoad( font ); + } - }, onProgress, onError ); + } - }, + } - parse: function ( json ) { + }; - return new THREE.Font( json ); + }() ), - } + clone: function () { -} ); + return new this.constructor( this.geometry, this.material ).copy( this ); -// File:src/loaders/ImageLoader.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + } ); -THREE.ImageLoader = function ( manager ) { + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + function PlaneBufferGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneBufferGeometry = this.isBufferGeometry = true; -}; + BufferGeometry.call( this ); -Object.assign( THREE.ImageLoader.prototype, { + this.type = 'PlaneBufferGeometry'; - load: function ( url, onLoad, onProgress, onError ) { + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - var scope = this; + var width_half = width / 2; + var height_half = height / 2; - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - image.onload = function () { + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - URL.revokeObjectURL( image.src ); + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - if ( onLoad ) onLoad( image ); + var segment_width = width / gridX; + var segment_height = height / gridY; - scope.manager.itemEnd( url ); + 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; - if ( url.indexOf( 'data:' ) === 0 ) { + for ( var iy = 0; iy < gridY1; iy ++ ) { - image.src = url; + var y = iy * segment_height - height_half; - } else { + for ( var ix = 0; ix < gridX1; ix ++ ) { - var loader = new THREE.XHRLoader(); - loader.setPath( this.path ); - loader.setResponseType( 'blob' ); - loader.load( url, function ( blob ) { + var x = ix * segment_width - width_half; - image.src = URL.createObjectURL( blob ); + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - }, onProgress, onError ); + normals[ offset + 2 ] = 1; - } + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - scope.manager.itemStart( url ); + offset += 3; + offset2 += 2; - return image; + } - }, + } - setCrossOrigin: function ( value ) { + offset = 0; - this.crossOrigin = value; - return this; + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - }, + for ( var iy = 0; iy < gridY; iy ++ ) { - setPath: function ( value ) { + for ( var ix = 0; ix < gridX; ix ++ ) { - this.path = value; - return this; + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - } + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; -} ); + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; -// File:src/loaders/JSONLoader.js + offset += 6; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.JSONLoader = function ( manager ) { + } - if ( typeof manager === 'boolean' ) { + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + }; - } + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - this.withCredentials = false; + function Camera () { + this.isCamera = this.isObject3D = true; -}; + Object3D.call( this ); -Object.assign( THREE.JSONLoader.prototype, { + this.type = 'Camera'; - load: function( url, onLoad, onProgress, onError ) { + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - var scope = this; + }; - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url ); + Camera.prototype = Object.create( Object3D.prototype ); + Camera.prototype.constructor = Camera; - var loader = new THREE.XHRLoader( this.manager ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + Camera.prototype.getWorldDirection = function () { - var json = JSON.parse( text ); - var metadata = json.metadata; + var quaternion = new Quaternion(); - if ( metadata !== undefined ) { + return function getWorldDirection( optionalTarget ) { - var type = metadata.type; + var result = optionalTarget || new Vector3(); - if ( type !== undefined ) { + this.getWorldQuaternion( quaternion ); - if ( type.toLowerCase() === 'object' ) { + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + }; - } + }(); - if ( type.toLowerCase() === 'scene' ) { + Camera.prototype.lookAt = function () { - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + // This routine does not support cameras with rotated and/or translated parent(s) - } + var m1 = new Matrix4(); - } + return function lookAt( vector ) { - } + m1.lookAt( this.position, vector, this.up ); - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + this.quaternion.setFromRotationMatrix( m1 ); - }, onProgress, onError ); + }; - }, + }(); - setTexturePath: function ( value ) { + Camera.prototype.clone = function () { - this.texturePath = value; + return new this.constructor().copy( this ); - }, + }; - parse: function ( json, texturePath ) { + Camera.prototype.copy = function ( source ) { - var geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + Object3D.prototype.copy.call( this, source ); - parseModel( scale ); + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - parseSkin(); - parseMorphing( scale ); - parseAnimations(); + return this; - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + }; - function parseModel( scale ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - function isBitSet( value, position ) { + function PerspectiveCamera ( fov, aspect, near, far ) { + this.isPerspectiveCamera = true; - return value & ( 1 << position ); + Camera.call( this ); - } + this.type = 'PerspectiveCamera'; - var i, j, fi, + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - offset, zLength, + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; - colorIndex, normalIndex, uvIndex, materialIndex, + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - vertex, face, faceA, faceB, hex, normal, + this.updateProjectionMatrix(); - uvLayer, uv, u, v, + }; - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - nUvLayers = 0; + constructor: PerspectiveCamera, - if ( json.uvs !== undefined ) { + copy: function ( source ) { - // disregard empty arrays + Camera.prototype.copy.call( this, source ); - for ( i = 0; i < json.uvs.length; i ++ ) { + this.fov = source.fov; + this.zoom = source.zoom; - if ( json.uvs[ i ].length ) nUvLayers ++; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - } + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - for ( i = 0; i < nUvLayers; i ++ ) { + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - geometry.faceVertexUvs[ i ] = []; + return this; - } + }, - } + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength: function ( focalLength ) { - offset = 0; - zLength = vertices.length; + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - while ( offset < zLength ) { + this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - vertex = new THREE.Vector3(); + }, - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { - geometry.vertices.push( vertex ); + var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); - } + return 0.5 * this.getFilmHeight() / vExtentSlope; - offset = 0; - zLength = faces.length; + }, - while ( offset < zLength ) { + getEffectiveFOV: function () { - type = faces[ offset ++ ]; + return exports.Math.RAD2DEG * 2 * Math.atan( + Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + }, - 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 ); + getFilmWidth: function () { - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - if ( isQuad ) { + }, - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + getFilmHeight: function () { - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - offset += 4; + }, - if ( hasMaterial ) { + /** + * 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. + */ + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + this.aspect = fullWidth / fullHeight; - } + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - // to get face <=> uv index correspondence + this.updateProjectionMatrix(); - fi = geometry.faces.length; + }, - if ( hasFaceVertexUv ) { + clearViewOffset: function() { - for ( i = 0; i < nUvLayers; i ++ ) { + this.view = null; + this.updateProjectionMatrix(); - uvLayer = json.uvs[ i ]; + }, - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + updateProjectionMatrix: function () { - for ( j = 0; j < 4; j ++ ) { + var near = this.near, + top = near * Math.tan( + exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - uvIndex = faces[ offset ++ ]; + if ( view !== null ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - uv = new THREE.Vector2( u, v ); + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + } - } + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - } + this.projectionMatrix.makeFrustum( + left, left + width, top - height, top, near, this.far ); - } + }, - if ( hasFaceNormal ) { + toJSON: function ( meta ) { - normalIndex = faces[ offset ++ ] * 3; + var data = Object3D.prototype.toJSON.call( this, meta ); - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + data.object.fov = this.fov; + data.object.zoom = this.zoom; - faceB.normal.copy( faceA.normal ); + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - } + data.object.aspect = this.aspect; - if ( hasFaceVertexNormal ) { + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - for ( i = 0; i < 4; i ++ ) { + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - normalIndex = faces[ offset ++ ] * 3; + return data; - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } + } ); - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - } + function OrthographicCamera ( left, right, top, bottom, near, far ) { + this.isOrthographicCamera = true; - } + Camera.call( this ); + this.type = 'OrthographicCamera'; - if ( hasFaceColor ) { + this.zoom = 1; + this.view = null; - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - } + this.updateProjectionMatrix(); + }; - if ( hasFaceVertexColor ) { + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - for ( i = 0; i < 4; i ++ ) { + constructor: OrthographicCamera, - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + copy: function ( source ) { - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + Camera.prototype.copy.call( this, source ); - } + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - } + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + return this; - } else { + }, - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { - if ( hasMaterial ) { + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + this.updateProjectionMatrix(); - } + }, - // to get face <=> uv index correspondence + clearViewOffset: function() { - fi = geometry.faces.length; + this.view = null; + this.updateProjectionMatrix(); - if ( hasFaceVertexUv ) { + }, - for ( i = 0; i < nUvLayers; i ++ ) { + updateProjectionMatrix: function () { - uvLayer = json.uvs[ i ]; + 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; - geometry.faceVertexUvs[ i ][ fi ] = []; + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - for ( j = 0; j < 3; j ++ ) { + if ( this.view !== null ) { - uvIndex = faces[ offset ++ ]; + var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); + var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); + var scaleW = ( this.right - this.left ) / this.view.width; + var scaleH = ( this.top - this.bottom ) / this.view.height; - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + left += scaleW * ( this.view.offsetX / zoomW ); + right = left + scaleW * ( this.view.width / zoomW ); + top -= scaleH * ( this.view.offsetY / zoomH ); + bottom = top - scaleH * ( this.view.height / zoomH ); - uv = new THREE.Vector2( u, v ); + } - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - } + }, - } + toJSON: function ( meta ) { - } + var data = Object3D.prototype.toJSON.call( this, meta ); - if ( hasFaceNormal ) { + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; - normalIndex = faces[ offset ++ ] * 3; + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + return data; - } + } - if ( hasFaceVertexNormal ) { + } ); - for ( i = 0; i < 3; i ++ ) { + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author tschw + */ - normalIndex = faces[ offset ++ ] * 3; + function WebGLRenderer ( parameters ) { + this.isWebGLRenderer = true; - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + console.log( 'THREE.WebGLRenderer', "80dev" ); - face.vertexNormals.push( normal ); + parameters = parameters || {}; - } + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - } + _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; + var lights = []; - if ( hasFaceColor ) { + var opaqueObjects = []; + var opaqueObjectsLastIndex = - 1; + var transparentObjects = []; + var transparentObjectsLastIndex = - 1; - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + var morphInfluences = new Float32Array( 8 ); - } + var sprites = []; + var lensFlares = []; + // public properties - if ( hasFaceVertexColor ) { + this.domElement = _canvas; + this.context = null; - for ( i = 0; i < 3; i ++ ) { + // clearing - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - } + // scene graph - } + this.sortObjects = true; - geometry.faces.push( face ); + // user-defined clipping - } + this.clippingPlanes = []; + this.localClippingEnabled = false; - } + // physically based shading - } + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - function parseSkin() { + // physical lights - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + this.physicallyCorrectLights = false; - if ( json.skinWeights ) { + // tone mapping - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.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; + // morphs - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - } + // internal properties - } + var _this = this, - if ( json.skinIndices ) { + // internal state cache - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + _currentProgram = null, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, - 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; + _currentScissor = new Vector4(), + _currentScissorTest = null, - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); + _currentViewport = new Vector4(), - } + // - } + _usedTextureUnits = 0, - geometry.bones = json.bones; + // - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + _clearColor = new Color( 0x000000 ), + _clearAlpha = 0, - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + _width = _canvas.width, + _height = _canvas.height, - } + _pixelRatio = 1, - } + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - function parseMorphing( scale ) { + _viewport = new Vector4( 0, 0, _width, _height ), - if ( json.morphTargets !== undefined ) { + // frustum - for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { + _frustum = new Frustum(), - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + // clipping - var dstVertices = geometry.morphTargets[ i ].vertices; - var srcVertices = json.morphTargets[ i ].vertices; + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + _sphere = new Sphere(), - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + // camera matrices cache - dstVertices.push( vertex ); + _projScreenMatrix = new Matrix4(), - } + _vector3 = new Vector3(), - } + // light arrays cache - } + _lights = { - if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { + hash: '', - console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], - var faces = geometry.faces; - var morphColors = json.morphColors[ 0 ].colors; + shadows: [] - for ( var i = 0, l = faces.length; i < l; i ++ ) { + }, - faces[ i ].color.fromArray( morphColors, i * 3 ); + // info - } + _infoRender = { - } + calls: 0, + vertices: 0, + faces: 0, + points: 0 - } + }; - function parseAnimations() { + this.info = { - var outputAnimations = []; + render: _infoRender, + memory: { - // parse old style Bone/Hierarchy animations - var animations = []; + geometries: 0, + textures: 0 - if ( json.animation !== undefined ) { + }, + programs: null - animations.push( json.animation ); + }; - } - if ( json.animations !== undefined ) { + // initialize - if ( json.animations.length ) { + var _gl; - animations = animations.concat( json.animations ); + try { - } else { + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - animations.push( json.animations ); + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - } + if ( _gl === null ) { - } + if ( _canvas.getContext( 'webgl' ) !== null ) { - for ( var i = 0; i < animations.length; i ++ ) { + throw 'Error creating WebGL context with your selected attributes.'; - var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones ); - if ( clip ) outputAnimations.push( clip ); + } else { - } + throw 'Error creating WebGL context.'; - // parse implicit morph animations - if ( geometry.morphTargets ) { + } - // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); - outputAnimations = outputAnimations.concat( morphAnimationClips ); + } - } + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; + if ( _gl.getShaderPrecisionFormat === undefined ) { - } + _gl.getShaderPrecisionFormat = function () { - if ( json.materials === undefined || json.materials.length === 0 ) { + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - return { geometry: geometry }; + }; - } else { + } - var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - return { geometry: geometry, materials: materials }; + } catch ( error ) { - } + console.error( 'THREE.WebGLRenderer: ' + error ); - } + } -} ); + var extensions = new WebGLExtensions( _gl ); -// File:src/loaders/LoadingManager.js + extensions.get( 'WEBGL_depth_texture' ); + 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' ); + extensions.get( 'ANGLE_instanced_arrays' ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( extensions.get( 'OES_element_index_uint' ) ) { -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { + BufferGeometry.MaxIndex = 4294967296; - var scope = this; + } - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + var state = new WebGLState( _gl, extensions, paramThreeToGL ); + var properties = new WebGLProperties(); + var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); + var objects = new WebGLObjects( _gl, properties, this.info ); + var programCache = new WebGLPrograms( this, capabilities ); + var lightCache = new WebGLLights(); - this.itemStart = function ( url ) { + this.info.programs = programCache.programs; - itemsTotal ++; + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); - if ( isLoading === false ) { + // - if ( scope.onStart !== undefined ) { + var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var backgroundCamera2 = new PerspectiveCamera(); + var backgroundPlaneMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + ); + var backgroundBoxShader = exports.ShaderLib[ 'cube' ]; + var backgroundBoxMesh = new Mesh( + new BoxBufferGeometry( 5, 5, 5 ), + new ShaderMaterial( { + uniforms: backgroundBoxShader.uniforms, + vertexShader: backgroundBoxShader.vertexShader, + fragmentShader: backgroundBoxShader.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); - scope.onStart( url, itemsLoaded, itemsTotal ); + // - } + function getTargetPixelRatio() { - } + return _currentRenderTarget === null ? _pixelRatio : 1; - isLoading = true; + } - }; + function glClearColor( r, g, b, a ) { - this.itemEnd = function ( url ) { + if ( _premultipliedAlpha === true ) { - itemsLoaded ++; + r *= a; g *= a; b *= a; - if ( scope.onProgress !== undefined ) { + } - scope.onProgress( url, itemsLoaded, itemsTotal ); + state.clearColor( r, g, b, a ); - } + } - if ( itemsLoaded === itemsTotal ) { + function setDefaultGLState() { - isLoading = false; + state.init(); - if ( scope.onLoad !== undefined ) { + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - scope.onLoad(); + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } + } - } + function resetGLState() { - }; + _currentProgram = null; + _currentCamera = null; - this.itemError = function ( url ) { + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - if ( scope.onError !== undefined ) { + state.reset(); - scope.onError( url ); + } - } + setDefaultGLState(); - }; + this.context = _gl; + this.capabilities = capabilities; + this.extensions = extensions; + this.properties = properties; + this.state = state; -}; + // shadow map -THREE.DefaultLoadingManager = new THREE.LoadingManager(); + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); -// File:src/loaders/BufferGeometryLoader.js + this.shadowMap = shadowMap; -/** - * @author mrdoob / http://mrdoob.com/ - */ -THREE.BufferGeometryLoader = function ( manager ) { + // Plugins - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); -}; + // API -Object.assign( THREE.BufferGeometryLoader.prototype, { + this.getContext = function () { - load: function ( url, onLoad, onProgress, onError ) { + return _gl; - var scope = this; + }; - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + this.getContextAttributes = function () { - onLoad( scope.parse( JSON.parse( text ) ) ); + return _gl.getContextAttributes(); - }, onProgress, onError ); + }; - }, + this.forceContextLoss = function () { - parse: function ( json ) { + extensions.get( 'WEBGL_lose_context' ).loseContext(); - var geometry = new THREE.BufferGeometry(); + }; - var index = json.data.index; + this.getMaxAnisotropy = function () { - var TYPED_ARRAYS = { - 'Int8Array': Int8Array, - 'Uint8Array': Uint8Array, - 'Uint8ClampedArray': Uint8ClampedArray, - 'Int16Array': Int16Array, - 'Uint16Array': Uint16Array, - 'Int32Array': Int32Array, - 'Uint32Array': Uint32Array, - 'Float32Array': Float32Array, - 'Float64Array': Float64Array - }; + return capabilities.getMaxAnisotropy(); - if ( index !== undefined ) { + }; - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) ); + this.getPrecision = function () { - } + return capabilities.precision; - var attributes = json.data.attributes; + }; - for ( var key in attributes ) { + this.getPixelRatio = function () { - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + return _pixelRatio; - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + }; - } + this.setPixelRatio = function ( value ) { - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if ( value === undefined ) return; - if ( groups !== undefined ) { + _pixelRatio = value; - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + this.setSize( _viewport.z, _viewport.w, false ); - var group = groups[ i ]; + }; - geometry.addGroup( group.start, group.count, group.materialIndex ); + this.getSize = function () { - } + return { + width: _width, + height: _height + }; - } + }; - var boundingSphere = json.data.boundingSphere; + this.setSize = function ( width, height, updateStyle ) { - if ( boundingSphere !== undefined ) { + _width = width; + _height = height; - var center = new THREE.Vector3(); + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; - if ( boundingSphere.center !== undefined ) { + if ( updateStyle !== false ) { - center.fromArray( boundingSphere.center ); + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - } + } - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + this.setViewport( 0, 0, width, height ); - } + }; - return geometry; + this.setViewport = function ( x, y, width, height ) { - } + state.viewport( _viewport.set( x, y, width, height ) ); -} ); + }; -// File:src/loaders/MaterialLoader.js + this.setScissor = function ( x, y, width, height ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + state.scissor( _scissor.set( x, y, width, height ) ); -THREE.MaterialLoader = function ( manager ) { + }; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.textures = {}; + this.setScissorTest = function ( boolean ) { -}; + state.setScissorTest( _scissorTest = boolean ); -Object.assign( THREE.MaterialLoader.prototype, { + }; - load: function ( url, onLoad, onProgress, onError ) { + // Clearing - var scope = this; + this.getClearColor = function () { - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + return _clearColor; - onLoad( scope.parse( JSON.parse( text ) ) ); + }; - }, onProgress, onError ); + this.setClearColor = function ( color, alpha ) { - }, + _clearColor.set( color ); - setTextures: function ( value ) { + _clearAlpha = alpha !== undefined ? alpha : 1; - this.textures = value; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - }, + }; - getTexture: function ( name ) { + this.getClearAlpha = function () { - var textures = this.textures; + return _clearAlpha; - if ( textures[ name ] === undefined ) { + }; - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + this.setClearAlpha = function ( alpha ) { - } + _clearAlpha = alpha; - return textures[ name ]; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - }, + }; - parse: function ( json ) { - - var material = new THREE[ json.type ]; - - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.roughness !== undefined ) material.roughness = json.roughness; - if ( json.metalness !== undefined ) material.metalness = json.metalness; - 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.alphaTest !== undefined ) material.alphaTest = json.alphaTest; - if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; - if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; - if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - - // for PointsMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - - // maps - - if ( json.map !== undefined ) material.map = this.getTexture( json.map ); - - if ( json.alphaMap !== undefined ) { - - material.alphaMap = this.getTexture( json.alphaMap ); - material.transparent = true; + this.clear = function ( color, depth, stencil ) { - } + var bits = 0; - if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + 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; - if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); - if ( json.normalScale !== undefined ) { + _gl.clear( bits ); - var normalScale = json.normalScale; + }; - if ( Array.isArray( normalScale ) === false ) { + this.clearColor = function () { - // Blender exporter used to export a scalar. See #7459 + this.clear( true, false, false ); - normalScale = [ normalScale, normalScale ]; + }; - } + this.clearDepth = function () { - material.normalScale = new THREE.Vector2().fromArray( normalScale ); + this.clear( false, true, false ); - } + }; - if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + this.clearStencil = function () { - if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); + this.clear( false, false, true ); - if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + }; - if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - if ( json.envMap !== undefined ) { + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - material.envMap = this.getTexture( json.envMap ); - material.combine = THREE.MultiplyOperation; + }; - } + // Reset - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + this.resetGLState = resetGLState; - if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + this.dispose = function() { - if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + transparentObjects = []; + transparentObjectsLastIndex = -1; + opaqueObjects = []; + opaqueObjectsLastIndex = -1; - // MultiMaterial + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - if ( json.materials !== undefined ) { + }; - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + // Events - material.materials.push( this.parse( json.materials[ i ] ) ); + function onContextLost( event ) { - } + event.preventDefault(); - } + resetGLState(); + setDefaultGLState(); - return material; + properties.clear(); - } + } -} ); + function onMaterialDispose( event ) { -// File:src/loaders/ObjectLoader.js + var material = event.target; -/** - * @author mrdoob / http://mrdoob.com/ - */ + material.removeEventListener( 'dispose', onMaterialDispose ); -THREE.ObjectLoader = function ( manager ) { + deallocateMaterial( material ); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.texturePath = ''; + } -}; + // Buffer deallocation -Object.assign( THREE.ObjectLoader.prototype, { + function deallocateMaterial( material ) { - load: function ( url, onLoad, onProgress, onError ) { + releaseMaterialProgramReference( material ); - if ( this.texturePath === '' ) { + properties.delete( material ); - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + } - } - var scope = this; + function releaseMaterialProgramReference( material ) { - var loader = new THREE.XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + var programInfo = properties.get( material ).program; - scope.parse( JSON.parse( text ), onLoad ); + material.program = undefined; - }, onProgress, onError ); + if ( programInfo !== undefined ) { - }, + programCache.releaseProgram( programInfo ); - setTexturePath: function ( value ) { + } - this.texturePath = value; + } - }, + // Buffer rendering - setCrossOrigin: function ( value ) { + this.renderBufferImmediate = function ( object, program, material ) { - this.crossOrigin = value; + state.initAttributes(); - }, + var buffers = properties.get( object ); - parse: function ( json, onLoad ) { + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - var geometries = this.parseGeometries( json.geometries ); + var attributes = program.getAttributes(); - var images = this.parseImages( json.images, function () { + if ( object.hasPositions ) { - if ( onLoad !== undefined ) onLoad( object ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - } ); + state.enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); + } - var object = this.parseObject( json.object, geometries, materials ); + if ( object.hasNormals ) { - if ( json.animations ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - object.animations = this.parseAnimations( json.animations ); + if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { - } + for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { - if ( json.images === undefined || json.images.length === 0 ) { + var array = object.normalArray; - if ( onLoad !== undefined ) onLoad( object ); + var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; + var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; + var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; - } + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - return object; + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - }, + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - parseGeometries: function ( json ) { + } - var geometries = {}; + } - if ( json !== undefined ) { + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + state.enableAttribute( attributes.normal ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - var geometry; - var data = json[ i ]; + } - switch ( data.type ) { + if ( object.hasUvs && material.map ) { - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + state.enableAttribute( attributes.uv ); - break; + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + } - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + if ( object.hasColors && material.vertexColors !== NoColors ) { - break; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - case 'CircleGeometry': - case 'CircleBufferGeometry': + state.enableAttribute( attributes.color ); - geometry = new THREE[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); - - break; - - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - geometry = new THREE[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + } - break; + state.disableUnusedAttributes(); - case 'ConeGeometry': - case 'ConeBufferGeometry': + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - geometry = new THREE [ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + object.count = 0; - break; + }; - case 'SphereGeometry': - case 'SphereBufferGeometry': + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - geometry = new THREE[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + setMaterial( material ); - break; + var program = setProgram( camera, fog, material, object ); - case 'DodecahedronGeometry': - case 'IcosahedronGeometry': - case 'OctahedronGeometry': - case 'TetrahedronGeometry': + var updateBuffers = false; + var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; - geometry = new THREE[ data.type ]( - data.radius, - data.detail - ); + if ( geometryProgram !== _currentGeometryProgram ) { - break; + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - case 'RingGeometry': - case 'RingBufferGeometry': + } - geometry = new THREE[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + // morph targets - break; + var morphTargetInfluences = object.morphTargetInfluences; - case 'TorusGeometry': - case 'TorusBufferGeometry': + if ( morphTargetInfluences !== undefined ) { - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + var activeInfluences = []; - break; + for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + var influence = morphTargetInfluences[ i ]; + activeInfluences.push( [ influence, i ] ); - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + } - break; + activeInfluences.sort( absNumericalSort ); - case 'LatheGeometry': - case 'LatheBufferGeometry': + if ( activeInfluences.length > 8 ) { - geometry = new THREE[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + activeInfluences.length = 8; - break; + } - case 'BufferGeometry': + var morphAttributes = geometry.morphAttributes; - geometry = bufferGeometryLoader.parse( data ); + for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { - break; + var influence = activeInfluences[ i ]; + morphInfluences[ i ] = influence[ 0 ]; - case 'Geometry': + if ( influence[ 0 ] !== 0 ) { - geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; + var index = influence[ 1 ]; - break; + if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); + if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); - default: + } else { - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); + if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); - continue; + } - } + } - geometry.uuid = data.uuid; + program.getUniforms().setValue( + _gl, 'morphTargetInfluences', morphInfluences ); - if ( data.name !== undefined ) geometry.name = data.name; + updateBuffers = true; - geometries[ data.uuid ] = geometry; + } - } + // - } + var index = geometry.index; + var position = geometry.attributes.position; - return geometries; + if ( material.wireframe === true ) { - }, + index = objects.getWireframeAttribute( geometry ); - parseMaterials: function ( json, textures ) { + } - var materials = {}; + var renderer; - if ( json !== undefined ) { + if ( index !== null ) { - var loader = new THREE.MaterialLoader(); - loader.setTextures( textures ); + renderer = indexedBufferRenderer; + renderer.setIndex( index ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } else { - var material = loader.parse( json[ i ] ); - materials[ material.uuid ] = material; + renderer = bufferRenderer; - } + } - } + if ( updateBuffers ) { - return materials; + setupVertexAttributes( material, program, geometry ); - }, + if ( index !== null ) { - parseAnimations: function ( json ) { + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); - var animations = []; + } - for ( var i = 0; i < json.length; i ++ ) { + } - var clip = THREE.AnimationClip.parse( json[ i ] ); + // - animations.push( clip ); + var dataStart = 0; + var dataCount = Infinity; - } + if ( index !== null ) { - return animations; + dataCount = index.count; - }, + } else if ( position !== undefined ) { - parseImages: function ( json, onLoad ) { + dataCount = position.count; - var scope = this; - var images = {}; + } - function loadImage( url ) { + var rangeStart = geometry.drawRange.start; + var rangeCount = geometry.drawRange.count; - scope.manager.itemStart( url ); + var groupStart = group !== null ? group.start : 0; + var groupCount = group !== null ? group.count : Infinity; - return loader.load( url, function () { + var drawStart = Math.max( dataStart, rangeStart, groupStart ); + var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - scope.manager.itemEnd( url ); + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - } ); + // - } + if ( (object && object.isMesh) ) { - if ( json !== undefined && json.length > 0 ) { + if ( material.wireframe === true ) { - var manager = new THREE.LoadingManager( onLoad ); + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); - var loader = new THREE.ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + } else { - for ( var i = 0, l = json.length; i < l; i ++ ) { + switch ( object.drawMode ) { - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; - images[ image.uuid ] = loadImage( path ); + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - } + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; - } + } - return images; + } - }, - parseTextures: function ( json, images ) { + } else if ( (object && object.isLine) ) { - function parseConstant( value ) { + var lineWidth = material.linewidth; - if ( typeof( value ) === 'number' ) return value; + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - return THREE[ value ]; + if ( (object && object.isLineSegments) ) { - } + renderer.setMode( _gl.LINES ); - var textures = {}; + } else { - if ( json !== undefined ) { + renderer.setMode( _gl.LINE_STRIP ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var data = json[ i ]; + } else if ( (object && object.isPoints) ) { - if ( data.image === undefined ) { + renderer.setMode( _gl.POINTS ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + } - } + if ( (geometry && geometry.isInstancedBufferGeometry) ) { - if ( images[ data.image ] === undefined ) { + if ( geometry.maxInstancedCount > 0 ) { - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + renderer.renderInstances( geometry, drawStart, drawCount ); - } + } - var texture = new THREE.Texture( images[ data.image ] ); - texture.needsUpdate = true; + } else { - texture.uuid = data.uuid; + renderer.render( drawStart, drawCount ); - if ( data.name !== undefined ) texture.name = data.name; + } - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); + }; - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.wrap !== undefined ) { + function setupVertexAttributes( material, program, geometry, startIndex ) { - texture.wrapS = parseConstant( data.wrap[ 0 ] ); - texture.wrapT = parseConstant( data.wrap[ 1 ] ); + var extension; - } + if ( (geometry && geometry.isInstancedBufferGeometry) ) { - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + extension = extensions.get( 'ANGLE_instanced_arrays' ); - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + if ( extension === null ) { - textures[ data.uuid ] = texture; + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - } + } - } + } - return textures; + if ( startIndex === undefined ) startIndex = 0; - }, + state.initAttributes(); - parseObject: function () { + var geometryAttributes = geometry.attributes; - var matrix = new THREE.Matrix4(); + var programAttributes = program.getAttributes(); - return function parseObject( data, geometries, materials ) { + var materialDefaultAttributeValues = material.defaultAttributeValues; - var object; + for ( var name in programAttributes ) { - function getGeometry( name ) { + var programAttribute = programAttributes[ name ]; - if ( geometries[ name ] === undefined ) { + if ( programAttribute >= 0 ) { - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + var geometryAttribute = geometryAttributes[ name ]; - } + if ( geometryAttribute !== undefined ) { - return geometries[ name ]; + var type = _gl.FLOAT; + var array = geometryAttribute.array; + var normalized = geometryAttribute.normalized; - } + if ( array instanceof Float32Array ) { - function getMaterial( name ) { + type = _gl.FLOAT; - if ( name === undefined ) return undefined; + } else if ( array instanceof Float64Array ) { - if ( materials[ name ] === undefined ) { + console.warn("Unsupported data buffer format: Float64Array"); - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + } else if ( array instanceof Uint16Array ) { - } + type = _gl.UNSIGNED_SHORT; - return materials[ name ]; + } else if ( array instanceof Int16Array ) { - } + type = _gl.SHORT; - switch ( data.type ) { + } else if ( array instanceof Uint32Array ) { - case 'Scene': + type = _gl.UNSIGNED_INT; - object = new THREE.Scene(); + } else if ( array instanceof Int32Array ) { - break; + type = _gl.INT; - case 'PerspectiveCamera': + } else if ( array instanceof Int8Array ) { - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + type = _gl.BYTE; - if ( data.focus !== undefined ) object.focus = data.focus; - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; - if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + } else if ( array instanceof Uint8Array ) { - break; + type = _gl.UNSIGNED_BYTE; - case 'OrthographicCamera': + } - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + var size = geometryAttribute.itemSize; + var buffer = objects.getAttributeBuffer( geometryAttribute ); - break; + if ( (geometryAttribute && geometryAttribute.isInterleavedBufferAttribute) ) { - case 'AmbientLight': + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - object = new THREE.AmbientLight( data.color, data.intensity ); + if ( (data && data.isInstancedInterleavedBuffer) ) { - break; + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); - case 'DirectionalLight': + if ( geometry.maxInstancedCount === undefined ) { - object = new THREE.DirectionalLight( data.color, data.intensity ); + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - break; + } - case 'PointLight': + } else { - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + state.enableAttribute( programAttribute ); - break; + } - case 'SpotLight': + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + } else { - break; + if ( (geometryAttribute && geometryAttribute.isInstancedBufferAttribute) ) { - case 'HemisphereLight': + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + if ( geometry.maxInstancedCount === undefined ) { - break; + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - case 'Mesh': + } - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + } else { - if ( geometry.bones && geometry.bones.length > 0 ) { + state.enableAttribute( programAttribute ); - object = new THREE.SkinnedMesh( geometry, material ); + } - } else { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); - object = new THREE.Mesh( geometry, material ); + } - } + } else if ( materialDefaultAttributeValues !== undefined ) { - break; + var value = materialDefaultAttributeValues[ name ]; - case 'LOD': + if ( value !== undefined ) { - object = new THREE.LOD(); + switch ( value.length ) { - break; + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - case 'Line': + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - break; + default: + _gl.vertexAttrib1fv( programAttribute, value ); - case 'PointCloud': - case 'Points': + } - object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + } - break; + } - case 'Sprite': + } - object = new THREE.Sprite( getMaterial( data.material ) ); + } - break; + state.disableUnusedAttributes(); - case 'Group': + } - object = new THREE.Group(); + // Sorting - break; + function absNumericalSort( a, b ) { - default: + return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); - object = new THREE.Object3D(); + } - } + function painterSortStable ( a, b ) { - object.uuid = data.uuid; + if ( a.object.renderOrder !== b.object.renderOrder ) { - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + return a.object.renderOrder - b.object.renderOrder; - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { - } else { + return a.material.program.id - b.material.program.id; - 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 ); + } else if ( a.material.id !== b.material.id ) { - } + return a.material.id - b.material.id; - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + } else if ( a.z !== b.z ) { - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + return a.z - b.z; - if ( data.children !== undefined ) { + } else { - for ( var child in data.children ) { + return a.id - b.id; - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + } - } + } - } + function reversePainterSortStable ( a, b ) { - if ( data.type === 'LOD' ) { + if ( a.object.renderOrder !== b.object.renderOrder ) { - var levels = data.levels; + return a.object.renderOrder - b.object.renderOrder; - for ( var l = 0; l < levels.length; l ++ ) { + } if ( a.z !== b.z ) { - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + return b.z - a.z; - if ( child !== undefined ) { + } else { - object.addLevel( child, level.distance ); + return a.id - b.id; - } + } - } + } - } + // Rendering - return object; + this.render = function ( scene, camera, renderTarget, forceClear ) { - }; + if ( (camera && camera.isCamera) === false ) { - }() + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; -} ); + } -// File:src/loaders/TextureLoader.js + var fog = scene.fog; -/** - * @author mrdoob / http://mrdoob.com/ - */ + // reset caching for this frame -THREE.TextureLoader = function ( manager ) { + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + // update scene graph -}; + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); -Object.assign( THREE.TextureLoader.prototype, { + // update camera matrices and frustum - load: function ( url, onLoad, onProgress, onError ) { + if ( camera.parent === null ) camera.updateMatrixWorld(); - var texture = new THREE.Texture(); + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - var loader = new THREE.ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); - loader.load( url, function ( image ) { + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + lights.length = 0; - texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat; - texture.image = image; - texture.needsUpdate = true; + opaqueObjectsLastIndex = - 1; + transparentObjectsLastIndex = - 1; - if ( onLoad !== undefined ) { + sprites.length = 0; + lensFlares.length = 0; - onLoad( texture ); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - } + projectObject( scene, camera ); - }, onProgress, onError ); + opaqueObjects.length = opaqueObjectsLastIndex + 1; + transparentObjects.length = transparentObjectsLastIndex + 1; - return texture; + if ( _this.sortObjects === true ) { - }, + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - setCrossOrigin: function ( value ) { + } - this.crossOrigin = value; - return this; + // - }, + if ( _clippingEnabled ) _clipping.beginShadows(); - setPath: function ( value ) { + setupShadows( lights ); - this.path = value; - return this; + shadowMap.render( scene, camera ); - } + setupLights( lights, camera ); -} ); + if ( _clippingEnabled ) _clipping.endShadows(); -// File:src/loaders/CubeTextureLoader.js + // -/** - * @author mrdoob / http://mrdoob.com/ - */ + _infoRender.calls = 0; + _infoRender.vertices = 0; + _infoRender.faces = 0; + _infoRender.points = 0; -THREE.CubeTextureLoader = function ( manager ) { + if ( renderTarget === undefined ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + renderTarget = null; -}; + } -Object.assign( THREE.CubeTextureLoader.prototype, { + this.setRenderTarget( renderTarget ); - load: function ( urls, onLoad, onProgress, onError ) { + // - var texture = new THREE.CubeTexture(); + var background = scene.background; - var loader = new THREE.ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + if ( background === null ) { - var loaded = 0; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - function loadTexture( i ) { + } else if ( (background && background.isColor) ) { - loader.load( urls[ i ], function ( image ) { + glClearColor( background.r, background.g, background.b, 1 ); - texture.images[ i ] = image; + } - loaded ++; + if ( this.autoClear || forceClear ) { - if ( loaded === 6 ) { + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + if ( (background && background.isCubeTexture) ) { - } + backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); - }, undefined, onError ); + backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); + backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); - } + backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; + backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); - for ( var i = 0; i < urls.length; ++ i ) { + objects.update( backgroundBoxMesh ); - loadTexture( i ); + _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - } + } else if ( (background && background.isTexture) ) { - return texture; + backgroundPlaneMesh.material.map = background; - }, + objects.update( backgroundPlaneMesh ); - setCrossOrigin: function ( value ) { + _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); - this.crossOrigin = value; - return this; + } - }, + // - setPath: function ( value ) { + if ( scene.overrideMaterial ) { - this.path = value; - return this; + var overrideMaterial = scene.overrideMaterial; - } + renderObjects( opaqueObjects, camera, fog, overrideMaterial ); + renderObjects( transparentObjects, camera, fog, overrideMaterial ); -} ); + } else { -// File:src/loaders/BinaryTextureLoader.js + // opaque pass (front-to-back order) -/** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + state.setBlending( NoBlending ); + renderObjects( opaqueObjects, camera, fog ); -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) { + // transparent pass (back-to-front order) - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + renderObjects( transparentObjects, camera, fog ); - // override in sub classes - this._parser = null; + } -}; + // custom render plugins (post pass) -Object.assign( THREE.BinaryTextureLoader.prototype, { + spritePlugin.render( scene, camera ); + lensFlarePlugin.render( scene, camera, _currentViewport ); - load: function ( url, onLoad, onProgress, onError ) { + // Generate mipmap if we're using any kind of mipmap filtering - var scope = this; + if ( renderTarget ) { - var texture = new THREE.DataTexture(); + textures.updateRenderTargetMipmap( renderTarget ); - var loader = new THREE.XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); + } - loader.load( url, function ( buffer ) { + // Ensure depth buffer writing is enabled so it can be cleared on next render - var texData = scope._parser( buffer ); + state.setDepthTest( true ); + state.setDepthWrite( true ); + state.setColorWrite( true ); - if ( ! texData ) return; + // _gl.finish(); - if ( undefined !== texData.image ) { + }; - texture.image = texData.image; + function pushRenderItem( object, geometry, material, z, group ) { - } else if ( undefined !== texData.data ) { + var array, index; - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + // allocate the next position in the appropriate array - } + if ( material.transparent ) { - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + array = transparentObjects; + index = ++ transparentObjectsLastIndex; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + } else { - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + array = opaqueObjects; + index = ++ opaqueObjectsLastIndex; - if ( undefined !== texData.format ) { + } - texture.format = texData.format; + // recycle existing render item or grow the array - } - if ( undefined !== texData.type ) { + var renderItem = array[ index ]; - texture.type = texData.type; + if ( renderItem !== undefined ) { - } + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.z = _vector3.z; + renderItem.group = group; - if ( undefined !== texData.mipmaps ) { + } else { - texture.mipmaps = texData.mipmaps; + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + z: _vector3.z, + group: group + }; - } + // assert( index === array.length ); + array.push( renderItem ); - if ( 1 === texData.mipmapCount ) { + } - texture.minFilter = THREE.LinearFilter; + } - } + // TODO Duplicated code (Frustum) - texture.needsUpdate = true; + function isObjectViewable( object ) { - if ( onLoad ) onLoad( texture, texData ); + var geometry = object.geometry; - }, onProgress, onError ); + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); + _sphere.copy( geometry.boundingSphere ). + applyMatrix4( object.matrixWorld ); - return texture; + return isSphereViewable( _sphere ); - } + } -} ); + function isSpriteViewable( sprite ) { -// File:src/loaders/CompressedTextureLoader.js + _sphere.center.set( 0, 0, 0 ); + _sphere.radius = 0.7071067811865476; + _sphere.applyMatrix4( sprite.matrixWorld ); -/** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + return isSphereViewable( _sphere ); -THREE.CompressedTextureLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + function isSphereViewable( sphere ) { - // override in sub classes - this._parser = null; + if ( ! _frustum.intersectsSphere( sphere ) ) return false; -}; + var numPlanes = _clipping.numPlanes; -Object.assign( THREE.CompressedTextureLoader.prototype, { + if ( numPlanes === 0 ) return true; - load: function ( url, onLoad, onProgress, onError ) { + var planes = _this.clippingPlanes, - var scope = this; + center = sphere.center, + negRad = - sphere.radius, + i = 0; - var images = []; + do { - var texture = new THREE.CompressedTexture(); - texture.image = images; + // out when deeper than radius in the negative halfspace + if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; - var loader = new THREE.XHRLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + } while ( ++ i !== numPlanes ); - function loadTexture( i ) { + return true; - loader.load( url[ i ], function ( buffer ) { + } - var texDatas = scope._parser( buffer, true ); + function projectObject( object, camera ) { - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + if ( object.visible === false ) return; - loaded += 1; + if ( object.layers.test( camera.layers ) ) { - if ( loaded === 6 ) { + if ( (object && object.isLight) ) { - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = THREE.LinearFilter; + lights.push( object ); - texture.format = texDatas.format; - texture.needsUpdate = true; + } else if ( (object && object.isSprite) ) { - if ( onLoad ) onLoad( texture ); + if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { - } + sprites.push( object ); - }, onProgress, onError ); + } - } + } else if ( (object && object.isLensFlare) ) { - if ( Array.isArray( url ) ) { + lensFlares.push( object ); - var loaded = 0; + } else if ( (object && object.isImmediateRenderObject) ) { - for ( var i = 0, il = url.length; i < il; ++ i ) { + if ( _this.sortObjects === true ) { - loadTexture( i ); + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - } + } - } else { + pushRenderItem( object, null, object.material, _vector3.z, null ); - // compressed cubemap texture stored in a single DDS file + } else if ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) { - loader.load( url, function ( buffer ) { + if ( (object && object.isSkinnedMesh) ) { - var texDatas = scope._parser( buffer, true ); + object.skeleton.update(); - if ( texDatas.isCubemap ) { + } - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { - for ( var f = 0; f < faces; f ++ ) { + var material = object.material; - images[ f ] = { mipmaps : [] }; + if ( material.visible === true ) { - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + if ( _this.sortObjects === true ) { - 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; + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - } + } - } + var geometry = objects.update( object ); - } else { + if ( (material && material.isMultiMaterial) ) { - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + var groups = geometry.groups; + var materials = material.materials; - } + for ( var i = 0, l = groups.length; i < l; i ++ ) { - if ( texDatas.mipmapCount === 1 ) { + var group = groups[ i ]; + var groupMaterial = materials[ group.materialIndex ]; - texture.minFilter = THREE.LinearFilter; + if ( groupMaterial.visible === true ) { - } + pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + } - }, onProgress, onError ); + } else { - } + pushRenderItem( object, geometry, material, _vector3.z, null ); - return texture; + } - }, + } - setPath: function ( value ) { + } - this.path = value; - return this; + } - } + } -} ); + var children = object.children; -// File:src/materials/Material.js + for ( var i = 0, l = children.length; i < l; i ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + projectObject( children[ i ], camera ); -THREE.Material = function () { + } - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + } - this.uuid = THREE.Math.generateUUID(); + function renderObjects( renderList, camera, fog, overrideMaterial ) { - this.name = ''; - this.type = 'Material'; + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - this.fog = true; - this.lights = true; + var renderItem = renderList[ i ]; - this.blending = THREE.NormalBlending; - this.side = THREE.FrontSide; - this.shading = THREE.SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = THREE.NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + var object = renderItem.object; + var geometry = renderItem.geometry; + var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; + var group = renderItem.group; - this.opacity = 1; - this.transparent = false; + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + if ( (object && object.isImmediateRenderObject) ) { - this.depthFunc = THREE.LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + setMaterial( material ); - this.clippingPlanes = null; - this.clipShadows = false; + var program = setProgram( camera, fog, material, object ); - this.colorWrite = true; + _currentGeometryProgram = ''; - this.precision = null; // override the renderer's default precision for this material + object.render( function ( object ) { - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + _this.renderBufferImmediate( object, program, material ); - this.alphaTest = 0; - this.premultipliedAlpha = false; + } ); - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + } else { - this.visible = true; + _this.renderBufferDirect( camera, fog, geometry, material, object, group ); - this._needsUpdate = true; + } -}; + } -THREE.Material.prototype = { + } - constructor: THREE.Material, + function initMaterial( material, fog, object ) { - get needsUpdate() { + var materialProperties = properties.get( material ); - return this._needsUpdate; + var parameters = programCache.getParameters( + material, _lights, fog, _clipping.numPlanes, object ); - }, + var code = programCache.getProgramCode( material, parameters ); - set needsUpdate( value ) { + var program = materialProperties.program; + var programChange = true; - if ( value === true ) this.update(); - this._needsUpdate = value; + if ( program === undefined ) { - }, + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - setValues: function ( values ) { + } else if ( program.code !== code ) { - if ( values === undefined ) return; + // changed glsl or parameters + releaseMaterialProgramReference( material ); - for ( var key in values ) { + } else if ( parameters.shaderID !== undefined ) { - var newValue = values[ key ]; + // same glsl and uniform list + return; - if ( newValue === undefined ) { + } else { - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + // only rebuild uniform list + programChange = false; - } + } - var currentValue = this[ key ]; + if ( programChange ) { - if ( currentValue === undefined ) { + if ( parameters.shaderID ) { - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + var shader = exports.ShaderLib[ parameters.shaderID ]; - } + materialProperties.__webglShader = { + name: material.type, + uniforms: exports.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - if ( currentValue instanceof THREE.Color ) { + } else { - currentValue.set( newValue ); + materialProperties.__webglShader = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + } - currentValue.copy( newValue ); + material.__webglShader = materialProperties.__webglShader; - } else if ( key === 'overdraw' ) { + program = programCache.acquireProgram( material, parameters, code ); - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + materialProperties.program = program; + material.program = program; - } else { + } - this[ key ] = newValue; + var attributes = program.getAttributes(); - } + if ( material.morphTargets ) { - } + material.numSupportedMorphTargets = 0; - }, + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - toJSON: function ( meta ) { + if ( attributes[ 'morphTarget' + i ] >= 0 ) { - var isRoot = meta === undefined; + material.numSupportedMorphTargets ++; - if ( isRoot ) { + } - meta = { - textures: {}, - images: {} - }; + } - } + } - var data = { - metadata: { - version: 4.4, - type: 'Material', - generator: 'Material.toJSON' - } - }; + if ( material.morphNormals ) { - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + material.numSupportedMorphNormals = 0; - if ( this.name !== '' ) data.name = this.name; + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - if ( this.color instanceof THREE.Color ) data.color = this.color.getHex(); + if ( attributes[ 'morphNormal' + i ] >= 0 ) { - if ( this.roughness !== undefined ) data.roughness = this.roughness; - if ( this.metalness !== undefined ) data.metalness = this.metalness; + material.numSupportedMorphNormals ++; - if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex(); - if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; + } - if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap instanceof THREE.Texture ) { + } - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + } - } - if ( this.normalMap instanceof THREE.Texture ) { + var uniforms = materialProperties.__webglShader.uniforms; - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale.toArray(); + if ( ! ( (material && material.isShaderMaterial) ) && + ! ( (material && material.isRawShaderMaterial) ) || + material.clipping === true ) { - } - if ( this.displacementMap instanceof THREE.Texture ) { + materialProperties.numClippingPlanes = _clipping.numPlanes; + uniforms.clippingPlanes = _clipping.uniform; - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + } - } - if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + if ( material.lights ) { - if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + // store the light setup it was created for - if ( this.envMap instanceof THREE.Texture ) { + materialProperties.lightsHash = _lights.hash; - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + // wire up the material to this renderer's lighting state - } + uniforms.ambientLightColor.value = _lights.ambient; + uniforms.directionalLights.value = _lights.directional; + uniforms.spotLights.value = _lights.spot; + uniforms.pointLights.value = _lights.point; + uniforms.hemisphereLights.value = _lights.hemi; - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + uniforms.directionalShadowMap.value = _lights.directionalShadowMap; + uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; + uniforms.spotShadowMap.value = _lights.spotShadowMap; + uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; + uniforms.pointShadowMap.value = _lights.pointShadowMap; + uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; - if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending; - if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading; - if ( this.side !== THREE.FrontSide ) data.side = this.side; - if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors; + } - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; - if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; - if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - if ( this.wireframe === true ) data.wireframe = this.wireframe; - if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - // TODO: Copied from Object3D.toJSON + materialProperties.uniformsList = uniformsList; + materialProperties.dynamicUniforms = + exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); - function extractFromCache ( cache ) { + } - var values = []; + function setMaterial( material ) { - for ( var key in cache ) { + if ( material.side !== DoubleSide ) + state.enable( _gl.CULL_FACE ); + else + state.disable( _gl.CULL_FACE ); - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + state.setFlipSided( material.side === BackSide ); - } + if ( material.transparent === true ) { - return values; + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - } + } else { - if ( isRoot ) { + state.setBlending( NoBlending ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + } - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + state.setDepthFunc( material.depthFunc ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); + state.setColorWrite( material.colorWrite ); + state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - } + } - return data; + function setProgram( camera, fog, material, object ) { - }, + _usedTextureUnits = 0; - clone: function () { + var materialProperties = properties.get( material ); - return new this.constructor().copy( this ); + if ( _clippingEnabled ) { - }, + if ( _localClippingEnabled || camera !== _currentCamera ) { - copy: function ( source ) { + var useCache = + camera === _currentCamera && + material.id === _currentMaterialId; - this.name = source.name; + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + _clipping.setState( + material.clippingPlanes, material.clipShadows, + camera, materialProperties, useCache ); - this.fog = source.fog; - this.lights = source.lights; + } - this.blending = source.blending; - this.side = source.side; - this.shading = source.shading; - this.vertexColors = source.vertexColors; + if ( materialProperties.numClippingPlanes !== undefined && + materialProperties.numClippingPlanes !== _clipping.numPlanes ) { - this.opacity = source.opacity; - this.transparent = source.transparent; + material.needsUpdate = true; - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + } - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + } - this.colorWrite = source.colorWrite; + if ( materialProperties.program === undefined ) { - this.precision = source.precision; + material.needsUpdate = true; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + } - this.alphaTest = source.alphaTest; + if ( materialProperties.lightsHash !== undefined && + materialProperties.lightsHash !== _lights.hash ) { - this.premultipliedAlpha = source.premultipliedAlpha; + material.needsUpdate = true; - this.overdraw = source.overdraw; + } - this.visible = source.visible; - this.clipShadows = source.clipShadows; + if ( material.needsUpdate ) { - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + initMaterial( material, fog, object ); + material.needsUpdate = false; - if ( srcPlanes !== null ) { + } - var n = srcPlanes.length; - dstPlanes = new Array( n ); + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - for ( var i = 0; i !== n; ++ i ) - dstPlanes[ i ] = srcPlanes[ i ].clone(); + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.__webglShader.uniforms; - } + if ( program.id !== _currentProgram ) { - this.clippingPlanes = dstPlanes; + _gl.useProgram( program.program ); + _currentProgram = program.id; - return this; + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - }, + } - update: function () { + if ( material.id !== _currentMaterialId ) { - this.dispatchEvent( { type: 'update' } ); + _currentMaterialId = material.id; - }, + refreshMaterial = true; - dispose: function () { + } - this.dispatchEvent( { type: 'dispose' } ); + if ( refreshProgram || camera !== _currentCamera ) { - } + p_uniforms.set( _gl, camera, 'projectionMatrix' ); -}; + if ( capabilities.logarithmicDepthBuffer ) { -Object.assign( THREE.Material.prototype, THREE.EventDispatcher.prototype ); + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); -THREE.MaterialIdCount = 0; + } -// File:src/materials/LineBasicMaterial.js -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + if ( camera !== _currentCamera ) { -THREE.LineBasicMaterial = function ( parameters ) { + _currentCamera = camera; - THREE.Material.call( this ); + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: - this.type = 'LineBasicMaterial'; + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - this.color = new THREE.Color( 0xffffff ); + } - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - this.lights = false; + if ( (material && material.isShaderMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + material.envMap ) { - this.setValues( parameters ); + var uCamPos = p_uniforms.map.cameraPosition; -}; + if ( uCamPos !== undefined ) { -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); -THREE.LineBasicMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); + if ( (material && material.isMeshPhongMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshBasicMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isShaderMaterial) || + material.skinning ) { - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); - return this; + } -}; + p_uniforms.set( _gl, _this, 'toneMappingExposure' ); + p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); -// File:src/materials/LineDashedMaterial.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + // 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.LineDashedMaterial = function ( parameters ) { + if ( material.skinning ) { - THREE.Material.call( this ); + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - this.type = 'LineDashedMaterial'; + var skeleton = object.skeleton; - this.color = new THREE.Color( 0xffffff ); + if ( skeleton ) { - this.linewidth = 1; + if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + p_uniforms.set( _gl, skeleton, 'boneTexture' ); + p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); + p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); - this.lights = false; + } else { - this.setValues( parameters ); + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); -}; + } -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; + } -THREE.LineDashedMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + if ( refreshMaterial ) { - this.color.copy( source.color ); + if ( material.lights ) { - this.linewidth = source.linewidth; + // the current material requires lighting info - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required - return this; + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); -}; + } -// File:src/materials/MeshBasicMaterial.js + // refresh uniforms common to several materials -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + if ( fog && material.fog ) { -THREE.MeshBasicMaterial = function ( parameters ) { + refreshUniformsFog( m_uniforms, fog ); - THREE.Material.call( this ); + } - this.type = 'MeshBasicMaterial'; + if ( (material && material.isMeshBasicMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isMeshDepthMaterial) ) { - this.color = new THREE.Color( 0xffffff ); // emissive + refreshUniformsCommon( m_uniforms, material ); - this.map = null; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + // refresh single material specific uniforms - this.specularMap = null; + if ( (material && material.isLineBasicMaterial) ) { - this.alphaMap = null; + refreshUniformsLine( m_uniforms, material ); - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + } else if ( (material && material.isLineDashedMaterial) ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); - this.skinning = false; - this.morphTargets = false; + } else if ( (material && material.isPointsMaterial) ) { - this.lights = false; + refreshUniformsPoints( m_uniforms, material ); - this.setValues( parameters ); + } else if ( (material && material.isMeshLambertMaterial) ) { -}; + refreshUniformsLambert( m_uniforms, material ); -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; + } else if ( (material && material.isMeshPhongMaterial) ) { -THREE.MeshBasicMaterial.prototype.copy = function ( source ) { + refreshUniformsPhong( m_uniforms, material ); - THREE.Material.prototype.copy.call( this, source ); + } else if ( (material && material.isMeshPhysicalMaterial) ) { - this.color.copy( source.color ); + refreshUniformsPhysical( m_uniforms, material ); - this.map = source.map; + } else if ( (material && material.isMeshStandardMaterial) ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + refreshUniformsStandard( m_uniforms, material ); - this.specularMap = source.specularMap; + } else if ( (material && material.isMeshDepthMaterial) ) { - this.alphaMap = source.alphaMap; + if ( material.displacementMap ) { - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + m_uniforms.displacementMap.value = material.displacementMap; + m_uniforms.displacementScale.value = material.displacementScale; + m_uniforms.displacementBias.value = material.displacementBias; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + } else if ( (material && material.isMeshNormalMaterial) ) { - return this; + m_uniforms.opacity.value = material.opacity; -}; + } -// File:src/materials/MeshDepthMaterial.js + exports.WebGLUniforms.upload( + _gl, materialProperties.uniformsList, m_uniforms, _this ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / https://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + } -THREE.MeshDepthMaterial = function ( parameters ) { - THREE.Material.call( this ); + // common matrices - this.type = 'MeshDepthMaterial'; + p_uniforms.set( _gl, object, 'modelViewMatrix' ); + p_uniforms.set( _gl, object, 'normalMatrix' ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - this.depthPacking = THREE.BasicDepthPacking; - this.skinning = false; - this.morphTargets = false; + // dynamic uniforms - this.map = null; + var dynUniforms = materialProperties.dynamicUniforms; - this.alphaMap = null; + if ( dynUniforms !== null ) { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + exports.WebGLUniforms.evalDynamic( + dynUniforms, m_uniforms, object, camera ); - this.wireframe = false; - this.wireframeLinewidth = 1; + exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); - this.fog = false; - this.lights = false; + } - this.setValues( parameters ); + return program; -}; + } -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; + // Uniforms (refresh uniforms objects) -THREE.MeshDepthMaterial.prototype.copy = function ( source ) { + function refreshUniformsCommon ( uniforms, material ) { - THREE.Material.prototype.copy.call( this, source ); + uniforms.opacity.value = material.opacity; - this.depthPacking = source.depthPacking; + uniforms.diffuse.value = material.color; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + if ( material.emissive ) { - this.map = source.map; + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - this.alphaMap = source.alphaMap; + } - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + uniforms.map.value = material.map; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + if ( material.aoMap ) { - return this; + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; -}; + } -// File:src/materials/MeshLambertMaterial.js + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + var uvScaleMap; -THREE.MeshLambertMaterial = function ( parameters ) { + if ( material.map ) { - THREE.Material.call( this ); + uvScaleMap = material.map; - this.type = 'MeshLambertMaterial'; + } else if ( material.specularMap ) { - this.color = new THREE.Color( 0xffffff ); // diffuse + uvScaleMap = material.specularMap; - this.map = null; + } else if ( material.displacementMap ) { - this.lightMap = null; - this.lightMapIntensity = 1.0; + uvScaleMap = material.displacementMap; - this.aoMap = null; - this.aoMapIntensity = 1.0; + } else if ( material.normalMap ) { - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + uvScaleMap = material.normalMap; - this.specularMap = null; + } else if ( material.bumpMap ) { - this.alphaMap = null; + uvScaleMap = material.bumpMap; - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + } else if ( material.roughnessMap ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + uvScaleMap = material.roughnessMap; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + } else if ( material.metalnessMap ) { - this.setValues( parameters ); + uvScaleMap = material.metalnessMap; -}; + } else if ( material.alphaMap ) { -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; + uvScaleMap = material.alphaMap; -THREE.MeshLambertMaterial.prototype.copy = function ( source ) { + } else if ( material.emissiveMap ) { - THREE.Material.prototype.copy.call( this, source ); + uvScaleMap = material.emissiveMap; - this.color.copy( source.color ); + } - this.map = source.map; + if ( uvScaleMap !== undefined ) { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + // backwards compatibility + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + uvScaleMap = uvScaleMap.texture; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + } - this.specularMap = source.specularMap; + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - this.alphaMap = source.alphaMap; + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + uniforms.envMap.value = material.envMap; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + // don't flip CubeTexture envMaps, flip everything else: + // WebGLRenderTargetCube will be flipped for backwards compatibility + // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture + // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future + uniforms.flipEnvMap.value = ( ! ( (material.envMap && material.envMap.isCubeTexture) ) ) ? 1 : - 1; - return this; + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; -}; + } -// File:src/materials/MeshNormalMaterial.js + function refreshUniformsLine ( uniforms, material ) { -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; -THREE.MeshNormalMaterial = function ( parameters ) { + } - THREE.Material.call( this, parameters ); + function refreshUniformsDash ( uniforms, material ) { - this.type = 'MeshNormalMaterial'; + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - this.wireframe = false; - this.wireframeLinewidth = 1; + } - this.fog = false; - this.lights = false; - this.morphTargets = false; + function refreshUniformsPoints ( uniforms, material ) { - this.setValues( parameters ); + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * _pixelRatio; + uniforms.scale.value = _canvas.clientHeight * 0.5; -}; + uniforms.map.value = material.map; -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; + if ( material.map !== null ) { -THREE.MeshNormalMaterial.prototype.copy = function ( source ) { + var offset = material.map.offset; + var repeat = material.map.repeat; - THREE.Material.prototype.copy.call( this, source ); + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + } - return this; + } -}; + function refreshUniformsFog ( uniforms, fog ) { -// File:src/materials/MeshPhongMaterial.js + uniforms.fogColor.value = fog.color; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + if ( (fog && fog.isFog) ) { -THREE.MeshPhongMaterial = function ( parameters ) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - THREE.Material.call( this ); + } else if ( (fog && fog.isFogExp2) ) { - this.type = 'MeshPhongMaterial'; + uniforms.fogDensity.value = fog.density; - this.color = new THREE.Color( 0xffffff ); // diffuse - this.specular = new THREE.Color( 0x111111 ); - this.shininess = 30; + } - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + function refreshUniformsLambert ( uniforms, material ) { - this.aoMap = null; - this.aoMapIntensity = 1.0; + if ( material.lightMap ) { - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - this.bumpMap = null; - this.bumpScale = 1; + } - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + if ( material.emissiveMap ) { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uniforms.emissiveMap.value = material.emissiveMap; - this.specularMap = null; + } - this.alphaMap = null; + } - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + function refreshUniformsPhong ( uniforms, material ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + uniforms.specular.value = material.specular; + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + if ( material.lightMap ) { - this.setValues( parameters ); + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; -}; + } -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; + if ( material.emissiveMap ) { -THREE.MeshPhongMaterial.prototype.copy = function ( source ) { + uniforms.emissiveMap.value = material.emissiveMap; - THREE.Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + if ( material.bumpMap ) { - this.map = source.map; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + } - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( material.normalMap ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + if ( material.displacementMap ) { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - this.specularMap = source.specularMap; + } - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + function refreshUniformsStandard ( uniforms, material ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + if ( material.roughnessMap ) { - return this; + uniforms.roughnessMap.value = material.roughnessMap; -}; + } -// File:src/materials/MeshStandardMaterial.js + if ( material.metalnessMap ) { -/** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * roughness: , - * metalness: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * roughnessMap: new THREE.Texture( ), - * - * metalnessMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * envMapIntensity: - * - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + uniforms.metalnessMap.value = material.metalnessMap; -THREE.MeshStandardMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + if ( material.lightMap ) { - this.defines = { 'STANDARD': '' }; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - this.type = 'MeshStandardMaterial'; + } - this.color = new THREE.Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + if ( material.emissiveMap ) { - this.map = null; + uniforms.emissiveMap.value = material.emissiveMap; - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + if ( material.bumpMap ) { - this.emissive = new THREE.Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - this.bumpMap = null; - this.bumpScale = 1; + } - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + if ( material.normalMap ) { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - this.roughnessMap = null; + } - this.metalnessMap = null; + if ( material.displacementMap ) { - this.alphaMap = null; + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - this.envMap = null; - this.envMapIntensity = 1.0; + } - this.refractionRatio = 0.98; + if ( material.envMap ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + } - this.setValues( parameters ); + } -}; + function refreshUniformsPhysical ( uniforms, material ) { -THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial; + uniforms.clearCoat.value = material.clearCoat; + uniforms.clearCoatRoughness.value = material.clearCoatRoughness; -THREE.MeshStandardMaterial.prototype.copy = function ( source ) { + refreshUniformsStandard( uniforms, material ); - THREE.Material.prototype.copy.call( this, source ); + } - this.defines = { 'STANDARD': '' }; + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + function markUniformsLightsNeedsUpdate ( uniforms, value ) { - this.map = source.map; + uniforms.ambientLightColor.needsUpdate = value; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + uniforms.directionalLights.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + } - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + // Lighting - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + function setupShadows ( lights ) { - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + var lightShadowsLength = 0; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + for ( var i = 0, l = lights.length; i < l; i ++ ) { - this.roughnessMap = source.roughnessMap; + var light = lights[ i ]; - this.metalnessMap = source.metalnessMap; + if ( light.castShadow ) { - this.alphaMap = source.alphaMap; + _lights.shadows[ lightShadowsLength ++ ] = light; - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + } - this.refractionRatio = source.refractionRatio; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + _lights.shadows.length = lightShadowsLength; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - return this; + function setupLights ( lights, camera ) { -}; + var l, ll, light, + r = 0, g = 0, b = 0, + color, + intensity, + distance, + shadowMap, -// File:src/materials/MeshPhysicalMaterial.js + viewMatrix = camera.matrixWorldInverse, -/** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * } - */ + directionalLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0; -THREE.MeshPhysicalMaterial = function ( parameters ) { + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - THREE.MeshStandardMaterial.call( this ); + light = lights[ l ]; - this.defines = { 'PHYSICAL': '' }; + color = light.color; + intensity = light.intensity; + distance = light.distance; - this.type = 'MeshPhysicalMaterial'; + shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - this.reflectivity = 0.5; // maps to F0 = 0.04 + if ( (light && light.isAmbientLight) ) { - this.clearCoat = 0.0; - this.clearCoatRoughness = 0.0; + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - this.setValues( parameters ); + } else if ( (light && light.isDirectionalLight) ) { -}; + var uniforms = lightCache.get( light ); -THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); -THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial; + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); -THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { + uniforms.shadow = light.castShadow; - THREE.MeshStandardMaterial.prototype.copy.call( this, source ); + if ( light.castShadow ) { - this.defines = { 'PHYSICAL': '' }; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - this.reflectivity = source.reflectivity; + } - this.clearCoat = source.clearCoat; - this.clearCoatRoughness = source.clearCoatRoughness; + _lights.directionalShadowMap[ directionalLength ] = shadowMap; + _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + _lights.directional[ directionalLength ++ ] = uniforms; - return this; + } else if ( (light && light.isSpotLight) ) { -}; + var uniforms = lightCache.get( light ); -// File:src/materials/MultiMaterial.js + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; -THREE.MultiMaterial = function ( materials ) { + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - this.uuid = THREE.Math.generateUUID(); + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - this.type = 'MultiMaterial'; + uniforms.shadow = light.castShadow; - this.materials = materials instanceof Array ? materials : []; + if ( light.castShadow ) { - this.visible = true; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; -}; + } -THREE.MultiMaterial.prototype = { + _lights.spotShadowMap[ spotLength ] = shadowMap; + _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + _lights.spot[ spotLength ++ ] = uniforms; - constructor: THREE.MultiMaterial, + } else if ( (light && light.isPointLight) ) { - toJSON: function ( meta ) { + var uniforms = lightCache.get( light ); - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - var materials = this.materials; + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - for ( var i = 0, l = materials.length; i < l; i ++ ) { + uniforms.shadow = light.castShadow; - var material = materials[ i ].toJSON( meta ); - delete material.metadata; + if ( light.castShadow ) { - output.materials.push( material ); + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - } + } - output.visible = this.visible; + _lights.pointShadowMap[ pointLength ] = shadowMap; - return output; + if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - }, + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); - clone: function () { + } - var material = new this.constructor(); + // for point lights we set the shadow matrix to be a translation-only matrix + // equal to inverse of the light's position + _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); + _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); - for ( var i = 0; i < this.materials.length; i ++ ) { + _lights.point[ pointLength ++ ] = uniforms; - material.materials.push( this.materials[ i ].clone() ); + } else if ( (light && light.isHemisphereLight) ) { - } + var uniforms = lightCache.get( light ); - material.visible = this.visible; + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); - return material; + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); - } + _lights.hemi[ hemiLength ++ ] = uniforms; -}; + } -// File:src/materials/PointsMaterial.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * } - */ + _lights.ambient[ 0 ] = r; + _lights.ambient[ 1 ] = g; + _lights.ambient[ 2 ] = b; -THREE.PointsMaterial = function ( parameters ) { + _lights.directional.length = directionalLength; + _lights.spot.length = spotLength; + _lights.point.length = pointLength; + _lights.hemi.length = hemiLength; - THREE.Material.call( this ); + _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; - this.type = 'PointsMaterial'; + } - this.color = new THREE.Color( 0xffffff ); + // GL state setting - this.map = null; + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - this.size = 1; - this.sizeAttenuation = true; + state.setCullFace( cullFace ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); - this.lights = false; + }; - this.setValues( parameters ); + // Textures -}; + function allocTextureUnit() { -THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial; + var textureUnit = _usedTextureUnits; -THREE.PointsMaterial.prototype.copy = function ( source ) { + if ( textureUnit >= capabilities.maxTextures ) { - THREE.Material.prototype.copy.call( this, source ); + console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); - this.color.copy( source.color ); + } - this.map = source.map; + _usedTextureUnits += 1; - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + return textureUnit; - return this; + } -}; + this.allocTextureUnit = allocTextureUnit; -// File:src/materials/ShaderMaterial.js + // this.setTexture2D = setTexture2D; + this.setTexture2D = ( function() { -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + var warned = false; -THREE.ShaderMaterial = function ( parameters ) { + // backwards compatibility: peel texture.texture + return function setTexture2D( texture, slot ) { - THREE.Material.call( this ); + if ( (texture && texture.isWebGLRenderTarget) ) { - this.type = 'ShaderMaterial'; + if ( ! warned ) { - this.defines = {}; - this.uniforms = {}; + console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warned = true; - 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}'; + } - this.linewidth = 1; + texture = texture.texture; - this.wireframe = false; - this.wireframeLinewidth = 1; + } - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + textures.setTexture2D( texture, slot ); - this.skinning = false; // set to use skinning attribute streams - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + }; - this.extensions = { - derivatives: false, // set to use derivatives - fragDepth: false, // set to use fragment depth values - drawBuffers: false, // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + }() ); - // 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.setTexture = ( function() { - this.index0AttributeName = undefined; + var warned = false; - if ( parameters !== undefined ) { + return function setTexture( texture, slot ) { - if ( parameters.attributes !== undefined ) { + if ( ! warned ) { - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); + warned = true; - } + } - this.setValues( parameters ); + textures.setTexture2D( texture, slot ); - } + }; -}; + }() ); -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; + this.setTextureCube = ( function() { -THREE.ShaderMaterial.prototype.copy = function ( source ) { + var warned = false; - THREE.Material.prototype.copy.call( this, source ); + return function setTextureCube( texture, slot ) { - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + // backwards compatibility: peel texture.texture + if ( (texture && texture.isWebGLRenderTargetCube) ) { - this.uniforms = THREE.UniformsUtils.clone( source.uniforms ); + if ( ! warned ) { - this.defines = source.defines; + console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warned = true; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + } - this.lights = source.lights; - this.clipping = source.clipping; + texture = texture.texture; - this.skinning = source.skinning; + } - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture + // TODO: unify these code paths + if ( (texture && texture.isCubeTexture) || + ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - this.extensions = source.extensions; + // CompressedTexture can have Array in image :/ - return this; + // this function alone should take care of cube textures + textures.setTextureCube( texture, slot ); -}; + } else { -THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { + // assumed: texture property of THREE.WebGLRenderTargetCube - var data = THREE.Material.prototype.toJSON.call( this, meta ); + textures.setTextureCubeDynamic( texture, slot ); - data.uniforms = this.uniforms; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + } - return data; + }; -}; + }() ); -// File:src/materials/RawShaderMaterial.js + this.getCurrentRenderTarget = function() { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return _currentRenderTarget; -THREE.RawShaderMaterial = function ( parameters ) { + }; - THREE.ShaderMaterial.call( this, parameters ); + this.setRenderTarget = function ( renderTarget ) { - this.type = 'RawShaderMaterial'; + _currentRenderTarget = renderTarget; -}; + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; + textures.setupRenderTarget( renderTarget ); -// File:src/materials/SpriteMaterial.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2() - * } - */ + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var framebuffer; -THREE.SpriteMaterial = function ( parameters ) { + if ( renderTarget ) { - THREE.Material.call( this ); + var renderTargetProperties = properties.get( renderTarget ); - this.type = 'SpriteMaterial'; + if ( isCube ) { - this.color = new THREE.Color( 0xffffff ); - this.map = null; + framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; - this.rotation = 0; + } else { - this.fog = false; - this.lights = false; + framebuffer = renderTargetProperties.__webglFramebuffer; - this.setValues( parameters ); + } -}; + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; + _currentViewport.copy( renderTarget.viewport ); -THREE.SpriteMaterial.prototype.copy = function ( source ) { + } else { - THREE.Material.prototype.copy.call( this, source ); + framebuffer = null; - this.color.copy( source.color ); - this.map = source.map; + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); + _currentScissorTest = _scissorTest; - this.rotation = source.rotation; + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); - return this; + } -}; + if ( _currentFramebuffer !== framebuffer ) { -// File:src/materials/ShadowMaterial.js + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _currentFramebuffer = framebuffer; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.ShadowMaterial = function () { - - THREE.ShaderMaterial.call( this, { - uniforms: THREE.UniformsUtils.merge( [ - THREE.UniformsLib[ "lights" ], - { - opacity: { value: 1.0 } - } - ] ), - vertexShader: THREE.ShaderChunk[ 'shadow_vert' ], - fragmentShader: THREE.ShaderChunk[ 'shadow_frag' ] - } ); - - this.lights = true; - this.transparent = true; - - Object.defineProperties( this, { - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function ( value ) { - this.uniforms.opacity.value = value; - } - } - } ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); -}; + state.viewport( _currentViewport ); -THREE.ShadowMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.ShadowMaterial.prototype.constructor = THREE.ShadowMaterial; + if ( isCube ) { -// File:src/textures/Texture.js + var textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + } -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + }; - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - this.uuid = THREE.Math.generateUUID(); + if ( (renderTarget && renderTarget.isWebGLRenderTarget) === false ) { - this.name = ''; - this.sourceFile = ''; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; - this.mipmaps = []; + } - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + if ( framebuffer ) { - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + var restore = false; - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + if ( framebuffer !== _currentFramebuffer ) { - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + restore = true; - 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) + } + try { - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding; + var texture = renderTarget.texture; - this.version = 0; - this.onUpdate = null; + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { -}; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; + } -THREE.Texture.prototype = { + if ( texture.type !== UnsignedByteType && + paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && + ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && + ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { - constructor: THREE.Texture, + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - set needsUpdate( value ) { + } - if ( value === true ) this.version ++; + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - }, + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - clone: function () { + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { - return new this.constructor().copy( this ); + _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); - }, + } - copy: function ( source ) { + } else { - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - this.mapping = source.mapping; + } - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + } finally { - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + if ( restore ) { - this.anisotropy = source.anisotropy; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - this.format = source.format; - this.type = source.type; + } - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + } - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + } - return this; + }; - }, + // Map three.js constants to WebGL constants - toJSON: function ( meta ) { + function paramThreeToGL ( p ) { - if ( meta.textures[ this.uuid ] !== undefined ) { + var extension; - return meta.textures[ this.uuid ]; + if ( p === RepeatWrapping ) return _gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - } + if ( p === NearestFilter ) return _gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - function getDataURL( image ) { + if ( p === LinearFilter ) return _gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - var canvas; + if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - if ( image.toDataURL !== undefined ) { + if ( p === ByteType ) return _gl.BYTE; + if ( p === ShortType ) return _gl.SHORT; + if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === IntType ) return _gl.INT; + if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === FloatType ) return _gl.FLOAT; - canvas = image; + extension = extensions.get( 'OES_texture_half_float' ); - } else { + if ( extension !== null ) { - canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + } - } + if ( p === AlphaFormat ) return _gl.ALPHA; + if ( p === RGBFormat ) return _gl.RGB; + if ( p === RGBAFormat ) return _gl.RGBA; + if ( p === LuminanceFormat ) return _gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - if ( canvas.width > 2048 || canvas.height > 2048 ) { + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - return canvas.toDataURL( 'image/jpeg', 0.6 ); + if ( p === ZeroFactor ) return _gl.ZERO; + if ( p === OneFactor ) return _gl.ONE; + if ( p === SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - } else { + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - return canvas.toDataURL( 'image/png' ); + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - } + if ( extension !== null ) { - } + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - var output = { - metadata: { - version: 4.4, - type: 'Texture', - generator: 'Texture.toJSON' - }, + } - uuid: this.uuid, - name: this.name, + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - mapping: this.mapping, + if ( extension !== null ) { - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + } - flipY: this.flipY - }; + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - if ( this.image !== undefined ) { + if ( extension !== null ) { - // TODO: Move to THREE.Image + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; - var image = this.image; + } - if ( image.uuid === undefined ) { + extension = extensions.get( 'EXT_blend_minmax' ); - image.uuid = THREE.Math.generateUUID(); // UGH + if ( extension !== null ) { - } + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; - if ( meta.images[ image.uuid ] === undefined ) { + } - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + return 0; - } + } - output.image = image.uuid; + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - meta.textures[ this.uuid ] = output; + function FogExp2 ( color, density ) { + this.isFogExp2 = true; - return output; + this.name = ''; - }, + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - dispose: function () { + }; - this.dispatchEvent( { type: 'dispose' } ); + FogExp2.prototype.clone = function () { - }, + return new FogExp2( this.color.getHex(), this.density ); - transformUv: function ( uv ) { + }; - if ( this.mapping !== THREE.UVMapping ) return; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - uv.multiply( this.repeat ); - uv.add( this.offset ); + function Fog ( color, near, far ) { + this.isFog = true; - if ( uv.x < 0 || uv.x > 1 ) { + this.name = ''; - switch ( this.wrapS ) { + this.color = new Color( color ); - case THREE.RepeatWrapping: + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - uv.x = uv.x - Math.floor( uv.x ); - break; + }; - case THREE.ClampToEdgeWrapping: + Fog.prototype.clone = function () { - uv.x = uv.x < 0 ? 0 : 1; - break; + return new Fog( this.color.getHex(), this.near, this.far ); - case THREE.MirroredRepeatWrapping: + }; - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - uv.x = Math.ceil( uv.x ) - uv.x; + function Scene () { + this.isScene = this.isObject3D = true; - } else { + Object3D.call( this ); - uv.x = uv.x - Math.floor( uv.x ); + this.type = 'Scene'; - } - break; + this.background = null; + this.fog = null; + this.overrideMaterial = null; - } + this.autoUpdate = true; // checked by the renderer - } + }; - if ( uv.y < 0 || uv.y > 1 ) { + Scene.prototype = Object.create( Object3D.prototype ); + Scene.prototype.constructor = Scene; - switch ( this.wrapT ) { + Scene.prototype.copy = function ( source, recursive ) { - case THREE.RepeatWrapping: + Object3D.prototype.copy.call( this, source, recursive ); - uv.y = uv.y - Math.floor( uv.y ); - break; + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); - case THREE.ClampToEdgeWrapping: + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - uv.y = uv.y < 0 ? 0 : 1; - break; + return this; - case THREE.MirroredRepeatWrapping: + }; - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - uv.y = Math.ceil( uv.y ) - uv.y; + function LensFlare ( texture, size, distance, blending, color ) { + this.isLensFlare = true; - } else { + Object3D.call( this ); - uv.y = uv.y - Math.floor( uv.y ); + this.lensFlares = []; - } - break; + this.positionScreen = new Vector3(); + this.customUpdateCallback = undefined; - } + if ( texture !== undefined ) { - } + this.add( texture, size, distance, blending, color ); - if ( this.flipY ) { + } - uv.y = 1 - uv.y; + }; - } + LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: LensFlare, -}; + copy: function ( source ) { -Object.assign( THREE.Texture.prototype, THREE.EventDispatcher.prototype ); + Object3D.prototype.copy.call( this, source ); -THREE.TextureIdCount = 0; + this.positionScreen.copy( source.positionScreen ); + this.customUpdateCallback = source.customUpdateCallback; -// File:src/textures/DepthTexture.js + for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { -/** - * @author Matt DesLauriers / @mattdesl - */ + this.lensFlares.push( source.lensFlares[ i ] ); -THREE.DepthTexture = function ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + } - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, THREE.DepthFormat, type, anisotropy ); + return this; - this.image = { width: width, height: height }; + }, - this.type = type !== undefined ? type : THREE.UnsignedShortType; + add: function ( texture, size, distance, blending, color, opacity ) { - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + if ( size === undefined ) size = - 1; + if ( distance === undefined ) distance = 0; + if ( opacity === undefined ) opacity = 1; + if ( color === undefined ) color = new Color( 0xffffff ); + if ( blending === undefined ) blending = NormalBlending; - this.flipY = false; - this.generateMipmaps = false; + 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 in front z = 1 is back + scale: 1, // scale + rotation: 0, // rotation + opacity: opacity, // opacity + color: color, // color + blending: blending // blending + } ); -THREE.DepthTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DepthTexture.prototype.constructor = THREE.DepthTexture; + }, -// File:src/textures/CanvasTexture.js + /* + * 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. + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + updateLensFlares: function () { -THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; - THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + for ( f = 0; f < fl; f ++ ) { - this.needsUpdate = true; + flare = this.lensFlares[ f ]; -}; + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; -THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture; + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; -// File:src/textures/CubeTexture.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + } ); - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * uvOffset: new THREE.Vector2(), + * uvScale: new THREE.Vector2() + * } + */ - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + function SpriteMaterial ( parameters ) { + this.isSpriteMaterial = this.isMaterial = true; - this.flipY = false; + Material.call( this ); -}; + this.type = 'SpriteMaterial'; -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; + this.color = new Color( 0xffffff ); + this.map = null; -Object.defineProperty( THREE.CubeTexture.prototype, 'images', { + this.rotation = 0; - get: function () { + this.fog = false; + this.lights = false; - return this.image; + this.setValues( parameters ); - }, + }; - set: function ( value ) { + SpriteMaterial.prototype = Object.create( Material.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; - this.image = value; + SpriteMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); -} ); + this.color.copy( source.color ); + this.map = source.map; -// File:src/textures/CompressedTexture.js + this.rotation = source.rotation; -/** - * @author alteredq / http://alteredqualia.com/ - */ + return this; -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + }; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + function Sprite ( material ) { + this.isSprite = true; - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + Object3D.call( this ); - this.flipY = false; + this.type = 'Sprite'; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - this.generateMipmaps = false; + }; -}; + Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; + constructor: Sprite, -// File:src/textures/DataTexture.js + raycast: ( function () { -/** - * @author alteredq / http://alteredqualia.com/ - */ + var matrixPosition = new Vector3(); -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + return function raycast( raycaster, intersects ) { - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - this.image = { data: data, width: width, height: height }; + var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); + var guessSizeSq = this.scale.x * this.scale.y / 4; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + if ( distanceSq > guessSizeSq ) { - this.flipY = false; - this.generateMipmaps = false; + return; -}; + } -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; + intersects.push( { -// File:src/textures/VideoTexture.js + distance: Math.sqrt( distanceSq ), + point: this.position, + face: null, + object: this -/** - * @author mrdoob / http://mrdoob.com/ - */ + } ); -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 ); + }() ), - this.generateMipmaps = false; + clone: function () { - var scope = this; + return new this.constructor( this.material ).copy( this ); - function update() { + } - requestAnimationFrame( update ); + } ); - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - scope.needsUpdate = true; + function LOD () { + this.isLOD = true; - } + Object3D.call( this ); - } + this.type = 'LOD'; - update(); + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); -}; + }; -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; -// File:src/objects/Group.js + LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { -/** - * @author mrdoob / http://mrdoob.com/ - */ + constructor: LOD, -THREE.Group = function () { + copy: function ( source ) { - THREE.Object3D.call( this ); + Object3D.prototype.copy.call( this, source, false ); - this.type = 'Group'; + var levels = source.levels; -}; + for ( var i = 0, l = levels.length; i < l; i ++ ) { -THREE.Group.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + var level = levels[ i ]; - constructor: THREE.Group + this.addLevel( level.object.clone(), level.distance ); -} ); + } -// File:src/objects/Points.js + return this; -/** - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.Points = function ( geometry, material ) { + addLevel: function ( object, distance ) { - THREE.Object3D.call( this ); + if ( distance === undefined ) distance = 0; - this.type = 'Points'; + distance = Math.abs( distance ); - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } ); + var levels = this.levels; -}; + for ( var l = 0; l < levels.length; l ++ ) { -THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + if ( distance < levels[ l ].distance ) { - constructor: THREE.Points, + break; - raycast: ( function () { + } - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + } - return function raycast( raycaster, intersects ) { + levels.splice( l, 0, { distance: distance, object: object } ); - var object = this; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + this.add( object ); - // Checking boundingSphere distance to ray + }, - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + getObjectForDistance: function ( distance ) { - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + var levels = this.levels; - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + for ( var i = 1, l = levels.length; i < l; i ++ ) { - // + if ( distance < levels[ i ].distance ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + break; - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new THREE.Vector3(); + } - function testPoint( point, index ) { + } - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + return levels[ i - 1 ].object; - if ( rayPointDistanceSq < localThresholdSq ) { + }, - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( matrixWorld ); + raycast: ( function () { - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + var matrixPosition = new Vector3(); - if ( distance < raycaster.near || distance > raycaster.far ) return; + return function raycast( raycaster, intersects ) { - intersects.push( { + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - } ); + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - } + }; - } + }() ), - if ( geometry instanceof THREE.BufferGeometry ) { + update: function () { - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + var v1 = new Vector3(); + var v2 = new Vector3(); - if ( index !== null ) { + return function update( camera ) { - var indices = index.array; + var levels = this.levels; - for ( var i = 0, il = indices.length; i < il; i ++ ) { + if ( levels.length > 1 ) { - var a = indices[ i ]; + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); - position.fromArray( positions, a * 3 ); + var distance = v1.distanceTo( v2 ); - testPoint( position, a ); + levels[ 0 ].object.visible = true; - } + for ( var i = 1, l = levels.length; i < l; i ++ ) { - } else { + if ( distance >= levels[ i ].distance ) { - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - position.fromArray( positions, i * 3 ); + } else { - testPoint( position, i ); + break; - } + } - } + } - } else { + for ( ; i < l; i ++ ) { - var vertices = geometry.vertices; + levels[ i ].object.visible = false; - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + } - testPoint( vertices[ i ], i ); + } - } + }; - } + }(), - }; + toJSON: function ( meta ) { - }() ), + var data = Object3D.prototype.toJSON.call( this, meta ); - clone: function () { + data.object.levels = []; - return new this.constructor( this.geometry, this.material ).copy( this ); + var levels = this.levels; - } + for ( var i = 0, l = levels.length; i < l; i ++ ) { -} ); + var level = levels[ i ]; -// File:src/objects/Line.js + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.Line = function ( geometry, material, mode ) { + return data; - if ( mode === 1 ) { + } - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new THREE.LineSegments( geometry, material ); + } ); - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - THREE.Object3D.call( this ); + function DataTexture ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isDataTexture = this.isTexture = true; - this.type = 'Line'; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); + this.image = { data: data, width: width, height: height }; -}; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; -THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + this.flipY = false; + this.generateMipmaps = false; - constructor: THREE.Line, + }; - raycast: ( function () { + DataTexture.prototype = Object.create( Texture.prototype ); + DataTexture.prototype.constructor = DataTexture; - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - return function raycast( raycaster, intersects ) { + function Skeleton ( bones, boneInverses, useVertexTexture ) { + this.isSkeleton = true; - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; + this.identityMatrix = new Matrix4(); - // Checking boundingSphere distance to ray + // copy the bone array - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + bones = bones || []; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + this.bones = bones.slice( 0 ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + // create a bone texture or an array of floats - // + if ( this.useVertexTexture ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this instanceof THREE.LineSegments ? 2 : 1; - if ( geometry instanceof THREE.BufferGeometry ) { + var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = exports.Math.nextPowerOfTwo( Math.ceil( size ) ); + size = Math.max( size, 4 ); - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + this.boneTextureWidth = size; + this.boneTextureHeight = size; - if ( index !== null ) { + this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel + this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); - var indices = index.array; + } else { - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - var a = indices[ i ]; - var b = indices[ i + 1 ]; + } - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + // use the supplied bone inverses or calculate the inverses - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + if ( boneInverses === undefined ) { - if ( distSq > precisionSq ) continue; + this.calculateInverses(); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + } else { - var distance = raycaster.ray.origin.distanceTo( interRay ); + if ( this.bones.length === boneInverses.length ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + this.boneInverses = boneInverses.slice( 0 ); - intersects.push( { + } else { - 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 + console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); - } ); + this.boneInverses = []; - } + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - } else { + this.boneInverses.push( new Matrix4() ); - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + } - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + } - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + } - if ( distSq > precisionSq ) continue; + }; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + Object.assign( Skeleton.prototype, { - var distance = raycaster.ray.origin.distanceTo( interRay ); + calculateInverses: function () { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + this.boneInverses = []; - intersects.push( { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - 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 inverse = new Matrix4(); - } ); + if ( this.bones[ b ] ) { - } + inverse.getInverse( this.bones[ b ].matrixWorld ); - } + } - } else if ( geometry instanceof THREE.Geometry ) { + this.boneInverses.push( inverse ); - var vertices = geometry.vertices; - var nbVertices = vertices.length; + } - for ( var i = 0; i < nbVertices - 1; i += step ) { + }, - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + pose: function () { - if ( distSq > precisionSq ) continue; + var bone; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + // recover the bind-time world matrices - var distance = raycaster.ray.origin.distanceTo( interRay ); + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + bone = this.bones[ b ]; - intersects.push( { + if ( bone ) { - 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 + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); - } ); + } - } + } - } + // compute the local matrices, positions, rotations and scales - }; + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - }() ), + bone = this.bones[ b ]; - clone: function () { + if ( bone ) { - return new this.constructor( this.geometry, this.material ).copy( this ); + if ( (bone.parent && bone.parent.isBone) ) { - } + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); -} ); + } else { -// File:src/objects/LineSegments.js + bone.matrix.copy( bone.matrixWorld ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.LineSegments = function ( geometry, material ) { + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - THREE.Line.call( this, geometry, material ); + } - this.type = 'LineSegments'; + } -}; + }, -THREE.LineSegments.prototype = Object.assign( Object.create( THREE.Line.prototype ), { + update: ( function () { - constructor: THREE.LineSegments + var offsetMatrix = new Matrix4(); -} ); + return function update() { -// File:src/objects/Mesh.js + // flatten bone matrices to array -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { -THREE.Mesh = function ( geometry, material ) { + // compute the offset between the current and the original transform - THREE.Object3D.call( this ); + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - this.type = 'Mesh'; + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.toArray( this.boneMatrices, b * 16 ); - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + } - this.drawMode = THREE.TrianglesDrawMode; + if ( this.useVertexTexture ) { - this.updateMorphTargets(); + this.boneTexture.needsUpdate = true; -}; + } -THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + }; - constructor: THREE.Mesh, + } )(), - setDrawMode: function ( value ) { + clone: function () { - this.drawMode = value; + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); - }, + } - copy: function ( source ) { + } ); - THREE.Object3D.prototype.copy.call( this, source ); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - this.drawMode = source.drawMode; + function Bone ( skin ) { + this.isBone = true; - return this; + Object3D.call( this ); - }, + this.type = 'Bone'; - updateMorphTargets: function () { + this.skin = skin; - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + }; - this.morphTargetBase = - 1; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + constructor: Bone, - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + copy: function ( source ) { - } + Object3D.prototype.copy.call( this, source ); - } + this.skin = source.skin; - }, + return this; - getMorphTargetIndexByName: function ( name ) { + } - if ( this.morphTargetDictionary[ name ] !== undefined ) { + } ); - return this.morphTargetDictionary[ name ]; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - } + function SkinnedMesh ( geometry, material, useVertexTexture ) { + this.isSkinnedMesh = true; - console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); + Mesh.call( this, geometry, material ); - return 0; + this.type = 'SkinnedMesh'; - }, + this.bindMode = "attached"; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); - raycast: ( function () { + // init bones - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + var bones = []; - var tempA = new THREE.Vector3(); - var tempB = new THREE.Vector3(); - var tempC = new THREE.Vector3(); + if ( this.geometry && this.geometry.bones !== undefined ) { - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + var bone, gbone; - var barycoord = new THREE.Vector3(); + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - var intersectionPoint = new THREE.Vector3(); - var intersectionPointWorld = new THREE.Vector3(); + gbone = this.geometry.bones[ b ]; - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + bone = new Bone( this ); + bones.push( bone ); - THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + } - uv1.add( uv2 ).add( uv3 ); + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - return uv1.clone(); + gbone = this.geometry.bones[ b ]; - } + if ( gbone.parent !== - 1 && gbone.parent !== null && + bones[ gbone.parent ] !== undefined ) { - function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { + bones[ gbone.parent ].add( bones[ b ] ); - var intersect; - var material = object.material; + } else { - if ( material.side === THREE.BackSide ) { + this.add( bones[ b ] ); - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + } - } else { + } - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point ); + } - } + this.normalizeSkinWeights(); - if ( intersect === null ) return null; + this.updateMatrixWorld( true ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); - intersectionPointWorld.copy( point ); - intersectionPointWorld.applyMatrix4( object.matrixWorld ); + }; - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - if ( distance < raycaster.near || distance > raycaster.far ) return null; + SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - return { - distance: distance, - point: intersectionPointWorld.clone(), - object: object - }; + constructor: SkinnedMesh, - } + bind: function( skeleton, bindMatrix ) { - function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { + this.skeleton = skeleton; - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + if ( bindMatrix === undefined ) { - var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); + this.updateMatrixWorld( true ); - if ( intersection ) { + this.skeleton.calculateInverses(); - if ( uvs ) { + bindMatrix = this.matrixWorld; - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + } - intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - } + }, - intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ); - intersection.faceIndex = a; + pose: function () { - } + this.skeleton.pose(); - return intersection; + }, - } + normalizeSkinWeights: function () { - return function raycast( raycaster, intersects ) { + if ( (this.geometry && this.geometry.isGeometry) ) { - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { - if ( material === undefined ) return; + var sw = this.geometry.skinWeights[ i ]; - // Checking boundingSphere distance to ray + var scale = 1.0 / sw.lengthManhattan(); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( scale !== Infinity ) { - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + sw.multiplyScalar( scale ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + } else { - // + sw.set( 1, 0, 0, 0 ); // do something reasonable - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + } - // Check boundingBox before continuing + } - if ( geometry.boundingBox !== null ) { + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; + var vec = new Vector4(); - } + var skinWeight = this.geometry.attributes.skinWeight; - var uvs, intersection; + for ( var i = 0; i < skinWeight.count; i ++ ) { - if ( geometry instanceof THREE.BufferGeometry ) { + vec.x = skinWeight.getX( i ); + vec.y = skinWeight.getY( i ); + vec.z = skinWeight.getZ( i ); + vec.w = skinWeight.getW( i ); - var a, b, c; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + var scale = 1.0 / vec.lengthManhattan(); - if ( attributes.uv !== undefined ) { + if ( scale !== Infinity ) { - uvs = attributes.uv.array; + vec.multiplyScalar( scale ); - } + } else { - if ( index !== null ) { + vec.set( 1, 0, 0, 0 ); // do something reasonable - var indices = index.array; + } - for ( var i = 0, l = indices.length; i < l; i += 3 ) { + skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); - a = indices[ i ]; - b = indices[ i + 1 ]; - c = indices[ i + 2 ]; + } - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + } - if ( intersection ) { + }, - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics - intersects.push( intersection ); + updateMatrixWorld: function( force ) { - } + Mesh.prototype.updateMatrixWorld.call( this, true ); - } + if ( this.bindMode === "attached" ) { - } else { + this.bindMatrixInverse.getInverse( this.matrixWorld ); + } else if ( this.bindMode === "detached" ) { - for ( var i = 0, l = positions.length; i < l; i += 9 ) { + this.bindMatrixInverse.getInverse( this.bindMatrix ); - a = i / 3; - b = a + 1; - c = a + 2; + } else { - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); - if ( intersection ) { + } - intersection.index = a; // triangle number in positions buffer semantics - intersects.push( intersection ); + }, - } + clone: function() { - } + return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); - } + } - } else if ( geometry instanceof THREE.Geometry ) { + } ); - var fvA, fvB, fvC; - var isFaceMaterial = material instanceof THREE.MultiMaterial; - var materials = isFaceMaterial === true ? material.materials : null; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } + */ - var vertices = geometry.vertices; - var faces = geometry.faces; - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; + function LineBasicMaterial ( parameters ) { + this.isLineBasicMaterial = this.isMaterial = true; - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + Material.call( this ); - var face = faces[ f ]; - var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; + this.type = 'LineBasicMaterial'; - if ( faceMaterial === undefined ) continue; + this.color = new Color( 0xffffff ); - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - if ( faceMaterial.morphTargets === true ) { + this.lights = false; - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + this.setValues( parameters ); - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + }; - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + LineBasicMaterial.prototype = Object.create( Material.prototype ); + LineBasicMaterial.prototype.constructor = LineBasicMaterial; - var influence = morphInfluences[ t ]; + LineBasicMaterial.prototype.copy = function ( source ) { - if ( influence === 0 ) continue; + Material.prototype.copy.call( this, source ); - var targets = morphTargets[ t ].vertices; + this.color.copy( source.color ); - vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); - vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); - vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - } + return this; - vA.add( fvA ); - vB.add( fvB ); - vC.add( fvC ); + }; - fvA = vA; - fvB = vB; - fvC = vC; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function Line ( geometry, material, mode ) { + this.isLine = true; - intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); + if ( mode === 1 ) { - if ( intersection ) { + console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); + return new LineSegments( geometry, material ); - if ( uvs ) { + } - var uvs_f = uvs[ f ]; - uvA.copy( uvs_f[ 0 ] ); - uvB.copy( uvs_f[ 1 ] ); - uvC.copy( uvs_f[ 2 ] ); + Object3D.call( this ); - intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); + this.type = 'Line'; - } + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); - intersection.face = face; - intersection.faceIndex = f; - intersects.push( intersection ); + }; - } + Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Line, - } + raycast: ( function () { - }; + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - }() ), + return function raycast( raycaster, intersects ) { - clone: function () { + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - return new this.constructor( this.geometry, this.material ).copy( this ); + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; - } + // Checking boundingSphere distance to ray -} ); + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); -// File:src/objects/Bone.js + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; -THREE.Bone = function ( skin ) { + // - THREE.Object3D.call( this ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - this.type = 'Bone'; + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - this.skin = skin; + if ( (geometry && geometry.isBufferGeometry) ) { -}; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; -THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + if ( index !== null ) { - constructor: THREE.Bone, + var indices = index.array; - copy: function ( source ) { + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - THREE.Object3D.prototype.copy.call( this, source ); + var a = indices[ i ]; + var b = indices[ i + 1 ]; - this.skin = source.skin; + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - return this; + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - } + if ( distSq > precisionSq ) continue; -} ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation -// File:src/objects/Skeleton.js + var distance = raycaster.ray.origin.distanceTo( interRay ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + if ( distance < raycaster.near || distance > raycaster.far ) continue; -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { + intersects.push( { - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + 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 - this.identityMatrix = new THREE.Matrix4(); + } ); - // copy the bone array + } - bones = bones || []; + } else { - this.bones = bones.slice( 0 ); + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { - // create a bone texture or an array of floats + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - if ( this.useVertexTexture ) { + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + if ( distSq > precisionSq ) continue; + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) ); - size = Math.max( size, 4 ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - this.boneTextureWidth = size; - this.boneTextureHeight = size; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - 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 ); + intersects.push( { - } else { + 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 - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + } ); - } + } - // use the supplied bone inverses or calculate the inverses + } - if ( boneInverses === undefined ) { + } else if ( (geometry && geometry.isGeometry) ) { - this.calculateInverses(); + var vertices = geometry.vertices; + var nbVertices = vertices.length; - } else { + for ( var i = 0; i < nbVertices - 1; i += step ) { - if ( this.bones.length === boneInverses.length ) { + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - this.boneInverses = boneInverses.slice( 0 ); + if ( distSq > precisionSq ) continue; - } else { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - this.boneInverses = []; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + intersects.push( { - this.boneInverses.push( new THREE.Matrix4() ); + 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 - } + } ); - } + } - } + } -}; + }; -Object.assign( THREE.Skeleton.prototype, { + }() ), - calculateInverses: function () { + clone: function () { - this.boneInverses = []; + return new this.constructor( this.geometry, this.material ).copy( this ); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + } - var inverse = new THREE.Matrix4(); + } ); - if ( this.bones[ b ] ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - inverse.getInverse( this.bones[ b ].matrixWorld ); + function LineSegments ( geometry, material ) { + this.isLineSegments = true; - } + Line.call( this, geometry, material ); - this.boneInverses.push( inverse ); + this.type = 'LineSegments'; - } + }; - }, + LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - pose: function () { + constructor: LineSegments - var bone; + } ); - // recover the bind-time world matrices + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * } + */ - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + function PointsMaterial ( parameters ) { + this.isPointsMaterial = this.isMaterial = true; - bone = this.bones[ b ]; + Material.call( this ); - if ( bone ) { + this.type = 'PointsMaterial'; - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); + this.color = new Color( 0xffffff ); - } + this.map = null; - } + this.size = 1; + this.sizeAttenuation = true; - // compute the local matrices, positions, rotations and scales + this.lights = false; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + this.setValues( parameters ); - bone = this.bones[ b ]; + }; - if ( bone ) { + PointsMaterial.prototype = Object.create( Material.prototype ); + PointsMaterial.prototype.constructor = PointsMaterial; - if ( bone.parent instanceof THREE.Bone ) { + PointsMaterial.prototype.copy = function ( source ) { - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + Material.prototype.copy.call( this, source ); - } else { + this.color.copy( source.color ); - bone.matrix.copy( bone.matrixWorld ); + this.map = source.map; - } + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + return this; - } + }; - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - }, + function Points ( geometry, material ) { + this.isPoints = true; - update: ( function () { + Object3D.call( this ); - var offsetMatrix = new THREE.Matrix4(); + this.type = 'Points'; - return function update() { + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); - // flatten bone matrices to array + }; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - // compute the offset between the current and the original transform + constructor: Points, - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; + raycast: ( function () { - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.toArray( this.boneMatrices, b * 16 ); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - } + return function raycast( raycaster, intersects ) { - if ( this.useVertexTexture ) { + var object = this; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; - this.boneTexture.needsUpdate = true; + // Checking boundingSphere distance to ray - } + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - }; + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - } )(), + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - clone: function () { + // - return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - } + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; + var position = new Vector3(); -} ); + function testPoint( point, index ) { -// File:src/objects/SkinnedMesh.js + var rayPointDistanceSq = ray.distanceSqToPoint( point ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + if ( rayPointDistanceSq < localThresholdSq ) { -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( matrixWorld ); - THREE.Mesh.call( this, geometry, material ); + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - this.type = 'SkinnedMesh'; + if ( distance < raycaster.near || distance > raycaster.far ) return; - this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); + intersects.push( { - // init bones + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint.clone(), + index: index, + face: null, + object: object - // 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; + if ( (geometry && geometry.isBufferGeometry) ) { - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - gbone = this.geometry.bones[ b ]; + if ( index !== null ) { - bone = new THREE.Bone( this ); - bones.push( bone ); + var indices = index.array; - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + for ( var i = 0, il = indices.length; i < il; i ++ ) { - } + var a = indices[ i ]; - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + position.fromArray( positions, a * 3 ); - gbone = this.geometry.bones[ b ]; + testPoint( position, a ); - if ( gbone.parent !== - 1 && gbone.parent !== null && - bones[ gbone.parent ] !== undefined ) { + } - bones[ gbone.parent ].add( bones[ b ] ); + } else { - } else { + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - this.add( bones[ b ] ); + position.fromArray( positions, i * 3 ); - } + testPoint( position, i ); - } + } - } + } - this.normalizeSkinWeights(); + } else { - this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + var vertices = geometry.vertices; -}; + for ( var i = 0, l = vertices.length; i < l; i ++ ) { + testPoint( vertices[ i ], i ); -THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype ), { + } - constructor: THREE.SkinnedMesh, + } - bind: function( skeleton, bindMatrix ) { + }; - this.skeleton = skeleton; + }() ), - if ( bindMatrix === undefined ) { + clone: function () { - this.updateMatrixWorld( true ); + return new this.constructor( this.geometry, this.material ).copy( this ); - this.skeleton.calculateInverses(); + } - bindMatrix = this.matrixWorld; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + function Group () { + this.isGroup = true; - }, + Object3D.call( this ); - pose: function () { + this.type = 'Group'; - this.skeleton.pose(); + }; - }, + Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - normalizeSkinWeights: function () { + constructor: Group - if ( this.geometry instanceof THREE.Geometry ) { + } ); - for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var sw = this.geometry.skinWeights[ i ]; + function VideoTexture ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isVideoTexture = this.isTexture = true; - var scale = 1.0 / sw.lengthManhattan(); + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - if ( scale !== Infinity ) { + this.generateMipmaps = false; - sw.multiplyScalar( scale ); + var scope = this; - } else { + function update() { - sw.set( 1, 0, 0, 0 ); // do something reasonable + requestAnimationFrame( update ); - } + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { - } + scope.needsUpdate = true; - } else if ( this.geometry instanceof THREE.BufferGeometry ) { + } - var vec = new THREE.Vector4(); + } - var skinWeight = this.geometry.attributes.skinWeight; + update(); - for ( var i = 0; i < skinWeight.count; i ++ ) { + }; - vec.x = skinWeight.getX( i ); - vec.y = skinWeight.getY( i ); - vec.z = skinWeight.getZ( i ); - vec.w = skinWeight.getW( i ); + VideoTexture.prototype = Object.create( Texture.prototype ); + VideoTexture.prototype.constructor = VideoTexture; - var scale = 1.0 / vec.lengthManhattan(); + /** + * @author alteredq / http://alteredqualia.com/ + */ - if ( scale !== Infinity ) { + function CompressedTexture ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isCompressedTexture = this.isTexture = true; - vec.multiplyScalar( scale ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - } else { + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - vec.set( 1, 0, 0, 0 ); // do something reasonable + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - } + this.flipY = false; - skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - } + this.generateMipmaps = false; - } + }; - }, + CompressedTexture.prototype = Object.create( Texture.prototype ); + CompressedTexture.prototype.constructor = CompressedTexture; - updateMatrixWorld: function( force ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + function CanvasTexture ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isCanvasTexture = this.isTexture = true; - if ( this.bindMode === "attached" ) { + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.bindMatrixInverse.getInverse( this.matrixWorld ); + this.needsUpdate = true; - } else if ( this.bindMode === "detached" ) { + }; - this.bindMatrixInverse.getInverse( this.bindMatrix ); + CanvasTexture.prototype = Object.create( Texture.prototype ); + CanvasTexture.prototype.constructor = CanvasTexture; - } else { + /** + * @author Matt DesLauriers / @mattdesl + */ - console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); + function DepthTexture ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + this.isDepthTexture = this.isTexture = true; - } + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, DepthFormat, type, anisotropy ); - }, + this.image = { width: width, height: height }; - clone: function() { + this.type = type !== undefined ? type : UnsignedShortType; - return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - } + this.flipY = false; + this.generateMipmaps = false; -} ); + }; -// File:src/objects/LOD.js + DepthTexture.prototype = Object.create( Texture.prototype ); + DepthTexture.prototype.constructor = DepthTexture; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.LOD = function () { + function ShadowMaterial () { + this.isShadowMaterial = this.isShaderMaterial = this.isMaterial = true; - THREE.Object3D.call( this ); + ShaderMaterial.call( this, { + uniforms: exports.UniformsUtils.merge( [ + exports.UniformsLib[ "lights" ], + { + opacity: { value: 1.0 } + } + ] ), + vertexShader: ShaderChunk[ 'shadow_vert' ], + fragmentShader: ShaderChunk[ 'shadow_frag' ] + } ); - this.type = 'LOD'; + this.lights = true; + this.transparent = true; - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - } - } ); + Object.defineProperties( this, { + opacity: { + enumerable: true, + get: function () { + return this.uniforms.opacity.value; + }, + set: function ( value ) { + this.uniforms.opacity.value = value; + } + } + } ); -}; + }; + ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); + ShadowMaterial.prototype.constructor = ShadowMaterial; -THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + /** + * @author mrdoob / http://mrdoob.com/ + */ - constructor: THREE.LOD, + function RawShaderMaterial ( parameters ) { + this.isRawShaderMaterial = this.isShaderMaterial = this.isMaterial = true; - copy: function ( source ) { + ShaderMaterial.call( this, parameters ); - THREE.Object3D.prototype.copy.call( this, source, false ); + this.type = 'RawShaderMaterial'; - var levels = source.levels; + }; - for ( var i = 0, l = levels.length; i < l; i ++ ) { + RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); + RawShaderMaterial.prototype.constructor = RawShaderMaterial; - var level = levels[ i ]; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.addLevel( level.object.clone(), level.distance ); + function MultiMaterial ( materials ) { + this.isMultiMaterial = true; - } + this.uuid = exports.Math.generateUUID(); - return this; + this.type = 'MultiMaterial'; - }, + this.materials = materials instanceof Array ? materials : []; - addLevel: function ( object, distance ) { + this.visible = true; - if ( distance === undefined ) distance = 0; + }; - distance = Math.abs( distance ); + MultiMaterial.prototype = { - var levels = this.levels; + constructor: MultiMaterial, - for ( var l = 0; l < levels.length; l ++ ) { + toJSON: function ( meta ) { - if ( distance < levels[ l ].distance ) { + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type, + materials: [] + }; - break; + var materials = this.materials; - } + for ( var i = 0, l = materials.length; i < l; i ++ ) { - } + var material = materials[ i ].toJSON( meta ); + delete material.metadata; - levels.splice( l, 0, { distance: distance, object: object } ); + output.materials.push( material ); - this.add( object ); + } - }, + output.visible = this.visible; - getObjectForDistance: function ( distance ) { + return output; - var levels = this.levels; + }, - for ( var i = 1, l = levels.length; i < l; i ++ ) { + clone: function () { - if ( distance < levels[ i ].distance ) { + var material = new this.constructor(); - break; + for ( var i = 0; i < this.materials.length; i ++ ) { - } + material.materials.push( this.materials[ i ].clone() ); - } + } - return levels[ i - 1 ].object; + material.visible = this.visible; - }, + return material; - raycast: ( function () { + } - var matrixPosition = new THREE.Vector3(); + }; - return function raycast( raycaster, intersects ) { + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * roughness: , + * metalness: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * roughnessMap: new THREE.Texture( ), + * + * metalnessMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * envMapIntensity: + * + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + function MeshStandardMaterial ( parameters ) { + this.isMeshStandardMaterial = this.isMaterial = true; - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + Material.call( this ); - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + this.defines = { 'STANDARD': '' }; - }; + this.type = 'MeshStandardMaterial'; - }() ), + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 0.5; + this.metalness = 0.5; - update: function () { + this.map = null; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + this.lightMap = null; + this.lightMapIntensity = 1.0; - return function update( camera ) { + this.aoMap = null; + this.aoMapIntensity = 1.0; - var levels = this.levels; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - if ( levels.length > 1 ) { + this.bumpMap = null; + this.bumpScale = 1; - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); - var distance = v1.distanceTo( v2 ); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - levels[ 0 ].object.visible = true; + this.roughnessMap = null; - for ( var i = 1, l = levels.length; i < l; i ++ ) { + this.metalnessMap = null; - if ( distance >= levels[ i ].distance ) { + this.alphaMap = null; - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + this.envMap = null; + this.envMapIntensity = 1.0; - } else { + this.refractionRatio = 0.98; - break; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - } + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - } + this.setValues( parameters ); - for ( ; i < l; i ++ ) { + }; - levels[ i ].object.visible = false; + MeshStandardMaterial.prototype = Object.create( Material.prototype ); + MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; - } + MeshStandardMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - }; + this.defines = { 'STANDARD': '' }; - }(), + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - toJSON: function ( meta ) { + this.map = source.map; - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - data.object.levels = []; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - var levels = this.levels; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - for ( var i = 0, l = levels.length; i < l; i ++ ) { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - var level = levels[ i ]; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - } + this.roughnessMap = source.roughnessMap; - return data; + this.metalnessMap = source.metalnessMap; - } + this.alphaMap = source.alphaMap; -} ); + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; -// File:src/objects/Sprite.js + this.refractionRatio = source.refractionRatio; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; -THREE.Sprite = function ( material ) { + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - THREE.Object3D.call( this ); + return this; - this.type = 'Sprite'; + }; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * reflectivity: + * } + */ -}; + function MeshPhysicalMaterial ( parameters ) { + this.isMeshPhysicalMaterial = this.isMeshStandardMaterial = this.isMaterial = true; -THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + MeshStandardMaterial.call( this ); - constructor: THREE.Sprite, + this.defines = { 'PHYSICAL': '' }; - raycast: ( function () { + this.type = 'MeshPhysicalMaterial'; - var matrixPosition = new THREE.Vector3(); + this.reflectivity = 0.5; // maps to F0 = 0.04 - return function raycast( raycaster, intersects ) { + this.clearCoat = 0.0; + this.clearCoatRoughness = 0.0; - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + this.setValues( parameters ); - var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); - var guessSizeSq = this.scale.x * this.scale.y / 4; + }; - if ( distanceSq > guessSizeSq ) { + MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; - return; + MeshPhysicalMaterial.prototype.copy = function ( source ) { - } + MeshStandardMaterial.prototype.copy.call( this, source ); - intersects.push( { + this.defines = { 'PHYSICAL': '' }; - distance: Math.sqrt( distanceSq ), - point: this.position, - face: null, - object: this + this.reflectivity = source.reflectivity; - } ); + this.clearCoat = source.clearCoat; + this.clearCoatRoughness = source.clearCoatRoughness; - }; + return this; - }() ), + }; - clone: function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * specular: , + * shininess: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - return new this.constructor( this.material ).copy( this ); + function MeshPhongMaterial ( parameters ) { + this.isMeshPhongMaterial = this.isMaterial = true; - } + Material.call( this ); -} ); + this.type = 'MeshPhongMaterial'; -// File:src/objects/LensFlare.js + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + this.map = null; -THREE.LensFlare = function ( texture, size, distance, blending, color ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - THREE.Object3D.call( this ); + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.lensFlares = []; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; + this.bumpMap = null; + this.bumpScale = 1; - if ( texture !== undefined ) { + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); - this.add( texture, size, distance, blending, color ); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - } + this.specularMap = null; -}; + this.alphaMap = null; -THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - constructor: THREE.LensFlare, + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - copy: function ( source ) { + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - THREE.Object3D.prototype.copy.call( this, source ); + this.setValues( parameters ); - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + }; - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + MeshPhongMaterial.prototype = Object.create( Material.prototype ); + MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; - this.lensFlares.push( source.lensFlares[ i ] ); + MeshPhongMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - return this; + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - }, + this.map = source.map; - add: function ( texture, size, distance, blending, color, opacity ) { - - 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; - - 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 in front z = 1 is back - scale: 1, // scale - rotation: 0, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending // blending - } ); + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - }, + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - /* - * 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. - */ + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - updateLensFlares: function () { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - for ( f = 0; f < fl; f ++ ) { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - flare = this.lensFlares[ f ]; + this.specularMap = source.specularMap; - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + this.alphaMap = source.alphaMap; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; -} ); + return this; -// File:src/scenes/Scene.js + }; -/** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * opacity: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ -THREE.Scene = function () { + function MeshNormalMaterial ( parameters ) { + this.isMeshNormalMaterial = this.isMaterial = true; - THREE.Object3D.call( this ); + Material.call( this, parameters ); - this.type = 'Scene'; + this.type = 'MeshNormalMaterial'; - this.background = null; - this.fog = null; - this.overrideMaterial = null; + this.wireframe = false; + this.wireframeLinewidth = 1; - this.autoUpdate = true; // checked by the renderer + this.fog = false; + this.lights = false; + this.morphTargets = false; -}; + this.setValues( parameters ); -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; + }; -THREE.Scene.prototype.copy = function ( source, recursive ) { + MeshNormalMaterial.prototype = Object.create( Material.prototype ); + MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; - THREE.Object3D.prototype.copy.call( this, source, recursive ); + MeshNormalMaterial.prototype.copy = function ( source ) { - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + Material.prototype.copy.call( this, source ); - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - return this; + return this; -}; + }; -// File:src/scenes/Fog.js + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + function MeshLambertMaterial ( parameters ) { + this.isMeshLambertMaterial = this.isMaterial = true; -THREE.Fog = function ( color, near, far ) { + Material.call( this ); - this.name = ''; + this.type = 'MeshLambertMaterial'; - this.color = new THREE.Color( color ); + this.color = new Color( 0xffffff ); // diffuse - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + this.map = null; -}; + this.lightMap = null; + this.lightMapIntensity = 1.0; -THREE.Fog.prototype.clone = function () { + this.aoMap = null; + this.aoMapIntensity = 1.0; - return new THREE.Fog( this.color.getHex(), this.near, this.far ); + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; -}; + this.specularMap = null; -// File:src/scenes/FogExp2.js + this.alphaMap = null; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; -THREE.FogExp2 = function ( color, density ) { + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - this.name = ''; + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - this.color = new THREE.Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + this.setValues( parameters ); -}; + }; -THREE.FogExp2.prototype.clone = function () { + MeshLambertMaterial.prototype = Object.create( Material.prototype ); + MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; - return new THREE.FogExp2( this.color.getHex(), this.density ); + MeshLambertMaterial.prototype.copy = function ( source ) { -}; + Material.prototype.copy.call( this, source ); -// File:src/renderers/shaders/ShaderChunk.js + this.color.copy( source.color ); -THREE.ShaderChunk = {}; + this.map = source.map; -// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; -THREE.ShaderChunk[ 'alphamap_fragment' ] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; -// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; -THREE.ShaderChunk[ 'alphamap_pars_fragment' ] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n"; + this.specularMap = source.specularMap; -// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl + this.alphaMap = source.alphaMap; -THREE.ShaderChunk[ 'alphatest_fragment' ] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; -// File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; -THREE.ShaderChunk[ 'aomap_fragment' ] = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_ENVMAP ) && defined( PHYSICAL )\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n #endif\n#endif\n"; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; -// File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl + return this; -THREE.ShaderChunk[ 'aomap_pars_fragment' ] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; + }; -// File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ -THREE.ShaderChunk[ 'begin_vertex' ] = "\nvec3 transformed = vec3( position );\n"; + function LineDashedMaterial ( parameters ) { + this.isLineDashedMaterial = this.isMaterial = true; -// File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl + Material.call( this ); -THREE.ShaderChunk[ 'beginnormal_vertex' ] = "\nvec3 objectNormal = vec3( normal );\n"; + this.type = 'LineDashedMaterial'; -// File:src/renderers/shaders/ShaderChunk/bsdfs.glsl + this.color = new Color( 0xffffff ); -THREE.ShaderChunk[ 'bsdfs' ] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n return any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n float maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n return distanceFalloff * maxDistanceCutoffFactor;\n#else\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n return 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n return ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n return sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + this.linewidth = 1; -// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; -THREE.ShaderChunk[ 'bumpmap_pars_fragment' ] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\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 return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n"; + this.lights = false; -// File:src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl + this.setValues( parameters ); -THREE.ShaderChunk[ 'clipping_planes_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n for ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n vec4 plane = clippingPlanes[ i ];\n if ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n }\n#endif\n"; + }; -// File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl + LineDashedMaterial.prototype = Object.create( Material.prototype ); + LineDashedMaterial.prototype.constructor = LineDashedMaterial; -THREE.ShaderChunk[ 'clipping_planes_pars_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n #if ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n #endif\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; + LineDashedMaterial.prototype.copy = function ( source ) { -// File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl + Material.prototype.copy.call( this, source ); -THREE.ShaderChunk[ 'clipping_planes_pars_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n#endif\n"; + this.color.copy( source.color ); -// File:src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl + this.linewidth = source.linewidth; -THREE.ShaderChunk[ 'clipping_planes_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n vViewPosition = - mvPosition.xyz;\n#endif\n"; + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; -// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl + return this; -THREE.ShaderChunk[ 'color_fragment' ] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif"; + }; -// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'color_pars_fragment' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n"; + exports.Cache = { -// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl + enabled: false, -THREE.ShaderChunk[ 'color_pars_vertex' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif"; + files: {}, -// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl + add: function ( key, file ) { -THREE.ShaderChunk[ 'color_vertex' ] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif"; + if ( this.enabled === false ) return; -// File:src/renderers/shaders/ShaderChunk/common.glsl + // console.log( 'THREE.Cache', 'Adding key:', key ); -THREE.ShaderChunk[ 'common' ] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n}\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 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 - distance * planeNormal + point;\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 lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n"; + this.files[ key ] = file; -// File:src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl + }, -THREE.ShaderChunk[ 'cube_uv_reflection_fragment' ] = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n vec3 absDirection = abs(direction);\n int face = -1;\n if( absDirection.x > absDirection.z ) {\n if(absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0 : 3;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n else {\n if(absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2 : 5;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n return face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n float scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n float dxRoughness = dFdx(roughness);\n float dyRoughness = dFdy(roughness);\n vec3 dx = dFdx( vec * scale * dxRoughness );\n vec3 dy = dFdy( vec * scale * dyRoughness );\n float d = max( dot( dx, dx ), dot( dy, dy ) );\n d = clamp(d, 1.0, cubeUV_rangeClamp);\n float mipLevel = 0.5 * log2(d);\n return vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n mipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n float a = 16.0 * cubeUV_rcpTextureSize;\n vec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n vec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n float powScale = exp2_packed.x * exp2_packed.y;\n float scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n float mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n bool bRes = mipLevel == 0.0;\n scale = bRes && (scale < a) ? a : scale;\n vec3 r;\n vec2 offset;\n int face = getFaceFromDirection(direction);\n float rcpPowScale = 1.0 / powScale;\n if( face == 0) {\n r = vec3(direction.x, -direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 1) {\n r = vec3(direction.y, direction.x, direction.z);\n offset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 2) {\n r = vec3(direction.z, direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 3) {\n r = vec3(direction.x, direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else if( face == 4) {\n r = vec3(direction.y, direction.x, -direction.z);\n offset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else {\n r = vec3(direction.z, -direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n r = normalize(r);\n float texelOffset = 0.5 * cubeUV_rcpTextureSize;\n vec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n vec2 base = offset + vec2( texelOffset );\n return base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n float roughnessVal = roughness* cubeUV_maxLods3;\n float r1 = floor(roughnessVal);\n float r2 = r1 + 1.0;\n float t = fract(roughnessVal);\n vec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n float s = mipInfo.y;\n float level0 = mipInfo.x;\n float level1 = level0 + 1.0;\n level1 = level1 > 5.0 ? 5.0 : level1;\n level0 += min( floor( s + 0.5 ), 5.0 );\n vec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n vec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n vec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n vec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n vec4 result = mix(color10, color20, t);\n return vec4(result.rgb, 1.0);\n}\n#endif\n"; + get: function ( key ) { -// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl + if ( this.enabled === false ) return; -THREE.ShaderChunk[ 'defaultnormal_vertex' ] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + // console.log( 'THREE.Cache', 'Checking key:', key ); -// File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl + return this.files[ key ]; -THREE.ShaderChunk[ 'displacementmap_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; + }, -// File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl + remove: function ( key ) { -THREE.ShaderChunk[ 'displacementmap_pars_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n"; + delete this.files[ key ]; -// File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl + }, -THREE.ShaderChunk[ 'emissivemap_fragment' ] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; + clear: function () { -// File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl + this.files = {}; -THREE.ShaderChunk[ 'emissivemap_pars_fragment' ] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'encodings_pars_fragment' ] = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/shaders/ShaderChunk/encodings_fragment.glsl + function LoadingManager ( onLoad, onProgress, onError ) { + this.isLoadingManager = true; -THREE.ShaderChunk[ 'encodings_fragment' ] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + var scope = this; -// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl + var isLoading = false, itemsLoaded = 0, itemsTotal = 0; -THREE.ShaderChunk[ 'envmap_fragment' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\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 #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 envColor = envMapTexelToLinear( envColor );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n"; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; -// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl + this.itemStart = function ( url ) { -THREE.ShaderChunk[ 'envmap_pars_fragment' ] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n varying vec3 vWorldPosition;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n"; + itemsTotal ++; -// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl + if ( isLoading === false ) { -THREE.ShaderChunk[ 'envmap_pars_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif\n"; + if ( scope.onStart !== undefined ) { -// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl + scope.onStart( url, itemsLoaded, itemsTotal ); -THREE.ShaderChunk[ 'envmap_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl + } -THREE.ShaderChunk[ 'fog_fragment' ] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; + isLoading = true; -// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'fog_pars_fragment' ] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; + this.itemEnd = function ( url ) { -// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl + itemsLoaded ++; -THREE.ShaderChunk[ 'lightmap_fragment' ] = "#ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; + if ( scope.onProgress !== undefined ) { -// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl + scope.onProgress( url, itemsLoaded, itemsTotal ); -THREE.ShaderChunk[ 'lightmap_pars_fragment' ] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl + if ( itemsLoaded === itemsTotal ) { -THREE.ShaderChunk[ 'lights_lambert_vertex' ] = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n getPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n getSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n #endif\n }\n#endif\n"; + isLoading = false; -// File:src/renderers/shaders/ShaderChunk/lights_pars.glsl + if ( scope.onLoad !== undefined ) { -THREE.ShaderChunk[ 'lights_pars' ] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n directLight.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n if ( testLightInRange( lightDistance, pointLight.distance ) ) {\n directLight.color = pointLight.color;\n directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n float angleCos = dot( directLight.direction, spotLight.direction );\n if ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n directLight.color = spotLight.color;\n directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n vec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n #include \n vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n #else\n vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n vec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n #else\n vec4 envMapColor = vec4( 0.0 );\n #endif\n return PI * envMapColor.rgb * envMapIntensity;\n }\n float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n float maxMIPLevelScalar = float( maxMIPLevel );\n float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n }\n vec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #include \n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\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 #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\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 #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #endif\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n"; + scope.onLoad(); -// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl + } -THREE.ShaderChunk[ 'lights_phong_fragment' ] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + } -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl + }; -THREE.ShaderChunk[ 'lights_phong_pars_fragment' ] = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material ) (0)\n"; + this.itemError = function ( url ) { -// File:src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl + if ( scope.onError !== undefined ) { -THREE.ShaderChunk[ 'lights_physical_fragment' ] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n material.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n material.clearCoat = saturate( clearCoat ); material.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + scope.onError( url ); -// File:src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl + } -THREE.ShaderChunk[ 'lights_physical_pars_fragment' ] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n #ifndef STANDARD\n float clearCoat;\n float clearCoatRoughness;\n #endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n return DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n #ifndef STANDARD\n float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n #else\n float clearCoatDHR = 0.0;\n #endif\n reflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n reflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n #ifndef STANDARD\n reflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n #endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n #ifndef STANDARD\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNL = dotNV;\n float clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n #else\n float clearCoatDHR = 0.0;\n #endif\n reflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n #ifndef STANDARD\n reflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n #endif\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n"; + }; -// File:src/renderers/shaders/ShaderChunk/lights_template.glsl + }; -THREE.ShaderChunk[ 'lights_template' ] = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #ifdef USE_LIGHTMAP\n vec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #endif\n #if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n irradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n #endif\n RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n vec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n #ifndef STANDARD\n vec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n #else\n vec3 clearCoatRadiance = vec3( 0.0 );\n #endif\n \n RE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; + exports.DefaultLoadingManager = new LoadingManager(); -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'logdepthbuf_fragment' ] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; + function XHRLoader ( manager ) { + this.isXHRLoader = true; -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.ShaderChunk[ 'logdepthbuf_pars_fragment' ] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n"; + }; -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl + Object.assign( XHRLoader.prototype, { -THREE.ShaderChunk[ 'logdepthbuf_pars_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif"; + load: function ( url, onLoad, onProgress, onError ) { -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl + if ( this.path !== undefined ) url = this.path + url; -THREE.ShaderChunk[ 'logdepthbuf_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n"; + var scope = this; -// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl + var cached = exports.Cache.get( url ); -THREE.ShaderChunk[ 'map_fragment' ] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n#endif\n"; + if ( cached !== undefined ) { -// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl + scope.manager.itemStart( url ); -THREE.ShaderChunk[ 'map_pars_fragment' ] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n"; + setTimeout( function () { -// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl + if ( onLoad ) onLoad( cached ); -THREE.ShaderChunk[ 'map_particle_fragment' ] = "#ifdef USE_MAP\n vec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n diffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; + scope.manager.itemEnd( url ); -// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl + }, 0 ); -THREE.ShaderChunk[ 'map_particle_pars_fragment' ] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n"; + return cached; -// File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl + } -THREE.ShaderChunk[ 'metalnessmap_fragment' ] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n"; + var request = new XMLHttpRequest(); + request.overrideMimeType( 'text/plain' ); + request.open( 'GET', url, true ); -// File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl + request.addEventListener( 'load', function ( event ) { -THREE.ShaderChunk[ 'metalnessmap_pars_fragment' ] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; + var response = event.target.response; -// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl + exports.Cache.add( url, response ); -THREE.ShaderChunk[ 'morphnormal_vertex' ] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; + if ( this.status === 200 ) { -// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl + if ( onLoad ) onLoad( response ); -THREE.ShaderChunk[ 'morphtarget_pars_vertex' ] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif"; + scope.manager.itemEnd( url ); -// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl + } else if ( this.status === 0 ) { -THREE.ShaderChunk[ 'morphtarget_vertex' ] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n"; + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. -// File:src/renderers/shaders/ShaderChunk/normal_flip.glsl + console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); -THREE.ShaderChunk[ 'normal_flip' ] = "#ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n float flipNormal = 1.0;\n#endif\n"; + if ( onLoad ) onLoad( response ); -// File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl + scope.manager.itemEnd( url ); -THREE.ShaderChunk[ 'normal_fragment' ] = "#ifdef FLAT_SHADED\n vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; + } else { -// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl + if ( onError ) onError( event ); -THREE.ShaderChunk[ 'normalmap_pars_fragment' ] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\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 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 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#endif\n"; + scope.manager.itemError( url ); -// File:src/renderers/shaders/ShaderChunk/packing.glsl + } -THREE.ShaderChunk[ 'packing' ] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * PackFactors ), v );\n r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + }, false ); -// File:src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl + if ( onProgress !== undefined ) { -THREE.ShaderChunk[ 'premultiplied_alpha_fragment' ] = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; + request.addEventListener( 'progress', function ( event ) { -// File:src/renderers/shaders/ShaderChunk/project_vertex.glsl + onProgress( event ); -THREE.ShaderChunk[ 'project_vertex' ] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n"; + }, false ); -// File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl + } -THREE.ShaderChunk[ 'roughnessmap_fragment' ] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n"; + request.addEventListener( 'error', function ( event ) { -// File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl + if ( onError ) onError( event ); -THREE.ShaderChunk[ 'roughnessmap_pars_fragment' ] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; + scope.manager.itemError( url ); -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl + }, false ); -THREE.ShaderChunk[ 'shadowmap_pars_fragment' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n float texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n const vec2 offset = vec2( 0.0, 1.0 );\n vec2 texelSize = vec2( 1.0 ) / size;\n vec2 centroidUV = floor( uv * size + 0.5 ) / size;\n float lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n float lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n float rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n float rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n vec2 f = fract( uv * size + 0.5 );\n float a = mix( lb, lt, f.y );\n float b = mix( rb, rt, f.y );\n float c = mix( a, b, f.x );\n return c;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\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 bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n vec3 lightToPosition = shadowCoord.xyz;\n vec3 bd3D = normalize( lightToPosition );\n float dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n return (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n#endif\n"; + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl + request.send( null ); -THREE.ShaderChunk[ 'shadowmap_pars_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n#endif\n"; + scope.manager.itemStart( url ); -// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl + return request; -THREE.ShaderChunk[ 'shadowmap_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n }\n #endif\n#endif\n"; + }, -// File:src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl + setPath: function ( value ) { -THREE.ShaderChunk[ 'shadowmask_pars_fragment' ] = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n shadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n shadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n shadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #endif\n return shadow;\n}\n"; + this.path = value; + return this; -// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl + }, -THREE.ShaderChunk[ 'skinbase_vertex' ] = "#ifdef USE_SKINNING\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#endif"; + setResponseType: function ( value ) { -// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl + this.responseType = value; + return this; -THREE.ShaderChunk[ 'skinning_pars_vertex' ] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\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 mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n"; + }, -// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl + setWithCredentials: function ( value ) { -THREE.ShaderChunk[ 'skinning_vertex' ] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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#endif\n"; + this.withCredentials = value; + return this; -// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl + } -THREE.ShaderChunk[ 'skinnormal_vertex' ] = "#ifdef USE_SKINNING\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 objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; + } ); -// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl + /** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ -THREE.ShaderChunk[ 'specularmap_fragment' ] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; + function CompressedTextureLoader ( manager ) { + this.isCompressedTextureLoader = true; -// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.ShaderChunk[ 'specularmap_pars_fragment' ] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; + // override in sub classes + this._parser = null; -// File:src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl + }; -THREE.ShaderChunk[ 'tonemapping_fragment' ] = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; + Object.assign( CompressedTextureLoader.prototype, { -// File:src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl + load: function ( url, onLoad, onProgress, onError ) { -THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; + var scope = this; -// File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl + var images = []; -THREE.ShaderChunk[ 'uv2_pars_fragment' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif"; + var texture = new CompressedTexture(); + texture.image = images; -// File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl + var loader = new XHRLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); -THREE.ShaderChunk[ 'uv2_pars_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif"; + function loadTexture( i ) { -// File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl + loader.load( url[ i ], function ( buffer ) { -THREE.ShaderChunk[ 'uv2_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif"; + var texDatas = scope._parser( buffer, true ); -// File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; -THREE.ShaderChunk[ 'uv_pars_fragment' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n#endif"; + loaded += 1; -// File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl + if ( loaded === 6 ) { -THREE.ShaderChunk[ 'uv_pars_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n"; + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; -// File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl + texture.format = texDatas.format; + texture.needsUpdate = true; -THREE.ShaderChunk[ 'uv_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif"; + if ( onLoad ) onLoad( texture ); -// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl + } -THREE.ShaderChunk[ 'worldpos_vertex' ] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n"; + }, onProgress, onError ); -// File:src/renderers/shaders/UniformsUtils.js + } -/** - * Uniform Utilities - */ + if ( Array.isArray( url ) ) { -THREE.UniformsUtils = { + var loaded = 0; - merge: function ( uniforms ) { + for ( var i = 0, il = url.length; i < il; ++ i ) { - var merged = {}; + loadTexture( i ); - for ( var u = 0; u < uniforms.length; u ++ ) { + } - var tmp = this.clone( uniforms[ u ] ); + } else { - for ( var p in tmp ) { + // compressed cubemap texture stored in a single DDS file - merged[ p ] = tmp[ p ]; + loader.load( url, function ( buffer ) { - } + var texDatas = scope._parser( buffer, true ); - } + if ( texDatas.isCubemap ) { - return merged; + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; - }, + for ( var f = 0; f < faces; f ++ ) { - clone: function ( uniforms_src ) { + images[ f ] = { mipmaps : [] }; - var uniforms_dst = {}; + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { - for ( var u in uniforms_src ) { + 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; - uniforms_dst[ u ] = {}; + } - for ( var p in uniforms_src[ u ] ) { + } - var parameter_src = uniforms_src[ u ][ p ]; + } else { - 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.Matrix3 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; - uniforms_dst[ u ][ p ] = parameter_src.clone(); + } - } else if ( Array.isArray( parameter_src ) ) { + if ( texDatas.mipmapCount === 1 ) { - uniforms_dst[ u ][ p ] = parameter_src.slice(); + texture.minFilter = LinearFilter; - } else { + } - uniforms_dst[ u ][ p ] = parameter_src; + texture.format = texDatas.format; + texture.needsUpdate = true; - } + if ( onLoad ) onLoad( texture ); - } + }, onProgress, onError ); - } + } - return uniforms_dst; + return texture; - } + }, -}; + setPath: function ( value ) { -// File:src/renderers/shaders/UniformsLib.js + this.path = value; + return this; -/** - * Uniforms library for shared webgl shaders - */ + } -THREE.UniformsLib = { + } ); - common: { + /** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + */ - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, + var DataTextureLoader = BinaryTextureLoader; + function BinaryTextureLoader ( manager ) { - "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) }, + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - "specularMap": { value: null }, - "alphaMap": { value: null }, + // override in sub classes + this._parser = null; - "envMap": { value: null }, - "flipEnvMap": { value: - 1 }, - "reflectivity": { value: 1.0 }, - "refractionRatio": { value: 0.98 } + }; - }, + Object.assign( BinaryTextureLoader.prototype, { - aomap: { + load: function ( url, onLoad, onProgress, onError ) { - "aoMap": { value: null }, - "aoMapIntensity": { value: 1 } + var scope = this; - }, + var texture = new DataTexture(); - lightmap: { + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); - "lightMap": { value: null }, - "lightMapIntensity": { value: 1 } + loader.load( url, function ( buffer ) { - }, + var texData = scope._parser( buffer ); - emissivemap: { + if ( ! texData ) return; - "emissiveMap": { value: null } + if ( undefined !== texData.image ) { - }, + texture.image = texData.image; - bumpmap: { + } else if ( undefined !== texData.data ) { - "bumpMap": { value: null }, - "bumpScale": { value: 1 } + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; - }, + } - normalmap: { + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; - "normalMap": { value: null }, - "normalScale": { value: new THREE.Vector2( 1, 1 ) } + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; - }, + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; - displacementmap: { + if ( undefined !== texData.format ) { - "displacementMap": { value: null }, - "displacementScale": { value: 1 }, - "displacementBias": { value: 0 } + texture.format = texData.format; - }, + } + if ( undefined !== texData.type ) { - roughnessmap: { + texture.type = texData.type; - "roughnessMap": { value: null } + } - }, + if ( undefined !== texData.mipmaps ) { - metalnessmap: { + texture.mipmaps = texData.mipmaps; - "metalnessMap": { value: null } + } - }, + if ( 1 === texData.mipmapCount ) { - fog: { + texture.minFilter = LinearFilter; - "fogDensity": { value: 0.00025 }, - "fogNear": { value: 1 }, - "fogFar": { value: 2000 }, - "fogColor": { value: new THREE.Color( 0xffffff ) } + } - }, + texture.needsUpdate = true; - lights: { - - "ambientLightColor": { value: [] }, - - "directionalLights": { value: [], properties: { - "direction": {}, - "color": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "directionalShadowMap": { value: [] }, - "directionalShadowMatrix": { value: [] }, - - "spotLights": { value: [], properties: { - "color": {}, - "position": {}, - "direction": {}, - "distance": {}, - "coneCos": {}, - "penumbraCos": {}, - "decay": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "spotShadowMap": { value: [] }, - "spotShadowMatrix": { value: [] }, - - "pointLights": { value: [], properties: { - "color": {}, - "position": {}, - "decay": {}, - "distance": {}, - - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, - - "pointShadowMap": { value: [] }, - "pointShadowMatrix": { value: [] }, - - "hemisphereLights": { value: [], properties: { - "direction": {}, - "skyColor": {}, - "groundColor": {} - } } + if ( onLoad ) onLoad( texture, texData ); - }, + }, onProgress, onError ); - points: { - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, - "size": { value: 1.0 }, - "scale": { value: 1.0 }, - "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) } + return texture; - } + } -}; + } ); -// File:src/renderers/shaders/ShaderLib/cube_frag.glsl + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.ShaderChunk[ 'cube_frag' ] = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n gl_FragColor.a *= opacity;\n}\n"; + function ImageLoader ( manager ) { + this.isImageLoader = true; -// File:src/renderers/shaders/ShaderLib/cube_vert.glsl + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -THREE.ShaderChunk[ 'cube_vert' ] = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include \n #include \n}\n"; + }; -// File:src/renderers/shaders/ShaderLib/depth_frag.glsl + Object.assign( ImageLoader.prototype, { -THREE.ShaderChunk[ 'depth_frag' ] = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( 1.0 );\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n #endif\n}\n"; + load: function ( url, onLoad, onProgress, onError ) { -// File:src/renderers/shaders/ShaderLib/depth_vert.glsl + var scope = this; -THREE.ShaderChunk[ 'depth_vert' ] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + image.onload = function () { -// File:src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl + URL.revokeObjectURL( image.src ); -THREE.ShaderChunk[ 'distanceRGBA_frag' ] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n #include \n gl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n"; + if ( onLoad ) onLoad( image ); -// File:src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl + scope.manager.itemEnd( url ); -THREE.ShaderChunk[ 'distanceRGBA_vert' ] = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition;\n}\n"; + }; -// File:src/renderers/shaders/ShaderLib/equirect_frag.glsl + if ( url.indexOf( 'data:' ) === 0 ) { -THREE.ShaderChunk[ 'equirect_frag' ] = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldPosition );\n vec2 sampleUV;\n sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n gl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; + image.src = url; -// File:src/renderers/shaders/ShaderLib/equirect_vert.glsl + } else { -THREE.ShaderChunk[ 'equirect_vert' ] = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include \n #include \n}\n"; + var loader = new XHRLoader(); + loader.setPath( this.path ); + loader.setResponseType( 'blob' ); + loader.load( url, function ( blob ) { -// File:src/renderers/shaders/ShaderLib/linedashed_frag.glsl + image.src = URL.createObjectURL( blob ); -THREE.ShaderChunk[ 'linedashed_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + }, onProgress, onError ); -// File:src/renderers/shaders/ShaderLib/linedashed_vert.glsl + } -THREE.ShaderChunk[ 'linedashed_vert' ] = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vLineDistance = scale * lineDistance;\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n}\n"; + scope.manager.itemStart( url ); -// File:src/renderers/shaders/ShaderLib/meshbasic_frag.glsl + return image; -THREE.ShaderChunk[ 'meshbasic_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight;\n reflectedLight.directDiffuse = vec3( 0.0 );\n reflectedLight.directSpecular = vec3( 0.0 );\n reflectedLight.indirectDiffuse = diffuseColor.rgb;\n reflectedLight.indirectSpecular = vec3( 0.0 );\n #include \n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + }, -// File:src/renderers/shaders/ShaderLib/meshbasic_vert.glsl + setCrossOrigin: function ( value ) { -THREE.ShaderChunk[ 'meshbasic_vert' ] = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_ENVMAP\n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + this.crossOrigin = value; + return this; -// File:src/renderers/shaders/ShaderLib/meshlambert_frag.glsl + }, -THREE.ShaderChunk[ 'meshlambert_frag' ] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n reflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n #include \n reflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n #ifdef DOUBLE_SIDED\n reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n #else\n reflectedLight.directDiffuse = vLightFront;\n #endif\n reflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + setPath: function ( value ) { -// File:src/renderers/shaders/ShaderLib/meshlambert_vert.glsl + this.path = value; + return this; -THREE.ShaderChunk[ 'meshlambert_vert' ] = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}\n"; + } -// File:src/renderers/shaders/ShaderLib/meshphong_frag.glsl + } ); -THREE.ShaderChunk[ 'meshphong_frag' ] = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/renderers/shaders/ShaderLib/meshphong_vert.glsl + function CubeTextureLoader ( manager ) { + this.isCubeTextureLoader = true; -THREE.ShaderChunk[ 'meshphong_vert' ] = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}\n"; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; -// File:src/renderers/shaders/ShaderLib/meshphysical_frag.glsl + }; -THREE.ShaderChunk[ 'meshphysical_frag' ] = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n uniform float clearCoat;\n uniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + Object.assign( CubeTextureLoader.prototype, { -// File:src/renderers/shaders/ShaderLib/meshphysical_vert.glsl + load: function ( urls, onLoad, onProgress, onError ) { -THREE.ShaderChunk[ 'meshphysical_vert' ] = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n}\n"; + var texture = new CubeTexture(); -// File:src/renderers/shaders/ShaderLib/normal_frag.glsl + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); -THREE.ShaderChunk[ 'normal_frag' ] = "uniform float opacity;\nvarying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n #include \n gl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n #include \n}\n"; + var loaded = 0; -// File:src/renderers/shaders/ShaderLib/normal_vert.glsl + function loadTexture( i ) { -THREE.ShaderChunk[ 'normal_vert' ] = "varying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n vNormal = normalize( normalMatrix * normal );\n #include \n #include \n #include \n #include \n #include \n}\n"; + loader.load( urls[ i ], function ( image ) { -// File:src/renderers/shaders/ShaderLib/points_frag.glsl + texture.images[ i ] = image; -THREE.ShaderChunk[ 'points_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include \n #include \n #include \n #include \n}\n"; + loaded ++; -// File:src/renderers/shaders/ShaderLib/points_vert.glsl + if ( loaded === 6 ) { -THREE.ShaderChunk[ 'points_vert' ] = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #ifdef USE_SIZEATTENUATION\n gl_PointSize = size * ( scale / - mvPosition.z );\n #else\n gl_PointSize = size;\n #endif\n #include \n #include \n #include \n #include \n}\n"; + texture.needsUpdate = true; -// File:src/renderers/shaders/ShaderLib/shadow_frag.glsl + if ( onLoad ) onLoad( texture ); -THREE.ShaderChunk[ 'shadow_frag' ] = "uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n gl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n"; + } -// File:src/renderers/shaders/ShaderLib/shadow_vert.glsl + }, undefined, onError ); -THREE.ShaderChunk[ 'shadow_vert' ] = "#include \nvoid main() {\n #include \n #include \n #include \n #include \n}\n"; + } -// File:src/renderers/shaders/ShaderLib.js + for ( var i = 0; i < urls.length; ++ i ) { -/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + loadTexture( i ); + } -THREE.ShaderLib = { + return texture; - 'basic': { + }, - uniforms: THREE.UniformsUtils.merge( [ + setCrossOrigin: function ( value ) { - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'fog' ] + this.crossOrigin = value; + return this; - ] ), + }, - vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ] + setPath: function ( value ) { - }, + this.path = value; + return this; - 'lambert': { + } - uniforms: THREE.UniformsUtils.merge( [ + } ); - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + /** + * @author mrdoob / http://mrdoob.com/ + */ - { - "emissive" : { value: new THREE.Color( 0x000000 ) } - } + function TextureLoader ( manager ) { + this.isTextureLoader = true; - ] ), + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ] + }; - }, + Object.assign( TextureLoader.prototype, { - 'phong': { + load: function ( url, onLoad, onProgress, onError ) { - uniforms: THREE.UniformsUtils.merge( [ + var texture = new Texture(); - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + loader.load( url, function ( image ) { - { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "specular" : { value: new THREE.Color( 0x111111 ) }, - "shininess": { value: 30 } - } + // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. + var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - ] ), + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.image = image; + texture.needsUpdate = true; - vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ] + if ( onLoad !== undefined ) { - }, + onLoad( texture ); - 'standard': { + } - uniforms: THREE.UniformsUtils.merge( [ + }, onProgress, onError ); - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'roughnessmap' ], - THREE.UniformsLib[ 'metalnessmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + return texture; - { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "roughness": { value: 0.5 }, - "metalness": { value: 0 }, - "envMapIntensity" : { value: 1 }, // temporary - } + }, - ] ), + setCrossOrigin: function ( value ) { - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + this.crossOrigin = value; + return this; - }, + }, - 'points': { + setPath: function ( value ) { - uniforms: THREE.UniformsUtils.merge( [ + this.path = value; + return this; - THREE.UniformsLib[ 'points' ], - THREE.UniformsLib[ 'fog' ] + } - ] ), + } ); - vertexShader: THREE.ShaderChunk[ 'points_vert' ], - fragmentShader: THREE.ShaderChunk[ 'points_frag' ] + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - }, + function Light ( color, intensity ) { + this.isLight = true; - 'dashed': { + Object3D.call( this ); - uniforms: THREE.UniformsUtils.merge( [ + this.type = 'Light'; - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'fog' ], + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; - { - "scale" : { value: 1 }, - "dashSize" : { value: 1 }, - "totalSize": { value: 2 } - } + this.receiveShadow = undefined; - ] ), + }; - vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ], - fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ] + Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: Light, - 'depth': { + copy: function ( source ) { - uniforms: THREE.UniformsUtils.merge( [ + Object3D.prototype.copy.call( this, source ); - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'displacementmap' ] + this.color.copy( source.color ); + this.intensity = source.intensity; - ] ), + return this; - vertexShader: THREE.ShaderChunk[ 'depth_vert' ], - fragmentShader: THREE.ShaderChunk[ 'depth_frag' ] + }, - }, + toJSON: function ( meta ) { - 'normal': { + var data = Object3D.prototype.toJSON.call( this, meta ); - uniforms: { + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - "opacity" : { value: 1.0 } + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - }, + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; - vertexShader: THREE.ShaderChunk[ 'normal_vert' ], - fragmentShader: THREE.ShaderChunk[ 'normal_frag' ] + return data; - }, + } - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + } ); - 'cube': { + /** + * @author alteredq / http://alteredqualia.com/ + */ - uniforms: { - "tCube": { value: null }, - "tFlip": { value: - 1 }, - "opacity": { value: 1.0 } - }, + function HemisphereLight ( skyColor, groundColor, intensity ) { + this.isHemisphereLight = true; - vertexShader: THREE.ShaderChunk[ 'cube_vert' ], - fragmentShader: THREE.ShaderChunk[ 'cube_frag' ] + Light.call( this, skyColor, intensity ); - }, + this.type = 'HemisphereLight'; - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + this.castShadow = undefined; - 'equirect': { + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - uniforms: { - "tEquirect": { value: null }, - "tFlip": { value: - 1 } - }, + this.groundColor = new Color( groundColor ); - vertexShader: THREE.ShaderChunk[ 'equirect_vert' ], - fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ] + }; - }, + HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - 'distanceRGBA': { + constructor: HemisphereLight, - uniforms: { + copy: function ( source ) { - "lightPos": { value: new THREE.Vector3() } + Light.prototype.copy.call( this, source ); - }, + this.groundColor.copy( source.groundColor ); - vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ] + return this; - } + } -}; + } ); -THREE.ShaderLib[ 'physical' ] = { + /** + * @author mrdoob / http://mrdoob.com/ + */ - uniforms: THREE.UniformsUtils.merge( [ + function LightShadow ( camera ) { + this.isLightShadow = true; - THREE.ShaderLib[ 'standard' ].uniforms, + this.camera = camera; - { - "clearCoat": { value: 0 }, - "clearCoatRoughness": { value: 0 } - } + this.bias = 0; + this.radius = 1; - ] ), + this.mapSize = new Vector2( 512, 512 ); - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + this.map = null; + this.matrix = new Matrix4(); -}; + }; -// File:src/renderers/WebGLRenderer.js + Object.assign( LightShadow.prototype, { -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author tschw - */ + copy: function ( source ) { -THREE.WebGLRenderer = function ( parameters ) { + this.camera = source.camera.clone(); - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + this.bias = source.bias; + this.radius = source.radius; - parameters = parameters || {}; + this.mapSize.copy( source.mapSize ); - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + return this; - _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; + }, - var lights = []; + clone: function () { - var opaqueObjects = []; - var opaqueObjectsLastIndex = - 1; - var transparentObjects = []; - var transparentObjectsLastIndex = - 1; + return new this.constructor().copy( this ); - var morphInfluences = new Float32Array( 8 ); + } - var sprites = []; - var lensFlares = []; + } ); - // public properties + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.domElement = _canvas; - this.context = null; + function SpotLightShadow () { + this.isSpotLightShadow = true; - // clearing + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + }; - // scene graph + SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - this.sortObjects = true; + constructor: SpotLightShadow, - // user-defined clipping + update: function ( light ) { - this.clippingPlanes = []; - this.localClippingEnabled = false; + var fov = exports.Math.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || 500; - // physically based shading + var camera = this.camera; - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - // physical lights + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); - this.physicallyCorrectLights = false; + } - // tone mapping + } - this.toneMapping = THREE.LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + } ); - // morphs + /** + * @author alteredq / http://alteredqualia.com/ + */ - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + function SpotLight ( color, intensity, distance, angle, penumbra, decay ) { + this.isSpotLight = true; - // internal properties + Light.call( this, color, intensity ); - var _this = this, + this.type = 'SpotLight'; - // internal state cache + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - _currentProgram = null, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, + this.target = new Object3D(); - _currentScissor = new THREE.Vector4(), - _currentScissorTest = null, + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * Math.PI; + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / Math.PI; + } + } ); - _currentViewport = new THREE.Vector4(), + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - // + this.shadow = new SpotLightShadow(); - _usedTextureUnits = 0, + }; - // + SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0, + constructor: SpotLight, - _width = _canvas.width, - _height = _canvas.height, + copy: function ( source ) { - _pixelRatio = 1, + Light.prototype.copy.call( this, source ); - _scissor = new THREE.Vector4( 0, 0, _width, _height ), - _scissorTest = false, + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - _viewport = new THREE.Vector4( 0, 0, _width, _height ), + this.target = source.target.clone(); - // frustum + this.shadow = source.shadow.clone(); - _frustum = new THREE.Frustum(), + return this; - // clipping + } - _clipping = new THREE.WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + } ); - _sphere = new THREE.Sphere(), + /** + * @author mrdoob / http://mrdoob.com/ + */ - // camera matrices cache - _projScreenMatrix = new THREE.Matrix4(), + function PointLight ( color, intensity, distance, decay ) { + this.isPointLight = true; - _vector3 = new THREE.Vector3(), + Light.call( this, color, intensity ); - // light arrays cache + this.type = 'PointLight'; - _lights = { + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * 4 * Math.PI; - hash: '', + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / ( 4 * Math.PI ); + } + } ); - ambient: [ 0, 0, 0 ], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - shadows: [] + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - }, + }; - // info + PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - _infoRender = { + constructor: PointLight, - calls: 0, - vertices: 0, - faces: 0, - points: 0 + copy: function ( source ) { - }; + Light.prototype.copy.call( this, source ); - this.info = { + this.distance = source.distance; + this.decay = source.decay; - render: _infoRender, - memory: { + this.shadow = source.shadow.clone(); - geometries: 0, - textures: 0 + return this; - }, - programs: null + } - }; + } ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - // initialize + function DirectionalLightShadow ( light ) { + this.isDirectionalLightShadow = true; - var _gl; + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - try { + }; - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + constructor: DirectionalLightShadow - if ( _gl === null ) { + } ); - if ( _canvas.getContext( 'webgl' ) !== null ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - throw 'Error creating WebGL context with your selected attributes.'; + function DirectionalLight ( color, intensity ) { + this.isDirectionalLight = true; - } else { + Light.call( this, color, intensity ); - throw 'Error creating WebGL context.'; + this.type = 'DirectionalLight'; - } + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - } + this.target = new Object3D(); - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + this.shadow = new DirectionalLightShadow(); - if ( _gl.getShaderPrecisionFormat === undefined ) { + }; - _gl.getShaderPrecisionFormat = function () { + DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + constructor: DirectionalLight, - }; + copy: function ( source ) { - } + Light.prototype.copy.call( this, source ); - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + this.target = source.target.clone(); - } catch ( error ) { + this.shadow = source.shadow.clone(); - console.error( 'THREE.WebGLRenderer: ' + error ); + return this; - } + } - var extensions = new THREE.WebGLExtensions( _gl ); + } ); - extensions.get( 'WEBGL_depth_texture' ); - 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' ); - extensions.get( 'ANGLE_instanced_arrays' ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( extensions.get( 'OES_element_index_uint' ) ) { + function AmbientLight ( color, intensity ) { + this.isAmbientLight = true; - THREE.BufferGeometry.MaxIndex = 4294967296; + Light.call( this, color, intensity ); - } + this.type = 'AmbientLight'; - var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); + this.castShadow = undefined; - var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new THREE.WebGLProperties(); - var textures = new THREE.WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); - var objects = new THREE.WebGLObjects( _gl, properties, this.info ); - var programCache = new THREE.WebGLPrograms( this, capabilities ); - var lightCache = new THREE.WebGLLights(); + }; - this.info.programs = programCache.programs; + AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + constructor: AmbientLight - // + } ); - var backgroundCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - var backgroundCamera2 = new THREE.PerspectiveCamera(); - var backgroundPlaneMesh = new THREE.Mesh( - new THREE.PlaneBufferGeometry( 2, 2 ), - new THREE.MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) - ); - var backgroundBoxShader = THREE.ShaderLib[ 'cube' ]; - var backgroundBoxMesh = new THREE.Mesh( - new THREE.BoxBufferGeometry( 5, 5, 5 ), - new THREE.ShaderMaterial( { - uniforms: backgroundBoxShader.uniforms, - vertexShader: backgroundBoxShader.vertexShader, - fragmentShader: backgroundBoxShader.fragmentShader, - side: THREE.BackSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); + /** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - // + exports.AnimationUtils = { - function getTargetPixelRatio() { + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function( array, from, to ) { - return _currentRenderTarget === null ? _pixelRatio : 1; + if ( exports.AnimationUtils.isTypedArray( array ) ) { - } + return new array.constructor( array.subarray( from, to ) ); - function glClearColor( r, g, b, a ) { + } - if ( _premultipliedAlpha === true ) { + return array.slice( from, to ); - r *= a; g *= a; b *= a; + }, - } + // converts an array to a specific type + convertArray: function( array, type, forceClone ) { - state.clearColor( r, g, b, a ); + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - } + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - function setDefaultGLState() { + return new type( array ); // create typed array - state.init(); + } - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + return Array.prototype.slice.call( array ); // create Array - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + }, - } + isTypedArray: function( object ) { - function resetGLState() { + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); - _currentProgram = null; - _currentCamera = null; + }, - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + // returns an array by which times and values can be sorted + getKeyframeOrder: function( times ) { - state.reset(); + function compareTime( i, j ) { - } + return times[ i ] - times[ j ]; - setDefaultGLState(); + } - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.properties = properties; - this.state = state; + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - // shadow map + result.sort( compareTime ); - var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects, capabilities ); + return result; - this.shadowMap = shadowMap; + }, + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function( values, stride, order ) { - // Plugins + var nValues = values.length; + var result = new values.constructor( nValues ); - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - // API + var srcOffset = order[ i ] * stride; - this.getContext = function () { + for ( var j = 0; j !== stride; ++ j ) { - return _gl; + result[ dstOffset ++ ] = values[ srcOffset + j ]; - }; + } - this.getContextAttributes = function () { + } - return _gl.getContextAttributes(); + return result; - }; + }, - this.forceContextLoss = function () { + // function for parsing AOS keyframe formats + flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { - extensions.get( 'WEBGL_lose_context' ).loseContext(); + var i = 1, key = jsonKeys[ 0 ]; - }; + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - this.getMaxAnisotropy = function () { + key = jsonKeys[ i ++ ]; - return capabilities.getMaxAnisotropy(); + } - }; + if ( key === undefined ) return; // no data - this.getPrecision = function () { + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - return capabilities.precision; + if ( Array.isArray( value ) ) { - }; + do { - this.getPixelRatio = function () { + value = key[ valuePropertyName ]; - return _pixelRatio; + if ( value !== undefined ) { - }; + times.push( key.time ); + values.push.apply( values, value ); // push all elements - this.setPixelRatio = function ( value ) { + } - if ( value === undefined ) return; + key = jsonKeys[ i ++ ]; - _pixelRatio = value; + } while ( key !== undefined ); - this.setSize( _viewport.z, _viewport.w, false ); + } else if ( value.toArray !== undefined ) { + // ...assume THREE.Math-ish - }; + do { - this.getSize = function () { + value = key[ valuePropertyName ]; - return { - width: _width, - height: _height - }; + if ( value !== undefined ) { - }; + times.push( key.time ); + value.toArray( values, values.length ); - this.setSize = function ( width, height, updateStyle ) { + } - _width = width; - _height = height; + key = jsonKeys[ i ++ ]; - _canvas.width = width * _pixelRatio; - _canvas.height = height * _pixelRatio; + } while ( key !== undefined ); - if ( updateStyle !== false ) { + } else { + // otherwise push as-is - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + do { - } + value = key[ valuePropertyName ]; - this.setViewport( 0, 0, width, height ); + if ( value !== undefined ) { - }; + times.push( key.time ); + values.push( value ); - this.setViewport = function ( x, y, width, height ) { + } - state.viewport( _viewport.set( x, y, width, height ) ); + key = jsonKeys[ i ++ ]; - }; + } while ( key !== undefined ); - this.setScissor = function ( x, y, width, height ) { + } - state.scissor( _scissor.set( x, y, width, height ) ); + } - }; + }; - this.setScissorTest = function ( boolean ) { + /** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: + * + * http://www.oodesign.com/template-method-pattern.html + * + * @author tschw + */ - state.setScissorTest( _scissorTest = boolean ); + function Interpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isInterpolant = true; - }; + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - // Clearing + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - this.getClearColor = function () { + }; - return _clearColor; + Interpolant.prototype = { - }; + constructor: Interpolant, - this.setClearColor = function ( color, alpha ) { + evaluate: function( t ) { - _clearColor.set( color ); + var pp = this.parameterPositions, + i1 = this._cachedIndex, - _clearAlpha = alpha !== undefined ? alpha : 1; + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + validate_interval: { - }; + seek: { - this.getClearAlpha = function () { + var right; - return _clearAlpha; + linear_scan: { + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - }; + for ( var giveUpAt = i1 + 2; ;) { - this.setClearAlpha = function ( alpha ) { + if ( t1 === undefined ) { - _clearAlpha = alpha; + if ( t < t0 ) break forward_scan; - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + // after end - }; + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - this.clear = function ( color, depth, stencil ) { + } - var bits = 0; + if ( i1 === giveUpAt ) break; // this loop - 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; + t0 = t1; + t1 = pp[ ++ i1 ]; - _gl.clear( bits ); + if ( t < t1 ) { - }; + // we have arrived at the sought interval + break seek; - this.clearColor = function () { + } - this.clear( true, false, false ); + } - }; + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - this.clearDepth = function () { + } - this.clear( false, true, false ); + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - }; + // looping? - this.clearStencil = function () { + var t1global = pp[ 1 ]; - this.clear( false, false, true ); + if ( t < t1global ) { - }; + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + } - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + // linear reverse scan - }; + for ( var giveUpAt = i1 - 2; ;) { - // Reset + if ( t0 === undefined ) { - this.resetGLState = resetGLState; + // before start - this.dispose = function() { + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - transparentObjects = []; - transparentObjectsLastIndex = -1; - opaqueObjects = []; - opaqueObjectsLastIndex = -1; + } - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + if ( i1 === giveUpAt ) break; // this loop - }; + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - // Events + if ( t >= t0 ) { - function onContextLost( event ) { + // we have arrived at the sought interval + break seek; - event.preventDefault(); + } - resetGLState(); - setDefaultGLState(); + } - properties.clear(); + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - } + } - function onMaterialDispose( event ) { + // the interval is valid - var material = event.target; + break validate_interval; - material.removeEventListener( 'dispose', onMaterialDispose ); + } // linear scan - deallocateMaterial( material ); + // binary search - } + while ( i1 < right ) { - // Buffer deallocation + var mid = ( i1 + right ) >>> 1; - function deallocateMaterial( material ) { + if ( t < pp[ mid ] ) { - releaseMaterialProgramReference( material ); + right = mid; - properties.delete( material ); + } else { - } + i1 = mid + 1; + } - function releaseMaterialProgramReference( material ) { + } - var programInfo = properties.get( material ).program; + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - material.program = undefined; + // check boundary cases, again - if ( programInfo !== undefined ) { + if ( t0 === undefined ) { - programCache.releaseProgram( programInfo ); + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - } + } - } + if ( t1 === undefined ) { - // Buffer rendering + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - this.renderBufferImmediate = function ( object, program, material ) { + } - state.initAttributes(); + } // seek - var buffers = properties.get( object ); + this._cachedIndex = i1; - if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); - if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); - if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); - if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); + this.intervalChanged_( i1, t0, t1 ); - var attributes = program.getAttributes(); + } // validate_interval - if ( object.hasPositions ) { + return this.interpolate_( i1, t0, t, t1 ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - } + // --- Protected interface - if ( object.hasNormals ) { + DefaultSettings_: {}, - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + getSettings_: function() { - if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) { + return this.settings || this.DefaultSettings_; - for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { + }, - var array = object.normalArray; + copySampleValue_: function( index ) { - var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; - var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; - var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; + // copies a sample value to the result buffer - array[ i + 0 ] = nx; - array[ i + 1 ] = ny; - array[ i + 2 ] = nz; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + for ( var i = 0; i !== stride; ++ i ) { - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + result[ i ] = values[ offset + i ]; - } + } - } + return result; - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( attributes.normal ); + // Template methods for derived classes: - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + interpolate_: function( i1, t0, t, t1 ) { - } + throw new Error( "call to abstract method" ); + // implementations shall return this.resultBuffer - if ( object.hasUvs && material.map ) { + }, - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + intervalChanged_: function( i1, t0, t1 ) { - state.enableAttribute( attributes.uv ); + // empty - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + } - } + }; - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + Object.assign( Interpolant.prototype, { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + beforeStart_: //( 0, t, t0 ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_, - state.enableAttribute( attributes.color ); + afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_ - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + } ); - } + /** + * Fast and simple cubic spline interpolant. + * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. + * + * @author tschw + */ - state.disableUnusedAttributes(); + function CubicInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isCubicInterpolant = true; - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - object.count = 0; + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; - }; + }; - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - setMaterial( material ); + constructor: CubicInterpolant, - var program = setProgram( camera, fog, material, object ); + DefaultSettings_: { - var updateBuffers = false; - var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - if ( geometryProgram !== _currentGeometryProgram ) { + }, - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + intervalChanged_: function( i1, t0, t1 ) { - } + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - // morph targets + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - var morphTargetInfluences = object.morphTargetInfluences; + if ( tPrev === undefined ) { - if ( morphTargetInfluences !== undefined ) { + switch ( this.getSettings_().endingStart ) { - var activeInfluences = []; + case ZeroSlopeEnding: - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + break; - } + case WrapAroundEnding: - activeInfluences.sort( absNumericalSort ); + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - if ( activeInfluences.length > 8 ) { + break; - activeInfluences.length = 8; + default: // ZeroCurvatureEnding - } + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - var morphAttributes = geometry.morphAttributes; + } - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + } - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; + if ( tNext === undefined ) { - if ( influence[ 0 ] !== 0 ) { + switch ( this.getSettings_().endingEnd ) { - var index = influence[ 1 ]; + case ZeroSlopeEnding: - if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); - if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - } else { + break; - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + case WrapAroundEnding: - } + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - } + break; - program.getUniforms().setValue( - _gl, 'morphTargetInfluences', morphInfluences ); + default: // ZeroCurvatureEnding - updateBuffers = true; + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - } + } - // + } - var index = geometry.index; - var position = geometry.attributes.position; + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - if ( material.wireframe === true ) { + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; - index = objects.getWireframeAttribute( geometry ); + }, - } + interpolate_: function( i1, t0, t, t1 ) { - var renderer; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - if ( index !== null ) { + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - renderer = indexedBufferRenderer; - renderer.setIndex( index ); + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - } else { + // evaluate polynomials - renderer = bufferRenderer; + var sP = - wP * ppp + 2 * wP * pp - wP * p; + var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; + var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + var sN = wN * ppp - wN * pp; - } + // combine data linearly - if ( updateBuffers ) { + for ( var i = 0; i !== stride; ++ i ) { - setupVertexAttributes( material, program, geometry ); + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; - if ( index !== null ) { + } - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); + return result; - } + } - } + } ); - // + /** + * @author tschw + */ - var dataStart = 0; - var dataCount = Infinity; + function LinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isLinearInterpolant = true; - if ( index !== null ) { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - dataCount = index.count; + }; - } else if ( position !== undefined ) { + LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - dataCount = position.count; + constructor: LinearInterpolant, - } + interpolate_: function( i1, t0, t, t1 ) { - var rangeStart = geometry.drawRange.start; - var rangeCount = geometry.drawRange.count; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - var groupStart = group !== null ? group.start : 0; - var groupCount = group !== null ? group.count : Infinity; + offset1 = i1 * stride, + offset0 = offset1 - stride, - var drawStart = Math.max( dataStart, rangeStart, groupStart ); - var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + for ( var i = 0; i !== stride; ++ i ) { - // + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - if ( object instanceof THREE.Mesh ) { + } - if ( material.wireframe === true ) { + return result; - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( _gl.LINES ); + } - } else { + } ); - switch ( object.drawMode ) { + /** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - case THREE.TrianglesDrawMode: - renderer.setMode( _gl.TRIANGLES ); - break; + function DiscreteInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isDiscreteInterpolant = true; - case THREE.TriangleStripDrawMode: - renderer.setMode( _gl.TRIANGLE_STRIP ); - break; + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - case THREE.TriangleFanDrawMode: - renderer.setMode( _gl.TRIANGLE_FAN ); - break; + }; - } + DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - } + constructor: DiscreteInterpolant, + interpolate_: function( i1, t0, t, t1 ) { - } else if ( object instanceof THREE.Line ) { + return this.copySampleValue_( i1 - 1 ); - var lineWidth = material.linewidth; + } - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + } ); - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + var KeyframeTrackPrototype; - if ( object instanceof THREE.LineSegments ) { + KeyframeTrackPrototype = { - renderer.setMode( _gl.LINES ); + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, - } else { + DefaultInterpolation: InterpolateLinear, - renderer.setMode( _gl.LINE_STRIP ); + InterpolantFactoryMethodDiscrete: function( result ) { - } + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); - } else if ( object instanceof THREE.Points ) { + }, - renderer.setMode( _gl.POINTS ); + InterpolantFactoryMethodLinear: function( result ) { - } + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + }, - if ( geometry.maxInstancedCount > 0 ) { + InterpolantFactoryMethodSmooth: function( result ) { - renderer.renderInstances( geometry, drawStart, drawCount ); + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); - } + }, - } else { + setInterpolation: function( interpolation ) { - renderer.render( drawStart, drawCount ); + var factoryMethod; - } + switch ( interpolation ) { - }; + case InterpolateDiscrete: - function setupVertexAttributes( material, program, geometry, startIndex ) { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - var extension; + break; - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + case InterpolateLinear: - extension = extensions.get( 'ANGLE_instanced_arrays' ); + factoryMethod = this.InterpolantFactoryMethodLinear; - if ( extension === null ) { + break; - console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + case InterpolateSmooth: - } + factoryMethod = this.InterpolantFactoryMethodSmooth; - } + break; - if ( startIndex === undefined ) startIndex = 0; + } - state.initAttributes(); + if ( factoryMethod === undefined ) { - var geometryAttributes = geometry.attributes; + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - var programAttributes = program.getAttributes(); + if ( this.createInterpolant === undefined ) { - var materialDefaultAttributeValues = material.defaultAttributeValues; + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - for ( var name in programAttributes ) { + this.setInterpolation( this.DefaultInterpolation ); - var programAttribute = programAttributes[ name ]; + } else { - if ( programAttribute >= 0 ) { + throw new Error( message ); // fatal, in this case - var geometryAttribute = geometryAttributes[ name ]; + } - if ( geometryAttribute !== undefined ) { + } - var type = _gl.FLOAT; - var array = geometryAttribute.array; - var normalized = geometryAttribute.normalized; + console.warn( message ); + return; - if ( array instanceof Float32Array ) { + } - type = _gl.FLOAT; + this.createInterpolant = factoryMethod; - } else if ( array instanceof Float64Array ) { + }, - console.warn("Unsupported data buffer format: Float64Array"); + getInterpolation: function() { - } else if ( array instanceof Uint16Array ) { + switch ( this.createInterpolant ) { - type = _gl.UNSIGNED_SHORT; + case this.InterpolantFactoryMethodDiscrete: - } else if ( array instanceof Int16Array ) { + return InterpolateDiscrete; - type = _gl.SHORT; + case this.InterpolantFactoryMethodLinear: - } else if ( array instanceof Uint32Array ) { + return InterpolateLinear; - type = _gl.UNSIGNED_INT; + case this.InterpolantFactoryMethodSmooth: - } else if ( array instanceof Int32Array ) { + return InterpolateSmooth; - type = _gl.INT; + } - } else if ( array instanceof Int8Array ) { + }, - type = _gl.BYTE; + getValueSize: function() { - } else if ( array instanceof Uint8Array ) { + return this.values.length / this.times.length; - type = _gl.UNSIGNED_BYTE; + }, - } + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { - var size = geometryAttribute.itemSize; - var buffer = objects.getAttributeBuffer( geometryAttribute ); + if( timeOffset !== 0.0 ) { - if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) { + var times = this.times; - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + for( var i = 0, n = times.length; i !== n; ++ i ) { - if ( data instanceof THREE.InstancedInterleavedBuffer ) { + times[ i ] += timeOffset; - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); + } - if ( geometry.maxInstancedCount === undefined ) { + } - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + return this; - } + }, - } else { + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { - state.enableAttribute( programAttribute ); + if( timeScale !== 1.0 ) { - } + var times = this.times; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); + for( var i = 0, n = times.length; i !== n; ++ i ) { - } else { + times[ i ] *= timeScale; - if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) { + } - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); + } - if ( geometry.maxInstancedCount === undefined ) { + return this; - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + }, - } + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function( startTime, endTime ) { - } else { + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; - state.enableAttribute( programAttribute ); + while ( from !== nKeys && times[ from ] < startTime ) ++ from; + while ( to !== -1 && times[ to ] > endTime ) -- to; - } + ++ to; // inclusive -> exclusive bound - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); + if( from !== 0 || to !== nKeys ) { - } + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - } else if ( materialDefaultAttributeValues !== undefined ) { + var stride = this.getValueSize(); + this.times = exports.AnimationUtils.arraySlice( times, from, to ); + this.values = exports.AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); - var value = materialDefaultAttributeValues[ name ]; + } - if ( value !== undefined ) { + return this; - switch ( value.length ) { + }, - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + var valid = true; - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - default: - _gl.vertexAttrib1fv( programAttribute, value ); + console.error( "invalid value size in track", this ); + valid = false; - } + } - } + var times = this.times, + values = this.values, - } + nKeys = times.length; - } + if( nKeys === 0 ) { - } + console.error( "track is empty", this ); + valid = false; - state.disableUnusedAttributes(); + } - } + var prevTime = null; - // Sorting + for( var i = 0; i !== nKeys; i ++ ) { - function absNumericalSort( a, b ) { + var currTime = times[ i ]; - return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - } + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; - function painterSortStable ( a, b ) { + } - if ( a.object.renderOrder !== b.object.renderOrder ) { + if( prevTime !== null && prevTime > currTime ) { - return a.object.renderOrder - b.object.renderOrder; + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; - } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { + } - return a.material.program.id - b.material.program.id; + prevTime = currTime; - } else if ( a.material.id !== b.material.id ) { + } - return a.material.id - b.material.id; + if ( values !== undefined ) { - } else if ( a.z !== b.z ) { + if ( exports.AnimationUtils.isTypedArray( values ) ) { - return a.z - b.z; + for ( var i = 0, n = values.length; i !== n; ++ i ) { - } else { + var value = values[ i ]; - return a.id - b.id; + if ( isNaN( value ) ) { - } + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; - } + } - function reversePainterSortStable ( a, b ) { + } - if ( a.object.renderOrder !== b.object.renderOrder ) { + } - return a.object.renderOrder - b.object.renderOrder; + } - } if ( a.z !== b.z ) { + return valid; - return b.z - a.z; + }, - } else { + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function() { - return a.id - b.id; + var times = this.times, + values = this.values, + stride = this.getValueSize(), - } + writeIndex = 1; - } + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - // Rendering + var keep = false; - this.render = function ( scene, camera, renderTarget, forceClear ) { + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - if ( camera instanceof THREE.Camera === false ) { + // remove adjacent keyframes scheduled at the same time - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - } + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - var fog = scene.fog; + for ( var j = 0; j !== stride; ++ j ) { - // reset caching for this frame + var value = values[ offset + j ]; - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - // update scene graph + keep = true; + break; - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + } - // update camera matrices and frustum + } - if ( camera.parent === null ) camera.updateMatrixWorld(); + } - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + // in-place compaction - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + if ( keep ) { - lights.length = 0; + if ( i !== writeIndex ) { - opaqueObjectsLastIndex = - 1; - transparentObjectsLastIndex = - 1; + times[ writeIndex ] = times[ i ]; - sprites.length = 0; - lensFlares.length = 0; + var readOffset = i * stride, + writeOffset = writeIndex * stride; - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + for ( var j = 0; j !== stride; ++ j ) { - projectObject( scene, camera ); + values[ writeOffset + j ] = values[ readOffset + j ]; - opaqueObjects.length = opaqueObjectsLastIndex + 1; - transparentObjects.length = transparentObjectsLastIndex + 1; + } - if ( _this.sortObjects === true ) { - opaqueObjects.sort( painterSortStable ); - transparentObjects.sort( reversePainterSortStable ); + } - } + ++ writeIndex; - // + } - if ( _clippingEnabled ) _clipping.beginShadows(); + } - setupShadows( lights ); + if ( writeIndex !== times.length ) { - shadowMap.render( scene, camera ); + this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - setupLights( lights, camera ); + } - if ( _clippingEnabled ) _clipping.endShadows(); + return this; - // + } - _infoRender.calls = 0; - _infoRender.vertices = 0; - _infoRender.faces = 0; - _infoRender.points = 0; + } - if ( renderTarget === undefined ) { + function KeyframeTrackConstructor ( name, times, values, interpolation ) { + this.isKeyframeTrack = true; - renderTarget = null; + if( name === undefined ) throw new Error( "track name is undefined" ); - } + if( times === undefined || times.length === 0 ) { - this.setRenderTarget( renderTarget ); + throw new Error( "no keyframes in track named " + name ); - // + } - var background = scene.background; + this.name = name; - if ( background === null ) { + this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + this.setInterpolation( interpolation || this.DefaultInterpolation ); - } else if ( background instanceof THREE.Color ) { + this.validate(); + this.optimize(); - glClearColor( background.r, background.g, background.b, 1 ); + } - } + /** + * + * A Track of vectored keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - if ( this.autoClear || forceClear ) { + function VectorKeyframeTrack ( name, times, values, interpolation ) { + this.isVectorKeyframeTrack = true; - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - } + }; - if ( background instanceof THREE.CubeTexture ) { + VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); + constructor: VectorKeyframeTrack, - backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); - backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); + ValueTypeName: 'vector' - backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; - backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); + // ValueBufferType is inherited - objects.update( backgroundBoxMesh ); + // DefaultInterpolation is inherited - _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); + } ); - } else if ( background instanceof THREE.Texture ) { + /** + * Spherical linear unit quaternion interpolant. + * + * @author tschw + */ - backgroundPlaneMesh.material.map = background; + function QuaternionLinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isQuaternionLinearInterpolant = true; - objects.update( backgroundPlaneMesh ); + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); + }; - } + QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - // + constructor: QuaternionLinearInterpolant, - if ( scene.overrideMaterial ) { + interpolate_: function( i1, t0, t, t1 ) { - var overrideMaterial = scene.overrideMaterial; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - renderObjects( opaqueObjects, camera, fog, overrideMaterial ); - renderObjects( transparentObjects, camera, fog, overrideMaterial ); + offset = i1 * stride, - } else { + alpha = ( t - t0 ) / ( t1 - t0 ); - // opaque pass (front-to-back order) + for ( var end = offset + stride; offset !== end; offset += 4 ) { - state.setBlending( THREE.NoBlending ); - renderObjects( opaqueObjects, camera, fog ); + Quaternion.slerpFlat( result, 0, + values, offset - stride, values, offset, alpha ); - // transparent pass (back-to-front order) + } - renderObjects( transparentObjects, camera, fog ); + return result; - } + } - // custom render plugins (post pass) + } ); - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentViewport ); + /** + * + * A Track of quaternion keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // Generate mipmap if we're using any kind of mipmap filtering + function QuaternionKeyframeTrack ( name, times, values, interpolation ) { + this.isQuaternionKeyframeTrack = true; - if ( renderTarget ) { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - textures.updateRenderTargetMipmap( renderTarget ); + }; - } + QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - // Ensure depth buffer writing is enabled so it can be cleared on next render + constructor: QuaternionKeyframeTrack, - state.setDepthTest( true ); - state.setDepthWrite( true ); - state.setColorWrite( true ); + ValueTypeName: 'quaternion', - // _gl.finish(); + // ValueBufferType is inherited - }; + DefaultInterpolation: InterpolateLinear, - function pushRenderItem( object, geometry, material, z, group ) { + InterpolantFactoryMethodLinear: function( result ) { - var array, index; + return new QuaternionLinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - // allocate the next position in the appropriate array + }, - if ( material.transparent ) { + InterpolantFactoryMethodSmooth: undefined // not yet implemented - array = transparentObjects; - index = ++ transparentObjectsLastIndex; + } ); - } else { + /** + * + * A Track of numeric keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - array = opaqueObjects; - index = ++ opaqueObjectsLastIndex; + function NumberKeyframeTrack ( name, times, values, interpolation ) { + this.isNumberKeyframeTrack = true; - } + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - // recycle existing render item or grow the array + }; - var renderItem = array[ index ]; + NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - if ( renderItem !== undefined ) { + constructor: NumberKeyframeTrack, - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.z = _vector3.z; - renderItem.group = group; + ValueTypeName: 'number', - } else { + // ValueBufferType is inherited - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - z: _vector3.z, - group: group - }; + // DefaultInterpolation is inherited - // assert( index === array.length ); - array.push( renderItem ); + } ); - } + /** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function StringKeyframeTrack ( name, times, values, interpolation ) { + this.isStringKeyframeTrack = true; - // TODO Duplicated code (Frustum) + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - function isObjectViewable( object ) { + }; - var geometry = object.geometry; + StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + constructor: StringKeyframeTrack, - _sphere.copy( geometry.boundingSphere ). - applyMatrix4( object.matrixWorld ); + ValueTypeName: 'string', + ValueBufferType: Array, - return isSphereViewable( _sphere ); + DefaultInterpolation: InterpolateDiscrete, - } + InterpolantFactoryMethodLinear: undefined, - function isSpriteViewable( sprite ) { + InterpolantFactoryMethodSmooth: undefined - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); + } ); - return isSphereViewable( _sphere ); + /** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function BooleanKeyframeTrack ( name, times, values ) { + this.isBooleanKeyframeTrack = true; - function isSphereViewable( sphere ) { + KeyframeTrackConstructor.call( this, name, times, values ); - if ( ! _frustum.intersectsSphere( sphere ) ) return false; + }; - var numPlanes = _clipping.numPlanes; + BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - if ( numPlanes === 0 ) return true; + constructor: BooleanKeyframeTrack, - var planes = _this.clippingPlanes, + ValueTypeName: 'bool', + ValueBufferType: Array, - center = sphere.center, - negRad = - sphere.radius, - i = 0; + DefaultInterpolation: InterpolateDiscrete, - do { + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - // out when deeper than radius in the negative halfspace - if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - } while ( ++ i !== numPlanes ); + } ); - return true; + /** + * + * A Track of keyframe values that represent color. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function ColorKeyframeTrack ( name, times, values, interpolation ) { + this.isColorKeyframeTrack = true; - function projectObject( object, camera ) { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - if ( object.visible === false ) return; + }; - if ( object.layers.test( camera.layers ) ) { + ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - if ( object instanceof THREE.Light ) { + constructor: ColorKeyframeTrack, - lights.push( object ); + ValueTypeName: 'color' - } else if ( object instanceof THREE.Sprite ) { + // ValueBufferType is inherited - if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { + // DefaultInterpolation is inherited - sprites.push( object ); - } + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. - } else if ( object instanceof THREE.LensFlare ) { + } ); - lensFlares.push( object ); + /** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } else if ( object instanceof THREE.ImmediateRenderObject ) { + function KeyframeTrack ( name, times, values, interpolation ) { + KeyframeTrackConstructor.apply( this, arguments ); + }; - if ( _this.sortObjects === true ) { + KeyframeTrack.prototype = KeyframeTrackPrototype; + KeyframeTrackPrototype.constructor = KeyframeTrack; - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + // Static methods: - } + Object.assign( KeyframeTrack, { - pushRenderItem( object, null, object.material, _vector3.z, null ); + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) { + parse: function( json ) { - if ( object instanceof THREE.SkinnedMesh ) { + if( json.type === undefined ) { - object.skeleton.update(); + throw new Error( "track type undefined, can not parse" ); - } + } - if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); - var material = object.material; + if ( json.times === undefined ) { - if ( material.visible === true ) { + var times = [], values = []; - if ( _this.sortObjects === true ) { + exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + json.times = times; + json.values = values; - } + } - var geometry = objects.update( object ); + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - if ( material instanceof THREE.MultiMaterial ) { + return trackType.parse( json ); - var groups = geometry.groups; - var materials = material.materials; + } else { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + // by default, we asssume a constructor compatible with the base + return new trackType( + json.name, json.times, json.values, json.interpolation ); - var group = groups[ i ]; - var groupMaterial = materials[ group.materialIndex ]; + } - if ( groupMaterial.visible === true ) { + }, - pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); + toJSON: function( track ) { - } + var trackType = track.constructor; - } + var json; - } else { + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - pushRenderItem( object, geometry, material, _vector3.z, null ); + json = trackType.toJSON( track ); - } + } else { - } + // by default, we assume the data can be serialized as-is + json = { - } + 'name': track.name, + 'times': exports.AnimationUtils.convertArray( track.times, Array ), + 'values': exports.AnimationUtils.convertArray( track.values, Array ) - } + }; - } + var interpolation = track.getInterpolation(); - var children = object.children; + if ( interpolation !== track.DefaultInterpolation ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + json.interpolation = interpolation; - projectObject( children[ i ], camera ); + } - } + } - } + json.type = track.ValueTypeName; // mandatory - function renderObjects( renderList, camera, fog, overrideMaterial ) { + return json; - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + }, - var renderItem = renderList[ i ]; + _getTrackTypeForValueTypeName: function( typeName ) { - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + switch( typeName.toLowerCase() ) { - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + case "scalar": + case "double": + case "float": + case "number": + case "integer": - if ( object instanceof THREE.ImmediateRenderObject ) { + return NumberKeyframeTrack; - setMaterial( material ); + case "vector": + case "vector2": + case "vector3": + case "vector4": - var program = setProgram( camera, fog, material, object ); + return VectorKeyframeTrack; - _currentGeometryProgram = ''; + case "color": - object.render( function ( object ) { + return ColorKeyframeTrack; - _this.renderBufferImmediate( object, program, material ); + case "quaternion": - } ); + return QuaternionKeyframeTrack; - } else { + case "bool": + case "boolean": - _this.renderBufferDirect( camera, fog, geometry, material, object, group ); + return BooleanKeyframeTrack; - } + case "string": - } + return StringKeyframeTrack; - } + } - function initMaterial( material, fog, object ) { + throw new Error( "Unsupported typeName: " + typeName ); - var materialProperties = properties.get( material ); + } - var parameters = programCache.getParameters( - material, _lights, fog, _clipping.numPlanes, object ); + } ); - var code = programCache.getProgramCode( material, parameters ); + /** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - var program = materialProperties.program; - var programChange = true; + function AnimationClip ( name, duration, tracks ) { + this.isAnimationClip = true; - if ( program === undefined ) { + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : -1; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + this.uuid = exports.Math.generateUUID(); - } else if ( program.code !== code ) { + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - // changed glsl or parameters - releaseMaterialProgramReference( material ); + this.resetDuration(); - } else if ( parameters.shaderID !== undefined ) { + } - // same glsl and uniform list - return; + // maybe only do these on demand, as doing them here could potentially slow down loading + // but leaving these here during development as this ensures a lot of testing of these functions + this.trim(); + this.optimize(); - } else { + }; - // only rebuild uniform list - programChange = false; + AnimationClip.prototype = { - } + constructor: AnimationClip, - if ( programChange ) { + resetDuration: function() { - if ( parameters.shaderID ) { + var tracks = this.tracks, + duration = 0; - var shader = THREE.ShaderLib[ parameters.shaderID ]; + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { - materialProperties.__webglShader = { - name: material.type, - uniforms: THREE.UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + var track = this.tracks[ i ]; - } else { + duration = Math.max( + duration, track.times[ track.times.length - 1 ] ); - materialProperties.__webglShader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + } - } + this.duration = duration; - material.__webglShader = materialProperties.__webglShader; + }, - program = programCache.acquireProgram( material, parameters, code ); + trim: function() { - materialProperties.program = program; - material.program = program; + for ( var i = 0; i < this.tracks.length; i ++ ) { - } + this.tracks[ i ].trim( 0, this.duration ); - var attributes = program.getAttributes(); + } - if ( material.morphTargets ) { + return this; - material.numSupportedMorphTargets = 0; + }, - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + optimize: function() { - if ( attributes[ 'morphTarget' + i ] >= 0 ) { + for ( var i = 0; i < this.tracks.length; i ++ ) { - material.numSupportedMorphTargets ++; + this.tracks[ i ].optimize(); - } + } - } + return this; - } + } - if ( material.morphNormals ) { + }; - material.numSupportedMorphNormals = 0; + // Static methods: - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { + Object.assign( AnimationClip, { - if ( attributes[ 'morphNormal' + i ] >= 0 ) { + parse: function( json ) { - material.numSupportedMorphNormals ++; + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - } + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - } + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); - } + } - var uniforms = materialProperties.__webglShader.uniforms; + return new AnimationClip( json.name, json.duration, tracks ); - if ( ! ( material instanceof THREE.ShaderMaterial ) && - ! ( material instanceof THREE.RawShaderMaterial ) || - material.clipping === true ) { + }, - materialProperties.numClippingPlanes = _clipping.numPlanes; - uniforms.clippingPlanes = _clipping.uniform; - } + toJSON: function( clip ) { - if ( material.lights ) { + var tracks = [], + clipTracks = clip.tracks; - // store the light setup it was created for + var json = { - materialProperties.lightsHash = _lights.hash; + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks - // wire up the material to this renderer's lighting state + }; - uniforms.ambientLightColor.value = _lights.ambient; - uniforms.directionalLights.value = _lights.directional; - uniforms.spotLights.value = _lights.spot; - uniforms.pointLights.value = _lights.point; - uniforms.hemisphereLights.value = _lights.hemi; + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - uniforms.directionalShadowMap.value = _lights.directionalShadowMap; - uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; - uniforms.spotShadowMap.value = _lights.spotShadowMap; - uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; - uniforms.pointShadowMap.value = _lights.pointShadowMap; - uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - } + } - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + return json; - materialProperties.uniformsList = uniformsList; - materialProperties.dynamicUniforms = - THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + }, - } - function setMaterial( material ) { + CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { - if ( material.side !== THREE.DoubleSide ) - state.enable( _gl.CULL_FACE ); - else - state.disable( _gl.CULL_FACE ); + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - state.setFlipSided( material.side === THREE.BackSide ); + for ( var i = 0; i < numMorphTargets; i ++ ) { - if ( material.transparent === true ) { + var times = []; + var values = []; - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - } else { + values.push( 0, 1, 0 ); - state.setBlending( THREE.NoBlending ); + var order = exports.AnimationUtils.getKeyframeOrder( times ); + times = exports.AnimationUtils.sortedArray( times, 1, order ); + values = exports.AnimationUtils.sortedArray( values, 1, order ); - } + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { - state.setDepthFunc( material.depthFunc ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); - state.setColorWrite( material.colorWrite ); - state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - } + } - function setProgram( camera, fog, material, object ) { + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + } - _usedTextureUnits = 0; + return new AnimationClip( name, -1, tracks ); - var materialProperties = properties.get( material ); + }, - if ( _clippingEnabled ) { + findByName: function( objectOrClipArray, name ) { - if ( _localClippingEnabled || camera !== _currentCamera ) { + var clipArray = objectOrClipArray; - var useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + if ( ! Array.isArray( objectOrClipArray ) ) { - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - _clipping.setState( - material.clippingPlanes, material.clipShadows, - camera, materialProperties, useCache ); + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - } + } - if ( materialProperties.numClippingPlanes !== undefined && - materialProperties.numClippingPlanes !== _clipping.numPlanes ) { + for ( var i = 0; i < clipArray.length; i ++ ) { - material.needsUpdate = true; + if ( clipArray[ i ].name === name ) { - } + return clipArray[ i ]; - } + } + } - if ( materialProperties.program === undefined ) { + return null; - material.needsUpdate = true; + }, - } + CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { - if ( materialProperties.lightsHash !== undefined && - materialProperties.lightsHash !== _lights.hash ) { + var animationToMorphTargets = {}; - material.needsUpdate = true; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - } + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { - if ( material.needsUpdate ) { + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - initMaterial( material, fog, object ); - material.needsUpdate = false; + if ( parts && parts.length > 1 ) { - } + var name = parts[ 1 ]; - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + var animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.__webglShader.uniforms; + animationToMorphTargets[ name ] = animationMorphTargets = []; - if ( program.id !== _currentProgram ) { + } - _gl.useProgram( program.program ); - _currentProgram = program.id; + animationMorphTargets.push( morphTarget ); - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + } - } + } - if ( material.id !== _currentMaterialId ) { + var clips = []; - _currentMaterialId = material.id; + for ( var name in animationToMorphTargets ) { - refreshMaterial = true; + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - } + } - if ( refreshProgram || camera !== _currentCamera ) { + return clips; - p_uniforms.set( _gl, camera, 'projectionMatrix' ); + }, - if ( capabilities.logarithmicDepthBuffer ) { + // parse the animation.hierarchy format + parseAnimation: function( animation, bones, nodeName ) { - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + if ( ! animation ) { - } + console.error( " no animation in JSONLoader data" ); + return null; + } - if ( camera !== _currentCamera ) { + var addNonemptyTrack = function( + trackType, trackName, animationKeys, propertyName, destTracks ) { - _currentCamera = camera; + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + var times = []; + var values = []; - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + exports.AnimationUtils.flattenJSON( + animationKeys, times, values, propertyName ); - } + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + destTracks.push( new trackType( trackName, times, values ) ); - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material.envMap ) { + } - var uCamPos = p_uniforms.map.cameraPosition; + } - if ( uCamPos !== undefined ) { + }; - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + var tracks = []; - } + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || -1; + var fps = animation.fps || 30; - } + var hierarchyTracks = animation.hierarchy || []; - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.ShaderMaterial || - material.skinning ) { + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + var animationKeys = hierarchyTracks[ h ].keys; - } + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - p_uniforms.set( _gl, _this, 'toneMappingExposure' ); - p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); + // process morph targets in a way exactly compatible + // with AnimationHandler.init( animation ) + if ( animationKeys[0].morphTargets ) { - } + // figure out all morph targets used in this track + var morphTargetNames = {}; + for ( var k = 0; k < animationKeys.length; k ++ ) { - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + if ( animationKeys[k].morphTargets ) { - if ( material.skinning ) { + for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; + } - var skeleton = object.skeleton; + } - if ( skeleton ) { + } - if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( var morphTargetName in morphTargetNames ) { - p_uniforms.set( _gl, skeleton, 'boneTexture' ); - p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); - p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); + var times = []; + var values = []; - } else { + for ( var m = 0; + m !== animationKeys[k].morphTargets.length; ++ m ) { - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + var animationKey = animationKeys[k]; - } + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - } + } - } + tracks.push( new NumberKeyframeTrack( + '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - if ( refreshMaterial ) { + } - if ( material.lights ) { + duration = morphTargetNames.length * ( fps || 1.0 ); - // the current material requires lighting info + } else { + // ...assume skeletal animation - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + var boneName = '.bones[' + bones[ h ].name + ']'; - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - } + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); - // refresh uniforms common to several materials + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - if ( fog && material.fog ) { + } - refreshUniformsFog( m_uniforms, fog ); + } - } + if ( tracks.length === 0 ) { - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.MeshDepthMaterial ) { + return null; - refreshUniformsCommon( m_uniforms, material ); + } - } + var clip = new AnimationClip( clipName, duration, tracks ); - // refresh single material specific uniforms + return clip; - if ( material instanceof THREE.LineBasicMaterial ) { + } - refreshUniformsLine( m_uniforms, material ); + } ); - } else if ( material instanceof THREE.LineDashedMaterial ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + function MaterialLoader ( manager ) { + this.isMaterialLoader = true; - } else if ( material instanceof THREE.PointsMaterial ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.textures = {}; - refreshUniformsPoints( m_uniforms, material ); + }; - } else if ( material instanceof THREE.MeshLambertMaterial ) { + Object.assign( MaterialLoader.prototype, { - refreshUniformsLambert( m_uniforms, material ); + load: function ( url, onLoad, onProgress, onError ) { - } else if ( material instanceof THREE.MeshPhongMaterial ) { + var scope = this; - refreshUniformsPhong( m_uniforms, material ); + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - } else if ( material instanceof THREE.MeshPhysicalMaterial ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - refreshUniformsPhysical( m_uniforms, material ); + }, onProgress, onError ); - } else if ( material instanceof THREE.MeshStandardMaterial ) { + }, - refreshUniformsStandard( m_uniforms, material ); + setTextures: function ( value ) { - } else if ( material instanceof THREE.MeshDepthMaterial ) { + this.textures = value; - if ( material.displacementMap ) { + }, - m_uniforms.displacementMap.value = material.displacementMap; - m_uniforms.displacementScale.value = material.displacementScale; - m_uniforms.displacementBias.value = material.displacementBias; + getTexture: function ( name ) { - } + var textures = this.textures; - } else if ( material instanceof THREE.MeshNormalMaterial ) { + if ( textures[ name ] === undefined ) { - m_uniforms.opacity.value = material.opacity; + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - } + } - THREE.WebGLUniforms.upload( - _gl, materialProperties.uniformsList, m_uniforms, _this ); + return textures[ name ]; - } + }, + parse: function ( json ) { - // common matrices + var material = new THREE[ json.type ]; - p_uniforms.set( _gl, object, 'modelViewMatrix' ); - p_uniforms.set( _gl, object, 'normalMatrix' ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.roughness !== undefined ) material.roughness = json.roughness; + if ( json.metalness !== undefined ) material.metalness = json.metalness; + 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.alphaTest !== undefined ) material.alphaTest = json.alphaTest; + if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + // for PointsMaterial + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - // dynamic uniforms + // maps - var dynUniforms = materialProperties.dynamicUniforms; + if ( json.map !== undefined ) material.map = this.getTexture( json.map ); - if ( dynUniforms !== null ) { + if ( json.alphaMap !== undefined ) { - THREE.WebGLUniforms.evalDynamic( - dynUniforms, m_uniforms, object, camera ); + material.alphaMap = this.getTexture( json.alphaMap ); + material.transparent = true; - THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + } - } + if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - return program; + if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); + if ( json.normalScale !== undefined ) { - } + var normalScale = json.normalScale; - // Uniforms (refresh uniforms objects) + if ( Array.isArray( normalScale ) === false ) { - function refreshUniformsCommon ( uniforms, material ) { + // Blender exporter used to export a scalar. See #7459 - uniforms.opacity.value = material.opacity; + normalScale = [ normalScale, normalScale ]; - uniforms.diffuse.value = material.color; + } - if ( material.emissive ) { + material.normalScale = new Vector2().fromArray( normalScale ); - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + } - } + if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); - if ( material.aoMap ) { + if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); - } + if ( json.envMap !== undefined ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map + material.envMap = this.getTexture( json.envMap ); + material.combine = MultiplyOperation; - var uvScaleMap; + } - if ( material.map ) { + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - uvScaleMap = material.map; + if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - } else if ( material.specularMap ) { + if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - uvScaleMap = material.specularMap; + // MultiMaterial - } else if ( material.displacementMap ) { + if ( json.materials !== undefined ) { - uvScaleMap = material.displacementMap; + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - } else if ( material.normalMap ) { + material.materials.push( this.parse( json.materials[ i ] ) ); - uvScaleMap = material.normalMap; + } - } else if ( material.bumpMap ) { + } - uvScaleMap = material.bumpMap; + return material; - } else if ( material.roughnessMap ) { + } - uvScaleMap = material.roughnessMap; + } ); - } else if ( material.metalnessMap ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - uvScaleMap = material.metalnessMap; + function BufferGeometryLoader ( manager ) { + this.isBufferGeometryLoader = true; - } else if ( material.alphaMap ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - uvScaleMap = material.alphaMap; + }; - } else if ( material.emissiveMap ) { + Object.assign( BufferGeometryLoader.prototype, { - uvScaleMap = material.emissiveMap; + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - if ( uvScaleMap !== undefined ) { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - // backwards compatibility - if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - uvScaleMap = uvScaleMap.texture; + }, onProgress, onError ); - } + }, - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + parse: function ( json ) { - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + var geometry = new BufferGeometry(); - } + var index = json.data.index; - uniforms.envMap.value = material.envMap; + var TYPED_ARRAYS = { + 'Int8Array': Int8Array, + 'Uint8Array': Uint8Array, + 'Uint8ClampedArray': Uint8ClampedArray, + 'Int16Array': Int16Array, + 'Uint16Array': Uint16Array, + 'Int32Array': Int32Array, + 'Uint32Array': Uint32Array, + 'Float32Array': Float32Array, + 'Float64Array': Float64Array + }; - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1; + if ( index !== undefined ) { - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - } + } - function refreshUniformsLine ( uniforms, material ) { + var attributes = json.data.attributes; - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + for ( var key in attributes ) { - } + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - function refreshUniformsDash ( uniforms, material ) { + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + } - } + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - function refreshUniformsPoints ( uniforms, material ) { + if ( groups !== undefined ) { - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _canvas.clientHeight * 0.5; + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - uniforms.map.value = material.map; + var group = groups[ i ]; - if ( material.map !== null ) { + geometry.addGroup( group.start, group.count, group.materialIndex ); - var offset = material.map.offset; - var repeat = material.map.repeat; + } - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + } - } + var boundingSphere = json.data.boundingSphere; - } + if ( boundingSphere !== undefined ) { - function refreshUniformsFog ( uniforms, fog ) { + var center = new Vector3(); - uniforms.fogColor.value = fog.color; + if ( boundingSphere.center !== undefined ) { - if ( fog instanceof THREE.Fog ) { + center.fromArray( boundingSphere.center ); - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + } - } else if ( fog instanceof THREE.FogExp2 ) { + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - uniforms.fogDensity.value = fog.density; + } - } + return geometry; - } + } - function refreshUniformsLambert ( uniforms, material ) { + } ); - if ( material.lightMap ) { + /** + * @author alteredq / http://alteredqualia.com/ + */ - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + function Loader () { + this.isLoader = true; - } + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; - if ( material.emissiveMap ) { + }; - uniforms.emissiveMap.value = material.emissiveMap; + Loader.prototype = { - } + constructor: Loader, - } + crossOrigin: undefined, - function refreshUniformsPhong ( uniforms, material ) { + extractUrlBase: function ( url ) { - uniforms.specular.value = material.specular; - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + var parts = url.split( '/' ); - if ( material.lightMap ) { + if ( parts.length === 1 ) return './'; - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + parts.pop(); - } + return parts.join( '/' ) + '/'; - if ( material.emissiveMap ) { + }, - uniforms.emissiveMap.value = material.emissiveMap; + initMaterials: function ( materials, texturePath, crossOrigin ) { - } + var array = []; - if ( material.bumpMap ) { + for ( var i = 0; i < materials.length; ++ i ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); - } + } - if ( material.normalMap ) { + return array; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + }, - } + createMaterial: ( function () { - if ( material.displacementMap ) { + var color, textureLoader, materialLoader; - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + return function createMaterial( m, texturePath, crossOrigin ) { - } + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); - } + // convert from old material format - function refreshUniformsStandard ( uniforms, material ) { + var textures = {}; - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + function loadTexture( path, repeat, offset, wrap, anisotropy ) { - if ( material.roughnessMap ) { + var fullPath = texturePath + path; + var loader = Loader.Handlers.get( fullPath ); - uniforms.roughnessMap.value = material.roughnessMap; + var texture; - } + if ( loader !== null ) { - if ( material.metalnessMap ) { + texture = loader.load( fullPath ); - uniforms.metalnessMap.value = material.metalnessMap; + } else { - } + textureLoader.setCrossOrigin( crossOrigin ); + texture = textureLoader.load( fullPath ); - if ( material.lightMap ) { + } - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + if ( repeat !== undefined ) { - } + texture.repeat.fromArray( repeat ); - if ( material.emissiveMap ) { + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; - uniforms.emissiveMap.value = material.emissiveMap; + } - } + if ( offset !== undefined ) { - if ( material.bumpMap ) { + texture.offset.fromArray( offset ); - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + } - } + if ( wrap !== undefined ) { - if ( material.normalMap ) { + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; - } + } - if ( material.displacementMap ) { + if ( anisotropy !== undefined ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + texture.anisotropy = anisotropy; - } + } - if ( material.envMap ) { + var uuid = exports.Math.generateUUID(); - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + textures[ uuid ] = texture; - } + return uuid; - } + } - function refreshUniformsPhysical ( uniforms, material ) { + // - uniforms.clearCoat.value = material.clearCoat; - uniforms.clearCoatRoughness.value = material.clearCoatRoughness; + var json = { + uuid: exports.Math.generateUUID(), + type: 'MeshLambertMaterial' + }; + + for ( var name in m ) { + + var value = m[ name ]; + + switch ( name ) { + case 'DbgColor': + case 'DbgIndex': + case 'opticalDensity': + case 'illumination': + break; + case 'DbgName': + json.name = value; + break; + case 'blending': + json.blending = THREE[ value ]; + break; + case 'colorAmbient': + case 'mapAmbient': + console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); + break; + case 'colorDiffuse': + json.color = color.fromArray( value ).getHex(); + break; + case 'colorSpecular': + json.specular = color.fromArray( value ).getHex(); + break; + case 'colorEmissive': + json.emissive = color.fromArray( value ).getHex(); + break; + case 'specularCoef': + json.shininess = value; + break; + case 'shading': + if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; + if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; + if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; + break; + case 'mapDiffuse': + json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + break; + case 'mapDiffuseRepeat': + case 'mapDiffuseOffset': + case 'mapDiffuseWrap': + case 'mapDiffuseAnisotropy': + break; + case 'mapEmissive': + json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); + break; + case 'mapEmissiveRepeat': + case 'mapEmissiveOffset': + case 'mapEmissiveWrap': + case 'mapEmissiveAnisotropy': + break; + case 'mapLight': + json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + break; + case 'mapLightRepeat': + case 'mapLightOffset': + case 'mapLightWrap': + case 'mapLightAnisotropy': + break; + case 'mapAO': + json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); + break; + case 'mapAORepeat': + case 'mapAOOffset': + case 'mapAOWrap': + case 'mapAOAnisotropy': + break; + case 'mapBump': + json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + break; + case 'mapBumpScale': + json.bumpScale = value; + break; + case 'mapBumpRepeat': + case 'mapBumpOffset': + case 'mapBumpWrap': + case 'mapBumpAnisotropy': + break; + case 'mapNormal': + json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + break; + case 'mapNormalFactor': + json.normalScale = [ value, value ]; + break; + case 'mapNormalRepeat': + case 'mapNormalOffset': + case 'mapNormalWrap': + case 'mapNormalAnisotropy': + break; + case 'mapSpecular': + json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + break; + case 'mapSpecularRepeat': + case 'mapSpecularOffset': + case 'mapSpecularWrap': + case 'mapSpecularAnisotropy': + break; + case 'mapMetalness': + json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); + break; + case 'mapMetalnessRepeat': + case 'mapMetalnessOffset': + case 'mapMetalnessWrap': + case 'mapMetalnessAnisotropy': + break; + case 'mapRoughness': + json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); + break; + case 'mapRoughnessRepeat': + case 'mapRoughnessOffset': + case 'mapRoughnessWrap': + case 'mapRoughnessAnisotropy': + break; + case 'mapAlpha': + json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + break; + case 'mapAlphaRepeat': + case 'mapAlphaOffset': + case 'mapAlphaWrap': + case 'mapAlphaAnisotropy': + break; + case 'flipSided': + json.side = BackSide; + break; + case 'doubleSided': + json.side = DoubleSide; + break; + case 'transparency': + console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); + json.opacity = value; + break; + case 'depthTest': + case 'depthWrite': + case 'colorWrite': + case 'opacity': + case 'reflectivity': + case 'transparent': + case 'visible': + case 'wireframe': + json[ name ] = value; + break; + case 'vertexColors': + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; + break; + default: + console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); + break; + } + + } + + if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; + if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; + + if ( json.opacity < 1 ) json.transparent = true; + + materialLoader.setTextures( textures ); + + return materialLoader.parse( json ); - refreshUniformsStandard( uniforms, material ); + }; - } + } )() - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + }; - function markUniformsLightsNeedsUpdate ( uniforms, value ) { + Loader.Handlers = { - uniforms.ambientLightColor.needsUpdate = value; + handlers: [], - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + add: function ( regex, loader ) { - } + this.handlers.push( regex, loader ); - // Lighting + }, - function setupShadows ( lights ) { + get: function ( file ) { - var lightShadowsLength = 0; + var handlers = this.handlers; - for ( var i = 0, l = lights.length; i < l; i ++ ) { + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - var light = lights[ i ]; + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - if ( light.castShadow ) { + if ( regex.test( file ) ) { - _lights.shadows[ lightShadowsLength ++ ] = light; + return loader; - } + } - } + } - _lights.shadows.length = lightShadowsLength; + return null; - } + } - function setupLights ( lights, camera ) { + }; - var l, ll, light, - r = 0, g = 0, b = 0, - color, - intensity, - distance, - shadowMap, + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - viewMatrix = camera.matrixWorldInverse, + function JSONLoader ( manager ) { + this.isJSONLoader = true; - directionalLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0; + if ( typeof manager === 'boolean' ) { - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); + manager = undefined; - light = lights[ l ]; + } - color = light.color; - intensity = light.intensity; - distance = light.distance; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + this.withCredentials = false; - if ( light instanceof THREE.AmbientLight ) { + }; - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + Object.assign( JSONLoader.prototype, { - } else if ( light instanceof THREE.DirectionalLight ) { + load: function( url, onLoad, onProgress, onError ) { - var uniforms = lightCache.get( light ); + var scope = this; - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - uniforms.shadow = light.castShadow; + var loader = new XHRLoader( this.manager ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - if ( light.castShadow ) { + var json = JSON.parse( text ); + var metadata = json.metadata; - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + if ( metadata !== undefined ) { - } + var type = metadata.type; - _lights.directionalShadowMap[ directionalLength ] = shadowMap; - _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - _lights.directional[ directionalLength ++ ] = uniforms; + if ( type !== undefined ) { - } else if ( light instanceof THREE.SpotLight ) { + if ( type.toLowerCase() === 'object' ) { - var uniforms = lightCache.get( light ); + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + } - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + if ( type.toLowerCase() === 'scene' ) { - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); + return; - uniforms.coneCos = Math.cos( light.angle ); - uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } - uniforms.shadow = light.castShadow; + } - if ( light.castShadow ) { + } - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + var object = scope.parse( json, texturePath ); + onLoad( object.geometry, object.materials ); - } + }, onProgress, onError ); - _lights.spotShadowMap[ spotLength ] = shadowMap; - _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - _lights.spot[ spotLength ++ ] = uniforms; + }, - } else if ( light instanceof THREE.PointLight ) { + setTexturePath: function ( value ) { - var uniforms = lightCache.get( light ); + this.texturePath = value; - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + }, - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + parse: function ( json, texturePath ) { - uniforms.shadow = light.castShadow; + var geometry = new Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - if ( light.castShadow ) { + parseModel( scale ); - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + parseSkin(); + parseMorphing( scale ); + parseAnimations(); - } + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - _lights.pointShadowMap[ pointLength ] = shadowMap; + function parseModel( scale ) { - if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { + function isBitSet( value, position ) { - _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4(); + return value & ( 1 << position ); - } + } - // for point lights we set the shadow matrix to be a translation-only matrix - // equal to inverse of the light's position - _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); - _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); + var i, j, fi, - _lights.point[ pointLength ++ ] = uniforms; + offset, zLength, - } else if ( light instanceof THREE.HemisphereLight ) { + colorIndex, normalIndex, uvIndex, materialIndex, - var uniforms = lightCache.get( light ); + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); + vertex, face, faceA, faceB, hex, normal, - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + uvLayer, uv, u, v, - _lights.hemi[ hemiLength ++ ] = uniforms; + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - } + nUvLayers = 0; - } + if ( json.uvs !== undefined ) { - _lights.ambient[ 0 ] = r; - _lights.ambient[ 1 ] = g; - _lights.ambient[ 2 ] = b; + // disregard empty arrays - _lights.directional.length = directionalLength; - _lights.spot.length = spotLength; - _lights.point.length = pointLength; - _lights.hemi.length = hemiLength; + for ( i = 0; i < json.uvs.length; i ++ ) { - _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; + if ( json.uvs[ i ].length ) nUvLayers ++; - } + } - // GL state setting + for ( i = 0; i < nUvLayers; i ++ ) { - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + geometry.faceVertexUvs[ i ] = []; - state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW ); + } - }; + } - // Textures + offset = 0; + zLength = vertices.length; - function allocTextureUnit() { + while ( offset < zLength ) { - var textureUnit = _usedTextureUnits; + vertex = new Vector3(); - if ( textureUnit >= capabilities.maxTextures ) { + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + geometry.vertices.push( vertex ); - } + } - _usedTextureUnits += 1; + offset = 0; + zLength = faces.length; - return textureUnit; + while ( offset < zLength ) { - } + type = faces[ offset ++ ]; - this.allocTextureUnit = allocTextureUnit; - // this.setTexture2D = setTexture2D; - this.setTexture2D = ( function() { + 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 ); - var warned = false; + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - // backwards compatibility: peel texture.texture - return function setTexture2D( texture, slot ) { + if ( isQuad ) { - if ( texture instanceof THREE.WebGLRenderTarget ) { + faceA = new Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - if ( ! warned ) { + faceB = new Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warned = true; + offset += 4; - } + if ( hasMaterial ) { - texture = texture.texture; + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - } + } - textures.setTexture2D( texture, slot ); + // to get face <=> uv index correspondence - }; + fi = geometry.faces.length; - }() ); + if ( hasFaceVertexUv ) { - this.setTexture = ( function() { + for ( i = 0; i < nUvLayers; i ++ ) { - var warned = false; + uvLayer = json.uvs[ i ]; - return function setTexture( texture, slot ) { + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = []; - if ( ! warned ) { + for ( j = 0; j < 4; j ++ ) { - console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); - warned = true; + uvIndex = faces[ offset ++ ]; - } + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - textures.setTexture2D( texture, slot ); + uv = new Vector2( u, v ); - }; + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - }() ); + } - this.setTextureCube = ( function() { + } - var warned = false; + } - return function setTextureCube( texture, slot ) { + if ( hasFaceNormal ) { - // backwards compatibility: peel texture.texture - if ( texture instanceof THREE.WebGLRenderTargetCube ) { + normalIndex = faces[ offset ++ ] * 3; - if ( ! warned ) { + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warned = true; + faceB.normal.copy( faceA.normal ); - } + } - texture = texture.texture; + if ( hasFaceVertexNormal ) { - } + for ( i = 0; i < 4; i ++ ) { - // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture - // TODO: unify these code paths - if ( texture instanceof THREE.CubeTexture || - ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { + normalIndex = faces[ offset ++ ] * 3; - // CompressedTexture can have Array in image :/ + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - // this function alone should take care of cube textures - textures.setTextureCube( texture, slot ); - } else { + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - // assumed: texture property of THREE.WebGLRenderTargetCube + } - textures.setTextureCubeDynamic( texture, slot ); + } - } - }; + if ( hasFaceColor ) { - }() ); + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - this.getCurrentRenderTarget = function() { + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - return _currentRenderTarget; + } - }; - this.setRenderTarget = function ( renderTarget ) { + if ( hasFaceVertexColor ) { - _currentRenderTarget = renderTarget; + for ( i = 0; i < 4; i ++ ) { - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - textures.setupRenderTarget( renderTarget ); + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); - } + } - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - var framebuffer; + } - if ( renderTarget ) { + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - var renderTargetProperties = properties.get( renderTarget ); + } else { - if ( isCube ) { + face = new Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; + if ( hasMaterial ) { - } else { + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - framebuffer = renderTargetProperties.__webglFramebuffer; + } - } + // to get face <=> uv index correspondence - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + fi = geometry.faces.length; - _currentViewport.copy( renderTarget.viewport ); + if ( hasFaceVertexUv ) { - } else { + for ( i = 0; i < nUvLayers; i ++ ) { - framebuffer = null; + uvLayer = json.uvs[ i ]; - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); - _currentScissorTest = _scissorTest; + geometry.faceVertexUvs[ i ][ fi ] = []; - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + for ( j = 0; j < 3; j ++ ) { - } + uvIndex = faces[ offset ++ ]; - if ( _currentFramebuffer !== framebuffer ) { + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _currentFramebuffer = framebuffer; + uv = new Vector2( u, v ); - } + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + } - state.viewport( _currentViewport ); + } - if ( isCube ) { + } - var textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); + if ( hasFaceNormal ) { - } + normalIndex = faces[ offset ++ ] * 3; - }; + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { + } - if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) { + if ( hasFaceVertexNormal ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + for ( i = 0; i < 3; i ++ ) { - } + normalIndex = faces[ offset ++ ] * 3; - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( framebuffer ) { + face.vertexNormals.push( normal ); - var restore = false; + } - if ( framebuffer !== _currentFramebuffer ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - restore = true; + if ( hasFaceColor ) { - } + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - try { + } - var texture = renderTarget.texture; - if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + if ( hasFaceVertexColor ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + for ( i = 0; i < 3; i ++ ) { - } + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); - if ( texture.type !== THREE.UnsignedByteType && - paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && - ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && - ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + } - } + geometry.faces.push( face ); - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + } - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + } - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + } - _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); + function parseSkin() { - } + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - } else { + if ( json.skinWeights ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + 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; - } finally { + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); - if ( restore ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + } - } + if ( json.skinIndices ) { - } + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - } + 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 Vector4( a, b, c, d ) ); - // Map three.js constants to WebGL constants + } - function paramThreeToGL ( p ) { + } - var extension; + geometry.bones = json.bones; - 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 ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - 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; + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + } - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + } - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + function parseMorphing( scale ) { - extension = extensions.get( 'OES_texture_half_float' ); + if ( json.morphTargets !== undefined ) { - if ( extension !== null ) { + for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { - if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - } + var dstVertices = geometry.morphTargets[ i ].vertices; + var srcVertices = json.morphTargets[ i ].vertices; - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT; + for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - 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 vertex = new Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - 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; + dstVertices.push( vertex ); - 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 ) { + } - 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; + if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { - } + console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + var faces = geometry.faces; + var morphColors = json.morphColors[ 0 ].colors; - if ( extension !== null ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - 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; + faces[ i ].color.fromArray( morphColors, i * 3 ); - } + } - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + } - if ( extension !== null ) { + } - if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + function parseAnimations() { - } + var outputAnimations = []; - extension = extensions.get( 'EXT_blend_minmax' ); + // parse old style Bone/Hierarchy animations + var animations = []; - if ( extension !== null ) { + if ( json.animation !== undefined ) { - if ( p === THREE.MinEquation ) return extension.MIN_EXT; - if ( p === THREE.MaxEquation ) return extension.MAX_EXT; + animations.push( json.animation ); - } + } - return 0; + if ( json.animations !== undefined ) { - } + if ( json.animations.length ) { -}; + animations = animations.concat( json.animations ); -// File:src/renderers/WebGLRenderTarget.js + } else { -/** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ + animations.push( json.animations ); -/* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers -*/ -THREE.WebGLRenderTarget = function ( width, height, options ) { + } - this.uuid = THREE.Math.generateUUID(); + } - this.width = width; - this.height = height; + for ( var i = 0; i < animations.length; i ++ ) { - this.scissor = new THREE.Vector4( 0, 0, width, height ); - this.scissorTest = false; + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + if ( clip ) outputAnimations.push( clip ); - this.viewport = new THREE.Vector4( 0, 0, width, height ); + } - options = options || {}; + // parse implicit morph animations + if ( geometry.morphTargets ) { - if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter; + // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + outputAnimations = outputAnimations.concat( morphAnimationClips ); - this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + } - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - this.depthTexture = null; + if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; -}; + } -Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototype, { + if ( json.materials === undefined || json.materials.length === 0 ) { - setSize: function ( width, height ) { + return { geometry: geometry }; - if ( this.width !== width || this.height !== height ) { + } else { - this.width = width; - this.height = height; + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); - this.dispose(); + return { geometry: geometry, materials: materials }; - } + } - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + } - }, + } ); - clone: function () { + /** + * @author mrdoob / http://mrdoob.com/ + */ - return new this.constructor().copy( this ); + function ObjectLoader ( manager ) { + this.isObjectLoader = true; - }, + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.texturePath = ''; - copy: function ( source ) { + }; - this.width = source.width; - this.height = source.height; + Object.assign( ObjectLoader.prototype, { - this.viewport.copy( source.viewport ); + load: function ( url, onLoad, onProgress, onError ) { - this.texture = source.texture.clone(); + if ( this.texturePath === '' ) { - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - return this; + } - }, + var scope = this; - dispose: function () { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - this.dispatchEvent( { type: 'dispose' } ); + scope.parse( JSON.parse( text ), onLoad ); - } + }, onProgress, onError ); -} ); + }, -// File:src/renderers/WebGLRenderTargetCube.js + setTexturePath: function ( value ) { -/** - * @author alteredq / http://alteredqualia.com - */ + this.texturePath = value; -THREE.WebGLRenderTargetCube = function ( width, height, options ) { + }, - THREE.WebGLRenderTarget.call( this, width, height, options ); + setCrossOrigin: function ( value ) { - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - this.activeMipMapLevel = 0; + this.crossOrigin = value; -}; + }, -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; + parse: function ( json, onLoad ) { -// File:src/renderers/webgl/WebGLBufferRenderer.js + var geometries = this.parseGeometries( json.geometries ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + var images = this.parseImages( json.images, function () { -THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { + if ( onLoad !== undefined ) onLoad( object ); - var mode; + } ); - function setMode( value ) { + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - mode = value; + var object = this.parseObject( json.object, geometries, materials ); - } + if ( json.animations ) { - function render( start, count ) { + object.animations = this.parseAnimations( json.animations ); - _gl.drawArrays( mode, start, count ); + } - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + if ( json.images === undefined || json.images.length === 0 ) { - } + if ( onLoad !== undefined ) onLoad( object ); - function renderInstances( geometry ) { + } - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + return object; - if ( extension === null ) { + }, - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + parseGeometries: function ( json ) { - } + var geometries = {}; - var position = geometry.attributes.position; + if ( json !== undefined ) { - var count = 0; + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); - if ( position instanceof THREE.InterleavedBufferAttribute ) { + for ( var i = 0, l = json.length; i < l; i ++ ) { - count = position.data.count; + var geometry; + var data = json[ i ]; - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + switch ( data.type ) { - } else { + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - count = position.count; + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + break; - } + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - } + break; - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + case 'CircleGeometry': + case 'CircleBufferGeometry': -}; + geometry = new THREE[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); -// File:src/renderers/webgl/WebGLClipping.js + break; -THREE.WebGLClipping = function() { + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - var scope = this, + geometry = new THREE[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + break; - plane = new THREE.Plane(), - viewNormalMatrix = new THREE.Matrix3(), + case 'ConeGeometry': + case 'ConeBufferGeometry': - uniform = { value: null, needsUpdate: false }; + geometry = new THREE [ data.type ]( + data.radius, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - this.uniform = uniform; - this.numPlanes = 0; + break; - this.init = function( planes, enableLocalClipping, camera ) { + case 'SphereGeometry': + case 'SphereBufferGeometry': - var enabled = - planes.length !== 0 || - enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || - localClippingEnabled; + geometry = new THREE[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - localClippingEnabled = enableLocalClipping; + break; - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + case 'DodecahedronGeometry': + case 'IcosahedronGeometry': + case 'OctahedronGeometry': + case 'TetrahedronGeometry': - return enabled; + geometry = new THREE[ data.type ]( + data.radius, + data.detail + ); - }; + break; - this.beginShadows = function() { + case 'RingGeometry': + case 'RingBufferGeometry': - renderingShadows = true; - projectPlanes( null ); + geometry = new THREE[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - }; + break; - this.endShadows = function() { + case 'TorusGeometry': + case 'TorusBufferGeometry': - renderingShadows = false; - resetGlobalState(); + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - }; + break; - this.setState = function( planes, clipShadows, camera, cache, fromCache ) { + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - if ( ! localClippingEnabled || - planes === null || planes.length === 0 || - renderingShadows && ! clipShadows ) { - // there's no local clipping + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - if ( renderingShadows ) { - // there's no global clipping + break; - projectPlanes( null ); + case 'LatheGeometry': + case 'LatheBufferGeometry': - } else { + geometry = new THREE[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - resetGlobalState(); - } + break; - } else { + case 'BufferGeometry': - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + geometry = bufferGeometryLoader.parse( data ); - dstArray = cache.clippingState || null; + break; - uniform.value = dstArray; // ensure unique state + case 'Geometry': - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; - for ( var i = 0; i !== lGlobal; ++ i ) { + break; - dstArray[ i ] = globalState[ i ]; + default: - } + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - cache.clippingState = dstArray; - this.numPlanes += nGlobal; + continue; - } + } + geometry.uuid = data.uuid; - }; + if ( data.name !== undefined ) geometry.name = data.name; - function resetGlobalState() { + geometries[ data.uuid ] = geometry; - if ( uniform.value !== globalState ) { + } - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + } - } + return geometries; - scope.numPlanes = numGlobalPlanes; + }, - } + parseMaterials: function ( json, textures ) { - function projectPlanes( planes, camera, dstOffset, skipTransform ) { + var materials = {}; - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + if ( json !== undefined ) { - if ( nPlanes !== 0 ) { + var loader = new MaterialLoader(); + loader.setTextures( textures ); - dstArray = uniform.value; + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( skipTransform !== true || dstArray === null ) { + var material = loader.parse( json[ i ] ); + materials[ material.uuid ] = material; - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; + } - viewNormalMatrix.getNormalMatrix( viewMatrix ); + } - if ( dstArray === null || dstArray.length < flatSize ) { + return materials; - dstArray = new Float32Array( flatSize ); + }, - } + parseAnimations: function ( json ) { - for ( var i = 0, i4 = dstOffset; - i !== nPlanes; ++ i, i4 += 4 ) { + var animations = []; - plane.copy( planes[ i ] ). - applyMatrix4( viewMatrix, viewNormalMatrix ); + for ( var i = 0; i < json.length; i ++ ) { - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + var clip = AnimationClip.parse( json[ i ] ); - } + animations.push( clip ); - } + } - uniform.value = dstArray; - uniform.needsUpdate = true; + return animations; - } + }, - scope.numPlanes = nPlanes; - return dstArray; + parseImages: function ( json, onLoad ) { - } + var scope = this; + var images = {}; -}; + function loadImage( url ) { + scope.manager.itemStart( url ); -// File:src/renderers/webgl/WebGLIndexedBufferRenderer.js + return loader.load( url, function () { -/** -* @author mrdoob / http://mrdoob.com/ -*/ + scope.manager.itemEnd( url ); -THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { + } ); - var mode; + } - function setMode( value ) { + if ( json !== undefined && json.length > 0 ) { - mode = value; + var manager = new LoadingManager( onLoad ); - } + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - var type, size; + for ( var i = 0, l = json.length; i < l; i ++ ) { - function setIndex( index ) { + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + images[ image.uuid ] = loadImage( path ); - type = _gl.UNSIGNED_INT; - size = 4; + } - } else { + } - type = _gl.UNSIGNED_SHORT; - size = 2; + return images; - } + }, - } + parseTextures: function ( json, images ) { - function render( start, count ) { + function parseConstant( value ) { - _gl.drawElements( mode, count, type, start * size ); + if ( typeof( value ) === 'number' ) return value; - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); - } + return THREE[ value ]; - function renderInstances( geometry, start, count ) { + } - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + var textures = {}; - if ( extension === null ) { + if ( json !== undefined ) { - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + for ( var i = 0, l = json.length; i < l; i ++ ) { - } + var data = json[ i ]; - extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); + if ( data.image === undefined ) { - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - } + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + } -}; + if ( images[ data.image ] === undefined ) { -// File:src/renderers/webgl/WebGLExtensions.js + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + } -THREE.WebGLExtensions = function ( gl ) { + var texture = new Texture( images[ data.image ] ); + texture.needsUpdate = true; - var extensions = {}; + texture.uuid = data.uuid; - this.get = function ( name ) { + if ( data.name !== undefined ) texture.name = data.name; - if ( extensions[ name ] !== undefined ) { + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); - return extensions[ name ]; + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.wrap !== undefined ) { - } + texture.wrapS = parseConstant( data.wrap[ 0 ] ); + texture.wrapT = parseConstant( data.wrap[ 1 ] ); - var extension; + } - switch ( name ) { + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + if ( data.flipY !== undefined ) texture.flipY = data.flipY; - 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; + textures[ data.uuid ] = texture; - 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; + } - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + } - case 'WEBGL_compressed_texture_etc1': - extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); - break; + return textures; - default: - extension = gl.getExtension( name ); + }, - } + parseObject: function () { - if ( extension === null ) { + var matrix = new Matrix4(); - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + return function parseObject( data, geometries, materials ) { - } + var object; - extensions[ name ] = extension; + function getGeometry( name ) { - return extension; + if ( geometries[ name ] === undefined ) { - }; + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); -}; + } -// File:src/renderers/webgl/WebGLCapabilities.js + return geometries[ name ]; -THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { + } - var maxAnisotropy; + function getMaterial( name ) { - function getMaxAnisotropy() { + if ( name === undefined ) return undefined; - if ( maxAnisotropy !== undefined ) return maxAnisotropy; + if ( materials[ name ] === undefined ) { - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - if ( extension !== null ) { + } - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + return materials[ name ]; - } else { + } - maxAnisotropy = 0; + switch ( data.type ) { - } + case 'Scene': - return maxAnisotropy; + object = new Scene(); - } + break; - function getMaxPrecision( precision ) { + case 'PerspectiveCamera': - if ( precision === 'highp' ) { + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - return 'highp'; + break; - } + case 'OrthographicCamera': - precision = 'mediump'; + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - } + break; - if ( precision === 'mediump' ) { + case 'AmbientLight': - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + object = new AmbientLight( data.color, data.intensity ); - return 'mediump'; + break; - } + case 'DirectionalLight': - } + object = new DirectionalLight( data.color, data.intensity ); - return 'lowp'; + break; - } + case 'PointLight': - this.getMaxAnisotropy = getMaxAnisotropy; - this.getMaxPrecision = getMaxPrecision; + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; + break; - this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); - this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + case 'SpotLight': - this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); - this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); - this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - this.vertexTextures = this.maxVertexTextures > 0; - this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); - this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; + break; - var _maxPrecision = getMaxPrecision( this.precision ); + case 'HemisphereLight': - if ( _maxPrecision !== this.precision ) { + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); - this.precision = _maxPrecision; + break; - } + case 'Mesh': - if ( this.logarithmicDepthBuffer ) { + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); + if ( geometry.bones && geometry.bones.length > 0 ) { - } + object = new SkinnedMesh( geometry, material ); -}; + } else { -// File:src/renderers/webgl/WebGLGeometries.js + object = new Mesh( geometry, material ); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + } -THREE.WebGLGeometries = function ( gl, properties, info ) { + break; - var geometries = {}; + case 'LOD': - function get( object ) { + object = new LOD(); - var geometry = object.geometry; + break; - if ( geometries[ geometry.id ] !== undefined ) { + case 'Line': - return geometries[ geometry.id ]; + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - } + break; - geometry.addEventListener( 'dispose', onGeometryDispose ); + case 'LineSegments': - var buffergeometry; + object = new THREE.LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - if ( geometry instanceof THREE.BufferGeometry ) { + break; - buffergeometry = geometry; + case 'PointCloud': + case 'Points': - } else if ( geometry instanceof THREE.Geometry ) { + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - if ( geometry._bufferGeometry === undefined ) { + break; - geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object ); + case 'Sprite': - } + object = new Sprite( getMaterial( data.material ) ); - buffergeometry = geometry._bufferGeometry; + break; - } + case 'Group': - geometries[ geometry.id ] = buffergeometry; + object = new Group(); - info.memory.geometries ++; + break; - return buffergeometry; + default: - } + object = new Object3D(); - function onGeometryDispose( event ) { + } - var geometry = event.target; - var buffergeometry = geometries[ geometry.id ]; + object.uuid = data.uuid; - if ( buffergeometry.index !== null ) { + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - deleteAttribute( buffergeometry.index ); + matrix.fromArray( data.matrix ); + matrix.decompose( object.position, object.quaternion, object.scale ); - } + } else { - deleteAttributes( buffergeometry.attributes ); + 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 ); - geometry.removeEventListener( 'dispose', onGeometryDispose ); + } - delete geometries[ geometry.id ]; + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - // TODO + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - var property = properties.get( geometry ); + if ( data.children !== undefined ) { - if ( property.wireframe ) { + for ( var child in data.children ) { - deleteAttribute( property.wireframe ); + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); - } + } - properties.delete( geometry ); + } - var bufferproperty = properties.get( buffergeometry ); + if ( data.type === 'LOD' ) { - if ( bufferproperty.wireframe ) { + var levels = data.levels; - deleteAttribute( bufferproperty.wireframe ); + for ( var l = 0; l < levels.length; l ++ ) { - } + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - properties.delete( buffergeometry ); + if ( child !== undefined ) { - // + object.addLevel( child, level.distance ); - info.memory.geometries --; + } - } + } - function getAttributeBuffer( attribute ) { + } - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + return object; - return properties.get( attribute.data ).__webglBuffer; + }; - } + }() - return properties.get( attribute ).__webglBuffer; + } ); - } + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - function deleteAttribute( attribute ) { + exports.ShapeUtils = { - var buffer = getAttributeBuffer( attribute ); + // calculate area of the contour polygon - if ( buffer !== undefined ) { + area: function ( contour ) { - gl.deleteBuffer( buffer ); - removeAttributeBuffer( attribute ); + var n = contour.length; + var a = 0.0; - } + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - } + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - function deleteAttributes( attributes ) { + } - for ( var name in attributes ) { + return a * 0.5; - deleteAttribute( attributes[ name ] ); + }, - } + triangulate: ( function () { - } + /** + * 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 + * + */ - function removeAttributeBuffer( attribute ) { + function snip( contour, u, v, w, n, verts ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + var p; + var ax, ay, bx, by; + var cx, cy, px, py; - properties.delete( attribute.data ); + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; - } else { + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; - properties.delete( attribute ); + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - } + if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - } + var aX, aY, bX, bY, cX, cY; + var apx, apy, bpx, bpy, cpx, cpy; + var cCROSSap, bCROSScp, aCROSSbp; - this.get = get; + aX = cx - bx; aY = cy - by; + bX = ax - cx; bY = ay - cy; + cX = bx - ax; cY = by - ay; -}; + for ( p = 0; p < n; p ++ ) { -// File:src/renderers/webgl/WebGLLights.js + px = contour[ verts[ p ] ].x; + py = contour[ verts[ p ] ].y; -/** -* @author mrdoob / http://mrdoob.com/ -*/ + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; -THREE.WebGLLights = function () { + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; - var lights = {}; + // see if p is inside triangle abc - this.get = function ( light ) { + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - if ( lights[ light.id ] !== undefined ) { + if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - return lights[ light.id ]; + } - } + return true; - var uniforms; - - switch ( light.type ) { - - case 'DirectionalLight': - uniforms = { - direction: new THREE.Vector3(), - color: new THREE.Color(), - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'SpotLight': - uniforms = { - position: new THREE.Vector3(), - direction: new THREE.Vector3(), - color: new THREE.Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'PointLight': - uniforms = { - position: new THREE.Vector3(), - color: new THREE.Color(), - distance: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new THREE.Vector2() - }; - break; - - case 'HemisphereLight': - uniforms = { - direction: new THREE.Vector3(), - skyColor: new THREE.Color(), - groundColor: new THREE.Color() - }; - break; + } - } + // takes in an contour array and returns - lights[ light.id ] = uniforms; + return function triangulate( contour, indices ) { - return uniforms; + var n = contour.length; - }; + if ( n < 3 ) return null; -}; + var result = [], + verts = [], + vertIndices = []; -// File:src/renderers/webgl/WebGLObjects.js + /* we want a counter-clockwise polygon in verts */ -/** -* @author mrdoob / http://mrdoob.com/ -*/ + var u, v, w; -THREE.WebGLObjects = function ( gl, properties, info ) { + if ( exports.ShapeUtils.area( contour ) > 0.0 ) { - var geometries = new THREE.WebGLGeometries( gl, properties, info ); + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - // + } else { - function update( object ) { + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. + } - var geometry = geometries.get( object ); + var nv = n; - if ( object.geometry instanceof THREE.Geometry ) { + /* remove nv - 2 vertices, creating 1 triangle every time */ - geometry.updateFromObject( object ); + var count = 2 * nv; /* error detection */ - } + for ( v = nv - 1; nv > 2; ) { - var index = geometry.index; - var attributes = geometry.attributes; + /* if we loop, it is probably a non-simple polygon */ - if ( index !== null ) { + if ( ( count -- ) <= 0 ) { - updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); + //** Triangulate: ERROR - probable bad polygon! - } + //throw ( "Warning, unable to triangulate polygon!" ); + //return null; + // Sometimes warning is fine, especially polygons are triangulated in reverse. + console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); - for ( var name in attributes ) { + if ( indices ) return vertIndices; + return result; - updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); + } - } + /* three consecutive vertices in current polygon, */ - // morph targets + 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 */ - var morphAttributes = geometry.morphAttributes; + if ( snip( contour, u, v, w, nv, verts ) ) { - for ( var name in morphAttributes ) { + var a, b, c, s, t; - var array = morphAttributes[ name ]; + /* true names of the vertices */ - for ( var i = 0, l = array.length; i < l; i ++ ) { + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - updateAttribute( array[ i ], gl.ARRAY_BUFFER ); + /* output Triangle */ - } + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); - } - return geometry; + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - } + /* remove v from the remaining polygon */ - function updateAttribute( attribute, bufferType ) { + for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute; + verts[ s ] = verts[ t ]; - var attributeProperties = properties.get( data ); + } - if ( attributeProperties.__webglBuffer === undefined ) { + nv --; - createBuffer( attributeProperties, data, bufferType ); + /* reset error detection counter */ - } else if ( attributeProperties.version !== data.version ) { + count = 2 * nv; - updateBuffer( attributeProperties, data, bufferType ); + } - } + } - } + if ( indices ) return vertIndices; + return result; - function createBuffer( attributeProperties, data, bufferType ) { + } - attributeProperties.__webglBuffer = gl.createBuffer(); - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + } )(), - var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; + triangulateShape: function ( contour, holes ) { - gl.bufferData( bufferType, data.array, usage ); + function removeDupEndPts(points) { - attributeProperties.version = data.version; + var l = points.length; - } + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - function updateBuffer( attributeProperties, data, bufferType ) { + points.pop(); - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + } - if ( data.dynamic === false || data.updateRange.count === - 1 ) { + } - // Not using update ranges + removeDupEndPts( contour ); + holes.forEach( removeDupEndPts ); - gl.bufferSubData( bufferType, 0, data.array ); + function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - } else if ( data.updateRange.count === 0 ) { + // inOtherPt needs to be collinear to the inSegment + if ( inSegPt1.x !== inSegPt2.x ) { - console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); + if ( inSegPt1.x < inSegPt2.x ) { - } else { + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, - data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); + } else { - data.updateRange.count = 0; // reset range + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } + } - attributeProperties.version = data.version; + } else { - } + if ( inSegPt1.y < inSegPt2.y ) { - function getAttributeBuffer( attribute ) { + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + } else { - return properties.get( attribute.data ).__webglBuffer; + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - } + } - return properties.get( attribute ).__webglBuffer; + } - } + } - function getWireframeAttribute( geometry ) { + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - var property = properties.get( geometry ); + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - if ( property.wireframe !== undefined ) { + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - return property.wireframe; + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - } + if ( Math.abs( limit ) > Number.EPSILON ) { - var indices = []; + // not parallel - var index = geometry.index; - var attributes = geometry.attributes; - var position = attributes.position; + var perpSeg2; + if ( limit > 0 ) { - // console.time( 'wireframe' ); + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - if ( index !== null ) { + } else { - var edges = {}; - var array = index.array; + if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - for ( var i = 0, l = array.length; i < l; i += 3 ) { + } - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + // i.e. to reduce rounding errors + // intersection at endpoint of segment#1? + if ( perpSeg2 === 0 ) { - if ( checkEdge( edges, a, b ) ) indices.push( a, b ); - if ( checkEdge( edges, b, c ) ) indices.push( b, c ); - if ( checkEdge( edges, c, a ) ) indices.push( c, a ); + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt1 ]; - } + } + if ( perpSeg2 === limit ) { - } else { + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt2 ]; - var array = attributes.position.array; + } + // intersection at endpoint of segment#2? + if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - var a = i + 0; - var b = i + 1; - var c = i + 2; + } else { - indices.push( a, b, b, c, c, a ); + // parallel or collinear + if ( ( perpSeg1 !== 0 ) || + ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - } + // they are collinear or degenerate + var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? + var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is 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 - // console.timeEnd( 'wireframe' ); + } + // segment#1 is a single point + if ( seg1Pt ) { - var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 ); + if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 + return [ inSeg1Pt1 ]; - updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + } + // segment#2 is a single point + if ( seg2Pt ) { - property.wireframe = attribute; + if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; - return attribute; + } - } + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if ( seg1dx !== 0 ) { - function checkEdge( edges, a, b ) { + // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - if ( a > b ) { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - var tmp = a; - a = b; - b = tmp; + } else { - } + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - var list = edges[ a ]; + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - if ( list === undefined ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - edges[ a ] = [ b ]; - return true; + } else { - } else if ( list.indexOf( b ) === -1 ) { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - list.push( b ); - return true; + } - } + } else { - return false; + // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - } + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - this.getAttributeBuffer = getAttributeBuffer; - this.getWireframeAttribute = getWireframeAttribute; + } else { - this.update = update; + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; -}; + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { -// File:src/renderers/webgl/WebGLProgram.js + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; -THREE.WebGLProgram = ( function () { + } else { - var programIdCount = 0; + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - function getEncodingComponents( encoding ) { + } - switch ( encoding ) { + } + if ( seg1minVal <= seg2minVal ) { - case THREE.LinearEncoding: - return [ 'Linear','( value )' ]; - case THREE.sRGBEncoding: - return [ 'sRGB','( value )' ]; - case THREE.RGBEEncoding: - return [ 'RGBE','( value )' ]; - case THREE.RGBM7Encoding: - return [ 'RGBM','( value, 7.0 )' ]; - case THREE.RGBM16Encoding: - return [ 'RGBM','( value, 16.0 )' ]; - case THREE.RGBDEncoding: - return [ 'RGBD','( value, 256.0 )' ]; - case THREE.GammaEncoding: - return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; - default: - throw new Error( 'unsupported encoding: ' + encoding ); + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal === seg2minVal ) { - } + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; - } + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; - function getTexelDecodingFunction( functionName, encoding ) { + } else { - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal === seg2maxVal ) { - } + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; - function getTexelEncodingFunction( functionName, encoding ) { + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; + } - } + } - function getToneMappingFunction( functionName, toneMapping ) { + } - var toneMappingName; + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - switch ( toneMapping ) { + // The order of legs is important - case THREE.LinearToneMapping: - toneMappingName = "Linear"; - break; + // 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; - case THREE.ReinhardToneMapping: - toneMappingName = "Reinhard"; - break; + // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. + var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; + var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - case THREE.Uncharted2ToneMapping: - toneMappingName = "Uncharted2"; - break; + if ( Math.abs( from2toAngle ) > Number.EPSILON ) { - case THREE.CineonToneMapping: - toneMappingName = "OptimizedCineon"; - break; + // angle != 180 deg. - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - } + if ( from2toAngle > 0 ) { - return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } + } else { - function generateExtensions( extensions, parameters, rendererExtensions ) { + // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - extensions = extensions || {}; + } - var chunks = [ - ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', - ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', - ]; + } else { - return chunks.filter( filterEmptyLine ).join( '\n' ); + // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); - } + } - function generateDefines( defines ) { + } - var chunks = []; - for ( var name in defines ) { + function removeHoles( contour, holes ) { - var value = defines[ name ]; + var shape = contour.concat(); // work on this shape + var hole; - if ( value === false ) continue; + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - chunks.push( '#define ' + name + ' ' + value ); + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; - } + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - return chunks.join( '\n' ); + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - } + var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); + if ( ! insideAngle ) { - function fetchAttributeLocations( gl, program, identifiers ) { + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; - var attributes = {}; + } - var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - for ( var i = 0; i < n; i ++ ) { + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - var info = gl.getActiveAttrib( program, i ); - var name = info.name; + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); + insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); + if ( ! insideAngle ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; - } + } - return attributes; + return true; - } + } - function filterEmptyLine( string ) { + function intersectsShapeEdge( inShapePt, inHolePt ) { - return string !== ''; + // 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; - function replaceLightNums( string, parameters ) { + } - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); + return false; - } + } - function parseIncludes( string ) { + var indepHoles = []; - var pattern = /#include +<([\w\d.]+)>/g; + function intersectsHoleEdge( inShapePt, inHolePt ) { - function replace( match, include ) { + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { - var replace = THREE.ShaderChunk[ include ]; + chkHole = holes[ indepHoles[ ihIdx ]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { - if ( replace === undefined ) { + nextIdx = hIdx + 1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - throw new Error( 'Can not resolve #include <' + include + '>' ); + } - } + } + return false; - return parseIncludes( replace ); + } - } + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; - return string.replace( pattern, replace ); + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - } + indepHoles.push( h ); - function unrollLoops( string ) { + } - var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { - function replace( match, start, end, snippet ) { + counter --; + if ( counter < 0 ) { - var unroll = ''; + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { + } - unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); + // 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; - return unroll; + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { - } + holeIdx = indepHoles[ h ]; - return string.replace( pattern, replace ); + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[ cutKey ] !== undefined ) continue; - } + hole = holes[ holeIdx ]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - return function WebGLProgram( renderer, code, material, parameters ) { + holePt = hole[ h2 ]; + if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - var gl = renderer.context; + holeIndex = h2; + indepHoles.splice( h, 1 ); - var extensions = material.extensions; - var defines = material.defines; + tmpShape1 = shape.slice( 0, shapeIndex + 1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex + 1 ); - var vertexShader = material.__webglShader.vertexShader; - var fragmentShader = material.__webglShader.fragmentShader; + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + minShapeIndex = shapeIndex; - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + break; - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { + } + if ( holeIndex >= 0 ) break; // hole-vertex found - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + failedCuts[ cutKey ] = true; // remember failure - } + } + if ( holeIndex >= 0 ) break; // hole-vertex found - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + } - if ( parameters.envMap ) { + } - switch ( material.envMap.mapping ) { + return shape; /* shape with no holes */ - case THREE.CubeReflectionMapping: - case THREE.CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + } - case THREE.CubeUVReflectionMapping: - case THREE.CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; - case THREE.EquirectangularReflectionMapping: - case THREE.EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; + var i, il, f, face, + key, index, + allPointsMap = {}; - case THREE.SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + // 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(); - switch ( material.envMap.mapping ) { + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - case THREE.CubeRefractionMapping: - case THREE.EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + Array.prototype.push.apply( allpoints, holes[ h ] ); - } + } - switch ( material.combine ) { + //console.log( "allpoints",allpoints, allpoints.length ); - case THREE.MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + // prepare all points map - case THREE.MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + for ( i = 0, il = allpoints.length; i < il; i ++ ) { - case THREE.AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + key = allpoints[ i ].x + ":" + allpoints[ i ].y; - } + if ( allPointsMap[ key ] !== undefined ) { - } + console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + } - // console.log( 'building new program ' ); + allPointsMap[ key ] = i; - // + } - var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - var customDefines = generateDefines( defines ); + var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - // + // check all face vertices against all points map - var program = gl.createProgram(); + for ( i = 0, il = triangles.length; i < il; i ++ ) { - var prefixVertex, prefixFragment; + face = triangles[ i ]; - if ( material instanceof THREE.RawShaderMaterial ) { + for ( f = 0; f < 3; f ++ ) { - prefixVertex = [ + key = face[ f ].x + ":" + face[ f ].y; - customDefines + index = allPointsMap[ key ]; - ].filter( filterEmptyLine ).join( '\n' ); + if ( index !== undefined ) { - prefixFragment = [ + face[ f ] = index; - customDefines + } - ].filter( filterEmptyLine ).join( '\n' ); + } - } else { + } - prefixVertex = [ + return triangles.concat(); - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + }, - '#define SHADER_NAME ' + material.__webglShader.name, + isClockWise: function ( pts ) { - customDefines, + return exports.ShapeUtils.area( pts ) < 0; - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + }, - '#define GAMMA_FACTOR ' + gammaFactorDefine, + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - '#define MAX_BONES ' + parameters.maxBones, + // Quad Bezier Functions - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + b2: ( function () { - parameters.flatShading ? '#define FLAT_SHADED' : '', + function b2p0( t, p ) { - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + var k = 1 - t; + return k * k * p; - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + } - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + function b2p1( t, p ) { - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + return 2 * ( 1 - t ) * t * p; - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + function b2p2( t, p ) { - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', + return t * t * p; - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', + } - '#ifdef USE_COLOR', + return function b2( t, p0, p1, p2 ) { - ' attribute vec3 color;', + return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - '#endif', + }; - '#ifdef USE_MORPHTARGETS', + } )(), - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + // Cubic Bezier Functions - ' #ifdef USE_MORPHNORMALS', + b3: ( function () { - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + function b3p0( t, p ) { - ' #else', + var k = 1 - t; + return k * k * k * p; - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + } - ' #endif', + function b3p1( t, p ) { - '#endif', + var k = 1 - t; + return 3 * k * k * t * p; - '#ifdef USE_SKINNING', + } - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', + function b3p2( t, p ) { - '#endif', + var k = 1 - t; + return 3 * k * t * t * p; - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); + function b3p3( t, p ) { - prefixFragment = [ + return t * t * t * p; - customExtensions, + } - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + return function b3( t, p0, p1, p2, p3 ) { - '#define SHADER_NAME ' + material.__webglShader.name, + return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - customDefines, + }; - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', + } )() - '#define GAMMA_FACTOR ' + gammaFactorDefine, + }; - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', + /** + * @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 + * + * A series of curves can be represented as a THREE.CurvePath + * + **/ - 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.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + /************************************************************** + * Abstract Curve base class + **************************************************************/ - parameters.flatShading ? '#define FLAT_SHADED' : '', + function Curve () { + this.isCurve = true; - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + }; - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + Curve.prototype = { - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + constructor: Curve, - parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', + getPoint: function ( t ) { - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); + return null; - parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', + }, - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - ( parameters.toneMapping !== THREE.NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== THREE.NoToneMapping ) ? THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== THREE.NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', + getPointAt: function ( u ) { - ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? THREE.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below - parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', - parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', - parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); - parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', + }, - '\n' + // Get sequence of points using getPoint( t ) - ].filter( filterEmptyLine ).join( '\n' ); + getPoints: function ( divisions ) { - } + if ( ! divisions ) divisions = 5; - vertexShader = parseIncludes( vertexShader, parameters ); - vertexShader = replaceLightNums( vertexShader, parameters ); + var points = []; - fragmentShader = parseIncludes( fragmentShader, parameters ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); + for ( var d = 0; d <= divisions; d ++ ) { - if ( material instanceof THREE.ShaderMaterial === false ) { + points.push( this.getPoint( d / divisions ) ); - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); + } - } + return points; - var vertexGlsl = prefixVertex + vertexShader; - var fragmentGlsl = prefixFragment + fragmentShader; + }, - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + // Get sequence of points using getPointAt( u ) - var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); - var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + getSpacedPoints: function ( divisions ) { - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); + if ( ! divisions ) divisions = 5; - // Force a particular attribute to index 0. + var points = []; - if ( material.index0AttributeName !== undefined ) { + for ( var d = 0; d <= divisions; d ++ ) { - gl.bindAttribLocation( program, 0, material.index0AttributeName ); + points.push( this.getPointAt( d / divisions ) ); - } else if ( parameters.morphTargets === true ) { + } - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + return points; - } + }, - gl.linkProgram( program ); + // Get total curve arc length - var programLog = gl.getProgramInfoLog( program ); - var vertexLog = gl.getShaderInfoLog( glVertexShader ); - var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); + getLength: function () { - var runnable = true; - var haveDiagnostics = true; + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); - // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); + }, - if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + // Get list of cumulative segment lengths - runnable = false; + getLengths: function ( divisions ) { - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); + if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; - } else if ( programLog !== '' ) { + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length === divisions + 1 ) + && ! this.needsUpdate ) { - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - } else if ( vertexLog === '' || fragmentLog === '' ) { + } - haveDiagnostics = false; + this.needsUpdate = false; - } + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - if ( haveDiagnostics ) { + cache.push( 0 ); - this.diagnostics = { + for ( p = 1; p <= divisions; p ++ ) { - runnable: runnable, - material: material, + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - programLog: programLog, + } - vertexShader: { + this.cacheArcLengths = cache; - log: vertexLog, - prefix: prefixVertex + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - }, + }, - fragmentShader: { + updateArcLengths: function() { - log: fragmentLog, - prefix: prefixFragment + this.needsUpdate = true; + this.getLengths(); - } + }, - }; + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - } + getUtoTmapping: function ( u, distance ) { - // clean up + var arcLengths = this.getLengths(); - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + var i = 0, il = arcLengths.length; - // set up caching for uniform locations + var targetArcLength; // The targeted u distance value to get - var cachedUniforms; + if ( distance ) { - this.getUniforms = function() { + targetArcLength = distance; - if ( cachedUniforms === undefined ) { + } else { - cachedUniforms = - new THREE.WebGLUniforms( gl, program, renderer ); + targetArcLength = u * arcLengths[ il - 1 ]; - } + } - return cachedUniforms; + //var time = Date.now(); - }; + // binary search for the index with largest value smaller than target u distance - // set up caching for attribute locations + var low = 0, high = il - 1, comparison; - var cachedAttributes; + while ( low <= high ) { - this.getAttributes = function() { + 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 - if ( cachedAttributes === undefined ) { + comparison = arcLengths[ i ] - targetArcLength; - cachedAttributes = fetchAttributeLocations( gl, program ); + if ( comparison < 0 ) { - } + low = i + 1; - return cachedAttributes; + } else if ( comparison > 0 ) { - }; + high = i - 1; - // free resource + } else { - this.destroy = function() { + high = i; + break; - gl.deleteProgram( program ); - this.program = undefined; + // DONE - }; + } - // DEPRECATED + } - Object.defineProperties( this, { + i = high; - uniforms: { - get: function() { + //console.log('b' , i, low, high, Date.now()- time); - console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); - return this.getUniforms(); + if ( arcLengths[ i ] === targetArcLength ) { - } - }, + var t = i / ( il - 1 ); + return t; - attributes: { - get: function() { + } - console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); - return this.getAttributes(); + // we could get finer grain at lengths, or use simple interpolation between two points - } - } + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - } ); + var segmentLength = lengthAfter - lengthBefore; + // determine where we are between the 'before' and 'after' points - // + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + // add that fractional amount to t - return this; + var t = ( i + segmentFraction ) / ( il - 1 ); - }; + return t; -} )(); + }, -// File:src/renderers/webgl/WebGLPrograms.js + // 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.WebGLPrograms = function ( renderer, capabilities ) { + getTangent: function( t ) { - var programs = []; + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points' - }; + // Capping in case of danger - var parameterNames = [ - "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", - "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", - "roughnessMap", "metalnessMap", - "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", - "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", - "maxBones", "useVertexTexture", "morphTargets", "morphNormals", - "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", - "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", - "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', - "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" - ]; + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - function allocateBones ( object ) { + var vec = pt2.clone().sub( pt1 ); + return vec.normalize(); - if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { + }, - return 1024; + getTangentAt: function ( u ) { - } else { + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - // 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 = capabilities.maxVertexUniforms; - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + }; - var maxBones = nVertexMatrices; + // TODO: Transformation for Curves? - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + /************************************************************** + * 3D Curves + **************************************************************/ - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + // A Factory method for creating new curve subclasses - if ( maxBones < object.skeleton.bones.length ) { + Curve.create = function ( constructor, getPointFunc ) { - console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); + constructor.prototype = Object.create( Curve.prototype ); + constructor.prototype.constructor = constructor; + constructor.prototype.getPoint = getPointFunc; - } + return constructor; - } + }; - return maxBones; + /************************************************************** + * Line + **************************************************************/ - } + function LineCurve ( v1, v2 ) { + this.isLineCurve = this.isCurve = true; - } + this.v1 = v1; + this.v2 = v2; - function getTextureEncodingFromMap( map, gammaOverrideLinear ) { + }; - var encoding; + LineCurve.prototype = Object.create( Curve.prototype ); + LineCurve.prototype.constructor = LineCurve; - if ( ! map ) { + LineCurve.prototype.getPoint = function ( t ) { - encoding = THREE.LinearEncoding; + if ( t === 1 ) { - } else if ( map instanceof THREE.Texture ) { + return this.v2.clone(); - encoding = map.encoding; + } - } else if ( map instanceof THREE.WebGLRenderTarget ) { + var point = this.v2.clone().sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); - encoding = map.texture.encoding; + return point; - } + }; - // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) { + // Line curve is linear, so we can overwrite default getPointAt - encoding = THREE.GammaEncoding; + LineCurve.prototype.getPointAt = function ( u ) { - } + return this.getPoint( u ); - return encoding; + }; - } + LineCurve.prototype.getTangent = function( t ) { - this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { + var tangent = this.v2.clone().sub( this.v1 ); - var shaderID = shaderIDs[ material.type ]; + return tangent.normalize(); - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + }; - var maxBones = allocateBones( object ); - var precision = renderer.getPrecision(); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - if ( material.precision !== null ) { + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - precision = capabilities.getMaxPrecision( material.precision ); + function CurvePath () { + this.isCurvePath = true; - if ( precision !== material.precision ) { + this.curves = []; - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + this.autoClose = false; // Automatically closes the path - } + }; - } + CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - var currentRenderTarget = renderer.getCurrentRenderTarget(); + constructor: CurvePath, - var parameters = { + add: function ( curve ) { - shaderID: shaderID, + this.curves.push( curve ); - precision: precision, - supportsVertexTextures: capabilities.vertexTextures, - outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), - envMap: !! material.envMap, - envMapMode: material.envMap && material.envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, + }, - combine: material.combine, + closePath: function () { - vertexColors: material.vertexColors, + // 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 ); - fog: !! fog, - useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, + if ( ! startPoint.equals( endPoint ) ) { - flatShading: material.shading === THREE.FlatShading, + this.curves.push( new LineCurve( endPoint, startPoint ) ); - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, + } - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, + }, - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numHemiLights: lights.hemi.length, + // 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') - numClippingPlanes: nClipPlanes, + getPoint: function ( t ) { - shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; - toneMapping: renderer.toneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, + // To think about boundaries points. - premultipliedAlpha: material.premultipliedAlpha, + while ( i < curveLengths.length ) { - alphaTest: material.alphaTest, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide, + if ( curveLengths[ i ] >= d ) { - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - }; + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - return parameters; + return curve.getPointAt( u ); - }; + } - this.getProgramCode = function ( material, parameters ) { + i ++; - var array = []; + } - if ( parameters.shaderID ) { + return null; - array.push( parameters.shaderID ); + // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { - this.delete = function ( object ) { + points.push( points[ 0 ] ); - delete properties[ object.uuid ]; + } - }; + return points; - this.clear = function () { + }, - properties = {}; + /************************************************************** + * Create Geometries Helpers + **************************************************************/ - }; + /// Generate geometry from path points (for Line or Points objects) -}; + createPointsGeometry: function ( divisions ) { -// File:src/renderers/webgl/WebGLShader.js + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); -THREE.WebGLShader = ( function () { + }, - function addLineNumbers( string ) { + // Generate geometry from equidistant sampling along the path - var lines = string.split( '\n' ); + createSpacedPointsGeometry: function ( divisions ) { - for ( var i = 0; i < lines.length; i ++ ) { + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + }, - } + createGeometry: function ( points ) { - return lines.join( '\n' ); + var geometry = new Geometry(); - } + for ( var i = 0, l = points.length; i < l; i ++ ) { - return function WebGLShader( gl, type, string ) { + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - var shader = gl.createShader( type ); + } - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + return geometry; - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + } - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); + } ); - } + /************************************************************** + * Ellipse curve + **************************************************************/ - if ( gl.getShaderInfoLog( shader ) !== '' ) { + function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.isEllipseCurve = this.isCurve = true; - console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); + this.aX = aX; + this.aY = aY; - } + this.xRadius = xRadius; + this.yRadius = yRadius; - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - return shader; + this.aClockwise = aClockwise; - }; + this.aRotation = aRotation || 0; -} )(); + }; -// File:src/renderers/webgl/WebGLShadowMap.js + EllipseCurve.prototype = Object.create( Curve.prototype ); + EllipseCurve.prototype.constructor = EllipseCurve; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + EllipseCurve.prototype.getPoint = function( t ) { -THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - var _gl = _renderer.context, - _state = _renderer.state, - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - _lightShadows = _lights.shadows, + if ( deltaAngle < Number.EPSILON ) { - _shadowMapSize = new THREE.Vector2(), - _maxShadowMapSize = new THREE.Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + if ( samePoints ) { - _lookTarget = new THREE.Vector3(), - _lightPositionWorld = new THREE.Vector3(), + deltaAngle = 0; - _renderList = [], + } else { - _MorphingFlag = 1, - _SkinningFlag = 2, + deltaAngle = twoPi; - _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, + } - _depthMaterials = new Array( _NumberOfMaterialVariants ), - _distanceMaterials = new Array( _NumberOfMaterialVariants ), + } - _materialCache = {}; + if ( this.aClockwise === true && ! samePoints ) { - var cubeDirections = [ - new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ), - new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 ) - ]; + if ( deltaAngle === twoPi ) { - var cubeUps = [ - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 ) - ]; + deltaAngle = - twoPi; - var cube2DViewPorts = [ - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(), - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4() - ]; + } else { - // init + deltaAngle = deltaAngle - twoPi; - var depthMaterialTemplate = new THREE.MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = THREE.RGBADepthPacking; - depthMaterialTemplate.clipping = true; + } - var distanceShader = THREE.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms ); + } - for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - var useMorphing = ( i & _MorphingFlag ) !== 0; - var useSkinning = ( i & _SkinningFlag ) !== 0; + if ( this.aRotation !== 0 ) { - var depthMaterial = depthMaterialTemplate.clone(); - depthMaterial.morphTargets = useMorphing; - depthMaterial.skinning = useSkinning; + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - _depthMaterials[ i ] = depthMaterial; + var tx = x - this.aX; + var ty = y - this.aY; - var distanceMaterial = new THREE.ShaderMaterial( { - defines: { - 'USE_SHADOWMAP': '' - }, - uniforms: distanceUniforms, - vertexShader: distanceShader.vertexShader, - fragmentShader: distanceShader.fragmentShader, - morphTargets: useMorphing, - skinning: useSkinning, - clipping: true - } ); + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - _distanceMaterials[ i ] = distanceMaterial; + } - } + return new Vector2( x, y ); - // + }; - var scope = this; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - this.enabled = false; + exports.CurveUtils = { - this.autoUpdate = true; - this.needsUpdate = false; + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - this.type = THREE.PCFShadowMap; + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - this.renderReverseSided = true; - this.renderSingleSided = true; + }, - this.render = function ( scene, camera ) { + // Puay Bing, thanks for helping with this derivative! - if ( scope.enabled === false ) return; - if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - if ( _lightShadows.length === 0 ) return; + 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; - // Set GL state for depth map. - _state.clearColor( 1, 1, 1, 1 ); - _state.disable( _gl.BLEND ); - _state.setDepthTest( true ); - _state.setScissorTest( false ); + }, - // render depth map + tangentSpline: function ( t, p0, p1, p2, p3 ) { - var faceCount, isPointLight; + // To check if my formulas are correct - for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { + 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 - var light = _lightShadows[ i ]; - var shadow = light.shadow; + return h00 + h10 + h01 + h11; - if ( shadow === undefined ) { + }, - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + // Catmull-Rom - } + interpolate: function( p0, p1, p2, p3, t ) { - var shadowCamera = shadow.camera; + 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; - _shadowMapSize.copy( shadow.mapSize ); - _shadowMapSize.min( _maxShadowMapSize ); + } - if ( light instanceof THREE.PointLight ) { + }; - faceCount = 6; - isPointLight = true; + /************************************************************** + * Spline curve + **************************************************************/ - var vpWidth = _shadowMapSize.x; - var vpHeight = _shadowMapSize.y; + function SplineCurve ( points /* array of Vector2 */ ) { + this.isSplineCurve = this.isCurve = true; - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction + this.points = ( points == undefined ) ? [] : points; - // positive X - cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); - // negative X - cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); - // positive Z - cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); - // negative Z - cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); - // positive Y - cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); - // negative Y - cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); + }; - _shadowMapSize.x *= 4.0; - _shadowMapSize.y *= 2.0; + SplineCurve.prototype = Object.create( Curve.prototype ); + SplineCurve.prototype.constructor = SplineCurve; - } else { + SplineCurve.prototype.getPoint = function ( t ) { - faceCount = 1; - isPointLight = false; + var points = this.points; + var point = ( points.length - 1 ) * t; - } + var intPoint = Math.floor( point ); + var weight = point - intPoint; - if ( shadow.map === null ) { + 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 pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat }; + var interpolate = exports.CurveUtils.interpolate; - shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + return new Vector2( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ) + ); - shadowCamera.updateProjectionMatrix(); + }; - } + /************************************************************** + * Cubic Bezier curve + **************************************************************/ - if ( shadow instanceof THREE.SpotLightShadow ) { + function CubicBezierCurve ( v0, v1, v2, v3 ) { + this.isCubicBezierCurve = this.isCurve = true; - shadow.update( light ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - } + }; - var shadowMap = shadow.map; - var shadowMatrix = shadow.matrix; + CubicBezierCurve.prototype = Object.create( Curve.prototype ); + CubicBezierCurve.prototype.constructor = CubicBezierCurve; - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + CubicBezierCurve.prototype.getPoint = function ( t ) { - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); + var b3 = exports.ShapeUtils.b3; - // render shadow map for each cube face (if omni-directional) or - // run a single pass if not + return new Vector2( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ); - for ( var face = 0; face < faceCount; face ++ ) { + }; - if ( isPointLight ) { + CubicBezierCurve.prototype.getTangent = function( t ) { - _lookTarget.copy( shadowCamera.position ); - _lookTarget.add( cubeDirections[ face ] ); - shadowCamera.up.copy( cubeUps[ face ] ); - shadowCamera.lookAt( _lookTarget ); + var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; - var vpDimensions = cube2DViewPorts[ face ]; - _state.viewport( vpDimensions ); + return new Vector2( + tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ).normalize(); - } else { + }; - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); + /************************************************************** + * Quadratic Bezier curve + **************************************************************/ - } - shadowCamera.updateMatrixWorld(); - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); + function QuadraticBezierCurve ( v0, v1, v2 ) { + this.isQuadraticBezierCurve = this.isCurve = true; - // compute shadow matrix + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - 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 - ); + }; - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - // update camera matrices and frustum - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + QuadraticBezierCurve.prototype.getPoint = function ( t ) { - // set object matrices & frustum culling + var b2 = exports.ShapeUtils.b2; - _renderList.length = 0; + return new Vector2( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ) + ); - projectObject( scene, camera, shadowCamera ); + }; - // render shadow map - // render regular objects - for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { + QuadraticBezierCurve.prototype.getTangent = function( t ) { - var object = _renderList[ j ]; - var geometry = _objects.update( object ); - var material = object.material; + var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; - if ( material instanceof THREE.MultiMaterial ) { + return new Vector2( + tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), + tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) + ).normalize(); - var groups = geometry.groups; - var materials = material.materials; + }; - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + var PathPrototype; - var group = groups[ k ]; - var groupMaterial = materials[ group.materialIndex ]; + PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { - if ( groupMaterial.visible === true ) { + fromPoints: function ( vectors ) { - var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - } + for ( var i = 1, l = vectors.length; i < l; i ++ ) { - } + this.lineTo( vectors[ i ].x, vectors[ i ].y ); - } else { + } - var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + }, - } + moveTo: function ( x, y ) { - } + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - } + }, - } + lineTo: function ( x, y ) { - // Restore GL state. - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - _renderer.setClearColor( clearColor, clearAlpha ); + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - scope.needsUpdate = false; + this.currentPoint.set( x, y ); - }; + }, - function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - var geometry = object.geometry; + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - var result = null; + this.curves.push( curve ); - var materialVariants = _depthMaterials; - var customMaterial = object.customDepthMaterial; + this.currentPoint.set( aX, aY ); - if ( isPointLight ) { + }, - materialVariants = _distanceMaterials; - customMaterial = object.customDistanceMaterial; + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - } + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - if ( ! customMaterial ) { + this.curves.push( curve ); - var useMorphing = false; + this.currentPoint.set( aX, aY ); - if ( material.morphTargets ) { + }, - if ( geometry instanceof THREE.BufferGeometry ) { + splineThru: function ( pts /*Array of Vector*/ ) { - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; + var npts = [ this.currentPoint.clone() ].concat( pts ); - } else if ( geometry instanceof THREE.Geometry ) { + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; + this.currentPoint.copy( pts[ pts.length - 1 ] ); - } + }, - } + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning; + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - var variantIndex = 0; + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - if ( useMorphing ) variantIndex |= _MorphingFlag; - if ( useSkinning ) variantIndex |= _SkinningFlag; + }, - result = materialVariants[ variantIndex ]; + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } else { + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - result = customMaterial; + }, - } + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - // in this case we need a unique material instance reflecting the - // appropriate state + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - var keyA = result.uuid, keyB = material.uuid; + }, - var materialsForVariant = _materialCache[ keyA ]; + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - if ( materialsForVariant === undefined ) { + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; + if ( this.curves.length > 0 ) { - } + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - var cachedMaterial = materialsForVariant[ keyB ]; + if ( ! firstPoint.equals( this.currentPoint ) ) { - if ( cachedMaterial === undefined ) { + this.lineTo( firstPoint.x, firstPoint.y ); - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + } - } + } - result = cachedMaterial; + this.curves.push( curve ); - } + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); - result.visible = material.visible; - result.wireframe = material.wireframe; + } - var side = material.side; + } ) - if ( scope.renderSingleSided && side == THREE.DoubleSide ) { + /** + * @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 + */ - side = THREE.FrontSide; + function TubeGeometry ( path, segments, radius, radialSegments, closed, taper ) { + this.isTubeGeometry = this.isGeometry = true; - } + Geometry.call( this ); - if ( scope.renderReverseSided ) { + this.type = 'TubeGeometry'; - if ( side === THREE.FrontSide ) side = THREE.BackSide; - else if ( side === THREE.BackSide ) side = THREE.FrontSide; + this.parameters = { + path: path, + segments: segments, + radius: radius, + radialSegments: radialSegments, + closed: closed, + taper: taper + }; - } + segments = segments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; + taper = taper || TubeGeometry.NoTaper; - result.side = side; + var grid = []; - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; + var scope = this, - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; + tangent, + normal, + binormal, - if ( isPointLight && result.uniforms.lightPos !== undefined ) { + numpoints = segments + 1, - result.uniforms.lightPos.value.copy( lightPositionWorld ); + u, v, r, - } + cx, cy, + pos, pos2 = new Vector3(), + i, j, + ip, jp, + a, b, c, d, + uva, uvb, uvc, uvd; - return result; + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; - } + // proxy internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - function projectObject( object, camera, shadowCamera ) { + function vert( x, y, z ) { - if ( object.visible === false ) return; + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; - if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) { + } - if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + // construct the grid - var material = object.material; + for ( i = 0; i < numpoints; i ++ ) { - if ( material.visible === true ) { + grid[ i ] = []; - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - _renderList.push( object ); + u = i / ( numpoints - 1 ); - } + pos = path.getPointAt( u ); - } + tangent = tangents[ i ]; + normal = normals[ i ]; + binormal = binormals[ i ]; - } + r = radius * taper( u ); - var children = object.children; + for ( j = 0; j < radialSegments; j ++ ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + v = j / radialSegments * 2 * Math.PI; - projectObject( children[ i ], camera, shadowCamera ); + 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; - } + grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); -}; + } -// File:src/renderers/webgl/WebGLState.js + } -/** -* @author mrdoob / http://mrdoob.com/ -*/ -THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { + // construct the mesh - var _this = this; + for ( i = 0; i < segments; i ++ ) { - this.buffers = { - color: new THREE.WebGLColorBuffer( gl, this ), - depth: new THREE.WebGLDepthBuffer( gl, this ), - stencil: new THREE.WebGLStencilBuffer( gl, this ) - }; + for ( j = 0; j < radialSegments; j ++ ) { - var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - var newAttributes = new Uint8Array( maxVertexAttributes ); - var enabledAttributes = new Uint8Array( maxVertexAttributes ); - var attributeDivisors = new Uint8Array( maxVertexAttributes ); + ip = ( closed ) ? ( i + 1 ) % segments : i + 1; + jp = ( j + 1 ) % radialSegments; - var capabilities = {}; + a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** + b = grid[ ip ][ j ]; + c = grid[ ip ][ jp ]; + d = grid[ i ][ jp ]; - var compressedTextureFormats = null; + uva = new Vector2( i / segments, j / radialSegments ); + uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; - var currentPremultipledAlpha = false; + this.faces.push( new Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - var currentFlipSided = null; - var currentCullFace = null; + this.faces.push( new Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - var currentLineWidth = null; + } - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + } - var currentScissorTest = null; + this.computeFaceNormals(); + this.computeVertexNormals(); - var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + }; - var currentTextureSlot = null; - var currentBoundTextures = {}; + TubeGeometry.prototype = Object.create( Geometry.prototype ); + TubeGeometry.prototype.constructor = TubeGeometry; - var currentScissor = new THREE.Vector4(); - var currentViewport = new THREE.Vector4(); + TubeGeometry.NoTaper = function ( u ) { - function createTexture( type, target, count ) { + return 1; - var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. - var texture = gl.createTexture(); + }; - gl.bindTexture( type, texture ); - gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + TubeGeometry.SinusoidalTaper = function ( u ) { - for ( var i = 0; i < count; i ++ ) { + return Math.sin( Math.PI * u ); - gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + }; - } + // For computing of Frenet frames, exposing the tangents, normals and binormals the spline + TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - return texture; + var normal = new Vector3(), - } + tangents = [], + normals = [], + binormals = [], - var emptyTextures = {}; - emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); - emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + vec = new Vector3(), + mat = new Matrix4(), - // + numpoints = segments + 1, + theta, + smallest, - this.init = function () { + tx, ty, tz, + i, u; - this.clearColor( 0, 0, 0, 1 ); - this.clearDepth( 1 ); - this.clearStencil( 0 ); - this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( THREE.LessEqualDepth ); + // expose internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - this.setFlipSided( false ); - this.setCullFace( THREE.CullFaceBack ); - this.enable( gl.CULL_FACE ); + // compute the tangent vectors for each segment on the path - this.enable( gl.BLEND ); - this.setBlending( THREE.NormalBlending ); + for ( i = 0; i < numpoints; i ++ ) { - }; + u = i / ( numpoints - 1 ); - this.initAttributes = function () { + tangents[ i ] = path.getTangentAt( u ); + tangents[ i ].normalize(); - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + } - newAttributes[ i ] = 0; + initialNormal3(); - } + /* + 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 initialNormal2() { - this.enableAttribute = function ( attribute ) { + // This uses the Frenet-Serret formula for deriving binormal + var t2 = path.getTangentAt( epsilon ); - newAttributes[ attribute ] = 1; + normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); + binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); - if ( enabledAttributes[ attribute ] === 0 ) { + normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + } + */ - } + function initialNormal3() { - if ( attributeDivisors[ attribute ] !== 0 ) { + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the smallest tangent xyz component - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + smallest = Number.MAX_VALUE; + tx = Math.abs( tangents[ 0 ].x ); + ty = Math.abs( tangents[ 0 ].y ); + tz = Math.abs( tangents[ 0 ].z ); - extension.vertexAttribDivisorANGLE( attribute, 0 ); - attributeDivisors[ attribute ] = 0; + if ( tx <= smallest ) { - } + smallest = tx; + normal.set( 1, 0, 0 ); - }; + } - this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { + if ( ty <= smallest ) { - newAttributes[ attribute ] = 1; + smallest = ty; + normal.set( 0, 1, 0 ); - if ( enabledAttributes[ attribute ] === 0 ) { + } - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + if ( tz <= smallest ) { - } + normal.set( 0, 0, 1 ); - if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + } - extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); - attributeDivisors[ attribute ] = meshPerAttribute; + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - } + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - }; + } - this.disableUnusedAttributes = function () { - for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { + // compute the slowly-varying normal and binormal vectors for each segment on the path - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + for ( i = 1; i < numpoints; i ++ ) { - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + normals[ i ] = normals[ i - 1 ].clone(); - } + binormals[ i ] = binormals[ i - 1 ].clone(); - } + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - }; + if ( vec.length() > Number.EPSILON ) { - this.enable = function ( id ) { + vec.normalize(); - if ( capabilities[ id ] !== true ) { + theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - gl.enable( id ); - capabilities[ id ] = true; + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - } + } - }; + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - this.disable = function ( id ) { + } - if ( capabilities[ id ] !== false ) { - gl.disable( id ); - capabilities[ id ] = false; + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - } + if ( closed ) { - }; + theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta /= ( numpoints - 1 ); - this.getCompressedTextureFormats = function () { + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - if ( compressedTextureFormats === null ) { + theta = - theta; - compressedTextureFormats = []; + } - if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || - extensions.get( 'WEBGL_compressed_texture_s3tc' ) || - extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { + for ( i = 1; i < numpoints; i ++ ) { - var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - for ( var i = 0; i < formats.length; i ++ ) { + } - compressedTextureFormats.push( formats[ i ] ); + } - } + }; - } + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * amount: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline is bevel + * bevelSegments: , // number of bevel layers + * + * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) + * frames: // containing arrays of tangents, normals, binormals + * + * uvGenerator: // object that provides UV generator functions + * + * } + **/ - } + function ExtrudeGeometry ( shapes, options ) { + this.isExtrudeGeometry = this.isGeometry = true; - return compressedTextureFormats; + if ( typeof( shapes ) === "undefined" ) { - }; + shapes = []; + return; - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + } - if ( blending !== THREE.NoBlending ) { + Geometry.call( this ); - this.enable( gl.BLEND ); + this.type = 'ExtrudeGeometry'; - } else { + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - this.disable( gl.BLEND ); - currentBlending = blending; // no blending, that is - return; + this.addShapeList( shapes, options ); - } + this.computeFaceNormals(); - if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - if ( blending === THREE.AdditiveBlending ) { + //this.computeVertexNormals(); - if ( premultipliedAlpha ) { + //console.log( "took", ( Date.now() - startTime ) ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); + }; - } else { + ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); + ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - } + var sl = shapes.length; - } else if ( blending === THREE.SubtractiveBlending ) { + for ( var s = 0; s < sl; s ++ ) { - if ( premultipliedAlpha ) { + var shape = shapes[ s ]; + this.addShape( shape, options ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); + } - } else { + }; - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - } + var amount = options.amount !== undefined ? options.amount : 100; - } else if ( blending === THREE.MultiplyBlending ) { + 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; - if ( premultipliedAlpha ) { + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - } else { + var steps = options.steps !== undefined ? options.steps : 1; - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - } + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; - } else { + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - if ( premultipliedAlpha ) { + extrudePts = extrudePath.getSpacedPoints( steps ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - } else { + // SETUP TNB variables - 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 ); + // Reuse TNB from TubeGeomtry for now. + // TODO1 - have a .isClosed in spline? - } + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); - } + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); - } + } - if ( blending === THREE.CustomBlending ) { + // Safeguards if bevels are not enabled - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + if ( ! bevelEnabled ) { - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + } - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + // Variables initialization - } + var ahole, h, hl; // looping of holes + var scope = this; - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + var shapesOffset = this.vertices.length; - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); + var shapePoints = shape.extractPoints( curveSegments ); - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - } + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - } else { + if ( reverse ) { - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; + vertices = vertices.reverse(); - } + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - }; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // TODO Deprecate + ahole = holes[ h ]; - this.setColorWrite = function ( colorWrite ) { + if ( exports.ShapeUtils.isClockWise( ahole ) ) { - this.buffers.color.setMask( colorWrite ); + holes[ h ] = ahole.reverse(); - }; + } - this.setDepthTest = function ( depthTest ) { + } - this.buffers.depth.setTest( depthTest ); + reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - }; + } - this.setDepthWrite = function ( depthWrite ) { - this.buffers.depth.setMask( depthWrite ); + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - }; + /* Vertices */ - this.setDepthFunc = function ( depthFunc ) { + var contour = vertices; // vertices has all points but contour has only points of circumference - this.buffers.depth.setFunc( depthFunc ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - }; + ahole = holes[ h ]; - this.setStencilTest = function ( stencilTest ) { + vertices = vertices.concat( ahole ); - this.buffers.stencil.setTest( stencilTest ); + } - }; - this.setStencilWrite = function ( stencilWrite ) { + function scalePt2 ( pt, vec, size ) { - this.buffers.stencil.setMask( stencilWrite ); + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - }; + return vec.clone().multiplyScalar( size ).add( pt ); - this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { + } - this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - }; - this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { + // Find directions for point movement - this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); - }; + function getBevelVec( inPt, inPrev, inNext ) { - // + // computes for inPt the corresponding point inPt' on a new contour + // shifted 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. - this.setFlipSided = function ( flipSided ) { + var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - if ( currentFlipSided !== flipSided ) { + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - if ( flipSided ) { + 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; - gl.frontFace( gl.CW ); + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - } else { + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - gl.frontFace( gl.CCW ); + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - } + // not collinear - currentFlipSided = flipSided; + // 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 - this.setCullFace = function ( cullFace ) { + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - if ( cullFace !== THREE.CullFaceNone ) { + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - this.enable( gl.CULL_FACE ); + // scaling factor for v_prev to intersection point - if ( cullFace !== currentCullFace ) { + 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 ); - if ( cullFace === THREE.CullFaceBack ) { + // vector from inPt to intersection point - gl.cullFace( gl.BACK ); + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - } else if ( cullFace === THREE.CullFaceFront ) { + // 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 ) { - gl.cullFace( gl.FRONT ); + return new Vector2( v_trans_x, v_trans_y ); - } else { + } else { - gl.cullFace( gl.FRONT_AND_BACK ); + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - } + } - } + } else { - } else { + // handle special case of collinear edges - this.disable( gl.CULL_FACE ); + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - } + if ( v_next_x > Number.EPSILON ) { - currentCullFace = cullFace; + direction_eq = true; - }; + } - this.setLineWidth = function ( width ) { + } else { - if ( width !== currentLineWidth ) { + if ( v_prev_x < - Number.EPSILON ) { - gl.lineWidth( width ); + if ( v_next_x < - Number.EPSILON ) { - currentLineWidth = width; + direction_eq = true; - } + } - }; + } else { - this.setPolygonOffset = function ( polygonOffset, factor, units ) { + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - if ( polygonOffset ) { + direction_eq = true; - this.enable( gl.POLYGON_OFFSET_FILL ); + } - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + } - gl.polygonOffset( factor, units ); + } - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + 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 { + } else { - this.disable( gl.POLYGON_OFFSET_FILL ); + // 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 ); - } + } - }; + } - this.getScissorTest = function () { + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - return currentScissorTest; + } - }; - this.setScissorTest = function ( scissorTest ) { + var contourMovements = []; - currentScissorTest = scissorTest; + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - if ( scissorTest ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - this.enable( gl.SCISSOR_TEST ); + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - } else { + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - this.disable( gl.SCISSOR_TEST ); + } - } + var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - }; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // texture + ahole = holes[ h ]; - this.activeTexture = function ( webglSlot ) { + oneHoleMovements = []; - if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - if ( currentTextureSlot !== webglSlot ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - } + } - }; + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - this.bindTexture = function ( webglType, webglTexture ) { + } - if ( currentTextureSlot === null ) { - _this.activeTexture(); + // Loop bevelSegments, 1 for the front, 1 for the back - } + for ( b = 0; b < bevelSegments; b ++ ) { - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + //for ( b = bevelSegments; b > 0; b -- ) { - if ( boundTexture === undefined ) { + t = b / bevelSegments; + z = bevelThickness * ( 1 - t ); - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; + //z = bevelThickness * t; + bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved + //bs = bevelSize * t; // linear - } + // contract shape - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + for ( i = 0, il = contour.length; i < il; i ++ ) { - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - boundTexture.type = webglType; - boundTexture.texture = webglTexture; + v( vert.x, vert.y, - z ); - } + } - }; + // expand holes - this.compressedTexImage2D = function () { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - try { + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - gl.compressedTexImage2D.apply( gl, arguments ); + for ( i = 0, il = ahole.length; i < il; i ++ ) { - } catch ( error ) { + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - console.error( error ); + v( vert.x, vert.y, - z ); - } + } - }; + } - this.texImage2D = function () { + } - try { + bs = bevelSize; - gl.texImage2D.apply( gl, arguments ); + // Back facing vertices - } catch ( error ) { + for ( i = 0; i < vlen; i ++ ) { - console.error( error ); + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - } + if ( ! extrudeByPath ) { - }; + v( vert.x, vert.y, 0 ); - // TODO Deprecate + } else { - this.clearColor = function ( r, g, b, a ) { + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - this.buffers.color.setClear( r, g, b, a ); + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - }; + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - this.clearDepth = function ( depth ) { + v( position2.x, position2.y, position2.z ); - this.buffers.depth.setClear( depth ); + } - }; + } - this.clearStencil = function ( stencil ) { + // Add stepped vertices... + // Including front facing vertices - this.buffers.stencil.setClear( stencil ); + var s; - }; + for ( s = 1; s <= steps; s ++ ) { - // + for ( i = 0; i < vlen; i ++ ) { - this.scissor = function ( scissor ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( currentScissor.equals( scissor ) === false ) { + if ( ! extrudeByPath ) { - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); + v( vert.x, vert.y, amount / steps * s ); - } + } else { - }; + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - this.viewport = function ( viewport ) { + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - if ( currentViewport.equals( viewport ) === false ) { + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); + v( position2.x, position2.y, position2.z ); - } + } - }; + } - // + } - this.reset = function () { - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + // Add bevel segments planes - if ( enabledAttributes[ i ] === 1 ) { + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + 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 ); - } + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - capabilities = {}; + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, amount + z ); - compressedTextureFormats = null; + } - currentTextureSlot = null; - currentBoundTextures = {}; + // expand holes - currentBlending = null; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - currentFlipSided = null; - currentCullFace = null; + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - this.buffers.color.reset(); - this.buffers.depth.reset(); - this.buffers.stencil.reset(); + for ( i = 0, il = ahole.length; i < il; i ++ ) { - }; + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); -}; + if ( ! extrudeByPath ) { -THREE.WebGLColorBuffer = function ( gl, state ) { + v( vert.x, vert.y, amount + z ); - var locked = false; + } else { - var color = new THREE.Vector4(); - var currentColorMask = null; - var currentColorClear = new THREE.Vector4(); + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - this.setMask = function ( colorMask ) { + } - if ( currentColorMask !== colorMask && ! locked ) { + } - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + } - } + } - }; + /* Faces */ - this.setLocked = function ( lock ) { + // Top and bottom faces - locked = lock; + buildLidFaces(); - }; + // Sides faces - this.setClear = function ( r, g, b, a ) { + buildSideFaces(); - color.set( r, g, b, a ); - if ( currentColorClear.equals( color ) === false ) { + ///// Internal functions - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + function buildLidFaces() { - } + if ( bevelEnabled ) { - }; + var layer = 0; // steps + 1 + var offset = vlen * layer; - this.reset = function () { + // Bottom faces - locked = false; + for ( i = 0; i < flen; i ++ ) { - currentColorMask = null; - currentColorClear = new THREE.Vector4(); + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - }; + } -}; + layer = steps + bevelSegments * 2; + offset = vlen * layer; -THREE.WebGLDepthBuffer = function( gl, state ) { + // Top faces - var locked = false; + for ( i = 0; i < flen; i ++ ) { - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - this.setTest = function ( depthTest ) { + } - if ( depthTest ) { + } else { - state.enable( gl.DEPTH_TEST ); + // Bottom faces - } else { + for ( i = 0; i < flen; i ++ ) { - state.disable( gl.DEPTH_TEST ); + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - } + } - }; + // Top faces - this.setMask = function( depthMask ){ + for ( i = 0; i < flen; i ++ ) { - if ( currentDepthMask !== depthMask && ! locked ) { + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + } - } + } - }; + } - this.setFunc = function ( depthFunc ) { + // Create faces for the z-sides of the shape - if ( currentDepthFunc !== depthFunc ) { + function buildSideFaces() { - if ( depthFunc ) { + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - switch ( depthFunc ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - case THREE.NeverDepth: + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - gl.depthFunc( gl.NEVER ); - break; + //, true + layeroffset += ahole.length; - case THREE.AlwaysDepth: + } - gl.depthFunc( gl.ALWAYS ); - break; + } - case THREE.LessDepth: + function sidewalls( contour, layeroffset ) { - gl.depthFunc( gl.LESS ); - break; + var j, k; + i = contour.length; - case THREE.LessEqualDepth: + while ( -- i >= 0 ) { - gl.depthFunc( gl.LEQUAL ); - break; + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - case THREE.EqualDepth: + //console.log('b', i,j, i-1, k,vertices.length); - gl.depthFunc( gl.EQUAL ); - break; + var s = 0, sl = steps + bevelSegments * 2; - case THREE.GreaterEqualDepth: + for ( s = 0; s < sl; s ++ ) { - gl.depthFunc( gl.GEQUAL ); - break; + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); - case THREE.GreaterDepth: + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - gl.depthFunc( gl.GREATER ); - break; + f4( a, b, c, d, contour, s, sl, j, k ); - case THREE.NotEqualDepth: + } - gl.depthFunc( gl.NOTEQUAL ); - break; + } - default: + } - gl.depthFunc( gl.LEQUAL ); - } + function v( x, y, z ) { - } else { + scope.vertices.push( new Vector3( x, y, z ) ); - gl.depthFunc( gl.LEQUAL ); + } - } + function f3( a, b, c ) { - currentDepthFunc = depthFunc; + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; - } + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); - }; + var uvs = uvgen.generateTopUV( scope, a, b, c ); - this.setLocked = function ( lock ) { + scope.faceVertexUvs[ 0 ].push( uvs ); - locked = lock; + } - }; + function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - this.setClear = function ( depth ) { + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; + d += shapesOffset; - if ( currentDepthClear !== depth ) { + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); - gl.clearDepth( depth ); - currentDepthClear = depth; + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - } + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - }; + } - this.reset = function () { + }; - locked = false; + ExtrudeGeometry.WorldUVGenerator = { - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; + generateTopUV: function ( geometry, indexA, indexB, indexC ) { - }; + var vertices = geometry.vertices; -}; + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; -THREE.WebGLStencilBuffer = function ( gl, state ) { + return [ + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) + ]; - var locked = false; + }, - var currentStencilMask = null; - var currentStencilFunc = null; - var currentStencilRef = null; - var currentStencilFuncMask = null; - var currentStencilFail = null; - var currentStencilZFail = null; - var currentStencilZPass = null; - var currentStencilClear = null; + generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { - this.setTest = function ( stencilTest ) { + var vertices = geometry.vertices; - if ( stencilTest ) { + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; + var d = vertices[ indexD ]; - state.enable( gl.STENCIL_TEST ); + if ( Math.abs( a.y - b.y ) < 0.01 ) { - } else { + return [ + new Vector2( a.x, 1 - a.z ), + new Vector2( b.x, 1 - b.z ), + new Vector2( c.x, 1 - c.z ), + new Vector2( d.x, 1 - d.z ) + ]; - state.disable( gl.STENCIL_TEST ); + } else { - } + return [ + new Vector2( a.y, 1 - a.z ), + new Vector2( b.y, 1 - b.z ), + new Vector2( c.y, 1 - c.z ), + new Vector2( d.y, 1 - d.z ) + ]; - }; + } - this.setMask = function ( stencilMask ) { + } + }; - if ( currentStencilMask !== stencilMask && ! locked ) { + /** + * @author jonobr1 / http://jonobr1.com + * + * Creates a one-sided polygonal geometry from a path shape. Similar to + * ExtrudeGeometry. + * + * parameters = { + * + * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. + * + * material: // material index for front and back faces + * uvGenerator: // object that provides UV generator functions + * + * } + **/ - gl.stencilMask( stencilMask ); - currentStencilMask = stencilMask; + function ShapeGeometry ( shapes, options ) { + this.isShapeGeometry = this.isGeometry = true; - } + Geometry.call( this ); - }; + this.type = 'ShapeGeometry'; - this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { + if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; - if ( currentStencilFunc !== stencilFunc || - currentStencilRef !== stencilRef || - currentStencilFuncMask !== stencilMask ) { + this.addShapeList( shapes, options ); - gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + this.computeFaceNormals(); - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; + }; - } + ShapeGeometry.prototype = Object.create( Geometry.prototype ); + ShapeGeometry.prototype.constructor = ShapeGeometry; - }; + /** + * Add an array of shapes to THREE.ShapeGeometry. + */ + ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - if ( currentStencilFail !== stencilFail || - currentStencilZFail !== stencilZFail || - currentStencilZPass !== stencilZPass ) { + this.addShape( shapes[ i ], options ); - gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + } - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; + return this; - } + }; - }; + /** + * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. + */ + ShapeGeometry.prototype.addShape = function ( shape, options ) { - this.setLocked = function ( lock ) { + if ( options === undefined ) options = {}; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - locked = lock; + var material = options.material; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - }; + // - this.setClear = function ( stencil ) { + var i, l, hole; - if ( currentStencilClear !== stencil ) { + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - gl.clearStencil( stencil ); - currentStencilClear = stencil; + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - } + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - }; + if ( reverse ) { - this.reset = function () { + vertices = vertices.reverse(); - locked = false; + // Maybe we should also check if holes are in the opposite direction, just to be safe... - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + for ( i = 0, l = holes.length; i < l; i ++ ) { - }; + hole = holes[ i ]; -}; + if ( exports.ShapeUtils.isClockWise( hole ) ) { -// File:src/renderers/webgl/WebGLTextures.js + holes[ i ] = hole.reverse(); -/** -* @author mrdoob / http://mrdoob.com/ -*/ + } -THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + } - var _infoMemory = info.memory; - var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + reverse = false; - // + } - function clampToMaxSize ( image, maxSize ) { + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - if ( image.width > maxSize || image.height > maxSize ) { + // Vertices - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + for ( i = 0, l = holes.length; i < l; i ++ ) { - var scale = maxSize / Math.max( image.width, image.height ); + hole = holes[ i ]; + vertices = vertices.concat( hole ); - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = Math.floor( image.width * scale ); - canvas.height = Math.floor( image.height * scale ); + } - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); + // - console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + var vert, vlen = vertices.length; + var face, flen = faces.length; - return canvas; + for ( i = 0; i < vlen; i ++ ) { - } + vert = vertices[ i ]; - return image; + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); - } + } - function isPowerOfTwo( image ) { + for ( i = 0; i < flen; i ++ ) { - return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ); + face = faces[ i ]; - } + var a = face[ 0 ] + shapesOffset; + var b = face[ 1 ] + shapesOffset; + var c = face[ 2 ] + shapesOffset; - function makePowerOfTwo( image ) { + this.faces.push( new Face3( a, b, c, null, null, material ) ); + this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); - if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { + } - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = THREE.Math.nearestPowerOfTwo( image.width ); - canvas.height = THREE.Math.nearestPowerOfTwo( image.height ); + }; - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, canvas.width, canvas.height ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + // 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. - return canvas; + function Shape () { + this.isShape = true; - } + Path.apply( this, arguments ); - return image; + this.holes = []; - } + }; - function textureNeedsPowerOfTwo( texture ) { + Shape.prototype = Object.assign( Object.create( PathPrototype ), { - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true; + constructor: Shape, - return false; + // Convenience method to return ExtrudeGeometry - } + extrude: function ( options ) { - // Fallback filters for non-power-of-2 textures + return new ExtrudeGeometry( this, options ); - function filterFallback ( f ) { + }, - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { + // Convenience method to return ShapeGeometry - return _gl.NEAREST; + makeGeometry: function ( options ) { - } + return new ShapeGeometry( this, options ); - return _gl.LINEAR; + }, - } + getPointsHoles: function ( divisions ) { - // + var holesPts = []; - function onTextureDispose( event ) { + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - var texture = event.target; + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - texture.removeEventListener( 'dispose', onTextureDispose ); + } - deallocateTexture( texture ); + return holesPts; - _infoMemory.textures --; + }, + // Get points of shape and holes (keypoints based on segments parameter) - } + extractAllPoints: function ( divisions ) { - function onRenderTargetDispose( event ) { + return { - var renderTarget = event.target; + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + }; - deallocateRenderTarget( renderTarget ); + }, - _infoMemory.textures --; + extractPoints: function ( divisions ) { - } + return this.extractAllPoints( divisions ); - // + } - function deallocateTexture( texture ) { + } ); - var textureProperties = properties.get( texture ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ - if ( texture.image && textureProperties.__image__webglTextureCube ) { + function Path ( points ) { + this.isPath = true; - // cube texture + CurvePath.call( this ); + this.currentPoint = new Vector2(); - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + if ( points ) { - } else { + this.fromPoints( points ); - // 2D texture + } - if ( textureProperties.__webglInit === undefined ) return; + }; - _gl.deleteTexture( textureProperties.__webglTexture ); + Path.prototype = PathPrototype; + PathPrototype.constructor = Path; - } - // remove all webgl properties - properties.delete( texture ); + // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" + function ShapePath() { + this.isShapePath = true; + this.subPaths = []; + this.currentPath = null; + } - } + ShapePath.prototype = { + moveTo: function ( x, y ) { + this.currentPath = new Path(); + this.subPaths.push(this.currentPath); + this.currentPath.moveTo( x, y ); + }, + lineTo: function ( x, y ) { + this.currentPath.lineTo( x, y ); + }, + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + }, + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + }, + splineThru: function ( pts ) { + this.currentPath.splineThru( pts ); + }, - function deallocateRenderTarget( renderTarget ) { + toShapes: function ( isCCW, noHoles ) { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + function toShapesNoHoles( inSubpaths ) { - if ( ! renderTarget ) return; + var shapes = []; - if ( textureProperties.__webglTexture !== undefined ) { + for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + var tmpPath = inSubpaths[ i ]; - } + var tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; - if ( renderTarget.depthTexture ) { + shapes.push( tmpShape ); - renderTarget.depthTexture.dispose(); + } - } + return shapes; - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + } - for ( var i = 0; i < 6; i ++ ) { + function isPointInsidePolygon( inPt, inPolygon ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + var polyLen = inPolygon.length; - } + // 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 ++ ) { - } else { + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - } + if ( Math.abs( edgeDy ) > Number.EPSILON ) { - properties.delete( renderTarget.texture ); - properties.delete( renderTarget ); + // 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 !!! - function setTexture2D( texture, slot ) { + } else { - var textureProperties = properties.get( texture ); + 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 - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + } - var image = texture.image; + } else { - if ( image === undefined ) { + // parallel or collinear + if ( inPt.y !== edgeLowPt.y ) continue; // parallel + // edge 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; - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); + } - } else if ( image.complete === false ) { + } - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); + return inside; - } else { + } - uploadTexture( textureProperties, texture, slot ); - return; + var isClockWise = exports.ShapeUtils.isClockWise; - } + var subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - } + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - } + var solid, tmpPath, tmpShape, shapes = []; - function setTextureCube ( texture, slot ) { + if ( subPaths.length === 1 ) { - var textureProperties = properties.get( texture ); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - if ( texture.image.length === 6 ) { + } - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - if ( ! textureProperties.__image__webglTextureCube ) { + // console.log("Holes first", holesFirst); - texture.addEventListener( 'dispose', onTextureDispose ); + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; - textureProperties.__image__webglTextureCube = _gl.createTexture(); + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - _infoMemory.textures ++; + for ( var i = 0, l = subPaths.length; i < l; i ++ ) { - } + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + if ( solid ) { - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - var isCompressed = texture instanceof THREE.CompressedTexture; - var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; - var cubeImage = []; + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; - for ( var i = 0; i < 6; i ++ ) { + //console.log('cw', i); - if ( ! isCompressed && ! isDataTexture ) { + } else { - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - } else { + //console.log('ccw', i); - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + } - } + } - } + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); - var image = cubeImage[ 0 ], - isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + if ( newShapes.length > 1 ) { - for ( var i = 0; i < 6; i ++ ) { + var ambiguous = false; + var toChange = []; - if ( ! isCompressed ) { + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - if ( isDataTexture ) { + betterShapeHoles[ sIdx ] = []; - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + } - } else { + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + var sho = newShapeHoles[ sIdx ]; - } + for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - } else { + var ho = sho[ hIdx ]; + var hole_unassigned = true; - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - mipmap = mipmaps[ j ]; + if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + } else { - state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + ambiguous = true; - } else { + } - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); + } - } + } + if ( hole_unassigned ) { - } else { + betterShapeHoles[ sIdx ].push( ho ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } - } + } - } + } + // console.log("ambiguous: ", ambiguous); + if ( toChange.length > 0 ) { - } + // console.log("to change: ", toChange); + if ( ! ambiguous ) newShapeHoles = betterShapeHoles; - } + } - if ( texture.generateMipmaps && isPowerOfTwoImage ) { + } - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + var tmpHoles; - } + for ( var i = 0, il = newShapes.length; i < il; i ++ ) { - textureProperties.__version = texture.version; + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; - if ( texture.onUpdate ) texture.onUpdate( texture ); + for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - } else { + tmpShape.holes.push( tmpHoles[ j ].h ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + } - } + } - } + //console.log("shape", shapes); - } + return shapes; - function setTextureCubeDynamic ( texture, slot ) { + } + } - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author mrdoob / http://mrdoob.com/ + */ - } + function Font ( data ) { + this.isFont = true; - function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) { + this.data = data; - var extension; + }; - if ( isPowerOfTwoImage ) { + Object.assign( Font.prototype, { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + generateShapes: function ( text, size, divisions ) { - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + function createPaths( text ) { - } else { + var chars = String( text ).split( '' ); + var scale = size / data.resolution; + var offset = 0; - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + var paths = []; - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + for ( var i = 0; i < chars.length; i ++ ) { - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); + var ret = createPath( chars[ i ], scale, offset ); + offset += ret.offset; - } + paths.push( ret.path ); - _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 paths; - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); + } - } + function createPath( c, scale, offset ) { - } + var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + if ( ! glyph ) return; - if ( extension ) { + var path = new ShapePath(); - if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; + var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + if ( glyph.o ) { - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - } + for ( var i = 0, l = outline.length; i < l; ) { - } + var action = outline[ i ++ ]; - } + switch ( action ) { - function uploadTexture( textureProperties, texture, slot ) { + case 'm': // moveTo - if ( textureProperties.__webglInit === undefined ) { + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - textureProperties.__webglInit = true; + path.moveTo( x, y ); - texture.addEventListener( 'dispose', onTextureDispose ); + break; - textureProperties.__webglTexture = _gl.createTexture(); + case 'l': // lineTo - _infoMemory.textures ++; + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - } + path.lineTo( x, y ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + break; - _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 ); + case 'q': // quadraticCurveTo - var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; - if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - image = makePowerOfTwo( image ); + laste = pts[ pts.length - 1 ]; - } + if ( laste ) { - var isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + cpx0 = laste.x; + cpy0 = laste.y; - setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - var mipmap, mipmaps = texture.mipmaps; + var t = i2 / divisions; + b2( t, cpx0, cpx1, cpx ); + b2( t, cpy0, cpy1, cpy ); - if ( texture instanceof THREE.DepthTexture ) { + } - // populate depth texture with dummy data + } - var internalFormat = _gl.DEPTH_COMPONENT; + break; - if ( texture.type === THREE.FloatType ) { + case 'b': // bezierCurveTo - if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); - internalFormat = _gl.DEPTH_COMPONENT32F; + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; + cpx2 = outline[ i ++ ] * scale + offset; + cpy2 = outline[ i ++ ] * scale; - } else if ( _isWebGL2 ) { + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - // WebGL 2.0 requires signed internalformat for glTexImage2D - internalFormat = _gl.DEPTH_COMPONENT16; + laste = pts[ pts.length - 1 ]; - } + if ( laste ) { - state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); + cpx0 = laste.x; + cpy0 = laste.y; - } else if ( texture instanceof THREE.DataTexture ) { + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - // 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 + var t = i2 / divisions; + b3( t, cpx0, cpx1, cpx2, cpx ); + b3( t, cpy0, cpy1, cpy2, cpy ); - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + } - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + } - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + break; - } + } - texture.generateMipmaps = false; + } - } else { + } - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + return { offset: glyph.ha * scale, path: path }; - } + } - } else if ( texture instanceof THREE.CompressedTexture ) { + // - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + if ( size === undefined ) size = 100; + if ( divisions === undefined ) divisions = 4; - mipmap = mipmaps[ i ]; + var data = this.data; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + var paths = createPaths( text ); + var shapes = []; - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - } else { + } - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + return shapes; - } + } - } else { + } ); - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function FontLoader ( manager ) { + this.isFontLoader = true; - } + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - } else { + }; - // regular Texture (image, video, canvas) + Object.assign( FontLoader.prototype, { - // 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 + load: function ( url, onLoad, onProgress, onError ) { - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + var scope = this; - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var loader = new XHRLoader( this.manager ); + loader.load( url, function ( text ) { - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + var json; - } + try { - texture.generateMipmaps = false; + json = JSON.parse( text ); - } else { + } catch ( e ) { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); + json = JSON.parse( text.substring( 65, text.length - 2 ) ); - } + } - } + var font = scope.parse( json ); - if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); + if ( onLoad ) onLoad( font ); - textureProperties.__version = texture.version; + }, onProgress, onError ); - if ( texture.onUpdate ) texture.onUpdate( texture ); + }, - } + parse: function ( json ) { - // Render targets + return new Font( json ); - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) { + } - var glFormat = paramThreeToGL( renderTarget.texture.format ); - var glType = paramThreeToGL( renderTarget.texture.type ); - state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + } ); - } + var context; - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage ( renderbuffer, renderTarget ) { + function getAudioContext () { + if ( context === undefined ) { + context = new ( window.AudioContext || window.webkitAudioContext )(); + } - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + return context; + } - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + /** + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + function AudioLoader ( manager ) { + this.isAudioLoader = true; - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + }; - } else { + Object.assign( AudioLoader.prototype, { - // FIXME: We don't support !depth !stencil - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + load: function ( url, onLoad, onProgress, onError ) { - } + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.load( url, function ( buffer ) { - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + var context = getAudioContext(); - } + context.decodeAudioData( buffer, function ( audioBuffer ) { - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture ( framebuffer, renderTarget ) { + onLoad( audioBuffer ); - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); + } ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + }, onProgress, onError ); - if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) { + } - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - // upload an empty depth texture with framebuffer size - if ( !properties.get( renderTarget.depthTexture ).__webglTexture || - renderTarget.depthTexture.image.width !== renderTarget.width || - renderTarget.depthTexture.image.height !== renderTarget.height ) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; - } + function StereoCamera () { + this.isStereoCamera = true; - setTexture2D( renderTarget.depthTexture, 0 ); + this.type = 'StereoCamera'; - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + this.aspect = 1; - } + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - var renderTargetProperties = properties.get( renderTarget ); + }; - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + Object.assign( StereoCamera.prototype, { - if ( renderTarget.depthTexture ) { + update: ( function () { - if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); + var focus, fov, aspect, near, far; - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); - } else { + return function update( camera ) { - if ( isCube ) { + var needsUpdate = focus !== camera.focus || fov !== camera.fov || + aspect !== camera.aspect * this.aspect || near !== camera.near || + far !== camera.far; - renderTargetProperties.__webglDepthbuffer = []; + if ( needsUpdate ) { - for ( var i = 0; i < 6; i ++ ) { + focus = camera.focus; + fov = camera.fov; + aspect = camera.aspect * this.aspect; + near = camera.near; + far = camera.far; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - } + var projectionMatrix = camera.projectionMatrix.clone(); + var eyeSep = 0.064 / 2; + var eyeSepOnProjection = eyeSep * near / focus; + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var xmin, xmax; - } else { + // translate xOffset - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + eyeLeft.elements[ 12 ] = - eyeSep; + eyeRight.elements[ 12 ] = eyeSep; - } + // for left eye - } + xmin = - ymax * aspect + eyeSepOnProjection; + xmax = ymax * aspect + eyeSepOnProjection; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - } + this.cameraL.projectionMatrix.copy( projectionMatrix ); - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + // for right eye - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + xmin = - ymax * aspect - eyeSepOnProjection; + xmax = ymax * aspect - eyeSepOnProjection; - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - textureProperties.__webglTexture = _gl.createTexture(); + this.cameraR.projectionMatrix.copy( projectionMatrix ); - _infoMemory.textures ++; + } - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); - // Setup framebuffer + }; - if ( isCube ) { + } )() - renderTargetProperties.__webglFramebuffer = []; + } ); - for ( var i = 0; i < 6; i ++ ) { + /** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + function CubeCamera ( near, far, cubeResolution ) { + this.isCubeCamera = this.isObject3D = true; - } + Object3D.call( this ); - } else { + this.type = 'CubeCamera'; - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + var fov = 90, aspect = 1; - } + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); - // Setup color buffer + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); - if ( isCube ) { + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); - for ( var i = 0; i < 6; i ++ ) { + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - } + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); - } else { + this.updateCubeMap = function ( renderer, scene ) { - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + if ( this.parent === null ) this.updateMatrixWorld(); - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - state.bindTexture( _gl.TEXTURE_2D, null ); + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.texture.generateMipmaps; - } + renderTarget.texture.generateMipmaps = false; - // Setup depth and stencil buffers + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); - if ( renderTarget.depthBuffer ) { + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); - setupDepthRenderbuffer( renderTarget ); + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); - } + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); - } + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); - function updateRenderTargetMipmap( renderTarget ) { + renderTarget.texture.generateMipmaps = generateMipmaps; - var texture = renderTarget.texture; + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); - if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== THREE.NearestFilter && - texture.minFilter !== THREE.LinearFilter ) { + renderer.setRenderTarget( null ); - var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - var webglTexture = properties.get( texture ).__webglTexture; + }; - state.bindTexture( target, webglTexture ); - _gl.generateMipmap( target ); - state.bindTexture( target, null ); + }; - } + CubeCamera.prototype = Object.create( Object3D.prototype ); + CubeCamera.prototype.constructor = CubeCamera; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.setTexture2D = setTexture2D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; + function AudioListener () { + this.isAudioListener = true; -}; + Object3D.call( this ); -// File:src/renderers/webgl/WebGLUniforms.js + this.type = 'AudioListener'; -/** - * - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [renderer] ) - * - * uploads a uniform value(s) - * the 'renderer' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (renderer factorizations): - * - * .upload( gl, seq, values, renderer ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * .splitDynamic( seq, values ) : filteredSeq - * - * filters 'seq' entries with dynamic entry and removes them from 'seq' - * - * - * Methods of the top-level container (renderer factorizations): - * - * .setValue( gl, name, value ) - * - * sets uniform with name 'name' to 'value' - * - * .set( gl, obj, prop ) - * - * sets uniform from object and property with same name than uniform - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - * - * @author tschw - * - */ + this.context = getAudioContext(); -THREE.WebGLUniforms = ( function() { // scope + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - var emptyTexture = new THREE.Texture(); - var emptyCubeTexture = new THREE.CubeTexture(); + this.filter = null; - // --- Base for inner nodes (including the root) --- + }; - var UniformContainer = function() { + AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.seq = []; - this.map = {}; + constructor: AudioListener, - }, + getInput: function () { - // --- Utilities --- + return this.gain; - // Array Caches (provide typed arrays for temporary by size) + }, - arrayCacheF32 = [], - arrayCacheI32 = [], + removeFilter: function ( ) { - uncacheTemporaryArrays = function() { + if ( this.filter !== null ) { - arrayCacheF32.length = 0; - arrayCacheI32.length = 0; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - }, + } - // Flattening for arrays of vectors and matrices + }, - flatten = function( array, nBlocks, blockSize ) { + getFilter: function () { - var firstElem = array[ 0 ]; + return this.filter; - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + }, - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + setFilter: function ( value ) { - if ( r === undefined ) { + if ( this.filter !== null ) { - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - } + } else { - if ( nBlocks !== 0 ) { + this.gain.disconnect( this.context.destination ); - firstElem.toArray( r, 0 ); + } - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - offset += blockSize; - array[ i ].toArray( r, offset ); + }, - } + getMasterVolume: function () { - } + return this.gain.gain.value; - return r; + }, - }, + setMasterVolume: function ( value ) { - // Texture unit allocation + this.gain.gain.value = value; - allocTexUnits = function( renderer, n ) { + }, - var r = arrayCacheI32[ n ]; + updateMatrixWorld: ( function () { - if ( r === undefined ) { + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + var orientation = new Vector3(); - } + return function updateMatrixWorld( force ) { - for ( var i = 0; i !== n; ++ i ) - r[ i ] = renderer.allocTextureUnit(); + Object3D.prototype.updateMatrixWorld.call( this, force ); - return r; + var listener = this.context.listener; + var up = this.up; - }, + this.matrixWorld.decompose( position, quaternion, scale ); - // --- Setters --- + orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + listener.setPosition( position.x, position.y, position.z ); + listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); - // Single scalar + }; - setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, - setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, + } )() - // Single float vector (from flat array or THREE.VectorN) + } ); - setValue2fv = function( gl, v ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); - else gl.uniform2f( this.addr, v.x, v.y ); + function Audio ( listener ) { + this.isAudio = true; - }, + Object3D.call( this ); - setValue3fv = function( gl, v ) { + this.type = 'Audio'; - if ( v.x !== undefined ) - gl.uniform3f( this.addr, v.x, v.y, v.z ); - else if ( v.r !== undefined ) - gl.uniform3f( this.addr, v.r, v.g, v.b ); - else - gl.uniform3fv( this.addr, v ); + this.context = listener.context; + this.source = this.context.createBufferSource(); + this.source.onended = this.onEnded.bind( this ); - }, + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - setValue4fv = function( gl, v ) { + this.autoplay = false; - if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); - else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + this.startTime = 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.sourceType = 'empty'; - }, + this.filters = []; - // Single matrix (from flat array or MatrixN) + }; - setValue2fm = function( gl, v ) { + Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - gl.uniformMatrix2fv( this.addr, false, v.elements || v ); + constructor: Audio, - }, + getOutput: function () { - setValue3fm = function( gl, v ) { + return this.gain; - gl.uniformMatrix3fv( this.addr, false, v.elements || v ); + }, - }, + setNodeSource: function ( audioNode ) { - setValue4fm = function( gl, v ) { + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); - gl.uniformMatrix4fv( this.addr, false, v.elements || v ); + return this; - }, + }, - // Single texture (2D / Cube) + setBuffer: function ( audioBuffer ) { - setValueT1 = function( gl, v, renderer ) { + this.source.buffer = audioBuffer; + this.sourceType = 'buffer'; - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTexture2D( v || emptyTexture, unit ); + if ( this.autoplay ) this.play(); - }, + return this; - setValueT6 = function( gl, v, renderer ) { + }, - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTextureCube( v || emptyCubeTexture, unit ); + play: function () { - }, + if ( this.isPlaying === true ) { - // Integer / Boolean vectors or arrays thereof (always flat arrays) + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, - setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, - setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, + } - // Helper to pick the right setter for the singular case + if ( this.hasPlaybackControl === false ) { - getSingularSetter = function( type ) { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - switch ( type ) { + } - case 0x1406: return setValue1f; // FLOAT - case 0x8b50: return setValue2fv; // _VEC2 - case 0x8b51: return setValue3fv; // _VEC3 - case 0x8b52: return setValue4fv; // _VEC4 + var source = this.context.createBufferSource(); - case 0x8b5a: return setValue2fm; // _MAT2 - case 0x8b5b: return setValue3fm; // _MAT3 - case 0x8b5c: return setValue4fm; // _MAT4 + source.buffer = this.source.buffer; + source.loop = this.source.loop; + source.onended = this.source.onended; + source.start( 0, this.startTime ); + source.playbackRate.value = this.playbackRate; - case 0x8b5e: return setValueT1; // SAMPLER_2D - case 0x8b60: return setValueT6; // SAMPLER_CUBE + this.isPlaying = true; - case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + this.source = source; - } + return this.connect(); - }, + }, - // Array of scalars + pause: function () { - setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, - setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, + if ( this.hasPlaybackControl === false ) { - // Array of vectors (flat or from THREE classes) + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - setValueV2a = function( gl, v ) { + } - gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); + this.source.stop(); + this.startTime = this.context.currentTime; + this.isPlaying = false; - }, + return this; - setValueV3a = function( gl, v ) { + }, - gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); + stop: function () { - }, + if ( this.hasPlaybackControl === false ) { - setValueV4a = function( gl, v ) { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); + } - }, + this.source.stop(); + this.startTime = 0; + this.isPlaying = false; - // Array of matrices (flat or from THREE clases) + return this; - setValueM2a = function( gl, v ) { + }, - gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); + connect: function () { - }, + if ( this.filters.length > 0 ) { - setValueM3a = function( gl, v ) { + this.source.connect( this.filters[ 0 ] ); - gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - }, + this.filters[ i - 1 ].connect( this.filters[ i ] ); - setValueM4a = function( gl, v ) { + } - gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - }, + } else { - // Array of textures (2D / Cube) + this.source.connect( this.getOutput() ); - setValueT1a = function( gl, v, renderer ) { + } - var n = v.length, - units = allocTexUnits( renderer, n ); + return this; - gl.uniform1iv( this.addr, units ); + }, - for ( var i = 0; i !== n; ++ i ) { + disconnect: function () { - renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + if ( this.filters.length > 0 ) { - } + this.source.disconnect( this.filters[ 0 ] ); - }, + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - setValueT6a = function( gl, v, renderer ) { + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - var n = v.length, - units = allocTexUnits( renderer, n ); + } - gl.uniform1iv( this.addr, units ); + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - for ( var i = 0; i !== n; ++ i ) { + } else { - renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + this.source.disconnect( this.getOutput() ); - } + } - }, + return this; + }, - // Helper to pick the right setter for a pure (bottom-level) array + getFilters: function () { - getPureArraySetter = function( type ) { + return this.filters; - switch ( type ) { + }, - case 0x1406: return setValue1fv; // FLOAT - case 0x8b50: return setValueV2a; // _VEC2 - case 0x8b51: return setValueV3a; // _VEC3 - case 0x8b52: return setValueV4a; // _VEC4 + setFilters: function ( value ) { - case 0x8b5a: return setValueM2a; // _MAT2 - case 0x8b5b: return setValueM3a; // _MAT3 - case 0x8b5c: return setValueM4a; // _MAT4 + if ( ! value ) value = []; - case 0x8b5e: return setValueT1a; // SAMPLER_2D - case 0x8b60: return setValueT6a; // SAMPLER_CUBE + if ( this.isPlaying === true ) { - case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + this.disconnect(); + this.filters = value; + this.connect(); - } + } else { - }, + this.filters = value; - // --- Uniform Classes --- + } - SingleUniform = function SingleUniform( id, activeInfo, addr ) { + return this; - this.id = id; - this.addr = addr; - this.setValue = getSingularSetter( activeInfo.type ); + }, - // this.path = activeInfo.name; // DEBUG + getFilter: function () { - }, + return this.getFilters()[ 0 ]; - PureArrayUniform = function( id, activeInfo, addr ) { + }, - this.id = id; - this.addr = addr; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + setFilter: function ( filter ) { - // this.path = activeInfo.name; // DEBUG + return this.setFilters( filter ? [ filter ] : [] ); - }, + }, - StructuredUniform = function( id ) { + setPlaybackRate: function ( value ) { - this.id = id; + if ( this.hasPlaybackControl === false ) { - UniformContainer.call( this ); // mix-in + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - }; + } - StructuredUniform.prototype.setValue = function( gl, value ) { + this.playbackRate = value; - // Note: Don't need an extra 'renderer' parameter, since samplers - // are not allowed in structured uniforms. + if ( this.isPlaying === true ) { - var seq = this.seq; + this.source.playbackRate.value = this.playbackRate; - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + } - var u = seq[ i ]; - u.setValue( gl, value[ u.id ] ); + return this; - } + }, - }; + getPlaybackRate: function () { - // --- Top-level --- + return this.playbackRate; - // Parser - builds up the property tree from the path strings + }, - var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, - // extracts - // - the identifier (member name or array index) - // - followed by an optional right bracket (found when array index) - // - followed by an optional left bracket or dot (type of subscript) - // - // Note: These portions can be read in a non-overlapping fashion and - // allow straightforward parsing of the hierarchy that WebGL encodes - // in the uniform names. + onEnded: function () { - addUniform = function( container, uniformObject ) { + this.isPlaying = false; - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + }, - }, + getLoop: function () { - parseUniform = function( activeInfo, addr, container ) { + if ( this.hasPlaybackControl === false ) { - var path = activeInfo.name, - pathLength = path.length; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + } - for (; ;) { + return this.source.loop; - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + }, - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + setLoop: function ( value ) { - if ( idIsIndex ) id = id | 0; // convert to integer + if ( this.hasPlaybackControl === false ) { - if ( subscript === undefined || - subscript === '[' && matchEnd + 2 === pathLength ) { - // bare name or "pure" bottom-level array "[0]" suffix + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + } - break; + this.source.loop = value; - } else { - // step into inner node / create it in case it doesn't exist + }, - var map = container.map, - next = map[ id ]; + getVolume: function () { - if ( next === undefined ) { + return this.gain.gain.value; - next = new StructuredUniform( id ); - addUniform( container, next ); + }, - } - container = next; + setVolume: function ( value ) { - } + this.gain.gain.value = value; - } + return this; - }, + } - // Root Container + } ); - WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - UniformContainer.call( this ); + function PositionalAudio ( listener ) { + this.isPositionalAudio = true; - this.renderer = renderer; + Audio.call( this, listener ); - var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + this.panner = this.context.createPanner(); + this.panner.connect( this.gain ); - for ( var i = 0; i !== n; ++ i ) { + }; - var info = gl.getActiveUniform( program, i ), - path = info.name, - addr = gl.getUniformLocation( program, path ); + PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - parseUniform( info, addr, this ); + constructor: PositionalAudio, - } + getOutput: function () { - }; + return this.panner; + }, - WebGLUniforms.prototype.setValue = function( gl, name, value ) { + getRefDistance: function () { - var u = this.map[ name ]; + return this.panner.refDistance; - if ( u !== undefined ) u.setValue( gl, value, this.renderer ); + }, - }; + setRefDistance: function ( value ) { - WebGLUniforms.prototype.set = function( gl, object, name ) { + this.panner.refDistance = value; - var u = this.map[ name ]; + }, - if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); + getRolloffFactor: function () { - }; + return this.panner.rolloffFactor; - WebGLUniforms.prototype.setOptional = function( gl, object, name ) { + }, - var v = object[ name ]; + setRolloffFactor: function ( value ) { - if ( v !== undefined ) this.setValue( gl, name, v ); + this.panner.rolloffFactor = value; - }; + }, + getDistanceModel: function () { - // Static interface + return this.panner.distanceModel; - WebGLUniforms.upload = function( gl, seq, values, renderer ) { + }, - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + setDistanceModel: function ( value ) { - var u = seq[ i ], - v = values[ u.id ]; + this.panner.distanceModel = value; - if ( v.needsUpdate !== false ) { - // note: always updating when .needsUpdate is undefined + }, - u.setValue( gl, v.value, renderer ); + getMaxDistance: function () { - } + return this.panner.maxDistance; - } + }, - }; + setMaxDistance: function ( value ) { - WebGLUniforms.seqWithValue = function( seq, values ) { + this.panner.maxDistance = value; - var r = []; + }, - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + updateMatrixWorld: ( function () { - var u = seq[ i ]; - if ( u.id in values ) r.push( u ); + var position = new Vector3(); - } + return function updateMatrixWorld( force ) { - return r; + Object3D.prototype.updateMatrixWorld.call( this, force ); - }; + position.setFromMatrixPosition( this.matrixWorld ); - WebGLUniforms.splitDynamic = function( seq, values ) { + this.panner.setPosition( position.x, position.y, position.z ); - var r = null, - n = seq.length, - w = 0; + }; - for ( var i = 0; i !== n; ++ i ) { + } )() - var u = seq[ i ], - v = values[ u.id ]; - if ( v && v.dynamic === true ) { + } ); - if ( r === null ) r = []; - r.push( u ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function AudioAnalyser ( audio, fftSize ) { + this.isAudioAnalyser = true; - // in-place compact 'seq', removing the matches - if ( w < i ) seq[ w ] = u; - ++ w; + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; - } + this.data = new Uint8Array( this.analyser.frequencyBinCount ); - } + audio.getOutput().connect( this.analyser ); - if ( w < n ) seq.length = w; + }; - return r; + Object.assign( AudioAnalyser.prototype, { - }; + getFrequencyData: function () { - WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { + this.analyser.getByteFrequencyData( this.data ); - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + return this.data; - var v = values[ seq[ i ].id ], - f = v.onUpdateCallback; + }, - if ( f !== undefined ) f.call( v, object, camera ); + getAverageFrequency: function () { - } + var value = 0, data = this.getFrequencyData(); - }; + for ( var i = 0; i < data.length; i ++ ) { - return WebGLUniforms; + value += data[ i ]; -} )(); + } -// File:src/renderers/webgl/plugins/LensFlarePlugin.js + return value / data.length; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.LensFlarePlugin = function ( renderer, flares ) { + } ); - var gl = renderer.context; - var state = renderer.state; + /** + * + * Buffered scene graph property that allows weighted accumulation. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var vertexBuffer, elementBuffer; - var shader, program, attributes, uniforms; + function PropertyMixer ( binding, typeName, valueSize ) { + this.isPropertyMixer = true; - var tempTexture, occlusionTexture; + this.binding = binding; + this.valueSize = valueSize; - function init() { + var bufferType = Float64Array, + mixFunction; - var vertices = new Float32Array( [ - - 1, - 1, 0, 0, - 1, - 1, 1, 0, - 1, 1, 1, 1, - - 1, 1, 0, 1 - ] ); + switch ( typeName ) { - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + case 'quaternion': mixFunction = this._slerp; break; - // buffers + case 'string': + case 'bool': - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + bufferType = Array, mixFunction = this._select; break; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + default: mixFunction = this._lerp; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + } - // textures + this.buffer = new bufferType( valueSize * 4 ); + // layout: [ incoming | accu0 | accu1 | orig ] + // + // interpolators can use .buffer as their .result + // the data then goes to 'incoming' + // + // 'accu0' and 'accu1' are used frame-interleaved for + // the cumulative result and are compared to detect + // changes + // + // 'orig' stores the original state of the property - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + this._mixBufferRegion = mixFunction; - state.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 ); + this.cumulativeWeight = 0; - state.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 ); + this.useCount = 0; + this.referenceCount = 0; - shader = { + }; - vertexShader: [ + PropertyMixer.prototype = { - "uniform lowp int renderType;", + constructor: PropertyMixer, - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + // accumulate data in the 'incoming' region into 'accu' + accumulate: function( accuIndex, weight ) { - "uniform sampler2D occlusionMap;", + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - "attribute vec2 position;", - "attribute vec2 uv;", + var buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride, - "varying vec2 vUV;", - "varying float vVisibility;", + currentWeight = this.cumulativeWeight; - "void main() {", + if ( currentWeight === 0 ) { - "vUV = uv;", + // accuN := incoming * weight - "vec2 pos = position;", + for ( var i = 0; i !== stride; ++ i ) { - "if ( renderType == 2 ) {", + buffer[ offset + i ] = buffer[ i ]; - "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 ) );", + } - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", + currentWeight = weight; - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + } else { - "}", + // accuN := accuN + incoming * weight - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + currentWeight += weight; + var mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - "}" + } - ].join( "\n" ), + this.cumulativeWeight = currentWeight; - fragmentShader: [ + }, - "uniform lowp int renderType;", + // apply the state of 'accu' to the binding when accus differ + apply: function( accuIndex ) { - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", + var stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - "varying vec2 vUV;", - "varying float vVisibility;", + weight = this.cumulativeWeight, - "void main() {", + binding = this.binding; - // pink square + this.cumulativeWeight = 0; - "if ( renderType == 0 ) {", + if ( weight < 1 ) { - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + // accuN := accuN + original * ( 1 - cumulativeWeight ) - // restore + var originalValueOffset = stride * 3; - "} else if ( renderType == 1 ) {", + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - "gl_FragColor = texture2D( map, vUV );", + } - // flare + for ( var i = stride, e = stride + stride; i !== e; ++ i ) { - "} else {", + if ( buffer[ i ] !== buffer[ i + stride ] ) { - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + // value has changed -> update scene graph - "}", + binding.setValue( buffer, offset ); + break; - "}" + } - ].join( "\n" ) + } - }; + }, - program = createProgram( shader ); + // remember the state of the bound property and copy it to both accus + saveOriginalState: function() { - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - }; + var binding = this.binding; - 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 buffer = this.buffer, + stride = this.valueSize, - } + originalValueOffset = stride * 3; - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ + binding.getValue( buffer, originalValueOffset ); - this.render = function ( scene, camera, viewport ) { + // accu[0..1] := orig -- initially detect changes against the original + for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { - if ( flares.length === 0 ) return; + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - var tempPosition = new THREE.Vector3(); + } - var invAspect = viewport.w / viewport.z, - halfViewportWidth = viewport.z * 0.5, - halfViewportHeight = viewport.w * 0.5; + this.cumulativeWeight = 0; - var size = 16 / viewport.w, - scale = new THREE.Vector2( size * invAspect, size ); + }, - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState: function() { - var validArea = new THREE.Box2(); + var originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); - validArea.min.set( 0, 0 ); - validArea.max.set( viewport.z - 16, viewport.w - 16 ); + }, - if ( program === undefined ) { - init(); + // mix functions - } + _select: function( buffer, dstOffset, srcOffset, t, stride ) { - gl.useProgram( program ); + if ( t >= 0.5 ) { - state.initAttributes(); - state.enableAttribute( attributes.vertex ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + for ( var i = 0; i !== stride; ++ i ) { - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/uniforms + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; - 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 ); + }, - state.disable( gl.CULL_FACE ); - state.setDepthWrite( false ); + _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - for ( var i = 0, l = flares.length; i < l; i ++ ) { + Quaternion.slerpFlat( buffer, dstOffset, + buffer, dstOffset, buffer, srcOffset, t ); - size = 16 / viewport.w; - scale.set( size * invAspect, size ); + }, - // calc object screen position + _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { - var flare = flares[ i ]; + var s = 1 - t; - tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); + for ( var i = 0; i !== stride; ++ i ) { - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); + var j = dstOffset + i; - // setup arrays for gl programs + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - screenPosition.copy( tempPosition ); + } - // horizontal and vertical coordinate of the lower left corner of the pixels to copy + } - screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; + }; - // screen cull + /** + * + * A reference to a real property in the scene graph. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - if ( validArea.containsPoint( screenPositionPixels ) === true ) { + function PropertyBinding ( rootNode, path, parsedPath ) { + this.isPropertyBinding = true; - // save current RGB to temp texture + this.path = path; + this.parsedPath = parsedPath || + PropertyBinding.parseTrackName( path ); - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, null ); - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + this.node = PropertyBinding.findNode( + rootNode, this.parsedPath.nodeName ) || rootNode; + this.rootNode = rootNode; - // 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 ); + PropertyBinding.prototype = { - state.disable( gl.BLEND ); - state.enable( gl.DEPTH_TEST ); + constructor: PropertyBinding, - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + getValue: function getValue_unbound( targetArray, offset ) { + this.bind(); + this.getValue( targetArray, offset ); - // copy result to occlusionMap + // Note: This class uses a State pattern on a per-method basis: + // 'bind' sets 'this.getValue' / 'setValue' and shadows the + // prototype version of these methods with one that represents + // the bound state. When the property is not found, the methods + // become no-ops. - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + }, + setValue: function getValue_unbound( sourceArray, offset ) { - // restore graphics + this.bind(); + this.setValue( sourceArray, offset ); - gl.uniform1i( uniforms.renderType, 1 ); - state.disable( gl.DEPTH_TEST ); + }, - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + // create getter / setter pair for a property in the scene graph + bind: function() { + var targetObject = this.node, + parsedPath = this.parsedPath, - // update object positions + objectName = parsedPath.objectName, + propertyName = parsedPath.propertyName, + propertyIndex = parsedPath.propertyIndex; - flare.positionScreen.copy( screenPosition ); + if ( ! targetObject ) { - if ( flare.customUpdateCallback ) { + targetObject = PropertyBinding.findNode( + this.rootNode, parsedPath.nodeName ) || this.rootNode; - flare.customUpdateCallback( flare ); + this.node = targetObject; - } else { + } - flare.updateLensFlares(); + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - } + // ensure there is a value node + if ( ! targetObject ) { - // render flares + console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); + return; - gl.uniform1i( uniforms.renderType, 2 ); - state.enable( gl.BLEND ); + } - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + if ( objectName ) { - var sprite = flare.lensFlares[ j ]; + var objectIndex = parsedPath.objectIndex; - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + case 'materials': - size = sprite.size * sprite.scale / viewport.w; + if ( ! targetObject.material ) { - scale.x = size * invAspect; - scale.y = size; + console.error( ' can not bind to material as node does not have a material', this ); + return; - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + } - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + if ( ! targetObject.material.materials ) { - state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture2D( sprite.texture, 1 ); + console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); + return; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + } - } + targetObject = targetObject.material.materials; - } + break; - } + case 'bones': - } + if ( ! targetObject.skeleton ) { - // restore gl + console.error( ' can not bind to bones as node does not have a skeleton', this ); + return; - state.enable( gl.CULL_FACE ); - state.enable( gl.DEPTH_TEST ); - state.setDepthWrite( true ); + } - renderer.resetGLState(); + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - }; + targetObject = targetObject.skeleton.bones; - function createProgram ( shader ) { + // support resolving morphTarget names into indices. + for ( var i = 0; i < targetObject.length; i ++ ) { - var program = gl.createProgram(); + if ( targetObject[ i ].name === objectIndex ) { - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + objectIndex = i; + break; - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + } - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + } - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + break; - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + default: - gl.linkProgram( program ); + if ( targetObject[ objectName ] === undefined ) { - return program; + console.error( ' can not bind to objectName of node, undefined', this ); + return; - } + } -}; + targetObject = targetObject[ objectName ]; -// File:src/renderers/webgl/plugins/SpritePlugin.js + } -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ -THREE.SpritePlugin = function ( renderer, sprites ) { + if ( objectIndex !== undefined ) { - var gl = renderer.context; - var state = renderer.state; + if ( targetObject[ objectIndex ] === undefined ) { - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); + return; - var texture; + } - // decompose matrixWorld + targetObject = targetObject[ objectIndex ]; - var spritePosition = new THREE.Vector3(); - var spriteRotation = new THREE.Quaternion(); - var spriteScale = new THREE.Vector3(); + } - function init() { + } - 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 - ] ); + // resolve property + var nodeProperty = targetObject[ propertyName ]; - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + if ( nodeProperty === undefined ) { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + var nodeName = parsedPath.nodeName; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + console.error( " trying to update property for track: " + nodeName + + '.' + propertyName + " but it wasn't found.", targetObject ); + return; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + } - program = createProgram(); + // determine versioning scheme + var versioning = this.Versioning.None; - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + if ( targetObject.needsUpdate !== undefined ) { // material - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + versioning = this.Versioning.NeedsUpdate; + this.targetObject = targetObject; - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + versioning = this.Versioning.MatrixWorldNeedsUpdate; + this.targetObject = targetObject; - 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' ), + // determine how the property gets bound + var bindingType = this.BindingType.Direct; - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + if ( propertyIndex !== undefined ) { + // access a sub element of the property array (only primitives are supported right now) - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = 8; - canvas.height = 8; + if ( propertyName === "morphTargetInfluences" ) { + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - texture = new THREE.Texture( canvas ); - texture.needsUpdate = true; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); + return; - } + } - this.render = function ( scene, camera ) { + if ( ! targetObject.geometry.morphTargets ) { - if ( sprites.length === 0 ) return; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); + return; - // setup gl + } - if ( program === undefined ) { + for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { - init(); + if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { - } + propertyIndex = i; + break; - gl.useProgram( program ); + } - state.initAttributes(); - state.enableAttribute( attributes.position ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + } - state.disable( gl.CULL_FACE ); - state.enable( gl.BLEND ); + } - 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 ); + bindingType = this.BindingType.ArrayElement; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + // must use copy for Object3D.Euler/Quaternion - state.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + bindingType = this.BindingType.HasFromToArray; - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + this.resolvedProperty = nodeProperty; - if ( fog ) { + } else if ( nodeProperty.length !== undefined ) { - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + bindingType = this.BindingType.EntireArray; - if ( fog instanceof THREE.Fog ) { + this.resolvedProperty = nodeProperty; - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + } else { - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + this.propertyName = propertyName; - } else if ( fog instanceof THREE.FogExp2 ) { + } - gl.uniform1f( uniforms.fogDensity, fog.density ); + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + }, - } + unbind: function() { - } else { + this.node = null; - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + // back to the prototype version of getValue / setValue + // note: avoiding to mutate the shape of 'this' via 'delete' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - } + } + }; - // update positions and sort + Object.assign( PropertyBinding.prototype, { // prototype, continued - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + // these are used to "bind" a nonexistent property + _getValue_unavailable: function() {}, + _setValue_unavailable: function() {}, - var sprite = sprites[ i ]; + // initial state of these methods that calls 'bind' + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, - sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + BindingType: { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }, - } + Versioning: { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }, - sprites.sort( painterSortStable ); + GetterByBindingType: [ - // render all sprites + function getValue_direct( buffer, offset ) { - var scale = []; + buffer[ offset ] = this.node[ this.propertyName ]; - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + }, - var sprite = sprites[ i ]; - var material = sprite.material; + function getValue_array( buffer, offset ) { - if ( material.visible === false ) continue; + var source = this.resolvedProperty; - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + for ( var i = 0, n = source.length; i !== n; ++ i ) { - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + buffer[ offset ++ ] = source[ i ]; - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + } - var fogType = 0; + }, - if ( scene.fog && material.fog ) { + function getValue_arrayElement( buffer, offset ) { - fogType = sceneFogType; + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; - } + }, - if ( oldFogType !== fogType ) { + function getValue_toArray( buffer, offset ) { - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + this.resolvedProperty.toArray( buffer, offset ); - } + } - if ( material.map !== null ) { + ], - gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + SetterByBindingTypeAndVersioning: [ - } else { + [ + // Direct - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + function setValue_direct( buffer, offset ) { - } + this.node[ this.propertyName ] = buffer[ offset ]; - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + }, - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + function setValue_direct_setNeedsUpdate( buffer, offset ) { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - if ( material.map ) { + }, - renderer.setTexture2D( material.map, 0 ); + function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - } else { + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - renderer.setTexture2D( texture, 0 ); + } - } + ], [ - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + // EntireArray - } + function setValue_array( buffer, offset ) { - // restore gl + var dest = this.resolvedProperty; - state.enable( gl.CULL_FACE ); + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - renderer.resetGLState(); + dest[ i ] = buffer[ offset ++ ]; - }; + } - function createProgram () { + }, - var program = gl.createProgram(); + function setValue_array_setNeedsUpdate( buffer, offset ) { - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var dest = this.resolvedProperty; - gl.shaderSource( vertexShader, [ + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - 'precision ' + renderer.getPrecision() + ' float;', + dest[ i ] = buffer[ offset ++ ]; - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', + } - 'attribute vec2 position;', - 'attribute vec2 uv;', + this.targetObject.needsUpdate = true; - 'varying vec2 vUV;', + }, - 'void main() {', + function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - 'vUV = uvOffset + uv * uvScale;', + var dest = this.resolvedProperty; - 'vec2 alignedPosition = position * scale;', + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + dest[ i ] = buffer[ offset ++ ]; - 'vec4 finalPosition;', + } - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', + this.targetObject.matrixWorldNeedsUpdate = true; - 'gl_Position = finalPosition;', + } - '}' + ], [ - ].join( '\n' ) ); + // ArrayElement - gl.shaderSource( fragmentShader, [ + function setValue_arrayElement( buffer, offset ) { - 'precision ' + renderer.getPrecision() + ' float;', + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - '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;', + function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - 'varying vec2 vUV;', + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - 'void main() {', + }, - 'vec4 texture = texture2D( map, vUV );', + function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - 'if ( texture.a < alphaTest ) discard;', + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + } - 'if ( fogType > 0 ) {', + ], [ - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + // HasToFromArray - 'if ( fogType == 1 ) {', + function setValue_fromArray( buffer, offset ) { - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + this.resolvedProperty.fromArray( buffer, offset ); - '} else {', + }, - 'const float LOG2 = 1.442695;', - 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + function setValue_fromArray_setNeedsUpdate( buffer, offset ) { - '}', + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', + }, - '}', + function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - '}' + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - ].join( '\n' ) ); + } - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + ] - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + ] - gl.linkProgram( program ); + } ); - return program; + PropertyBinding.Composite = + function( targetGroup, path, optionalParsedPath ) { - } + var parsedPath = optionalParsedPath || + PropertyBinding.parseTrackName( path ); - function painterSortStable ( a, b ) { + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - if ( a.renderOrder !== b.renderOrder ) { + }; - return a.renderOrder - b.renderOrder; + PropertyBinding.Composite.prototype = { - } else if ( a.z !== b.z ) { + constructor: PropertyBinding.Composite, - return b.z - a.z; + getValue: function( array, offset ) { - } else { + this.bind(); // bind all binding - return b.id - a.id; + var firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; - } + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); - } + }, -}; + setValue: function( array, offset ) { -// File:src/Three.Legacy.js + var bindings = this._bindings; -/** - * @author mrdoob / http://mrdoob.com/ - */ + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { -Object.assign( THREE, { - Face4: function ( a, b, c, d, normal, color, materialIndex ) { - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); - return new THREE.Face3( a, b, c, normal, color, materialIndex ); - }, - LineStrip: 0, - LinePieces: 1, - MeshFaceMaterial: THREE.MultiMaterial, - PointCloud: function ( geometry, material ) { - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); - }, - Particle: THREE.Sprite, - ParticleSystem: function ( geometry, material ) { - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); - }, - PointCloudMaterial: function ( parameters ) { - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - ParticleBasicMaterial: function ( parameters ) { - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - ParticleSystemMaterial: function ( parameters ) { - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); - }, - Vertex: function ( x, y, z ) { - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - return new THREE.Vector3( x, y, z ); - } -} ); + bindings[ i ].setValue( array, offset ); -// + } -Object.assign( THREE.Box2.prototype, { - empty: function () { - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - }, - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - } -} ); + }, -Object.assign( THREE.Box3.prototype, { - empty: function () { - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); - }, - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - }, - isIntersectionSphere: function ( sphere ) { - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - } -} ); - -Object.assign( THREE.Matrix3.prototype, { - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); - }, - multiplyVector3Array: function ( a ) { - console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); - } -} ); - -Object.assign( THREE.Matrix4.prototype, { - extractPosition: function ( m ) { - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); - }, - setRotationFromQuaternion: function ( q ) { - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); - }, - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); - return vector.applyProjection( this ); - }, - multiplyVector4: function ( vector ) { - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - }, - multiplyVector3Array: function ( a ) { - console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); - }, - rotateAxis: function ( v ) { - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); - }, - crossVector: function ( vector ) { - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); - }, - translate: function ( v ) { - console.error( 'THREE.Matrix4: .translate() has been removed.' ); - }, - rotateX: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); - }, - rotateY: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); - }, - rotateZ: function ( angle ) { - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); - }, - rotateByAxis: function ( axis, angle ) { - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); - } -} ); - -Object.assign( THREE.Plane.prototype, { - isIntersectionLine: function ( line ) { - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); - } -} ); - -Object.assign( THREE.Quaternion.prototype, { - multiplyVector3: function ( vector ) { - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); - } -} ); - -Object.assign( THREE.Ray.prototype, { - isIntersectionBox: function ( box ) { - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); - }, - isIntersectionPlane: function ( plane ) { - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); - }, - isIntersectionSphere: function ( sphere ) { - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); - } -} ); - -Object.assign( THREE.Vector3.prototype, { - setEulerFromRotationMatrix: function () { - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); - }, - setEulerFromQuaternion: function () { - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); - }, - getPositionFromMatrix: function ( m ) { - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); - }, - getScaleFromMatrix: function ( m ) { - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); - }, - getColumnFromMatrix: function ( index, matrix ) { - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); - } -} ); - -// - -Object.assign( THREE.Object3D.prototype, { - getChildByName: function ( name ) { - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); - }, - renderDepth: function ( value ) { - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); - }, - translate: function ( distance, axis ) { - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); - } -} ); - -Object.defineProperties( THREE.Object3D.prototype, { - eulerOrder: { - get: function () { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; - }, - set: function ( value ) { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; - } - }, - useQuaternion: { - get: function () { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - }, - set: function ( value ) { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - } - } -} ); - -Object.defineProperties( THREE.LOD.prototype, { - objects: { - get: function () { - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; - } - } -} ); - -// - -THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { - - console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + - "Use .setFocalLength and .filmGauge for a photographic setup." ); - - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); - -}; - -// - -Object.defineProperties( THREE.Light.prototype, { - onlyShadow: { - set: function ( value ) { - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); - } - }, - shadowCameraFov: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; - } - }, - shadowCameraLeft: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); - this.shadow.camera.left = value; - } - }, - shadowCameraRight: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); - this.shadow.camera.right = value; - } - }, - shadowCameraTop: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; - } - }, - shadowCameraBottom: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; - } - }, - shadowCameraNear: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; - } - }, - shadowCameraFar: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; - } - }, - shadowCameraVisible: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); - } - }, - shadowBias: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; - } - }, - shadowDarkness: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); - } - }, - shadowMapWidth: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; - } - }, - shadowMapHeight: { - set: function ( value ) { - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; - } - } -} ); - -// - -Object.defineProperties( THREE.BufferAttribute.prototype, { - length: { - get: function () { - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; - } - } -} ); - -Object.assign( THREE.BufferGeometry.prototype, { - addIndex: function ( index ) { - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); - }, - addDrawCall: function ( start, count, indexOffset ) { - if ( indexOffset !== undefined ) { - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); - } - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); - }, - clearDrawCalls: function () { - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); - }, - computeTangents: function () { - console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); - }, - computeOffsets: function () { - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); - } -} ); - -Object.defineProperties( THREE.BufferGeometry.prototype, { - drawcalls: { - get: function () { - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; - } - }, - offsets: { - get: function () { - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; - } - } -} ); - -// - -Object.defineProperties( THREE.Material.prototype, { - wrapAround: { - get: function () { - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); - }, - set: function ( value ) { - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); - } - }, - wrapRGB: { - get: function () { - console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' ); - return new THREE.Color(); - } - } -} ); - -Object.defineProperties( THREE.MeshPhongMaterial.prototype, { - metal: { - get: function () { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); - return false; - }, - set: function ( value ) { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); - } - } -} ); - -Object.defineProperties( THREE.ShaderMaterial.prototype, { - derivatives: { - get: function () { - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; - }, - set: function ( value ) { - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; - } - } -} ); - -// - -THREE.EventDispatcher.prototype = Object.assign( Object.create( { - - // Note: Extra base ensures these properties are not 'assign'ed. - - constructor: THREE.EventDispatcher, - - apply: function ( target ) { - - console.warn( "THREE.EventDispatcher: .apply is deprecated, " + - "just inherit or Object.assign the prototype to mix-in." ); - - Object.assign( target, this ); - - } - -} ), THREE.EventDispatcher.prototype ); - -// - -Object.assign( THREE.WebGLRenderer.prototype, { - supportsFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); - }, - supportsHalfFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); - }, - supportsStandardDerivatives: function () { - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); - }, - supportsCompressedTextureS3TC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); - }, - supportsCompressedTexturePVRTC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - }, - supportsBlendMinMax: function () { - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); - }, - supportsVertexTextures: function () { - return this.capabilities.vertexTextures; - }, - supportsInstancedArrays: function () { - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); - }, - enableScissorTest: function ( boolean ) { - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); - }, - initMaterial: function () { - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); - }, - addPrePlugin: function () { - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); - }, - addPostPlugin: function () { - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); - }, - updateShadowMap: function () { - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); - } -} ); - -Object.defineProperties( THREE.WebGLRenderer.prototype, { - shadowMapEnabled: { - get: function () { - return this.shadowMap.enabled; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; - } - }, - shadowMapType: { - get: function () { - return this.shadowMap.type; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; - } - }, - shadowMapCullFace: { - get: function () { - return this.shadowMap.cullFace; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); - this.shadowMap.cullFace = value; - } - } -} ); - -Object.defineProperties( THREE.WebGLShadowMap.prototype, { - cullFace: { - get: function () { - return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack; - }, - set: function ( cullFace ) { - var value = ( cullFace !== THREE.CullFaceBack ); - console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); - this.renderReverseSided = value; - } - } -} ); - -// - -Object.defineProperties( THREE.WebGLRenderTarget.prototype, { - wrapS: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; - } - }, - wrapT: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; - } - }, - magFilter: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; - } - }, - minFilter: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; - } - }, - anisotropy: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; - } - }, - offset: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; - } - }, - repeat: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; - } - }, - format: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; - } - }, - type: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; - } - }, - generateMipmaps: { - get: function () { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; - }, - set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; - } - } -} ); - -// - -Object.assign( THREE.Audio.prototype, { - load: function ( file ) { - console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' ); - var scope = this; - var audioLoader = new THREE.AudioLoader(); - audioLoader.load( file, function ( buffer ) { - scope.setBuffer( buffer ); - } ); - return this; - } -} ); - -Object.assign( THREE.AudioAnalyser.prototype, { - getData: function ( file ) { - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); - } -} ); - -// - -THREE.GeometryUtils = { - - merge: function ( geometry1, geometry2, materialIndexOffset ) { - - console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - - var matrix; - - if ( geometry2 instanceof THREE.Mesh ) { - - geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - - matrix = geometry2.matrix; - geometry2 = geometry2.geometry; - - } - - geometry1.merge( geometry2, matrix, materialIndexOffset ); - - }, - - center: function ( geometry ) { - - console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); - return geometry.center(); - - } - -}; - -THREE.ImageUtils = { - - crossOrigin: undefined, - - loadTexture: function ( url, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - - var loader = new THREE.TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - var texture = loader.load( url, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - - }, - - loadTextureCube: function ( urls, mapping, onLoad, onError ) { - - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - - var loader = new THREE.CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); - - var texture = loader.load( urls, onLoad, undefined, onError ); - - if ( mapping ) texture.mapping = mapping; - - return texture; - - }, - - loadCompressedTexture: function () { - - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - - }, - - loadCompressedTextureCube: function () { - - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); - - } - -}; - -// - -THREE.Projector = function () { - - console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); - - this.projectVector = function ( vector, camera ) { - - console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); - vector.project( camera ); - - }; - - this.unprojectVector = function ( vector, camera ) { - - console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); - vector.unproject( camera ); - - }; - - this.pickingRay = function ( vector, camera ) { - - console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); - - }; - -}; - -// - -THREE.CanvasRenderer = function () { - - console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); - - this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - this.clear = function () {}; - this.render = function () {}; - this.setClearColor = function () {}; - this.setSize = function () {}; - -}; - -// File:src/extras/CurveUtils.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.CurveUtils = { - - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - - }, - - // Puay Bing, thanks for helping with this derivative! - - tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - - 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; - - }, - - 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 - - return h00 + h10 + h01 + h11; - - }, - - // 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; - - } - -}; - -// File:src/extras/SceneUtils.js - -/** - * @author alteredq / http://alteredqualia.com/ - */ - -THREE.SceneUtils = { - - createMultiMaterialObject: function ( geometry, materials ) { - - var group = new THREE.Group(); - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); - - } - - return group; - - }, - - detach: function ( child, parent, scene ) { - - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); - - }, - - attach: function ( child, scene, parent ) { - - var matrixWorldInverse = new THREE.Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); - - scene.remove( child ); - parent.add( child ); - - } - -}; - -// File:src/extras/ShapeUtils.js - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ - -THREE.ShapeUtils = { - - // calculate area of the contour polygon - - area: function ( contour ) { - - var n = contour.length; - var a = 0.0; - - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - - } - - return a * 0.5; - - }, - - triangulate: ( function () { - - /** - * 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 - * - */ - - function snip( contour, u, v, w, n, verts ) { - - var p; - var ax, ay, bx, by; - var cx, cy, px, py; - - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; - - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; - - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; - - if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; - - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; - - for ( p = 0; p < n; p ++ ) { - - px = contour[ verts[ p ] ].x; - py = contour[ verts[ p ] ].y; - - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; - - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; - - // see if p is inside triangle abc - - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; - - if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - - } - - return true; - - } - - // takes in an contour array and returns - - return function triangulate( contour, indices ) { - - var n = contour.length; - - if ( n < 3 ) return null; - - var result = [], - verts = [], - vertIndices = []; - - /* we want a counter-clockwise polygon in verts */ - - var u, v, w; - - if ( THREE.ShapeUtils.area( contour ) > 0.0 ) { - - for ( v = 0; v < n; v ++ ) verts[ v ] = v; - - } else { - - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - - } - - var nv = n; - - /* remove nv - 2 vertices, creating 1 triangle every time */ - - var count = 2 * nv; /* error detection */ - - for ( v = nv - 1; nv > 2; ) { - - /* if we loop, it is probably a non-simple polygon */ - - if ( ( count -- ) <= 0 ) { - - //** Triangulate: ERROR - probable bad polygon! - - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); - - if ( indices ) return vertIndices; - return result; - - } - - /* three consecutive vertices in current polygon, */ - - 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 */ - - if ( snip( contour, u, v, w, nv, verts ) ) { - - var a, b, c, s, t; - - /* true names of the vertices */ - - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; - - /* output Triangle */ - - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); - - - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - - /* remove v from the remaining polygon */ - - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - - verts[ s ] = verts[ t ]; - - } - - nv --; - - /* reset error detection counter */ - - count = 2 * nv; - - } - - } - - if ( indices ) return vertIndices; - return result; - - } - - } )(), - - triangulateShape: function ( contour, holes ) { - - function removeDupEndPts(points) { - - var l = points.length; - - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - - points.pop(); - - } - - } - - removeDupEndPts( contour ); - holes.forEach( removeDupEndPts ); - - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - - // inOtherPt needs to be collinear 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 ) ); - - } - - } - - } - - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - - if ( Math.abs( limit ) > Number.EPSILON ) { - - // not parallel - - 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 []; - - } - - // 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 } ]; - - } else { - - // parallel or collinear - if ( ( perpSeg1 !== 0 ) || - ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - - // they are collinear or degenerate - var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? - var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is 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 ]; - - } - - // 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 ]; - - } - - } - - } - - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - - // The order of legs is important - - // 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; - - // 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 ) > Number.EPSILON ) { - - // angle != 180 deg. - - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - - 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 ); - - } - - } - - - function removeHoles( contour, holes ) { - - var shape = contour.concat(); // work on this shape - var hole; - - 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; - - 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; - - } - - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; - - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - - 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 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; - - } - - return false; - - } - - var indepHoles = []; - - 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 ++ ) { - - indepHoles.push( h ); - - } - - 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; - - } - - // 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; - - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { - - holeIdx = indepHoles[ h ]; - - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[ cutKey ] !== undefined ) continue; - - 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; - - 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 ); - - minShapeIndex = shapeIndex; - - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); - - break; - - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - failedCuts[ cutKey ] = true; // remember failure - - } - if ( holeIndex >= 0 ) break; // hole-vertex found - - } - - } - - return shape; /* shape with no holes */ - - } - - - 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. - - var allpoints = contour.concat(); - - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - - Array.prototype.push.apply( allpoints, holes[ h ] ); - - } - - //console.log( "allpoints",allpoints, allpoints.length ); - - // prepare all points map - - for ( i = 0, il = allpoints.length; i < il; i ++ ) { - - key = allpoints[ i ].x + ":" + allpoints[ i ].y; - - if ( allPointsMap[ key ] !== undefined ) { - - console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - - } - - allPointsMap[ key ] = i; - - } - - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); - - var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); - - // check all face vertices against all points map - - for ( i = 0, il = triangles.length; i < il; i ++ ) { - - face = triangles[ i ]; - - for ( f = 0; f < 3; f ++ ) { - - key = face[ f ].x + ":" + face[ f ].y; - - index = allPointsMap[ key ]; - - if ( index !== undefined ) { - - face[ f ] = index; - - } - - } - - } - - return triangles.concat(); - - }, - - isClockWise: function ( pts ) { - - return THREE.ShapeUtils.area( pts ) < 0; - - }, - - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - - // Quad Bezier Functions - - b2: ( function () { - - function b2p0( t, p ) { - - var k = 1 - t; - return k * k * p; - - } - - function b2p1( t, p ) { - - return 2 * ( 1 - t ) * t * p; - - } - - function b2p2( t, p ) { - - return t * t * p; - - } - - return function b2( t, p0, p1, p2 ) { - - return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - - }; + bind: function() { - } )(), + var bindings = this._bindings; - // Cubic Bezier Functions + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - b3: ( function () { + bindings[ i ].bind(); - function b3p0( t, p ) { + } - var k = 1 - t; - return k * k * k * p; + }, - } - - function b3p1( t, p ) { - - var k = 1 - t; - return 3 * k * k * t * p; - - } - - function b3p2( t, p ) { - - var k = 1 - t; - return 3 * k * t * t * p; - - } - - function b3p3( t, p ) { - - return t * t * t * p; - - } - - return function b3( t, p0, p1, p2, p3 ) { - - return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - - }; - - } )() - -}; - -// File:src/extras/core/Curve.js - -/** - * @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 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ - -/************************************************************** - * Abstract Curve base class - **************************************************************/ - -THREE.Curve = function () { - -}; - -THREE.Curve.prototype = { - - constructor: THREE.Curve, - - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] - - getPoint: function ( t ) { - - console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); - return null; - - }, - - // Get point at relative position in curve according to arc length - // - u [0 .. 1] - - getPointAt: function ( u ) { - - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); - - }, - - // Get sequence of points using getPoint( t ) - - getPoints: function ( divisions ) { - - if ( ! divisions ) divisions = 5; - - var points = []; - - for ( var d = 0; d <= divisions; d ++ ) { - - points.push( this.getPoint( d / divisions ) ); - - } - - return points; - - }, - - // Get sequence of points using getPointAt( u ) - - getSpacedPoints: function ( divisions ) { - - if ( ! divisions ) divisions = 5; - - var points = []; - - for ( var d = 0; d <= divisions; d ++ ) { - - points.push( this.getPointAt( d / divisions ) ); - - } - - return points; - - }, - - // Get total curve arc length - - getLength: function () { - - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; - - }, - - // Get list of cumulative segment lengths + unbind: function() { - getLengths: function ( divisions ) { + var bindings = this._bindings; - if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length === divisions + 1 ) - && ! this.needsUpdate ) { + bindings[ i ].unbind(); - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; + } - } - - this.needsUpdate = false; - - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; - - cache.push( 0 ); + } - for ( p = 1; p <= divisions; p ++ ) { + }; - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + PropertyBinding.create = function( root, path, parsedPath ) { - } + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - this.cacheArcLengths = cache; + return new PropertyBinding( root, path, parsedPath ); - return cache; // { sums: cache, sum:sum }; Sum is in the last element. + } else { - }, + return new PropertyBinding.Composite( root, path, parsedPath ); - updateArcLengths: function() { + } - this.needsUpdate = true; - this.getLengths(); + }; - }, + PropertyBinding.parseTrackName = function( trackName ) { - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + // matches strings in the form of: + // nodeName.property + // nodeName.property[accessor] + // nodeName.material.property[accessor] + // uuid.property[accessor] + // uuid.objectName[objectIndex].propertyName[propertyIndex] + // parentName/nodeName.property + // parentName/parentName/nodeName.property[index] + // .bone[Armature.DEF_cog].position + // created and tested via https://regex101.com/#javascript - getUtoTmapping: function ( u, distance ) { + var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; + var matches = re.exec( trackName ); - var arcLengths = this.getLengths(); + if ( ! matches ) { - var i = 0, il = arcLengths.length; + throw new Error( "cannot parse trackName at all: " + trackName ); - var targetArcLength; // The targeted u distance value to get + } - if ( distance ) { + if ( matches.index === re.lastIndex ) { - targetArcLength = distance; + re.lastIndex++; - } else { + } - targetArcLength = u * arcLengths[ il - 1 ]; + var results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 3 ], // allowed to be null, specified root node. + objectName: matches[ 5 ], + objectIndex: matches[ 7 ], + propertyName: matches[ 9 ], + propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set. + }; - } + if ( results.propertyName === null || results.propertyName.length === 0 ) { - //var time = Date.now(); + throw new Error( "can not parse propertyName from trackName: " + trackName ); - // binary search for the index with largest value smaller than target u distance + } - var low = 0, high = il - 1, comparison; + return results; - while ( low <= high ) { + }; - 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 + PropertyBinding.findNode = function( root, nodeName ) { - comparison = arcLengths[ i ] - targetArcLength; + if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { - if ( comparison < 0 ) { + return root; - low = i + 1; + } - } else if ( comparison > 0 ) { + // search into skeleton bones. + if ( root.skeleton ) { - high = i - 1; + var searchSkeleton = function( skeleton ) { - } else { + for( var i = 0; i < skeleton.bones.length; i ++ ) { - high = i; - break; + var bone = skeleton.bones[ i ]; - // DONE + if ( bone.name === nodeName ) { - } + return bone; - } + } + } - i = high; + return null; - //console.log('b' , i, low, high, Date.now()- time); + }; - if ( arcLengths[ i ] === targetArcLength ) { + var bone = searchSkeleton( root.skeleton ); - var t = i / ( il - 1 ); - return t; + if ( bone ) { - } + return bone; - // we could get finer grain at lengths, or use simple interpolation between two points + } + } - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + // search into node subtree. + if ( root.children ) { - var segmentLength = lengthAfter - lengthBefore; + var searchNodeSubtree = function( children ) { - // determine where we are between the 'before' and 'after' points + for( var i = 0; i < children.length; i ++ ) { - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + var childNode = children[ i ]; - // add that fractional amount to t + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - var t = ( i + segmentFraction ) / ( il - 1 ); + return childNode; - return t; + } - }, + var result = searchNodeSubtree( childNode.children ); - // 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 + if ( result ) return result; - getTangent: function( t ) { + } - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; + return null; - // Capping in case of danger + }; - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + var subTreeNode = searchNodeSubtree( root.children ); - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + if ( subTreeNode ) { - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); + return subTreeNode; - }, + } - getTangentAt: function ( u ) { + } - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + return null; - } + }; -}; + /** + * + * A group of objects that receives a shared animation state. + * + * Usage: + * + * - Add objects you would otherwise pass as 'root' to the + * constructor or the .clipAction method of AnimationMixer. + * + * - Instead pass this object as 'root'. + * + * - You can also add and remove objects later when the mixer + * is running. + * + * Note: + * + * Objects of this class appear as one object to the mixer, + * so cache control of the individual objects must be done + * on the group. + * + * Limitation: + * + * - The animated properties must be compatible among the + * all objects in the group. + * + * - A single property can either be controlled through a + * target group or directly, but not both. + * + * @author tschw + */ -// TODO: Transformation for Curves? + function AnimationObjectGroup( var_args ) { + this.isAnimationObjectGroup = true; -/************************************************************** - * 3D Curves - **************************************************************/ + this.uuid = exports.Math.generateUUID(); -// A Factory method for creating new curve subclasses + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); -THREE.Curve.create = function ( constructor, getPointFunc ) { + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite - constructor.prototype = Object.create( THREE.Curve.prototype ); - constructor.prototype.constructor = constructor; - constructor.prototype.getPoint = getPointFunc; + var indices = {}; + this._indicesByUUID = indices; // for bookkeeping - return constructor; + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { -}; + indices[ arguments[ i ].uuid ] = i; -// File:src/extras/core/CurvePath.js + } -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + var scope = this; -THREE.CurvePath = function () { + this.stats = { - this.curves = []; + objects: { + get total() { return scope._objects.length; }, + get inUse() { return this.total - scope.nCachedObjects_; } + }, - this.autoClose = false; // Automatically closes the path + get bindingsPerObject() { return scope._bindings.length; } -}; + }; -THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype ), { + }; - constructor: THREE.CurvePath, + AnimationObjectGroup.prototype = { - add: function ( curve ) { + constructor: AnimationObjectGroup, - this.curves.push( curve ); + add: function( var_args ) { - }, + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; - closePath: function () { + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - // 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 ); + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - if ( ! startPoint.equals( endPoint ) ) { + if ( index === undefined ) { - this.curves.push( new THREE.LineCurve( endPoint, startPoint ) ); + // unknown object -> add it to the ACTIVE region - } + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); - }, + // accounting is done, now do the same for all bindings - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - // 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') + bindings[ j ].push( + new PropertyBinding( + object, paths[ j ], parsedPaths[ j ] ) ); - getPoint: function ( t ) { + } - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; + } else if ( index < nCachedObjects ) { - // To think about boundaries points. + var knownObject = objects[ index ]; - while ( i < curveLengths.length ) { + // move existing object to the ACTIVE region - if ( curveLengths[ i ] >= d ) { + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - return curve.getPointAt( u ); + // accounting is done, now do the same for all bindings - } + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - i ++; + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + binding = bindingsForPath[ index ]; - } + bindingsForPath[ index ] = lastCached; - return null; + if ( binding === undefined ) { - // loop where sum != 0, sum > d , sum+1 = nCachedObjects ) { - var lengths = [], sums = 0; + // move existing object into the CACHED region - for ( var i = 0, l = this.curves.length; i < l; i ++ ) { + var lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - sums += this.curves[ i ].getLength(); - lengths.push( sums ); + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - } + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - this.cacheLengths = lengths; + // accounting is done, now do the same for all bindings - return lengths; + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - }, + var bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - getSpacedPoints: function ( divisions ) { + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - if ( ! divisions ) divisions = 40; + } - var points = []; + } - for ( var i = 0; i <= divisions; i ++ ) { + } // for arguments - points.push( this.getPoint( i / divisions ) ); + this.nCachedObjects_ = nCachedObjects; - } + }, - if ( this.autoClose ) { + // remove & forget + uncache: function( var_args ) { - points.push( points[ 0 ] ); + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - } + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - return points; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - }, + if ( index !== undefined ) { - getPoints: function ( divisions ) { + delete indicesByUUID[ uuid ]; - divisions = divisions || 12; + if ( index < nCachedObjects ) { - var points = [], last; + // object is cached, shrink the CACHED region - for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - var curve = curves[ i ]; - var resolution = curve instanceof THREE.EllipseCurve ? divisions * 2 - : curve instanceof THREE.LineCurve ? 1 - : curve instanceof THREE.SplineCurve ? divisions * curve.points.length - : divisions; + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - var pts = curve.getPoints( resolution ); + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - for ( var j = 0; j < pts.length; j++ ) { + // accounting is done, now do the same for all bindings - var point = pts[ j ]; + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - points.push( point ); - last = point; + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - } + } - } + } else { - if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { + // object is active, just swap with the last and pop - points.push( points[ 0 ] ); + var lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - } + indicesByUUID[ lastObject.uuid ] = index; + objects[ index ] = lastObject; + objects.pop(); - return points; + // accounting is done, now do the same for all bindings - }, + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - /************************************************************** - * Create Geometries Helpers - **************************************************************/ + var bindingsForPath = bindings[ j ]; - /// Generate geometry from path points (for Line or Points objects) + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - createPointsGeometry: function ( divisions ) { + } - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); + } // cached or active - }, + } // if object is known - // Generate geometry from equidistant sampling along the path + } // for arguments - createSpacedPointsGeometry: function ( divisions ) { + this.nCachedObjects_ = nCachedObjects; - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); + }, - }, + // Internal interface used by befriended PropertyBinding.Composite: - createGeometry: function ( points ) { + subscribe_: function( path, parsedPath ) { + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group - var geometry = new THREE.Geometry(); + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ], + bindings = this._bindings; - for ( var i = 0, l = points.length; i < l; i ++ ) { + if ( index !== undefined ) return bindings[ index ]; - var point = points[ i ]; - geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) ); + var paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); - } + index = bindings.length; - return geometry; + indicesByPath[ path ] = index; - } + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); -} ); + for ( var i = nCachedObjects, + n = objects.length; i !== n; ++ i ) { -// File:src/extras/core/Font.js + var object = objects[ i ]; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author mrdoob / http://mrdoob.com/ - */ + bindingsForPath[ i ] = + new PropertyBinding( object, path, parsedPath ); -THREE.Font = function ( data ) { + } - this.data = data; + return bindingsForPath; -}; + }, -Object.assign( THREE.Font.prototype, { + unsubscribe_: function( path ) { + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' - generateShapes: function ( text, size, divisions ) { + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; - function createPaths( text ) { + if ( index !== undefined ) { - var chars = String( text ).split( '' ); - var scale = size / data.resolution; - var offset = 0; + var paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - var paths = []; + indicesByPath[ lastBindingsPath ] = index; - for ( var i = 0; i < chars.length; i ++ ) { + bindings[ index ] = lastBindings; + bindings.pop(); - var ret = createPath( chars[ i ], scale, offset ); - offset += ret.offset; + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - paths.push( ret.path ); + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - } + } - return paths; + } - } + }; - function createPath( c, scale, offset ) { + /** + * + * Action provided by AnimationMixer for scheduling clip playback on specific + * objects. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + * + */ - var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; + function AnimationAction() { + this.isAnimationAction = true; - if ( ! glyph ) return; + throw new Error( "THREE.AnimationAction: " + + "Use mixer.clipAction for construction." ); - var path = new THREE.ShapePath(); + }; - var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3; - var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; + AnimationAction._new = + function AnimationAction( mixer, clip, localRoot ) { - if ( glyph.o ) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot || null; - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + var tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - for ( var i = 0, l = outline.length; i < l; ) { + var interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - var action = outline[ i ++ ]; + for ( var i = 0; i !== nTracks; ++ i ) { - switch ( action ) { + var interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - case 'm': // moveTo + } - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + this._interpolantSettings = interpolantSettings; - path.moveTo( x, y ); + this._interpolants = interpolants; // bound by the mixer - break; + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - case 'l': // lineTo + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - path.lineTo( x, y ); + this.loop = LoopRepeat; + this._loopCount = -1; - break; + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; - case 'q': // quadraticCurveTo + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; + this.timeScale = 1; + this._effectiveTimeScale = 1; - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + this.weight = 1; + this._effectiveWeight = 1; - laste = pts[ pts.length - 1 ]; + this.repetitions = Infinity; // no. of repetitions when looping - if ( laste ) { + this.paused = false; // false -> zero effective time scale + this.enabled = true; // true -> zero effective weight - cpx0 = laste.x; - cpy0 = laste.y; + this.clampWhenFinished = false; // keep feeding the last frame? - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true; // clips for start, loop and end - var t = i2 / divisions; - b2( t, cpx0, cpx1, cpx ); - b2( t, cpy0, cpy1, cpy ); + }; - } + AnimationAction._new.prototype = { - } + constructor: AnimationAction._new, - break; + // State & Scheduling - case 'b': // bezierCurveTo + play: function() { - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; - cpx2 = outline[ i ++ ] * scale + offset; - cpy2 = outline[ i ++ ] * scale; + this._mixer._activateAction( this ); - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + return this; - laste = pts[ pts.length - 1 ]; + }, - if ( laste ) { + stop: function() { - cpx0 = laste.x; - cpy0 = laste.y; + this._mixer._deactivateAction( this ); - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + return this.reset(); - var t = i2 / divisions; - b3( t, cpx0, cpx1, cpx2, cpx ); - b3( t, cpy0, cpy1, cpy2, cpy ); + }, - } + reset: function() { - } + this.paused = false; + this.enabled = true; - break; + this.time = 0; // restart clip + this._loopCount = -1; // forget previous loops + this._startTime = null; // forget scheduling - } + return this.stopFading().stopWarping(); - } + }, - } + isRunning: function() { - return { offset: glyph.ha * scale, path: path }; + var start = this._startTime; - } + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - // + }, - if ( size === undefined ) size = 100; - if ( divisions === undefined ) divisions = 4; + // return true when play has been called + isScheduled: function() { - var data = this.data; + return this._mixer._isActiveAction( this ); - var paths = createPaths( text ); - var shapes = []; + }, - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + startAt: function( time ) { - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + this._startTime = time; - } + return this; - return shapes; + }, - } + setLoop: function( mode, repetitions ) { -} ); + this.loop = mode; + this.repetitions = repetitions; -// File:src/extras/core/Path.js + return this; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ + }, -THREE.Path = function ( points ) { + // Weight - THREE.CurvePath.call( this ); - this.currentPoint = new THREE.Vector2(); + // set the weight stopping any scheduled fading + // although .enabled = false yields an effective weight of zero, this + // method does *not* change .enabled, because it would be confusing + setEffectiveWeight: function( weight ) { - if ( points ) { + this.weight = weight; - this.fromPoints( points ); + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - } + return this.stopFading(); -}; + }, -THREE.Path.prototype = Object.assign( Object.create( THREE.CurvePath.prototype ), { + // return the weight considering fading and .enabled + getEffectiveWeight: function() { - constructor: THREE.Path, + return this._effectiveWeight; - // Create path using straight lines to connect all points - // - vectors: array of Vector2 - fromPoints: function ( vectors ) { + }, - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + fadeIn: function( duration ) { - for ( var i = 1, l = vectors.length; i < l; i ++ ) { + return this._scheduleFading( duration, 0, 1 ); - this.lineTo( vectors[ i ].x, vectors[ i ].y ); + }, - } + fadeOut: function( duration ) { - }, + return this._scheduleFading( duration, 1, 0 ); - moveTo: function ( x, y ) { + }, - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + crossFadeFrom: function( fadeOutAction, duration, warp ) { - }, + var mixer = this._mixer; - lineTo: function ( x, y ) { + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - var curve = new THREE.LineCurve( this.currentPoint.clone(), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); + if( warp ) { - this.currentPoint.set( x, y ); + var fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - }, + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); - var curve = new THREE.QuadraticBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + return this; - this.currentPoint.set( aX, aY ); + }, - }, + crossFadeTo: function( fadeInAction, duration, warp ) { - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + return fadeInAction.crossFadeFrom( this, duration, warp ); - var curve = new THREE.CubicBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) - ); + }, - this.curves.push( curve ); + stopFading: function() { - this.currentPoint.set( aX, aY ); + var weightInterpolant = this._weightInterpolant; - }, + if ( weightInterpolant !== null ) { - splineThru: function ( pts /*Array of Vector*/ ) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - var npts = [ this.currentPoint.clone() ].concat( pts ); + } - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); + return this; - this.currentPoint.copy( pts[ pts.length - 1 ] ); + }, - }, + // Time Scale Control - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // set the weight stopping any scheduled warping + // although .paused = true yields an effective time scale of zero, this + // method does *not* change .paused, because it would be confusing + setEffectiveTimeScale: function( timeScale ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 :timeScale; - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + return this.stopWarping(); - }, + }, - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // return the time scale considering warping and .paused + getEffectiveTimeScale: function() { - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + return this._effectiveTimeScale; - }, + }, - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + setDuration: function( duration ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + this.timeScale = this._clip.duration / duration; - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + return this.stopWarping(); - }, + }, - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + syncWith: function( action ) { - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + this.time = action.time; + this.timeScale = action.timeScale; - if ( this.curves.length > 0 ) { + return this.stopWarping(); - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + }, - if ( ! firstPoint.equals( this.currentPoint ) ) { + halt: function( duration ) { - this.lineTo( firstPoint.x, firstPoint.y ); + return this.warp( this._effectiveTimeScale, 0, duration ); - } + }, - } + warp: function( startTimeScale, endTimeScale, duration ) { - this.curves.push( curve ); + var mixer = this._mixer, now = mixer.time, + interpolant = this._timeScaleInterpolant, - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + timeScale = this.timeScale; - } + if ( interpolant === null ) { -} ); + interpolant = mixer._lendControlInterpolant(), + this._timeScaleInterpolant = interpolant; + } -// minimal class for proxing functions to Path. Replaces old "extractSubpaths()" -THREE.ShapePath = function() { - this.subPaths = []; - this.currentPath = null; -} + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; -THREE.ShapePath.prototype = { - moveTo: function ( x, y ) { - this.currentPath = new THREE.Path(); - this.subPaths.push(this.currentPath); - this.currentPath.moveTo( x, y ); - }, - lineTo: function ( x, y ) { - this.currentPath.lineTo( x, y ); - }, - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - }, - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - }, - splineThru: function ( pts ) { - this.currentPath.splineThru( pts ); - }, + times[ 0 ] = now; + times[ 1 ] = now + duration; - toShapes: function ( isCCW, noHoles ) { + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - function toShapesNoHoles( inSubpaths ) { + return this; - var shapes = []; + }, - for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { + stopWarping: function() { - var tmpPath = inSubpaths[ i ]; + var timeScaleInterpolant = this._timeScaleInterpolant; - var tmpShape = new THREE.Shape(); - tmpShape.curves = tmpPath.curves; + if ( timeScaleInterpolant !== null ) { - shapes.push( tmpShape ); + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); - } + } - return shapes; + return this; - } + }, - function isPointInsidePolygon( inPt, inPolygon ) { + // Object Accessors - var polyLen = inPolygon.length; + getMixer: function() { - // 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 ++ ) { + return this._mixer; - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + }, - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + getClip: function() { - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + return this._clip; - // not parallel - if ( edgeDy < 0 ) { + }, - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + getRoot: function() { - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + return this._localRoot || this._mixer._root; - if ( inPt.y === edgeLowPt.y ) { + }, - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! + // Interna - } else { + _update: function( time, deltaTime, timeDirection, accuIndex ) { + // called by the mixer - 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 + var startTime = this._startTime; - } + if ( startTime !== null ) { - } else { + // check for scheduled start of action - // parallel or collinear - if ( inPt.y !== edgeLowPt.y ) continue; // parallel - // edge 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; + var timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - } + return; // yet to come / don't decide when delta = 0 - } + } - return inside; + // start - } + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; - var isClockWise = THREE.ShapeUtils.isClockWise; + } - var subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + // apply time scale and advance time - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + deltaTime *= this._updateTimeScale( time ); + var clipTime = this._updateTime( deltaTime ); + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - var solid, tmpPath, tmpShape, shapes = []; + var weight = this._updateWeight( time ); - if ( subPaths.length === 1 ) { + if ( weight > 0 ) { - tmpPath = subPaths[ 0 ]; - tmpShape = new THREE.Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + var interpolants = this._interpolants; + var propertyMixers = this._propertyBindings; - } + for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { - var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - // console.log("Holes first", holesFirst); + } - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + } - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + }, - for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + _updateWeight: function( time ) { - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + var weight = 0; - if ( solid ) { + if ( this.enabled ) { - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + weight = this.weight; + var interpolant = this._weightInterpolant; - newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + if ( interpolant !== null ) { - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - //console.log('cw', i); + weight *= interpolantValue; - } else { + if ( time > interpolant.parameterPositions[ 1 ] ) { - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + this.stopFading(); - //console.log('ccw', i); + if ( interpolantValue === 0 ) { - } + // faded out, disable + this.enabled = false; - } + } - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + } + } - if ( newShapes.length > 1 ) { + } - var ambiguous = false; - var toChange = []; + this._effectiveWeight = weight; + return weight; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + }, - betterShapeHoles[ sIdx ] = []; + _updateTimeScale: function( time ) { - } + var timeScale = 0; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + if ( ! this.paused ) { - var sho = newShapeHoles[ sIdx ]; + timeScale = this.timeScale; - for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + var interpolant = this._timeScaleInterpolant; - var ho = sho[ hIdx ]; - var hole_unassigned = true; + if ( interpolant !== null ) { - for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + timeScale *= interpolantValue; - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { + if ( time > interpolant.parameterPositions[ 1 ] ) { - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + this.stopWarping(); - } else { + if ( timeScale === 0 ) { - ambiguous = true; + // motion has halted, pause + this.paused = true; - } + } else { - } + // warp done - apply final time scale + this.timeScale = timeScale; - } - if ( hole_unassigned ) { + } - betterShapeHoles[ sIdx ].push( ho ); + } - } + } - } + } - } - // console.log("ambiguous: ", ambiguous); - if ( toChange.length > 0 ) { + this._effectiveTimeScale = timeScale; + return timeScale; - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + }, - } + _updateTime: function( deltaTime ) { - } + var time = this.time + deltaTime; - var tmpHoles; + if ( deltaTime === 0 ) return time; - for ( var i = 0, il = newShapes.length; i < il; i ++ ) { + var duration = this._clip.duration, - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + loop = this.loop, + loopCount = this._loopCount; - for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + if ( loop === LoopOnce ) { - tmpShape.holes.push( tmpHoles[ j ].h ); + if ( loopCount === -1 ) { + // just started - } + this.loopCount = 0; + this._setEndings( true, true, false ); - } + } - //console.log("shape", shapes); + handle_stop: { - return shapes; + if ( time >= duration ) { - } -} + time = duration; -// File:src/extras/core/Shape.js + } else if ( time < 0 ) { -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + time = 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. + } else break handle_stop; -THREE.Shape = function () { + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - THREE.Path.apply( this, arguments ); + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? -1 : 1 + } ); - this.holes = []; + } -}; + } else { // repetitive Repeat or PingPong -THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { + var pingPong = ( loop === LoopPingPong ); - constructor: THREE.Shape, + if ( loopCount === -1 ) { + // just started - // Convenience method to return ExtrudeGeometry + if ( deltaTime >= 0 ) { - extrude: function ( options ) { + loopCount = 0; - return new THREE.ExtrudeGeometry( this, options ); + this._setEndings( + true, this.repetitions === 0, pingPong ); - }, + } else { - // Convenience method to return ShapeGeometry + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - makeGeometry: function ( options ) { + this._setEndings( + this.repetitions === 0, true, pingPong ); - return new THREE.ShapeGeometry( this, options ); + } - }, + } - getPointsHoles: function ( divisions ) { + if ( time >= duration || time < 0 ) { + // wrap around - var holesPts = []; + var loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + loopCount += Math.abs( loopDelta ); - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + var pending = this.repetitions - loopCount; - } + if ( pending < 0 ) { + // have to stop (switch state, clamp time, fire event) - return holesPts; + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - }, + time = deltaTime > 0 ? duration : 0; - // Get points of shape and holes (keypoints based on segments parameter) + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : -1 + } ); - extractAllPoints: function ( divisions ) { + } else { + // keep running - return { + if ( pending === 0 ) { + // entering the last round - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + var atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - }; + } else { - }, + this._setEndings( false, false, pingPong ); - extractPoints: function ( divisions ) { + } - return this.extractAllPoints( divisions ); + this._loopCount = loopCount; - } + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); -} ); + } -// File:src/extras/curves/LineCurve.js + } -/************************************************************** - * Line - **************************************************************/ + if ( pingPong && ( loopCount & 1 ) === 1 ) { + // invert time for the "pong round" -THREE.LineCurve = function ( v1, v2 ) { + this.time = time; + return duration - time; - this.v1 = v1; - this.v2 = v2; + } -}; + } -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.LineCurve.prototype.constructor = THREE.LineCurve; + this.time = time; + return time; -THREE.LineCurve.prototype.getPoint = function ( t ) { + }, - if ( t === 1 ) { + _setEndings: function( atStart, atEnd, pingPong ) { - return this.v2.clone(); + var settings = this._interpolantSettings; - } + if ( pingPong ) { - var point = this.v2.clone().sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - return point; + } else { -}; + // assuming for LoopOnce atStart == atEnd == true -// Line curve is linear, so we can overwrite default getPointAt + if ( atStart ) { -THREE.LineCurve.prototype.getPointAt = function ( u ) { + settings.endingStart = this.zeroSlopeAtStart ? + ZeroSlopeEnding : ZeroCurvatureEnding; - return this.getPoint( u ); + } else { -}; + settings.endingStart = WrapAroundEnding; -THREE.LineCurve.prototype.getTangent = function( t ) { + } - var tangent = this.v2.clone().sub( this.v1 ); + if ( atEnd ) { - return tangent.normalize(); + settings.endingEnd = this.zeroSlopeAtEnd ? + ZeroSlopeEnding : ZeroCurvatureEnding; -}; + } else { -// File:src/extras/curves/QuadraticBezierCurve.js + settings.endingEnd = WrapAroundEnding; -/************************************************************** - * Quadratic Bezier curve - **************************************************************/ + } + } -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { + }, - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + _scheduleFading: function( duration, weightNow, weightThen ) { -}; + var mixer = this._mixer, now = mixer.time, + interpolant = this._weightInterpolant; -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; + if ( interpolant === null ) { + interpolant = mixer._lendControlInterpolant(), + this._weightInterpolant = interpolant; -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { + } - var b2 = THREE.ShapeUtils.b2; + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - return new THREE.Vector2( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ) - ); + times[ 0 ] = now; values[ 0 ] = weightNow; + times[ 1 ] = now + duration; values[ 1 ] = weightThen; -}; + return this; + } -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { + }; - var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier; + /** + * + * Player for AnimationClips. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - return new THREE.Vector2( - tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), - tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) - ).normalize(); + function AnimationMixer( root ) { + this.isAnimationMixer = true; -}; + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; -// File:src/extras/curves/CubicBezierCurve.js + this.time = 0; -/************************************************************** - * Cubic Bezier curve - **************************************************************/ + this.timeScale = 1.0; -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { + }; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { -}; + // return an action for a clip optionally using a custom root target + // object (this method allocates a lot of dynamic memory in case a + // previously unknown clip/root combination is specified) + clipAction: function( clip, optionalRoot ) { -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; + var root = optionalRoot || this._root, + rootUuid = root.uuid, -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - var b3 = THREE.ShapeUtils.b3; + clipUuid = clipObject !== null ? clipObject.uuid : clip, - return new THREE.Vector2( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ); + actionsForClip = this._actionsByClip[ clipUuid ], + prototypeAction = null; -}; + if ( actionsForClip !== undefined ) { -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { + var existingAction = + actionsForClip.actionByRoot[ rootUuid ]; - var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier; + if ( existingAction !== undefined ) { - return new THREE.Vector2( - tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ).normalize(); + return existingAction; -}; + } -// File:src/extras/curves/SplineCurve.js + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; -/************************************************************** - * Spline curve - **************************************************************/ + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { + } - this.points = ( points == undefined ) ? [] : points; + // clip must be known when specified via string + if ( clipObject === null ) return null; -}; + // allocate all resources required to run it + var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; + this._bindAction( newAction, prototypeAction ); -THREE.SplineCurve.prototype.getPoint = function ( t ) { + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - var points = this.points; - var point = ( points.length - 1 ) * t; + return newAction; - 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 ]; + // get an existing action + existingAction: function( clip, optionalRoot ) { - var interpolate = THREE.CurveUtils.interpolate; + var root = optionalRoot || this._root, + rootUuid = root.uuid, - return new THREE.Vector2( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ) - ); + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, -}; + clipUuid = clipObject ? clipObject.uuid : clip, -// File:src/extras/curves/EllipseCurve.js + actionsForClip = this._actionsByClip[ clipUuid ]; -/************************************************************** - * Ellipse curve - **************************************************************/ + if ( actionsForClip !== undefined ) { -THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + return actionsForClip.actionByRoot[ rootUuid ] || null; - this.aX = aX; - this.aY = aY; + } - this.xRadius = xRadius; - this.yRadius = yRadius; + return null; - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + }, - this.aClockwise = aClockwise; + // deactivates all previously scheduled actions + stopAllAction: function() { - this.aRotation = aRotation || 0; + var actions = this._actions, + nActions = this._nActiveActions, + bindings = this._bindings, + nBindings = this._nActiveBindings; -}; + this._nActiveActions = 0; + this._nActiveBindings = 0; -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; + for ( var i = 0; i !== nActions; ++ i ) { -THREE.EllipseCurve.prototype.getPoint = function( t ) { + actions[ i ].reset(); - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + } - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + for ( var i = 0; i !== nBindings; ++ i ) { - if ( deltaAngle < Number.EPSILON ) { + bindings[ i ].useCount = 0; - if ( samePoints ) { + } - deltaAngle = 0; + return this; - } else { + }, - deltaAngle = twoPi; + // advance the time and update apply the animation + update: function( deltaTime ) { - } + deltaTime *= this.timeScale; - } + var actions = this._actions, + nActions = this._nActiveActions, - if ( this.aClockwise === true && ! samePoints ) { + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - if ( deltaAngle === twoPi ) { + accuIndex = this._accuIndex ^= 1; - deltaAngle = - twoPi; + // run active actions - } else { + for ( var i = 0; i !== nActions; ++ i ) { - deltaAngle = deltaAngle - twoPi; + var action = actions[ i ]; - } + if ( action.enabled ) { - } + action._update( time, deltaTime, timeDirection, accuIndex ); - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + } - if ( this.aRotation !== 0 ) { + } - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + // update scene graph - var tx = x - this.aX; - var ty = y - this.aY; + var bindings = this._bindings, + nBindings = this._nActiveBindings; - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + for ( var i = 0; i !== nBindings; ++ i ) { - } + bindings[ i ].apply( accuIndex ); - return new THREE.Vector2( x, y ); + } -}; + return this; -// File:src/extras/curves/ArcCurve.js + }, -/************************************************************** - * Arc curve - **************************************************************/ + // return this mixer's root target object + getRoot: function() { -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + return this._root; - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + }, -}; + // free all resources specific to a particular clip + uncacheClip: function( clip ) { -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; + var actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; -// File:src/extras/curves/LineCurve3.js + if ( actionsForClip !== undefined ) { -/************************************************************** - * Line3D - **************************************************************/ + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away -THREE.LineCurve3 = THREE.Curve.create( + var actionsToRemove = actionsForClip.knownActions; - function ( v1, v2 ) { + for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - this.v1 = v1; - this.v2 = v2; + var action = actionsToRemove[ i ]; - }, + this._deactivateAction( action ); - function ( t ) { + var cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - if ( t === 1 ) { + action._cacheIndex = null; + action._byClipCacheIndex = null; - return this.v2.clone(); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - } + this._removeInactiveBindingsForAction( action ); - var vector = new THREE.Vector3(); + } - vector.subVectors( this.v2, this.v1 ); // diff - vector.multiplyScalar( t ); - vector.add( this.v1 ); + delete actionsByClip[ clipUuid ]; - return vector; + } - } + }, -); + // free all resources specific to a particular root target object + uncacheRoot: function( root ) { -// File:src/extras/curves/QuadraticBezierCurve3.js + var rootUuid = root.uuid, + actionsByClip = this._actionsByClip; -/************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ + for ( var clipUuid in actionsByClip ) { -THREE.QuadraticBezierCurve3 = THREE.Curve.create( + var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - function ( v0, v1, v2 ) { + if ( action !== undefined ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this._deactivateAction( action ); + this._removeInactiveAction( action ); - }, + } - function ( t ) { + } - var b2 = THREE.ShapeUtils.b2; + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - return new THREE.Vector3( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ), - b2( t, this.v0.z, this.v1.z, this.v2.z ) - ); + if ( bindingByName !== undefined ) { - } + for ( var trackName in bindingByName ) { -); + var binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); -// File:src/extras/curves/CubicBezierCurve3.js + } -/************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ + } -THREE.CubicBezierCurve3 = THREE.Curve.create( + }, - function ( v0, v1, v2, v3 ) { + // remove a targeted clip from the cache + uncacheAction: function( clip, optionalRoot ) { - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + var action = this.existingAction( clip, optionalRoot ); - }, + if ( action !== null ) { - function ( t ) { + this._deactivateAction( action ); + this._removeInactiveAction( action ); - var b3 = THREE.ShapeUtils.b3; + } - return new THREE.Vector3( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), - b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) - ); + } - } + } ); -); + AnimationMixer._Action = AnimationAction._new; -// File:src/extras/curves/SplineCurve3.js + // Implementation details: -/************************************************************** - * Spline 3D curve - **************************************************************/ + Object.assign( AnimationMixer.prototype, { + _bindAction: function( action, prototypeAction ) { -THREE.SplineCurve3 = THREE.Curve.create( + var root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName, + bindingsByName = bindingsByRoot[ rootUuid ]; - function ( points /* array of Vector3 */ ) { + if ( bindingsByName === undefined ) { - console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); - this.points = ( points == undefined ) ? [] : points; + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - }, + } - function ( t ) { + for ( var i = 0; i !== nTracks; ++ i ) { - var points = this.points; - var point = ( points.length - 1 ) * t; + var track = tracks[ i ], + trackName = track.name, + binding = bindingsByName[ trackName ]; - var intPoint = Math.floor( point ); - var weight = point - intPoint; + if ( binding !== undefined ) { - 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 ]; + bindings[ i ] = binding; - var interpolate = THREE.CurveUtils.interpolate; + } else { - return new THREE.Vector3( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ), - interpolate( point0.z, point1.z, point2.z, point3.z, weight ) - ); + binding = bindings[ i ]; - } + if ( binding !== undefined ) { -); + // existing binding, make sure the cache knows -// File:src/extras/curves/CatmullRomCurve3.js + if ( binding._cacheIndex === null ) { -/** - * @author zz85 https://github.com/zz85 - * - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf - * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 - */ + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); -THREE.CatmullRomCurve3 = ( function() { + } - var - tmp = new THREE.Vector3(), - px = new CubicPoly(), - py = new CubicPoly(), - pz = new CubicPoly(); + continue; - /* - Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM + } - This CubicPoly class could be used for reusing some variables and calculations, - but for three.js curve use, it could be possible inlined and flatten into a single function call - which can be placed in CurveUtils. - */ + var path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - function CubicPoly() { + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - } + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { - - this.c0 = x0; - this.c1 = t0; - this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - this.c3 = 2 * x0 - 2 * x1 + t0 + t1; + bindings[ i ] = binding; - }; + } - CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { + interpolants[ i ].resultBuffer = binding.buffer; - // compute tangents when parameterized in [t1,t2] - var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + } - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + }, - // initCubicPoly - this.init( x1, x2, t1, t2 ); + _activateAction: function( action ) { - }; + if ( ! this._isActiveAction( action ) ) { - // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 - CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { + if ( action._cacheIndex === null ) { - this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - }; + var rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - CubicPoly.prototype.calc = function( t ) { + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - var t2 = t * t; - var t3 = t2 * t; - return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; + this._addInactiveAction( action, clipUuid, rootUuid ); - }; + } - // Subclass Three.js curve - return THREE.Curve.create( + var bindings = action._propertyBindings; - function ( p /* array of Vector3 */ ) { + // increment reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - this.points = p || []; - this.closed = false; + var binding = bindings[ i ]; - }, + if ( binding.useCount ++ === 0 ) { - function ( t ) { + this._lendBinding( binding ); + binding.saveOriginalState(); - var points = this.points, - point, intPoint, weight, l; + } - l = points.length; + } - if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); + this._lendAction( action ); - point = ( l - ( this.closed ? 0 : 1 ) ) * t; - intPoint = Math.floor( point ); - weight = point - intPoint; + } - if ( this.closed ) { + }, - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; + _deactivateAction: function( action ) { - } else if ( weight === 0 && intPoint === l - 1 ) { + if ( this._isActiveAction( action ) ) { - intPoint = l - 2; - weight = 1; + var bindings = action._propertyBindings; - } + // decrement reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - var p0, p1, p2, p3; // 4 points + var binding = bindings[ i ]; - if ( this.closed || intPoint > 0 ) { + if ( -- binding.useCount === 0 ) { - p0 = points[ ( intPoint - 1 ) % l ]; + binding.restoreOriginalState(); + this._takeBackBinding( binding ); - } else { + } - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + } - } + this._takeBackAction( action ); - p1 = points[ intPoint % l ]; - p2 = points[ ( intPoint + 1 ) % l ]; + } - if ( this.closed || intPoint + 2 < l ) { + }, - p3 = points[ ( intPoint + 2 ) % l ]; + // Memory manager - } else { + _initMemoryManager: function() { - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - } + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< _Action > - used as prototypes + // actionByRoot: _Action - lookup + // } - if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { - // init Centripetal / Chordal Catmull-Rom - var pow = this.type === 'chordal' ? 0.5 : 0.25; - var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); - py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); - pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - } else if ( this.type === 'catmullrom' ) { + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - var tension = this.tension !== undefined ? this.tension : 0.5; - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); + var scope = this; - } + this.stats = { - var v = new THREE.Vector3( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); + actions: { + get total() { return scope._actions.length; }, + get inUse() { return scope._nActiveActions; } + }, + bindings: { + get total() { return scope._bindings.length; }, + get inUse() { return scope._nActiveBindings; } + }, + controlInterpolants: { + get total() { return scope._controlInterpolants.length; }, + get inUse() { return scope._nActiveControlInterpolants; } + } - return v; + }; - } + }, - ); + // Memory management for _Action objects -} )(); + _isActiveAction: function( action ) { -// File:src/extras/curves/ClosedSplineCurve3.js + var index = action._cacheIndex; + return index !== null && index < this._nActiveActions; -/************************************************************** - * Closed Spline 3D curve - **************************************************************/ + }, + _addInactiveAction: function( action, clipUuid, rootUuid ) { -THREE.ClosedSplineCurve3 = function ( points ) { + var actions = this._actions, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); + if ( actionsForClip === undefined ) { - THREE.CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; - this.closed = true; + actionsForClip = { -}; + knownActions: [ action ], + actionByRoot: {} -THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype ); + }; -// File:src/extras/geometries/BoxGeometry.js + action._byClipCacheIndex = 0; -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ + actionsByClip[ clipUuid ] = actionsForClip; -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } else { - THREE.Geometry.call( this ); + var knownActions = actionsForClip.knownActions; - this.type = 'BoxGeometry'; + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + } - this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + action._cacheIndex = actions.length; + actions.push( action ); -}; + actionsForClip.actionByRoot[ rootUuid ] = action; -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; + }, -THREE.CubeGeometry = THREE.BoxGeometry; + _removeInactiveAction: function( action ) { -// File:src/extras/geometries/BoxBufferGeometry.js + var actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); -THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + action._cacheIndex = null; - THREE.BufferGeometry.call( this ); - this.type = 'BoxBufferGeometry'; + var clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - var scope = this; + byClipCacheIndex = action._byClipCacheIndex; - // segments - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - // these are used to calculate buffer length - var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); - var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); + action._byClipCacheIndex = null; - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; - var numberOfVertices = 0; + var actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( actions._localRoot || this._root ).uuid; - // group variables - var groupStart = 0; + delete actionByRoot[ rootUuid ]; - // build each side of the box geometry - buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px - buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx - buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py - buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny - buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz - buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + if ( knownActionsForClip.length === 0 ) { - // build geometry - this.setIndex( 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 ) ); + delete actionsByClip[ clipUuid ]; - // helper functions + } - function calculateVertexCount ( w, h, d ) { + this._removeInactiveBindingsForAction( action ); - var vertices = 0; + }, - // calculate the amount of vertices for each side (plane) - vertices += (w + 1) * (h + 1) * 2; // xy - vertices += (w + 1) * (d + 1) * 2; // xz - vertices += (d + 1) * (h + 1) * 2; // zy + _removeInactiveBindingsForAction: function( action ) { - return vertices; + var bindings = action._propertyBindings; + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - } + var binding = bindings[ i ]; - function calculateIndexCount ( w, h, d ) { + if ( -- binding.referenceCount === 0 ) { - var index = 0; + this._removeInactiveBinding( binding ); - // calculate the amount of squares for each side - index += w * h * 2; // xy - index += w * d * 2; // xz - index += d * h * 2; // zy + } - return index * 6; // two triangles per square => six vertices per square + } - } + }, - function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + _lendAction: function( action ) { - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + var actions = this._actions, + prevIndex = action._cacheIndex, - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + lastActiveIndex = this._nActiveActions ++, - var vertexCounter = 0; - var groupCount = 0; + firstInactiveAction = actions[ lastActiveIndex ]; - var vector = new THREE.Vector3(); + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - // generate vertices, normals and uvs + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - for ( var iy = 0; iy < gridY1; iy ++ ) { + }, - var y = iy * segmentHeight - heightHalf; + _takeBackAction: function( action ) { - for ( var ix = 0; ix < gridX1; ix ++ ) { + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - var x = ix * segmentWidth - widthHalf; + var actions = this._actions, + prevIndex = action._cacheIndex, - // set values to correct vector component - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + firstInactiveIndex = -- this._nActiveActions, - // now apply vector to vertex buffer - vertices[ vertexBufferOffset ] = vector.x; - vertices[ vertexBufferOffset + 1 ] = vector.y; - vertices[ vertexBufferOffset + 2 ] = vector.z; + lastActiveAction = actions[ firstInactiveIndex ]; - // set values to correct vector component - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; - // now apply vector to normal buffer - normals[ vertexBufferOffset ] = vector.x; - normals[ vertexBufferOffset + 1 ] = vector.y; - normals[ vertexBufferOffset + 2 ] = vector.z; + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; - // uvs - uvs[ uvBufferOffset ] = ix / gridX; - uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); + }, - // update offsets and counters - vertexBufferOffset += 3; - uvBufferOffset += 2; - vertexCounter += 1; + // Memory management for PropertyMixer objects - } + _addInactiveBinding: function( binding, rootUuid, trackName ) { - } + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + bindings = this._bindings; - for ( iy = 0; iy < gridY; iy ++ ) { + if ( bindingByName === undefined ) { - for ( ix = 0; ix < gridX; ix ++ ) { + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; - // indices - var a = numberOfVertices + ix + gridX1 * iy; - var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); - var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + } - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + bindingByName[ trackName ] = binding; - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + binding._cacheIndex = bindings.length; + bindings.push( binding ); - // update offsets and counters - indexBufferOffset += 6; - groupCount += 6; + }, - } + _removeInactiveBinding: function( binding ) { - } + var bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, materialIndex ); + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - // calculate new start value for groups - groupStart += groupCount; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - // update total number of vertices - numberOfVertices += vertexCounter; + delete bindingByName[ trackName ]; - } + remove_empty_map: { -}; + for ( var _ in bindingByName ) break remove_empty_map; -THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry; + delete bindingsByRoot[ rootUuid ]; -// File:src/extras/geometries/CircleGeometry.js + } -/** - * @author hughes - */ + }, -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { + _lendBinding: function( binding ) { - THREE.Geometry.call( this ); + var bindings = this._bindings, + prevIndex = binding._cacheIndex, - this.type = 'CircleGeometry'; + lastActiveIndex = this._nActiveBindings ++, - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + firstInactiveBinding = bindings[ lastActiveIndex ]; - this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; -}; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; + }, -// File:src/extras/geometries/CircleBufferGeometry.js + _takeBackBinding: function( binding ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + var bindings = this._bindings, + prevIndex = binding._cacheIndex, -THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) { + firstInactiveIndex = -- this._nActiveBindings, - THREE.BufferGeometry.call( this ); + lastActiveBinding = bindings[ firstInactiveIndex ]; - this.type = 'CircleBufferGeometry'; + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; - radius = radius || 50; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + }, - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - var vertices = segments + 2; + // Memory management of Interpolants for weight and time scale - var positions = new Float32Array( vertices * 3 ); - var normals = new Float32Array( vertices * 3 ); - var uvs = new Float32Array( vertices * 2 ); + _lendControlInterpolant: function() { - // center data is already zero, but need to set a few extras - normals[ 2 ] = 1.0; - uvs[ 0 ] = 0.5; - uvs[ 1 ] = 0.5; + var interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++, + interpolant = interpolants[ lastActiveIndex ]; - for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { + if ( interpolant === undefined ) { - var segment = thetaStart + s / segments * thetaLength; + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, this._controlInterpolantsResultBuffer ); - positions[ i ] = radius * Math.cos( segment ); - positions[ i + 1 ] = radius * Math.sin( segment ); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; - normals[ i + 2 ] = 1; // normal z + } - uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; - uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; + return interpolant; - } + }, - var indices = []; + _takeBackControlInterpolant: function( interpolant ) { - for ( var i = 1; i <= segments; i ++ ) { + var interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - indices.push( i, i + 1, 0 ); + firstInactiveIndex = -- this._nActiveControlInterpolants, - } + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; -}; + }, -THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry; + _controlInterpolantsResultBuffer: new Float32Array( 1 ) -// File:src/extras/geometries/CylinderBufferGeometry.js + } ); -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + function Uniform ( value ) { + this.isUniform = true; - THREE.BufferGeometry.call( this ); + if ( typeof value === 'string' ) { - this.type = 'CylinderBufferGeometry'; + console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); + value = arguments[ 1 ]; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - var scope = this; + this.value = value; - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + this.dynamic = false; - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + }; - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; + Uniform.prototype = { - // used to calculate buffer length + constructor: Uniform, - var nbCap = 0; + onUpdate: function ( callback ) { - if ( openEnded === false ) { + this.dynamic = true; + this.onUpdateCallback = callback; - if ( radiusTop > 0 ) nbCap ++; - if ( radiusBottom > 0 ) nbCap ++; + return this; - } + } - var vertexCount = calculateVertexCount(); - var indexCount = calculateIndexCount(); + }; - // buffers + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + function InstancedBufferGeometry () { + this.isInstancedBufferGeometry = this.isBufferGeometry = true; - // helper variables + BufferGeometry.call( this ); - var index = 0, - indexOffset = 0, - indexArray = [], - halfHeight = height / 2; + this.type = 'InstancedBufferGeometry'; + this.maxInstancedCount = undefined; - // group variables - var groupStart = 0; + }; - // generate geometry + InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; - generateTorso(); + InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { - if ( openEnded === false ) { + this.groups.push( { - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + start: start, + count: count, + instances: instances - } + } ); - // build geometry + }; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + InstancedBufferGeometry.prototype.copy = function ( source ) { - // helper functions + var index = source.index; - function calculateVertexCount() { + if ( index !== null ) { - var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); + this.setIndex( index.clone() ); - if ( openEnded === false ) { + } - count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); + var attributes = source.attributes; - } + for ( var name in attributes ) { - return count; + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - } + } - function calculateIndexCount() { + var groups = source.groups; - var count = radialSegments * heightSegments * 2 * 3; + for ( var i = 0, l = groups.length; i < l; i ++ ) { - if ( openEnded === false ) { + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.instances ); - count += radialSegments * nbCap * 3; + } - } + return this; - return count; + }; - } + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - function generateTorso() { + function InterleavedBufferAttribute ( interleavedBuffer, itemSize, offset, normalized ) { + this.isInterleavedBufferAttribute = true; - var x, y; - var normal = new THREE.Vector3(); - var vertex = new THREE.Vector3(); + this.uuid = exports.Math.generateUUID(); - var groupCount = 0; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - // this will be used to calculate the normal - var tanTheta = ( radiusBottom - radiusTop ) / height; + this.normalized = normalized === true; - // generate vertices, normals and uvs + }; - for ( y = 0; y <= heightSegments; y ++ ) { - var indexRow = []; + InterleavedBufferAttribute.prototype = { - var v = y / heightSegments; + constructor: InterleavedBufferAttribute, - // calculate the radius of the current row - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + get length() { - for ( x = 0; x <= radialSegments; x ++ ) { + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); + return this.array.length; - var u = x / radialSegments; + }, - // vertex - vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); - vertex.y = - v * height + halfHeight; - vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + get count() { - // normal - normal.copy( vertex ); + return this.data.count; - // handle special case if radiusTop/radiusBottom is zero + }, - if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + get array() { - normal.x = Math.sin( u * thetaLength + thetaStart ); - normal.z = Math.cos( u * thetaLength + thetaStart ); + return this.data.array; - } + }, - normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + setX: function ( index, x ) { - // uv - uvs.setXY( index, u, 1 - v ); + this.data.array[ index * this.data.stride + this.offset ] = x; - // save index of vertex in respective row - indexRow.push( index ); + return this; - // increase index - index ++; + }, - } + setY: function ( index, y ) { - // now save vertices of the row in our index array - indexArray.push( indexRow ); + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - } + return this; - // generate indices + }, - for ( x = 0; x < radialSegments; x ++ ) { + setZ: function ( index, z ) { - for ( y = 0; y < heightSegments; y ++ ) { + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - // we use the index array to access the correct indices - var i1 = indexArray[ y ][ x ]; - var i2 = indexArray[ y + 1 ][ x ]; - var i3 = indexArray[ y + 1 ][ x + 1 ]; - var i4 = indexArray[ y ][ x + 1 ]; + return this; - // face one - indices.setX( indexOffset, i1 ); indexOffset ++; - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + }, - // face two - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i3 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + setW: function ( index, w ) { - // update counters - groupCount += 6; + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; - } + return this; - } + }, - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, 0 ); + getX: function ( index ) { - // calculate new start value for groups - groupStart += groupCount; + return this.data.array[ index * this.data.stride + this.offset ]; - } + }, - function generateCap( top ) { + getY: function ( index ) { - var x, centerIndexStart, centerIndexEnd; + return this.data.array[ index * this.data.stride + this.offset + 1 ]; - var uv = new THREE.Vector2(); - var vertex = new THREE.Vector3(); + }, - var groupCount = 0; + getZ: function ( index ) { - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + return this.data.array[ index * this.data.stride + this.offset + 2 ]; - // save the index of the first center vertex - centerIndexStart = index; + }, - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + getW: function ( index ) { - for ( x = 1; x <= radialSegments; x ++ ) { + return this.data.array[ index * this.data.stride + this.offset + 3 ]; - // vertex - vertices.setXYZ( index, 0, halfHeight * sign, 0 ); + }, - // normal - normals.setXYZ( index, 0, sign, 0 ); + setXY: function ( index, x, y ) { - // uv - uv.x = 0.5; - uv.y = 0.5; + index = index * this.data.stride + this.offset; - uvs.setXY( index, uv.x, uv.y ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - // increase index - index ++; + return this; - } + }, - // save the index of the last center vertex - centerIndexEnd = index; + setXYZ: function ( index, x, y, z ) { - // now we generate the surrounding vertices, normals and uvs + index = index * this.data.stride + this.offset; - for ( x = 0; x <= radialSegments; x ++ ) { + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + return this; - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + }, - // vertex - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + setXYZW: function ( index, x, y, z, w ) { - // normal - normals.setXYZ( index, 0, sign, 0 ); + index = index * this.data.stride + this.offset; - // uv - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.setXY( index, uv.x, uv.y ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - // increase index - index ++; + return this; - } + } - // generate indices + }; - for ( x = 0; x < radialSegments; x ++ ) { + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var c = centerIndexStart + x; - var i = centerIndexEnd + x; + function InterleavedBuffer ( array, stride ) { + this.isInterleavedBuffer = true; - if ( top === true ) { + this.uuid = exports.Math.generateUUID(); - // face top - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + this.array = array; + this.stride = stride; - } else { + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - // face bottom - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + this.version = 0; - } + }; - // update counters - groupCount += 3; + InterleavedBuffer.prototype = { - } + constructor: InterleavedBuffer, - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + get length () { - // calculate new start value for groups - groupStart += groupCount; + return this.array.length; - } + }, -}; + get count () { -THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry; + return this.array.length / this.stride; -// File:src/extras/geometries/CylinderGeometry.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - */ + set needsUpdate( value ) { -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + if ( value === true ) this.version ++; - THREE.Geometry.call( this ); + }, - this.type = 'CylinderGeometry'; + setDynamic: function ( value ) { - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.dynamic = value; - this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); - this.mergeVertices(); + return this; -}; + }, -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; + copy: function ( source ) { -// File:src/extras/geometries/ConeBufferGeometry.js + this.array = new source.array.constructor( source.array ); + this.stride = source.stride; + this.dynamic = source.dynamic; -/* - * @author: abelnation / http://github.com/abelnation - */ + return this; -THREE.ConeBufferGeometry = function ( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { - - THREE.CylinderBufferGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); - - this.type = 'ConeBufferGeometry'; - - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + }, -}; + copyAt: function ( index1, attribute, index2 ) { -THREE.ConeBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.ConeBufferGeometry.prototype.constructor = THREE.ConeBufferGeometry; + index1 *= this.stride; + index2 *= attribute.stride; -// File:src/extras/geometries/ConeGeometry.js + for ( var i = 0, l = this.stride; i < l; i ++ ) { -/** - * @author abelnation / http://github.com/abelnation - */ + this.array[ index1 + i ] = attribute.array[ index2 + i ]; -THREE.ConeGeometry = function ( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { - - THREE.CylinderGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); - - this.type = 'ConeGeometry'; - - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } -}; + return this; -THREE.ConeGeometry.prototype = Object.create( THREE.CylinderGeometry.prototype ); -THREE.ConeGeometry.prototype.constructor = THREE.ConeGeometry; + }, -// File:src/extras/geometries/EdgesGeometry.js + set: function ( value, offset ) { -/** - * @author WestLangley / http://github.com/WestLangley - */ + if ( offset === undefined ) offset = 0; -THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { + this.array.set( value, offset ); - THREE.BufferGeometry.call( this ); + return this; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + }, - var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle ); + clone: function () { - var edge = [ 0, 0 ], hash = {}; + return new this.constructor().copy( this ); - function sortFunction( a, b ) { + } - return a - b; + }; - } + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - var keys = [ 'a', 'b', 'c' ]; + function InstancedInterleavedBuffer ( array, stride, meshPerAttribute ) { + this.isInstancedInterleavedBuffer = this.isInterleavedBuffer = true; - var geometry2; + InterleavedBuffer.call( this, array, stride ); - if ( geometry instanceof THREE.BufferGeometry ) { + this.meshPerAttribute = meshPerAttribute || 1; - geometry2 = new THREE.Geometry(); - geometry2.fromBufferGeometry( geometry ); + }; - } else { + InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); + InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; - geometry2 = geometry.clone(); + InstancedInterleavedBuffer.prototype.copy = function ( source ) { - } + InterleavedBuffer.prototype.copy.call( this, source ); - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + this.meshPerAttribute = source.meshPerAttribute; - var vertices = geometry2.vertices; - var faces = geometry2.faces; + return this; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + }; - var face = faces[ i ]; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - for ( var j = 0; j < 3; j ++ ) { + function InstancedBufferAttribute ( array, itemSize, meshPerAttribute ) { + this.isInstancedBufferAttribute = this.isBufferAttribute = true; - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + BufferAttribute.call( this, array, itemSize ); - var key = edge.toString(); + this.meshPerAttribute = meshPerAttribute || 1; - if ( hash[ key ] === undefined ) { + }; - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; + InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; - } else { + InstancedBufferAttribute.prototype.copy = function ( source ) { - hash[ key ].face2 = i; + BufferAttribute.prototype.copy.call( this, source ); - } + this.meshPerAttribute = source.meshPerAttribute; - } + return this; - } + }; - var coords = []; + /** + * @author mrdoob / http://mrdoob.com/ + * @author bhouston / http://clara.io/ + * @author stephomi / http://stephaneginier.com/ + */ - for ( var key in hash ) { + function Raycaster ( origin, direction, near, far ) { + this.isRaycaster = true; - var h = hash[ key ]; + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { + this.near = near || 0; + this.far = far || Infinity; - var vertex = vertices[ h.vert1 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + this.params = { + Mesh: {}, + Line: {}, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; - vertex = vertices[ h.vert2 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + Object.defineProperties( this.params, { + PointCloud: { + get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; + } + } + } ); - } + }; - } + function ascSort( a, b ) { - this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) ); + return a.distance - b.distance; -}; + } -THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry; + function intersectObject( object, raycaster, intersects, recursive ) { -// File:src/extras/geometries/ExtrudeGeometry.js + if ( object.visible === false ) return; -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * amount: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline is bevel - * bevelSegments: , // number of bevel layers - * - * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) - * frames: // containing arrays of tangents, normals, binormals - * - * uvGenerator: // object that provides UV generator functions - * - * } - **/ - -THREE.ExtrudeGeometry = function ( shapes, options ) { - - if ( typeof( shapes ) === "undefined" ) { - - shapes = []; - return; + object.raycast( raycaster, intersects ); - } + if ( recursive === true ) { - THREE.Geometry.call( this ); + var children = object.children; - this.type = 'ExtrudeGeometry'; + for ( var i = 0, l = children.length; i < l; i ++ ) { - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + intersectObject( children[ i ], raycaster, intersects, true ); - this.addShapeList( shapes, options ); + } - this.computeFaceNormals(); + } - // 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 ) ); + Raycaster.prototype = { -}; + constructor: Raycaster, -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; + linePrecision: 1, -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { + set: function ( origin, direction ) { - var sl = shapes.length; + // direction is assumed to be normalized (for accurate distance calculations) - for ( var s = 0; s < sl; s ++ ) { + this.ray.set( origin, direction ); - var shape = shapes[ s ]; - this.addShape( shape, options ); + }, - } + setFromCamera: function ( coords, camera ) { -}; + if ( (camera && camera.isPerspectiveCamera) ) { -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - var amount = options.amount !== undefined ? options.amount : 100; + } else if ( (camera && camera.isOrthographicCamera) ) { - 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; + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + } else { - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + console.error( 'THREE.Raycaster: Unsupported camera type.' ); - var steps = options.steps !== undefined ? options.steps : 1; + } - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + }, - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; + intersectObject: function ( object, recursive ) { - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + var intersects = []; - extrudePts = extrudePath.getSpacedPoints( steps ); + intersectObject( object, this, intersects, recursive ); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + intersects.sort( ascSort ); - // SETUP TNB variables + return intersects; - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? + }, - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false ); + intersectObjects: function ( objects, recursive ) { - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + var intersects = []; - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); + if ( Array.isArray( objects ) === false ) { - } + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - // Safeguards if bevels are not enabled + } - if ( ! bevelEnabled ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - // Variables initialization + intersects.sort( ascSort ); - var ahole, h, hl; // looping of holes - var scope = this; + return intersects; - var shapesOffset = this.vertices.length; + } - var shapePoints = shape.extractPoints( curveSegments ); + }; - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + /** + * @author alteredq / http://alteredqualia.com/ + */ - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + function Clock ( autoStart ) { + this.isClock = true; - if ( reverse ) { + this.autoStart = ( autoStart !== undefined ) ? autoStart : true; - vertices = vertices.reverse(); + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + this.running = false; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + }; - ahole = holes[ h ]; + Clock.prototype = { - if ( THREE.ShapeUtils.isClockWise( ahole ) ) { + constructor: Clock, - holes[ h ] = ahole.reverse(); + start: function () { - } + this.startTime = ( performance || Date ).now(); - } + this.oldTime = this.startTime; + this.running = true; - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! + }, - } + stop: function () { + this.getElapsedTime(); + this.running = false; - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + }, - /* Vertices */ + getElapsedTime: function () { - var contour = vertices; // vertices has all points but contour has only points of circumference + this.getDelta(); + return this.elapsedTime; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + }, - ahole = holes[ h ]; + getDelta: function () { - vertices = vertices.concat( ahole ); + var diff = 0; - } + if ( this.autoStart && ! this.running ) { + this.start(); - function scalePt2 ( pt, vec, size ) { + } - if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); + if ( this.running ) { - return vec.clone().multiplyScalar( size ).add( pt ); + var newTime = ( performance || Date ).now(); - } + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + this.elapsedTime += diff; + } - // Find directions for point movement + return diff; + } - function getBevelVec( inPt, inPrev, inNext ) { + }; - // computes for inPt the corresponding point inPt' on a new contour - // shifted 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. + /** + * 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/ + */ - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt + function Spline ( points ) { + this.isSpline = true; - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + this.points = points; - 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 c = [], v3 = { x: 0, y: 0, z: 0 }, + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + this.initFromArray = function ( a ) { - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + this.points = []; - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + for ( var i = 0; i < a.length; i ++ ) { - // not collinear + this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; - // 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 + this.getPoint = function ( k ) { - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + point = ( this.points.length - 1 ) * k; + intPoint = Math.floor( point ); + weight = point - intPoint; - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + 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; - // scaling factor for v_prev to intersection point + pa = this.points[ c[ 0 ] ]; + pb = this.points[ c[ 1 ] ]; + pc = this.points[ c[ 2 ] ]; + pd = this.points[ c[ 3 ] ]; - 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 ); + w2 = weight * weight; + w3 = weight * w2; - // vector from inPt to intersection point + 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 ); - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + return v3; - // 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 ); + this.getControlPointsArray = function () { - } else { + var i, p, l = this.points.length, + coords = []; - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + for ( i = 0; i < l; i ++ ) { - } + p = this.points[ i ]; + coords[ i ] = [ p.x, p.y, p.z ]; - } else { + } - // handle special case of collinear edges + return coords; - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + }; - if ( v_next_x > Number.EPSILON ) { + // approximate length by summing linear segments - direction_eq = true; + this.getLength = function ( nSubDivisions ) { - } + var i, index, nSamples, position, + point = 0, intPoint = 0, oldIntPoint = 0, + oldPosition = new Vector3(), + tmpVec = new Vector3(), + chunkLengths = [], + totalLength = 0; - } else { + // first point has 0 length - if ( v_prev_x < - Number.EPSILON ) { + chunkLengths[ 0 ] = 0; - if ( v_next_x < - Number.EPSILON ) { + if ( ! nSubDivisions ) nSubDivisions = 100; - direction_eq = true; + nSamples = this.points.length * nSubDivisions; - } + oldPosition.copy( this.points[ 0 ] ); - } else { + for ( i = 1; i < nSamples; i ++ ) { - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + index = i / nSamples; - direction_eq = true; + position = this.getPoint( index ); + tmpVec.copy( position ); - } + totalLength += tmpVec.distanceTo( oldPosition ); - } + oldPosition.copy( position ); - } + point = ( this.points.length - 1 ) * index; + intPoint = Math.floor( point ); - if ( direction_eq ) { + if ( intPoint !== oldIntPoint ) { - // 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 ); + chunkLengths[ intPoint ] = totalLength; + oldIntPoint = intPoint; - } 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 ); + } - } + // last point ends with total length - } + chunkLengths[ chunkLengths.length ] = totalLength; - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + return { chunks: chunkLengths, total: totalLength }; - } + }; + this.reparametrizeByArcLength = function ( samplingCoef ) { - var contourMovements = []; + var i, j, + index, indexCurrent, indexNext, + realDistance, + sampling, position, + newpoints = [], + tmpVec = new Vector3(), + sl = this.getLength(); - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - if ( j === il ) j = 0; - if ( k === il ) k = 0; + for ( i = 1; i < this.points.length; i ++ ) { - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + //tmpVec.copy( this.points[ i - 1 ] ); + //linearDistance = tmpVec.distanceTo( this.points[ i ] ); - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; - } + sampling = Math.ceil( samplingCoef * realDistance / sl.total ); - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); + indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); + indexNext = i / ( this.points.length - 1 ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + for ( j = 1; j < sampling - 1; j ++ ) { - ahole = holes[ h ]; + index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); - oneHoleMovements = []; + position = this.getPoint( index ); + newpoints.push( tmpVec.copy( position ).clone() ); - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; + newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + } - } + this.points = newpoints; - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + }; - } + // Catmull-Rom + function interpolate( p0, p1, p2, p3, t, t2, t3 ) { - // Loop bevelSegments, 1 for the front, 1 for the back + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - for ( b = 0; b < bevelSegments; b ++ ) { + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - //for ( b = bevelSegments; b > 0; b -- ) { + } - t = b / bevelSegments; - z = bevelThickness * ( 1 - t ); + }; - //z = bevelThickness * t; - bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved - //bs = bevelSize * t; // linear + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The poles (phi) are at the positive and negative y axis. + * The equator starts at positive z. + */ - // contract shape + function Spherical ( radius, phi, theta ) { + this.isSpherical = true; - for ( i = 0, il = contour.length; i < il; i ++ ) { + this.radius = ( radius !== undefined ) ? radius : 1.0; + this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole + this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + return this; - v( vert.x, vert.y, - z ); + }; - } + Spherical.prototype = { - // expand holes + constructor: Spherical, - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + set: function ( radius, phi, theta ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + this.radius = radius; + this.phi = phi; + this.theta = theta; - for ( i = 0, il = ahole.length; i < il; i ++ ) { + return this; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + }, - v( vert.x, vert.y, - z ); + clone: function () { - } + return new this.constructor().copy( this ); - } + }, - } + copy: function ( other ) { - bs = bevelSize; + this.radius.copy( other.radius ); + this.phi.copy( other.phi ); + this.theta.copy( other.theta ); - // Back facing vertices + return this; - for ( i = 0; i < vlen; i ++ ) { + }, - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // restrict phi to be betwee EPS and PI-EPS + makeSafe: function() { - if ( ! extrudeByPath ) { + var EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - v( vert.x, vert.y, 0 ); + return this; - } else { + }, - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + setFromVector3: function( vec3 ) { - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + this.radius = vec3.length(); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis + this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + + } + + return this; + + }, + + }; + + /** + * @author alteredq / http://alteredqualia.com/ + */ + + function MorphBlendMesh( geometry, material ) { + this.isMorphBlendMesh = this.isMesh = true; + + Mesh.call( this, geometry, material ); + + this.animationsMap = {}; + this.animationsList = []; + + // prepare default animation + // (all frames played together in 1 second) + + var numFrames = this.geometry.morphTargets.length; + + var name = "__default"; + + var startFrame = 0; + var endFrame = numFrames - 1; + + var fps = numFrames / 1; + + this.createAnimation( name, startFrame, endFrame, fps ); + this.setAnimationWeight( name, 1 ); + + }; + + MorphBlendMesh.prototype = Object.create( Mesh.prototype ); + MorphBlendMesh.prototype.constructor = MorphBlendMesh; + + MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + + var animation = { + + start: start, + end: end, + + length: end - start + 1, + + fps: fps, + duration: ( end - start ) / fps, + + lastFrame: 0, + currentFrame: 0, + + active: false, + + time: 0, + direction: 1, + weight: 1, + + directionBackwards: false, + mirroredLoop: false + + }; + + this.animationsMap[ name ] = animation; + this.animationsList.push( animation ); + + }; + + MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { + + var pattern = /([a-z]+)_?(\d+)/i; + + var firstAnimation, frameRanges = {}; + + var geometry = this.geometry; + + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + + var morph = geometry.morphTargets[ i ]; + var chunks = morph.name.match( pattern ); + + if ( chunks && chunks.length > 1 ) { + + var name = chunks[ 1 ]; + + if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + + var range = frameRanges[ name ]; + + if ( i < range.start ) range.start = i; + if ( i > range.end ) range.end = i; + + if ( ! firstAnimation ) firstAnimation = name; + + } + + } + + for ( var name in frameRanges ) { + + var range = frameRanges[ name ]; + this.createAnimation( name, range.start, range.end, fps ); + + } + + this.firstAnimation = firstAnimation; + + }; + + MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = 1; + animation.directionBackwards = false; + + } + + }; + + MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.direction = - 1; + animation.directionBackwards = true; + + } + + }; + + MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.fps = fps; + animation.duration = ( animation.end - animation.start ) / animation.fps; + + } + + }; + + MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.duration = duration; + animation.fps = ( animation.end - animation.start ) / animation.duration; + + } + + }; + + MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.weight = weight; + + } + + }; + + MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.time = time; + + } + + }; + + MorphBlendMesh.prototype.getAnimationTime = function ( name ) { + + var time = 0; + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + time = animation.time; + + } + + return time; + + }; + + MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + + var duration = - 1; + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + duration = animation.duration; + + } + + return duration; + + }; + + MorphBlendMesh.prototype.playAnimation = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.time = 0; + animation.active = true; + + } else { + + console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + + } + + }; + + MorphBlendMesh.prototype.stopAnimation = function ( name ) { + + var animation = this.animationsMap[ name ]; + + if ( animation ) { + + animation.active = false; + + } + + }; + + MorphBlendMesh.prototype.update = function ( delta ) { + + for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { + + var animation = this.animationsList[ i ]; + + if ( ! animation.active ) continue; + + var frameTime = animation.duration / animation.length; + + animation.time += animation.direction * delta; + + if ( animation.mirroredLoop ) { + + if ( animation.time > animation.duration || animation.time < 0 ) { + + animation.direction *= - 1; + + if ( animation.time > animation.duration ) { + + animation.time = animation.duration; + animation.directionBackwards = true; + + } + + if ( animation.time < 0 ) { + + animation.time = 0; + animation.directionBackwards = false; + + } + + } + + } else { + + animation.time = animation.time % animation.duration; + + if ( animation.time < 0 ) animation.time += animation.duration; + + } + + var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var weight = animation.weight; + + if ( keyframe !== animation.currentFrame ) { + + this.morphTargetInfluences[ animation.lastFrame ] = 0; + this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + + this.morphTargetInfluences[ keyframe ] = 0; + + animation.lastFrame = animation.currentFrame; + animation.currentFrame = keyframe; + + } + + var mix = ( animation.time % frameTime ) / frameTime; + + if ( animation.directionBackwards ) mix = 1 - mix; + + if ( animation.currentFrame !== animation.lastFrame ) { + + this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; + this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; + + } else { + + this.morphTargetInfluences[ animation.currentFrame ] = weight; + + } + + } + + }; + + /** + * @author alteredq / http://alteredqualia.com/ + */ + + function ImmediateRenderObject ( material ) { + this.isImmediateRenderObject = this.isObject3D = true; + + Object3D.call( this ); + + this.material = material; + this.render = function ( renderCallback ) {}; + + }; + + ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); + ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function WireframeGeometry ( geometry ) { + this.isWireframeGeometry = this.isBufferGeometry = true; - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + BufferGeometry.call( this ); - v( position2.x, position2.y, position2.z ); + var edge = [ 0, 0 ], hash = {}; - } + function sortFunction( a, b ) { - } + return a - b; - // Add stepped vertices... - // Including front facing vertices + } - var s; + var keys = [ 'a', 'b', 'c' ]; - for ( s = 1; s <= steps; s ++ ) { + if ( (geometry && geometry.isGeometry) ) { - for ( i = 0; i < vlen; i ++ ) { + var vertices = geometry.vertices; + var faces = geometry.faces; + var numEdges = 0; - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // allocate maximal size + var edges = new Uint32Array( 6 * faces.length ); - if ( ! extrudeByPath ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - v( vert.x, vert.y, amount / steps * s ); + var face = faces[ i ]; - } else { + for ( var j = 0; j < 3; j ++ ) { - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + var key = edge.toString(); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + if ( hash[ key ] === undefined ) { - v( position2.x, position2.y, position2.z ); + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - } + } - } + } - } + } + var coords = new Float32Array( numEdges * 2 * 3 ); - // Add bevel segments planes + for ( var i = 0, l = numEdges; i < l; i ++ ) { - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + for ( var j = 0; j < 2; j ++ ) { - 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 ); + var vertex = vertices[ edges [ 2 * i + j ] ]; - // contract shape + var index = 6 * i + 3 * j; + coords[ index + 0 ] = vertex.x; + coords[ index + 1 ] = vertex.y; + coords[ index + 2 ] = vertex.z; - for ( i = 0, il = contour.length; i < il; i ++ ) { + } - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + } - } + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - // expand holes + } else if ( (geometry && geometry.isBufferGeometry) ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + if ( geometry.index !== null ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + // Indexed BufferGeometry - for ( i = 0, il = ahole.length; i < il; i ++ ) { + var indices = geometry.index.array; + var vertices = geometry.attributes.position; + var groups = geometry.groups; + var numEdges = 0; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + if ( groups.length === 0 ) { - if ( ! extrudeByPath ) { + geometry.addGroup( 0, indices.length ); - v( vert.x, vert.y, amount + z ); + } - } else { + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + for ( var o = 0, ol = groups.length; o < ol; ++ o ) { - } + var group = groups[ o ]; - } + var start = group.start; + var count = group.count; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - } + for ( var j = 0; j < 3; j ++ ) { - /* Faces */ + edge[ 0 ] = indices[ i + j ]; + edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); - // Top and bottom faces + var key = edge.toString(); - buildLidFaces(); + if ( hash[ key ] === undefined ) { - // Sides faces + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - buildSideFaces(); + } + } - ///// Internal functions + } - function buildLidFaces() { + } - if ( bevelEnabled ) { + var coords = new Float32Array( numEdges * 2 * 3 ); - var layer = 0; // steps + 1 - var offset = vlen * layer; + for ( var i = 0, l = numEdges; i < l; i ++ ) { - // Bottom faces + for ( var j = 0; j < 2; j ++ ) { - for ( i = 0; i < flen; i ++ ) { + var index = 6 * i + 3 * j; + var index2 = edges[ 2 * i + j ]; - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + coords[ index + 0 ] = vertices.getX( index2 ); + coords[ index + 1 ] = vertices.getY( index2 ); + coords[ index + 2 ] = vertices.getZ( index2 ); - } + } - layer = steps + bevelSegments * 2; - offset = vlen * layer; + } - // Top faces + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - for ( i = 0; i < flen; i ++ ) { + } else { - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + // non-indexed BufferGeometry - } + var vertices = geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; - } else { + var coords = new Float32Array( numEdges * 2 * 3 ); - // Bottom faces + for ( var i = 0, l = numTris; i < l; i ++ ) { - for ( i = 0; i < flen; i ++ ) { + for ( var j = 0; j < 3; j ++ ) { - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + var index = 18 * i + 6 * j; - } + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; - // Top faces + 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 ]; - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + } - } + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - } + } - } + } - // Create faces for the z-sides of the shape + }; - function buildSideFaces() { + WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); + WireframeGeometry.prototype.constructor = WireframeGeometry; - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + function WireframeHelper ( object, hex ) { + this.isWireframeHelper = this.isLineSegments = true; - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + var color = ( hex !== undefined ) ? hex : 0xffffff; - //, true - layeroffset += ahole.length; + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); - } + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - } + }; - function sidewalls( contour, layeroffset ) { + WireframeHelper.prototype = Object.create( LineSegments.prototype ); + WireframeHelper.prototype.constructor = WireframeHelper; - var j, k; - i = contour.length; + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - while ( -- i >= 0 ) { + function VertexNormalsHelper ( object, size, hex, linewidth ) { + this.isVertexNormalsHelper = this.isLineSegments = true; - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + this.object = object; - //console.log('b', i,j, i-1, k,vertices.length); + this.size = ( size !== undefined ) ? size : 1; - var s = 0, sl = steps + bevelSegments * 2; + var color = ( hex !== undefined ) ? hex : 0xff0000; - for ( s = 0; s < sl; s ++ ) { + var width = ( linewidth !== undefined ) ? linewidth : 1; - 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; + var nNormals = 0; - f4( a, b, c, d, contour, s, sl, j, k ); + var objGeometry = this.object.geometry; - } + if ( (objGeometry && objGeometry.isGeometry) ) { - } + nNormals = objGeometry.faces.length * 3; - } + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + nNormals = objGeometry.attributes.normal.count; - function v( x, y, z ) { + } - scope.vertices.push( new THREE.Vector3( x, y, z ) ); + // - } + var geometry = new BufferGeometry(); - function f3( a, b, c ) { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; + geometry.addAttribute( 'position', positions ); - scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - var uvs = uvgen.generateTopUV( scope, a, b, c ); + // - scope.faceVertexUvs[ 0 ].push( uvs ); + this.matrixAutoUpdate = false; - } + this.update(); - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + }; - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - d += shapesOffset; + VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); + VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; - scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) ); + VertexNormalsHelper.prototype.update = ( function () { - var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); + return function update() { - } + var keys = [ 'a', 'b', 'c' ]; -}; + this.object.updateMatrixWorld( true ); -THREE.ExtrudeGeometry.WorldUVGenerator = { + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - generateTopUV: function ( geometry, indexA, indexB, indexC ) { + var matrixWorld = this.object.matrixWorld; - var vertices = geometry.vertices; + var position = this.geometry.attributes.position; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; + // - return [ - new THREE.Vector2( a.x, a.y ), - new THREE.Vector2( b.x, b.y ), - new THREE.Vector2( c.x, c.y ) - ]; + var objGeometry = this.object.geometry; - }, + if ( (objGeometry && objGeometry.isGeometry) ) { - generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { + var vertices = objGeometry.vertices; - var vertices = geometry.vertices; + var faces = objGeometry.faces; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; - var d = vertices[ indexD ]; + var idx = 0; - if ( Math.abs( a.y - b.y ) < 0.01 ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - 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 ) - ]; + var face = faces[ i ]; - } else { + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - 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 ) - ]; + var vertex = vertices[ face[ keys[ j ] ] ]; - } + var normal = face.vertexNormals[ j ]; - } -}; + v1.copy( vertex ).applyMatrix4( matrixWorld ); -// File:src/extras/geometries/ShapeGeometry.js + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); -/** - * @author jonobr1 / http://jonobr1.com - * - * Creates a one-sided polygonal geometry from a path shape. Similar to - * ExtrudeGeometry. - * - * parameters = { - * - * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. - * - * material: // material index for front and back faces - * uvGenerator: // object that provides UV generator functions - * - * } - **/ + position.setXYZ( idx, v1.x, v1.y, v1.z ); -THREE.ShapeGeometry = function ( shapes, options ) { + idx = idx + 1; - THREE.Geometry.call( this ); + position.setXYZ( idx, v2.x, v2.y, v2.z ); - this.type = 'ShapeGeometry'; + idx = idx + 1; - if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; + } - this.addShapeList( shapes, options ); + } - this.computeFaceNormals(); + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { -}; + var objPos = objGeometry.attributes.position; -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; + var objNorm = objGeometry.attributes.normal; -/** - * Add an array of shapes to THREE.ShapeGeometry. - */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { + var idx = 0; - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + // for simplicity, ignore index and drawcalls, and render every normal - this.addShape( shapes[ i ], options ); + for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { - } + v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); - return this; + v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); -}; + v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); -/** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { + position.setXYZ( idx, v1.x, v1.y, v1.z ); - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + idx = idx + 1; - var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - // + idx = idx + 1; - var i, l, hole; + } - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); + } - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + position.needsUpdate = true; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + return this; - if ( reverse ) { + }; - vertices = vertices.reverse(); + }() ); - // Maybe we should also check if holes are in the opposite direction, just to be safe... + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - for ( i = 0, l = holes.length; i < l; i ++ ) { + function SpotLightHelper ( light ) { + this.isSpotLightHelper = this.isObject3D = true; - hole = holes[ i ]; + Object3D.call( this ); - if ( THREE.ShapeUtils.isClockWise( hole ) ) { + this.light = light; + this.light.updateMatrixWorld(); - holes[ i ] = hole.reverse(); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - } + var geometry = new BufferGeometry(); - } + var positions = [ + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, - 1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, - 1, 1 + ]; - reverse = false; + for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - } + var p1 = ( i / l ) * Math.PI * 2; + var p2 = ( j / l ) * Math.PI * 2; - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); - // Vertices + } - for ( i = 0, l = holes.length; i < l; i ++ ) { + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - hole = holes[ i ]; - vertices = vertices.concat( hole ); + var material = new LineBasicMaterial( { fog: false } ); - } + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); - // + this.update(); - var vert, vlen = vertices.length; - var face, flen = faces.length; + }; - for ( i = 0; i < vlen; i ++ ) { + SpotLightHelper.prototype = Object.create( Object3D.prototype ); + SpotLightHelper.prototype.constructor = SpotLightHelper; - vert = vertices[ i ]; + SpotLightHelper.prototype.dispose = function () { - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); + this.cone.geometry.dispose(); + this.cone.material.dispose(); - } + }; - for ( i = 0; i < flen; i ++ ) { + SpotLightHelper.prototype.update = function () { - face = faces[ i ]; + var vector = new Vector3(); + var vector2 = new Vector3(); - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; + return function update() { - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); + var coneLength = this.light.distance ? this.light.distance : 1000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - } + this.cone.scale.set( coneWidth, coneWidth, coneLength ); -}; + vector.setFromMatrixPosition( this.light.matrixWorld ); + vector2.setFromMatrixPosition( this.light.target.matrixWorld ); -// File:src/extras/geometries/LatheBufferGeometry.js + this.cone.lookAt( vector2.sub( vector ) ); -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - // 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 2PI) range of the lathed section - // 2PI is a closed lathe, less than 2PI is a portion. + }; -THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { + }(); - THREE.BufferGeometry.call( this ); + /** + * @author Sean Griffin / http://twitter.com/sgrif + * @author Michael Guerrero / http://realitymeltdown.com + * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com + */ - this.type = 'LatheBufferGeometry'; + function SkeletonHelper ( object ) { + this.isSkeletonHelper = this.isLineSegments = true; - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + this.bones = this.getBoneList( object ); - segments = Math.floor( segments ) || 12; - phiStart = phiStart || 0; - phiLength = phiLength || Math.PI * 2; + var geometry = new Geometry(); - // clamp phiLength so it's in range of [ 0, 2PI ] - phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 ); + for ( var i = 0; i < this.bones.length; i ++ ) { - // these are used to calculate buffer length - var vertexCount = ( segments + 1 ) * points.length; - var indexCount = segments * points.length * 2 * 3; + var bone = this.bones[ i ]; - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + if ( (bone.parent && bone.parent.isBone) ) { - // helper variables - var index = 0, indexOffset = 0, base; - var inversePointLength = 1.0 / ( points.length - 1 ); - var inverseSegments = 1.0 / segments; - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); - var i, j; + geometry.vertices.push( new Vector3() ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( 0, 0, 1 ) ); + geometry.colors.push( new Color( 0, 1, 0 ) ); - // generate vertices and uvs + } - for ( i = 0; i <= segments; i ++ ) { + } - var phi = phiStart + i * inverseSegments * phiLength; + geometry.dynamic = true; - var sin = Math.sin( phi ); - var cos = Math.cos( phi ); + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + LineSegments.call( this, geometry, material ); - // vertex - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + this.root = object; - // uv - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); - uvs.setXY( index, uv.x, uv.y ); + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - // increase index - index ++; + this.update(); - } + }; - } - // generate indices + SkeletonHelper.prototype = Object.create( LineSegments.prototype ); + SkeletonHelper.prototype.constructor = SkeletonHelper; - for ( i = 0; i < segments; i ++ ) { + SkeletonHelper.prototype.getBoneList = function( object ) { - for ( j = 0; j < ( points.length - 1 ); j ++ ) { + var boneList = []; - base = j + i * points.length; + if ( (object && object.isBone) ) { - // indices - var a = base; - var b = base + points.length; - var c = base + points.length + 1; - var d = base + 1; + boneList.push( object ); - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + } - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + for ( var i = 0; i < object.children.length; i ++ ) { - } + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); - } + } - // build geometry + return boneList; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'uv', uvs ); + }; - // generate normals + SkeletonHelper.prototype.update = function () { - this.computeVertexNormals(); + var geometry = this.geometry; - // if the geometry is closed, we need to average the normals along the seam. - // because the corresponding vertices are identical (but still have different UVs). + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - if( phiLength === Math.PI * 2 ) { + var boneMatrix = new Matrix4(); - var normals = this.attributes.normal.array; - var n1 = new THREE.Vector3(); - var n2 = new THREE.Vector3(); - var n = new THREE.Vector3(); + var j = 0; - // this is the buffer offset for the last line of vertices - base = segments * points.length * 3; + for ( var i = 0; i < this.bones.length; i ++ ) { - for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + var bone = this.bones[ i ]; - // select the normal of the vertex in the first line - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + if ( (bone.parent && bone.parent.isBone) ) { - // select the normal of the vertex in the last line - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); - // average normals - n.addVectors( n1, n2 ).normalize(); + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); - // assign the new values to both normals - normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; - normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; - normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; + j += 2; - } // next row + } - } + } -}; + geometry.verticesNeedUpdate = true; -THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry; + geometry.computeBoundingSphere(); -// File:src/extras/geometries/LatheGeometry.js + }; -/** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://clara.io - */ + /** + * @author benaadams / https://twitter.com/ben_a_adams + * based on THREE.SphereGeometry + */ -// 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 2PI) range of the lathed section -// 2PI is a closed lathe, less than 2PI is a portion. + function SphereBufferGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereBufferGeometry = this.isBufferGeometry = true; -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { + BufferGeometry.call( this ); - THREE.Geometry.call( this ); + this.type = 'SphereBufferGeometry'; - this.type = 'LatheGeometry'; + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + radius = radius || 50; - this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) ); - this.mergeVertices(); + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); -}; + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; -// File:src/extras/geometries/PlaneGeometry.js + var thetaEnd = thetaStart + thetaLength; -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { + var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - THREE.Geometry.call( this ); + var index = 0, vertices = [], normal = new Vector3(); - this.type = 'PlaneGeometry'; + for ( var y = 0; y <= heightSegments; y ++ ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + var verticesRow = []; - this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + var v = y / heightSegments; -}; + for ( var x = 0; x <= widthSegments; x ++ ) { -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; + var u = x / widthSegments; -// File:src/extras/geometries/PlaneBufferGeometry.js + var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + var py = radius * Math.cos( thetaStart + v * thetaLength ); + var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); -/** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + normal.set( px, py, pz ).normalize(); -THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { + positions.setXYZ( index, px, py, pz ); + normals.setXYZ( index, normal.x, normal.y, normal.z ); + uvs.setXY( index, u, 1 - v ); - THREE.BufferGeometry.call( this ); + verticesRow.push( index ); - this.type = 'PlaneBufferGeometry'; + index ++; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + } - var width_half = width / 2; - var height_half = height / 2; + vertices.push( verticesRow ); - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; + } - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + var indices = []; - var segment_width = width / gridX; - var segment_height = height / gridY; + for ( var y = 0; y < heightSegments; y ++ ) { - var vertices = new Float32Array( gridX1 * gridY1 * 3 ); - var normals = new Float32Array( gridX1 * gridY1 * 3 ); - var uvs = new Float32Array( gridX1 * gridY1 * 2 ); + for ( var x = 0; x < widthSegments; x ++ ) { - var offset = 0; - var offset2 = 0; + var v1 = vertices[ y ][ x + 1 ]; + var v2 = vertices[ y ][ x ]; + var v3 = vertices[ y + 1 ][ x ]; + var v4 = vertices[ y + 1 ][ x + 1 ]; - for ( var iy = 0; iy < gridY1; iy ++ ) { + if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); + if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); - var y = iy * segment_height - height_half; + } - for ( var ix = 0; ix < gridX1; ix ++ ) { + } - var x = ix * segment_width - width_half; + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); + this.addAttribute( 'position', positions ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - vertices[ offset ] = x; - vertices[ offset + 1 ] = - y; + this.boundingSphere = new Sphere( new Vector3(), radius ); - normals[ offset + 2 ] = 1; + }; - uvs[ offset2 ] = ix / gridX; - uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); + SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; - offset += 3; - offset2 += 2; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - } + function PointLightHelper ( light, sphereSize ) { + this.isPointLightHelper = this.isMesh = true; - } + this.light = light; + this.light.updateMatrixWorld(); - offset = 0; + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); + Mesh.call( this, geometry, material ); - for ( var iy = 0; iy < gridY; iy ++ ) { + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; - for ( var ix = 0; ix < gridX; ix ++ ) { + /* + var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - 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.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - indices[ offset ] = a; - indices[ offset + 1 ] = b; - indices[ offset + 2 ] = d; + var d = light.distance; - indices[ offset + 3 ] = b; - indices[ offset + 4 ] = c; - indices[ offset + 5 ] = d; + if ( d === 0.0 ) { - offset += 6; + this.lightDistance.visible = false; - } + } else { - } + this.lightDistance.scale.set( d, d, d ); - this.setIndex( 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 ) ); + } -}; + this.add( this.lightDistance ); + */ -THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; + }; -// File:src/extras/geometries/RingBufferGeometry.js + PointLightHelper.prototype = Object.create( Mesh.prototype ); + PointLightHelper.prototype.constructor = PointLightHelper; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + PointLightHelper.prototype.dispose = function () { -THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.geometry.dispose(); + this.material.dispose(); - THREE.BufferGeometry.call( this ); + }; - this.type = 'RingBufferGeometry'; + PointLightHelper.prototype.update = function () { - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - innerRadius = innerRadius || 20; - outerRadius = outerRadius || 50; + /* + var d = this.light.distance; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + if ( d === 0.0 ) { - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + this.lightDistance.visible = false; - // these are used to calculate buffer length - var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); - var indexCount = thetaSegments * phiSegments * 2 * 3; + } else { - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - // some helper variables - var index = 0, indexOffset = 0, segment; - var radius = innerRadius; - var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); - var j, i; + } + */ - // generate vertices, normals and uvs + }; - // values are generate from the inside of the ring to the outside + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( j = 0; j <= phiSegments; j ++ ) { + function SphereGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereGeometry = this.isGeometry = true; - for ( i = 0; i <= thetaSegments; i ++ ) { + Geometry.call( this ); - segment = thetaStart + i / thetaSegments * thetaLength; + this.type = 'SphereGeometry'; - // vertex - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - // normal - normals.setXYZ( index, 0, 0, 1 ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - // uv - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; - uvs.setXY( index, uv.x, uv.y ); + }; - // increase index - index++; + SphereGeometry.prototype = Object.create( Geometry.prototype ); + SphereGeometry.prototype.constructor = SphereGeometry; - } + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - // increase the radius for next row of vertices - radius += radiusStep; + function HemisphereLightHelper ( light, sphereSize ) { + this.isHemisphereLightHelper = this.isObject3D = true; - } + Object3D.call( this ); - // generate indices + this.light = light; + this.light.updateMatrixWorld(); - for ( j = 0; j < phiSegments; j ++ ) { + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - var thetaSegmentLevel = j * ( thetaSegments + 1 ); + this.colors = [ new Color(), new Color() ]; - for ( i = 0; i < thetaSegments; i ++ ) { + var geometry = new SphereGeometry( sphereSize, 4, 2 ); + geometry.rotateX( - Math.PI / 2 ); - segment = i + thetaSegmentLevel; + for ( var i = 0, il = 8; i < il; i ++ ) { - // indices - var a = segment; - var b = segment + thetaSegments + 1; - var c = segment + thetaSegments + 2; - var d = segment + 1; + geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; + } - // face two - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - } + this.lightSphere = new Mesh( geometry, material ); + this.add( this.lightSphere ); - } + this.update(); - // build geometry + }; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); + HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; -}; + HemisphereLightHelper.prototype.dispose = function () { -THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry; + this.lightSphere.geometry.dispose(); + this.lightSphere.material.dispose(); -// File:src/extras/geometries/RingGeometry.js + }; -/** - * @author Kaleb Murphy - */ + HemisphereLightHelper.prototype.update = function () { -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + var vector = new Vector3(); - THREE.Geometry.call( this ); + return function update() { - this.type = 'RingGeometry'; + this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + this.lightSphere.geometry.colorsNeedUpdate = true; - this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + }; -}; + }(); -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; + /** + * @author mrdoob / http://mrdoob.com/ + */ -// File:src/extras/geometries/SphereGeometry.js + function GridHelper ( size, divisions, color1, color2 ) { + this.isGridHelper = this.isLineSegments = true; -/** - * @author mrdoob / http://mrdoob.com/ - */ + divisions = divisions || 1; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + var center = divisions / 2; + var step = ( size * 2 ) / divisions; + var vertices = [], colors = []; - THREE.Geometry.call( this ); + for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { - this.type = 'SphereGeometry'; + vertices.push( - size, 0, k, size, 0, k ); + vertices.push( k, 0, - size, k, 0, size ); - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var color = i === center ? color1 : color2; - this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; -}; + } -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); -// File:src/extras/geometries/SphereBufferGeometry.js + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); -/** - * @author benaadams / https://twitter.com/ben_a_adams - * based on THREE.SphereGeometry - */ + LineSegments.call( this, geometry, material ); -THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + }; - THREE.BufferGeometry.call( this ); + GridHelper.prototype = Object.create( LineSegments.prototype ); + GridHelper.prototype.constructor = GridHelper; - this.type = 'SphereBufferGeometry'; + GridHelper.prototype.setColors = function () { - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - radius = radius || 50; + }; - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + function FaceNormalsHelper ( object, size, hex, linewidth ) { + this.isFaceNormalsHelper = this.isLineSegments = true; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + // FaceNormalsHelper only supports THREE.Geometry - var thetaEnd = thetaStart + thetaLength; + this.object = object; - var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); + this.size = ( size !== undefined ) ? size : 1; - var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var color = ( hex !== undefined ) ? hex : 0xffff00; - var index = 0, vertices = [], normal = new THREE.Vector3(); + var width = ( linewidth !== undefined ) ? linewidth : 1; - for ( var y = 0; y <= heightSegments; y ++ ) { + // - var verticesRow = []; + var nNormals = 0; - var v = y / heightSegments; + var objGeometry = this.object.geometry; - for ( var x = 0; x <= widthSegments; x ++ ) { + if ( (objGeometry && objGeometry.isGeometry) ) { - var u = x / widthSegments; + nNormals = objGeometry.faces.length; - var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - var py = radius * Math.cos( thetaStart + v * thetaLength ); - var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } else { - normal.set( px, py, pz ).normalize(); + console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); - positions.setXYZ( index, px, py, pz ); - normals.setXYZ( index, normal.x, normal.y, normal.z ); - uvs.setXY( index, u, 1 - v ); + } - verticesRow.push( index ); + // - index ++; + var geometry = new BufferGeometry(); - } + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - vertices.push( verticesRow ); + geometry.addAttribute( 'position', positions ); - } + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - var indices = []; + // - for ( var y = 0; y < heightSegments; y ++ ) { + this.matrixAutoUpdate = false; + this.update(); - for ( var x = 0; x < widthSegments; x ++ ) { + }; - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; + FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); + FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; - if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); - if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); + FaceNormalsHelper.prototype.update = ( function () { - } + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - } + return function update() { - this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) ); - this.addAttribute( 'position', positions ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + this.object.updateMatrixWorld( true ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + normalMatrix.getNormalMatrix( this.object.matrixWorld ); -}; + var matrixWorld = this.object.matrixWorld; -THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry; + var position = this.geometry.attributes.position; -// File:src/extras/geometries/TextGeometry.js + // -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: // how far from text outline is bevel - * } - */ + var objGeometry = this.object.geometry; -THREE.TextGeometry = function ( text, parameters ) { + var vertices = objGeometry.vertices; - parameters = parameters || {}; + var faces = objGeometry.faces; - var font = parameters.font; + var idx = 0; - if ( font instanceof THREE.Font === false ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new THREE.Geometry(); + var face = faces[ i ]; - } + var normal = face.normal; - var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); + v1.copy( vertices[ face.a ] ) + .add( vertices[ face.b ] ) + .add( vertices[ face.c ] ) + .divideScalar( 3 ) + .applyMatrix4( matrixWorld ); - // translate parameters to ExtrudeGeometry API + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - parameters.amount = parameters.height !== undefined ? parameters.height : 50; + position.setXYZ( idx, v1.x, v1.y, v1.z ); - // defaults + idx = idx + 1; - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - THREE.ExtrudeGeometry.call( this, shapes, parameters ); + idx = idx + 1; - this.type = 'TextGeometry'; + } -}; + position.needsUpdate = true; -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; + return this; -// File:src/extras/geometries/TorusBufferGeometry.js + }; -/** - * @author Mugen87 / https://github.com/Mugen87 - */ + }() ); -THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { + /** + * @author WestLangley / http://github.com/WestLangley + */ - THREE.BufferGeometry.call( this ); + function EdgesGeometry ( geometry, thresholdAngle ) { + this.isEdgesGeometry = this.isBufferGeometry = true; - this.type = 'TorusBufferGeometry'; + BufferGeometry.call( this ); - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - radius = radius || 100; - tube = tube || 40; - radialSegments = Math.floor( radialSegments ) || 8; - tubularSegments = Math.floor( tubularSegments ) || 6; - arc = arc || Math.PI * 2; + var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + var edge = [ 0, 0 ], hash = {}; - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); + function sortFunction( a, b ) { - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; + return a - b; - // helper variables - var center = new THREE.Vector3(); - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); + } - var j, i; + var keys = [ 'a', 'b', 'c' ]; - // generate vertices, normals and uvs + var geometry2; - for ( j = 0; j <= radialSegments; j ++ ) { + if ( (geometry && geometry.isBufferGeometry) ) { - for ( i = 0; i <= tubularSegments; i ++ ) { + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; + } else { - // vertex - 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 ); + geometry2 = geometry.clone(); - vertices[ vertexBufferOffset ] = vertex.x; - vertices[ vertexBufferOffset + 1 ] = vertex.y; - vertices[ vertexBufferOffset + 2 ] = vertex.z; + } - // this vector is used to calculate the normal - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - // normal - normal.subVectors( vertex, center ).normalize(); + var vertices = geometry2.vertices; + var faces = geometry2.faces; - normals[ vertexBufferOffset ] = normal.x; - normals[ vertexBufferOffset + 1 ] = normal.y; - normals[ vertexBufferOffset + 2 ] = normal.z; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - // uv - uvs[ uvBufferOffset ] = i / tubularSegments; - uvs[ uvBufferOffset + 1 ] = j / radialSegments; + var face = faces[ i ]; - // update offsets - vertexBufferOffset += 3; - uvBufferOffset += 2; + for ( var j = 0; j < 3; j ++ ) { - } + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - } + var key = edge.toString(); - // generate indices + if ( hash[ key ] === undefined ) { - for ( j = 1; j <= radialSegments; j ++ ) { + hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - for ( i = 1; i <= tubularSegments; i ++ ) { + } else { - // indices - 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; + hash[ key ].face2 = i; - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + } - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + } - // update offset - indexBufferOffset += 6; + } - } + var coords = []; - } + for ( var key in hash ) { - // build geometry - this.setIndex( 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 ) ); + var h = hash[ key ]; -}; + if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { -THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry; + var vertex = vertices[ h.vert1 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); -// File:src/extras/geometries/TorusGeometry.js + vertex = vertices[ h.vert2 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); -/** - * @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 ); + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); - this.type = 'TorusGeometry'; + }; - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); + EdgesGeometry.prototype.constructor = EdgesGeometry; - this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + /** + * @author WestLangley / http://github.com/WestLangley + * @param object THREE.Mesh whose geometry will be used + * @param hex line color + * @param thresholdAngle the minimum 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. + */ -}; + function EdgesHelper ( object, hex, thresholdAngle ) { + this.isEdgesHelper = this.isLineSegments = true; -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; + var color = ( hex !== undefined ) ? hex : 0xffffff; -// File:src/extras/geometries/TorusKnotBufferGeometry.js + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); -/** - * @author Mugen87 / https://github.com/Mugen87 - * - * see: http://www.blackpawn.com/texts/pqtorus/ - */ -THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - THREE.BufferGeometry.call( this ); + }; - this.type = 'TorusKnotBufferGeometry'; + EdgesHelper.prototype = Object.create( LineSegments.prototype ); + EdgesHelper.prototype.constructor = EdgesHelper; - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - radius = radius || 100; - tube = tube || 40; - tubularSegments = Math.floor( tubularSegments ) || 64; - radialSegments = Math.floor( radialSegments ) || 8; - p = p || 2; - q = q || 3; + function DirectionalLightHelper ( light, size ) { + this.isDirectionalLightHelper = this.isObject3D = true; - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + Object3D.call( this ); - // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + this.light = light; + this.light.updateMatrixWorld(); - // helper variables - var i, j, index = 0, indexOffset = 0; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); - var uv = new THREE.Vector2(); + if ( size === undefined ) size = 1; - var P1 = new THREE.Vector3(); - var P2 = new THREE.Vector3(); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); - var B = new THREE.Vector3(); - var T = new THREE.Vector3(); - var N = new THREE.Vector3(); + var material = new LineBasicMaterial( { fog: false } ); - // generate vertices, normals and uvs + this.add( new Line( geometry, material ) ); - for ( i = 0; i <= tubularSegments; ++ i ) { + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + this.add( new Line( geometry, material )); - var u = i / tubularSegments * p * Math.PI * 2; + this.update(); - // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. - // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions + }; - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); + DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; - // calculate orthonormal basis + DirectionalLightHelper.prototype.dispose = function () { - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - // normalize B, N. T can be ignored, we don't use it + lightPlane.geometry.dispose(); + lightPlane.material.dispose(); + targetLine.geometry.dispose(); + targetLine.material.dispose(); - B.normalize(); - N.normalize(); + }; - for ( j = 0; j <= radialSegments; ++ j ) { + DirectionalLightHelper.prototype.update = function () { - // now calculate the vertices. they are nothing more than an extrusion of the torus curve. - // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); - var v = j / radialSegments * Math.PI * 2; - var cx = - tube * Math.cos( v ); - var cy = tube * Math.sin( v ); + return function update() { - // now calculate the final vertex position. - // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve + v1.setFromMatrixPosition( this.light.matrixWorld ); + v2.setFromMatrixPosition( this.light.target.matrixWorld ); + v3.subVectors( v2, v1 ); - vertex.x = P1.x + ( cx * N.x + cy * B.x ); - vertex.y = P1.y + ( cx * N.y + cy * B.y ); - vertex.z = P1.z + ( cx * N.z + cy * B.z ); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - // vertex - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + lightPlane.lookAt( v3 ); + lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - normal.subVectors( vertex, P1 ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + targetLine.lookAt( v3 ); + targetLine.scale.z = v3.length(); - // uv - uv.x = i / tubularSegments; - uv.y = j / radialSegments; - uvs.setXY( index, uv.x, uv.y ); + }; - // increase index - index ++; + }(); - } + /** + * @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 + */ - } + function CameraHelper ( camera ) { + this.isCameraHelper = this.isLineSegments = true; - // generate indices + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); - for ( j = 1; j <= tubularSegments; j ++ ) { + var pointMap = {}; - for ( i = 1; i <= radialSegments; i ++ ) { + // colors - // indices - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + var hexFrustum = 0xffaa00; + var hexCone = 0xff0000; + var hexUp = 0x00aaff; + var hexTarget = 0xffffff; + var hexCross = 0x333333; - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + // near - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + addLine( "n1", "n2", hexFrustum ); + addLine( "n2", "n4", hexFrustum ); + addLine( "n4", "n3", hexFrustum ); + addLine( "n3", "n1", hexFrustum ); - } + // far - } + addLine( "f1", "f2", hexFrustum ); + addLine( "f2", "f4", hexFrustum ); + addLine( "f4", "f3", hexFrustum ); + addLine( "f3", "f1", hexFrustum ); - // build geometry + // sides - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + addLine( "n1", "f1", hexFrustum ); + addLine( "n2", "f2", hexFrustum ); + addLine( "n3", "f3", hexFrustum ); + addLine( "n4", "f4", hexFrustum ); - // this function calculates the current position on the torus curve + // cone - function calculatePositionOnCurve( u, p, q, radius, position ) { + addLine( "p", "n1", hexCone ); + addLine( "p", "n2", hexCone ); + addLine( "p", "n3", hexCone ); + addLine( "p", "n4", hexCone ); - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = q / p * u; - var cs = Math.cos( quOverP ); + // up - position.x = radius * ( 2 + cs ) * 0.5 * cu; - position.y = radius * ( 2 + cs ) * su * 0.5; - position.z = radius * Math.sin( quOverP ) * 0.5; + addLine( "u1", "u2", hexUp ); + addLine( "u2", "u3", hexUp ); + addLine( "u3", "u1", hexUp ); - } + // target -}; + addLine( "c", "t", hexTarget ); + addLine( "p", "c", hexCross ); -THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry; + // cross -// File:src/extras/geometries/TorusKnotGeometry.js + addLine( "cn1", "cn2", hexCross ); + addLine( "cn3", "cn4", hexCross ); -/** - * @author oosmoxiecode - */ + addLine( "cf1", "cf2", hexCross ); + addLine( "cf3", "cf4", hexCross ); -THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + function addLine( a, b, hex ) { - THREE.Geometry.call( this ); + addPoint( a, hex ); + addPoint( b, hex ); - this.type = 'TorusKnotGeometry'; + } - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + function addPoint( id, hex ) { - if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); - this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); - this.mergeVertices(); + if ( pointMap[ id ] === undefined ) { -}; + pointMap[ id ] = []; -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; + } -// File:src/extras/geometries/TubeGeometry.js + pointMap[ id ].push( geometry.vertices.length - 1 ); -/** - * @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 ) { + LineSegments.call( this, geometry, material ); - THREE.Geometry.call( this ); + this.camera = camera; + if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); - this.type = 'TubeGeometry'; + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - this.parameters = { - path: path, - segments: segments, - radius: radius, - radialSegments: radialSegments, - closed: closed, - taper: taper - }; + this.pointMap = pointMap; - segments = segments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; - taper = taper || THREE.TubeGeometry.NoTaper; + this.update(); - var grid = []; + }; - var scope = this, + CameraHelper.prototype = Object.create( LineSegments.prototype ); + CameraHelper.prototype.constructor = CameraHelper; - tangent, - normal, - binormal, + CameraHelper.prototype.update = function () { - numpoints = segments + 1, + var geometry, pointMap; - u, v, r, + var vector = new Vector3(); + var camera = new Camera(); - cx, cy, - pos, pos2 = new THREE.Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; + function setPoint( point, x, y, z ) { - var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; + vector.set( x, y, z ).unproject( camera ); - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + var points = pointMap[ point ]; - function vert( x, y, z ) { + if ( points !== undefined ) { - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; + for ( var i = 0, il = points.length; i < il; i ++ ) { - } + geometry.vertices[ points[ i ] ].copy( vector ); - // construct the grid + } - for ( i = 0; i < numpoints; i ++ ) { + } - grid[ i ] = []; + } - u = i / ( numpoints - 1 ); + return function update() { - pos = path.getPointAt( u ); + geometry = this.geometry; + pointMap = this.pointMap; - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; + var w = 1, h = 1; - r = radius * taper( u ); + // we need just camera projection matrix + // world matrix must be identity - for ( j = 0; j < radialSegments; j ++ ) { + camera.projectionMatrix.copy( this.camera.projectionMatrix ); - v = j / radialSegments * 2 * Math.PI; + // center / target - cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = r * Math.sin( v ); + setPoint( "c", 0, 0, - 1 ); + setPoint( "t", 0, 0, 1 ); - 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; + // near - grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); - } + // far - } + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); + setPoint( "f4", w, h, 1 ); + // up - // construct the mesh + setPoint( "u1", w * 0.7, h * 1.1, - 1 ); + setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); + setPoint( "u3", 0, h * 2, - 1 ); - for ( i = 0; i < segments; i ++ ) { + // cross - for ( j = 0; j < radialSegments; j ++ ) { + setPoint( "cf1", - w, 0, 1 ); + setPoint( "cf2", w, 0, 1 ); + setPoint( "cf3", 0, - h, 1 ); + setPoint( "cf4", 0, h, 1 ); - ip = ( closed ) ? ( i + 1 ) % segments : i + 1; - jp = ( j + 1 ) % radialSegments; + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); - a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = grid[ ip ][ j ]; - c = grid[ ip ][ jp ]; - d = grid[ i ][ jp ]; + geometry.verticesNeedUpdate = true; - 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 ); + }; - this.faces.push( new THREE.Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + }(); - this.faces.push( new THREE.Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as + */ - } + function BoxGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxGeometry = this.isGeometry = true; - } + Geometry.call( this ); - this.computeFaceNormals(); - this.computeVertexNormals(); + this.type = 'BoxGeometry'; -}; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); -THREE.TubeGeometry.NoTaper = function ( u ) { + }; - return 1; + BoxGeometry.prototype = Object.create( Geometry.prototype ); + BoxGeometry.prototype.constructor = BoxGeometry; -}; + exports.CubeGeometry = BoxGeometry; -THREE.TubeGeometry.SinusoidalTaper = function ( u ) { + /** + * @author WestLangley / http://github.com/WestLangley + */ - return Math.sin( Math.PI * u ); + // a helper to show the world-axis-aligned bounding box for an object -}; + function BoundingBoxHelper ( object, hex ) { + this.isBoundingBoxHelper = this.isMesh = true; -// For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { + var color = ( hex !== undefined ) ? hex : 0x888888; - var normal = new THREE.Vector3(), + this.object = object; - tangents = [], - normals = [], - binormals = [], + this.box = new Box3(); - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); - numpoints = segments + 1, - theta, - smallest, + }; - tx, ty, tz, - i, u; + BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); + BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; + BoundingBoxHelper.prototype.update = function () { - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + this.box.setFromObject( this.object ); - // compute the tangent vectors for each segment on the path + this.box.size( this.scale ); - for ( i = 0; i < numpoints; i ++ ) { + this.box.center( this.position ); - u = i / ( numpoints - 1 ); + }; - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function BoxHelper ( object, color ) { + this.isBoxHelper = this.isLineSegments = true; - initialNormal3(); + if ( color === undefined ) color = 0xffff00; - /* - 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(); - } + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + var positions = new Float32Array( 8 * 3 ); - function initialNormal2() { + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + if ( object !== undefined ) { - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + this.update( object ); - } - */ + } - function initialNormal3() { + }; - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component + BoxHelper.prototype = Object.create( LineSegments.prototype ); + BoxHelper.prototype.constructor = BoxHelper; - 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 ); + BoxHelper.prototype.update = ( function () { - if ( tx <= smallest ) { + var box = new Box3(); - smallest = tx; - normal.set( 1, 0, 0 ); + return function update( object ) { - } + if ( (object && object.isBox3) ) { - if ( ty <= smallest ) { + box.copy( object ); - smallest = ty; - normal.set( 0, 1, 0 ); + } else { - } + box.setFromObject( object ); - if ( tz <= smallest ) { + } - normal.set( 0, 0, 1 ); + if ( box.isEmpty() ) return; - } + var min = box.min; + var max = box.max; - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + 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 position = this.geometry.attributes.position; + var array = position.array; + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; + array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; + array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; + array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; - // compute the slowly-varying normal and binormal vectors for each segment on the path + position.needsUpdate = true; - for ( i = 1; i < numpoints; i ++ ) { + this.geometry.computeBoundingSphere(); - normals[ i ] = normals[ i - 1 ].clone(); + }; - binormals[ i ] = binormals[ i - 1 ].clone(); + } )(); - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( vec.length() > Number.EPSILON ) { + function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderBufferGeometry = this.isBufferGeometry = true; - vec.normalize(); + BufferGeometry.call( this ); - theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + this.type = 'CylinderBufferGeometry'; - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - } + var scope = this; - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + radiusTop = radiusTop !== undefined ? radiusTop : 20; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; + height = height !== undefined ? height : 100; - } + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + // used to calculate buffer length - if ( closed ) { + var nbCap = 0; - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); - theta /= ( numpoints - 1 ); + if ( openEnded === false ) { - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { + if ( radiusTop > 0 ) nbCap ++; + if ( radiusBottom > 0 ) nbCap ++; - theta = - theta; + } - } + var vertexCount = calculateVertexCount(); + var indexCount = calculateIndexCount(); - for ( i = 1; i < numpoints; i ++ ) { + // buffers - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - } + // helper variables - } + var index = 0, + indexOffset = 0, + indexArray = [], + halfHeight = height / 2; -}; + // group variables + var groupStart = 0; -// File:src/extras/geometries/PolyhedronGeometry.js + // generate geometry -/** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley -*/ + generateTorso(); -THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { + if ( openEnded === false ) { - THREE.Geometry.call( this ); + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - this.type = 'PolyhedronGeometry'; + } - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + // build geometry - radius = radius || 1; - detail = detail || 0; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - var that = this; + // helper functions - for ( var i = 0, l = vertices.length; i < l; i += 3 ) { + function calculateVertexCount() { - prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); - } + if ( openEnded === false ) { - var p = this.vertices; + count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); - var faces = []; + } - for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { + return count; - 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() ] ); + function calculateIndexCount() { - } + var count = radialSegments * heightSegments * 2 * 3; - var centroid = new THREE.Vector3(); + if ( openEnded === false ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + count += radialSegments * nbCap * 3; - subdivide( faces[ i ], detail ); + } - } + return count; + } - // Handle case when face straddles the seam + function generateTorso() { - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { + var x, y; + var normal = new Vector3(); + var vertex = new Vector3(); - var uvs = this.faceVertexUvs[ 0 ][ i ]; + var groupCount = 0; - var x0 = uvs[ 0 ].x; - var x1 = uvs[ 1 ].x; - var x2 = uvs[ 2 ].x; + // this will be used to calculate the normal + var tanTheta = ( radiusBottom - radiusTop ) / height; - var max = Math.max( x0, x1, x2 ); - var min = Math.min( x0, x1, x2 ); + // generate vertices, normals and uvs - if ( max > 0.9 && min < 0.1 ) { + for ( y = 0; y <= heightSegments; y ++ ) { - // 0.9 is somewhat arbitrary + var indexRow = []; - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; + var v = y / heightSegments; - } + // calculate the radius of the current row + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - } + for ( x = 0; x <= radialSegments; x ++ ) { + var u = x / radialSegments; - // Apply radius + // vertex + vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); + vertex.y = - v * height + halfHeight; + vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { + // normal + normal.copy( vertex ); - this.vertices[ i ].multiplyScalar( radius ); + // handle special case if radiusTop/radiusBottom is zero - } + if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + normal.x = Math.sin( u * thetaLength + thetaStart ); + normal.z = Math.cos( u * thetaLength + thetaStart ); - // Merge vertices + } - this.mergeVertices(); + normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - this.computeFaceNormals(); + // uv + uvs.setXY( index, u, 1 - v ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + // save index of vertex in respective row + indexRow.push( index ); + // increase index + index ++; - // Project vector onto sphere's surface + } - function prepare( vector ) { + // now save vertices of the row in our index array + indexArray.push( indexRow ); - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; + } - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. + // generate indices - 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 ); + for ( x = 0; x < radialSegments; x ++ ) { - return vertex; + for ( y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices + var i1 = indexArray[ y ][ x ]; + var i2 = indexArray[ y + 1 ][ x ]; + var i3 = indexArray[ y + 1 ][ x + 1 ]; + var i4 = indexArray[ y ][ x + 1 ]; + // face one + indices.setX( indexOffset, i1 ); indexOffset ++; + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - // Approximate a curved face with recursively sub-divided triangles. + // face two + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i3 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - function make( v1, v2, v3 ) { + // update counters + groupCount += 6; - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - that.faces.push( face ); + } - centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); + } - var azi = azimuth( centroid ); + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, 0 ); - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); + // calculate new start value for groups + groupStart += groupCount; - } + } + function generateCap( top ) { - // Analytically subdivide a face to the required detail level. + var x, centerIndexStart, centerIndexEnd; - function subdivide( face, detail ) { + var uv = new Vector2(); + var vertex = new Vector3(); - 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 groupCount = 0; - // Construct all of the vertices for this subdivision. + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; - for ( var i = 0 ; i <= cols; i ++ ) { + // save the index of the first center vertex + centerIndexStart = index; - v[ i ] = []; + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment - var aj = prepare( a.clone().lerp( c, i / cols ) ); - var bj = prepare( b.clone().lerp( c, i / cols ) ); - var rows = cols - i; + for ( x = 1; x <= radialSegments; x ++ ) { - for ( var j = 0; j <= rows; j ++ ) { + // vertex + vertices.setXYZ( index, 0, halfHeight * sign, 0 ); - if ( j === 0 && i === cols ) { + // normal + normals.setXYZ( index, 0, sign, 0 ); - v[ i ][ j ] = aj; + // uv + uv.x = 0.5; + uv.y = 0.5; - } else { + uvs.setXY( index, uv.x, uv.y ); - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); + // increase index + index ++; - } + } - } + // save the index of the last center vertex + centerIndexEnd = index; - } + // now we generate the surrounding vertices, normals and uvs - // Construct all of the faces. + for ( x = 0; x <= radialSegments; x ++ ) { - for ( var i = 0; i < cols ; i ++ ) { + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; - for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); - var k = Math.floor( j / 2 ); + // vertex + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - if ( j % 2 === 0 ) { + // normal + normals.setXYZ( index, 0, sign, 0 ); - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k ], - v[ i ][ k ] - ); + // uv + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.setXY( index, uv.x, uv.y ); - } else { + // increase index + index ++; - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k + 1 ], - v[ i + 1 ][ k ] - ); + } - } + // generate indices - } + for ( x = 0; x < radialSegments; x ++ ) { - } + var c = centerIndexStart + x; + var i = centerIndexEnd + x; - } + if ( top === true ) { + // face top + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - // Angle around the Y axis, counter-clockwise when looking from above. + } else { - function azimuth( vector ) { + // face bottom + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - return Math.atan2( vector.z, - vector.x ); + } - } + // update counters + groupCount += 3; + } - // Angle above the XZ plane. + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - function inclination( vector ) { + // calculate new start value for groups + groupStart += groupCount; - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + } - } + }; + CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - // Texture fixing helper. Spheres have some odd behaviours. + /** + * @author WestLangley / http://github.com/WestLangley + * @author zz85 / http://github.com/zz85 + * @author bhouston / http://clara.io + * + * Creates an arrow for visualizing directions + * + * Parameters: + * dir - Vector3 + * origin - Vector3 + * length - Number + * color - color in hex value + * headLength - Number + * headWidth - Number + */ - function correctUV( uv, vector, azimuth ) { + exports.ArrowHelper = ( function () { - 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(); + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - } + var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + coneGeometry.translate( 0, - 0.5, 0 ); + return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { -}; + // dir is assumed to be normalized -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; + Object3D.call( this ); -// File:src/extras/geometries/DodecahedronGeometry.js + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; -/** - * @author Abe Pazos / https://hamoid.com - */ + this.position.copy( origin ); -THREE.DodecahedronGeometry = function ( radius, detail ) { - - 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, - - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, - - // (±1/φ, ±φ, 0) - - r, - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, - - // (±φ, 0, ±1/φ) - - t, 0, - r, t, 0, - r, - - t, 0, r, t, 0, r - ]; - - 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 - ]; - - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - - this.type = 'DodecahedronGeometry'; - - this.parameters = { - radius: radius, - detail: detail - }; + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); -}; + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); -THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); -// File:src/extras/geometries/IcosahedronGeometry.js + }; -/** - * @author timothypratley / https://github.com/timothypratley - */ + }() ); -THREE.IcosahedronGeometry = function ( radius, detail ) { + exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); + exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + exports.ArrowHelper.prototype.setDirection = ( function () { - 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 axis = new Vector3(); + var radians; - 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 - ]; + return function setDirection( dir ) { - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + // dir is assumed to be normalized - this.type = 'IcosahedronGeometry'; + if ( dir.y > 0.99999 ) { - this.parameters = { - radius: radius, - detail: detail - }; + this.quaternion.set( 0, 0, 0, 1 ); -}; + } else if ( dir.y < - 0.99999 ) { -THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; + this.quaternion.set( 1, 0, 0, 0 ); -// File:src/extras/geometries/OctahedronGeometry.js + } else { -/** - * @author timothypratley / https://github.com/timothypratley - */ + axis.set( dir.z, 0, - dir.x ).normalize(); -THREE.OctahedronGeometry = function ( radius, detail ) { + radians = Math.acos( dir.y ); - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + this.quaternion.setFromAxisAngle( axis, radians ); - 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 ); + }; - this.type = 'OctahedronGeometry'; + }() ); - this.parameters = { - radius: radius, - detail: detail - }; + exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { -}; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; -THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; + this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); + this.line.updateMatrix(); -// File:src/extras/geometries/TetrahedronGeometry.js + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); -/** - * @author timothypratley / https://github.com/timothypratley - */ + }; -THREE.TetrahedronGeometry = function ( radius, detail ) { + exports.ArrowHelper.prototype.setColor = function ( color ) { - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + this.line.material.color.copy( color ); + this.cone.material.color.copy( color ); - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + }; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + /** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - this.type = 'TetrahedronGeometry'; + function AxisHelper ( size ) { + this.isAxisHelper = this.isLineSegments = true; - this.parameters = { - radius: radius, - detail: detail - }; + 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 + ] ); -THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; + 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 + ] ); -// File:src/extras/geometries/ParametricGeometry.js + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); -/** - * @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 material = new LineBasicMaterial( { vertexColors: VertexColors } ); -THREE.ParametricGeometry = function ( func, slices, stacks ) { + LineSegments.call( this, geometry, material ); - THREE.Geometry.call( this ); + }; - this.type = 'ParametricGeometry'; + AxisHelper.prototype = Object.create( LineSegments.prototype ); + AxisHelper.prototype.constructor = AxisHelper; - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + /** + * @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 verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; + function ParametricGeometry ( func, slices, stacks ) { + this.isParametricGeometry = this.isGeometry = true; - var i, j, p; - var u, v; + Geometry.call( this ); - var sliceCount = slices + 1; + this.type = 'ParametricGeometry'; - for ( i = 0; i <= stacks; i ++ ) { + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - v = i / stacks; + var verts = this.vertices; + var faces = this.faces; + var uvs = this.faceVertexUvs[ 0 ]; - for ( j = 0; j <= slices; j ++ ) { + var i, j, p; + var u, v; - u = j / slices; + var sliceCount = slices + 1; - p = func( u, v ); - verts.push( p ); + for ( i = 0; i <= stacks; i ++ ) { - } + v = i / stacks; - } + for ( j = 0; j <= slices; j ++ ) { - var a, b, c, d; - var uva, uvb, uvc, uvd; + u = j / slices; - for ( i = 0; i < stacks; i ++ ) { + p = func( u, v ); + verts.push( p ); - for ( j = 0; j < slices; j ++ ) { + } - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = ( i + 1 ) * sliceCount + j + 1; - d = ( i + 1 ) * sliceCount + j; + } - 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 a, b, c, d; + var uva, uvb, uvc, uvd; - faces.push( new THREE.Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); + for ( i = 0; i < stacks; i ++ ) { - faces.push( new THREE.Face3( b, c, d ) ); - uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); + for ( j = 0; j < slices; j ++ ) { - } + a = i * sliceCount + j; + b = i * sliceCount + j + 1; + c = ( i + 1 ) * sliceCount + j + 1; + d = ( i + 1 ) * sliceCount + j; - } + uva = new Vector2( j / slices, i / stacks ); + uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); - // console.log(this); + faces.push( new Face3( a, b, d ) ); + uvs.push( [ uva, uvb, uvd ] ); - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); + faces.push( new Face3( b, c, d ) ); + uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - this.computeFaceNormals(); - this.computeVertexNormals(); + } -}; + } -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; + // console.log(this); -// File:src/extras/geometries/WireframeGeometry.js + // magic bullet + // var diff = this.mergeVertices(); + // console.log('removed ', diff, ' vertices by merging'); -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.computeFaceNormals(); + this.computeVertexNormals(); -THREE.WireframeGeometry = function ( geometry ) { + }; - THREE.BufferGeometry.call( this ); + ParametricGeometry.prototype = Object.create( Geometry.prototype ); + ParametricGeometry.prototype.constructor = ParametricGeometry; - var edge = [ 0, 0 ], hash = {}; + /** + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley + */ - function sortFunction( a, b ) { + function PolyhedronGeometry ( vertices, indices, radius, detail ) { + this.isPolyhedronGeometry = this.isGeometry = true; - return a - b; + Geometry.call( this ); - } + this.type = 'PolyhedronGeometry'; - var keys = [ 'a', 'b', 'c' ]; + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - if ( geometry instanceof THREE.Geometry ) { + radius = radius || 1; + detail = detail || 0; - var vertices = geometry.vertices; - var faces = geometry.faces; - var numEdges = 0; + var that = this; - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); + for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - var face = faces[ i ]; + } - for ( var j = 0; j < 3; j ++ ) { + var p = this.vertices; - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + var faces = []; - var key = edge.toString(); + for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { - if ( hash[ key ] === undefined ) { + var v1 = p[ indices[ i ] ]; + var v2 = p[ indices[ i + 1 ] ]; + var v3 = p[ indices[ i + 2 ] ]; - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - } + } - } + var centroid = new Vector3(); - } + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var coords = new Float32Array( numEdges * 2 * 3 ); + subdivide( faces[ i ], detail ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { - var vertex = vertices[ edges [ 2 * i + j ] ]; + // Handle case when face straddles the seam - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; + for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - } + var uvs = this.faceVertexUvs[ 0 ][ i ]; - } + var x0 = uvs[ 0 ].x; + var x1 = uvs[ 1 ].x; + var x2 = uvs[ 2 ].x; - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); - } else if ( geometry instanceof THREE.BufferGeometry ) { + if ( max > 0.9 && min < 0.1 ) { - if ( geometry.index !== null ) { + // 0.9 is somewhat arbitrary - // Indexed BufferGeometry + if ( x0 < 0.2 ) uvs[ 0 ].x += 1; + if ( x1 < 0.2 ) uvs[ 1 ].x += 1; + if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - var indices = geometry.index.array; - var vertices = geometry.attributes.position; - var groups = geometry.groups; - var numEdges = 0; + } - if ( groups.length === 0 ) { + } - geometry.addGroup( 0, indices.length ); - } + // Apply radius - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - for ( var o = 0, ol = groups.length; o < ol; ++ o ) { + this.vertices[ i ].multiplyScalar( radius ); - var group = groups[ o ]; + } - var start = group.start; - var count = group.count; - for ( var i = start, il = start + count; i < il; i += 3 ) { + // Merge vertices - for ( var j = 0; j < 3; j ++ ) { + this.mergeVertices(); - edge[ 0 ] = indices[ i + j ]; - edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); + this.computeFaceNormals(); - var key = edge.toString(); + this.boundingSphere = new Sphere( new Vector3(), radius ); - if ( hash[ key ] === undefined ) { - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + // Project vector onto sphere's surface - } + function prepare( vector ) { - } + var vertex = vector.normalize().clone(); + vertex.index = that.vertices.push( vertex ) - 1; - } + // 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 Vector2( u, 1 - v ); - var coords = new Float32Array( numEdges * 2 * 3 ); + return vertex; - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { - var index = 6 * i + 3 * j; - var index2 = edges[ 2 * i + j ]; + // Approximate a curved face with recursively sub-divided triangles. - coords[ index + 0 ] = vertices.getX( index2 ); - coords[ index + 1 ] = vertices.getY( index2 ); - coords[ index + 2 ] = vertices.getZ( index2 ); + function make( v1, v2, v3 ) { - } + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + that.faces.push( face ); - } + centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + var azi = azimuth( centroid ); - } else { + that.faceVertexUvs[ 0 ].push( [ + correctUV( v1.uv, v1, azi ), + correctUV( v2.uv, v2, azi ), + correctUV( v3.uv, v3, azi ) + ] ); - // non-indexed BufferGeometry + } - var vertices = geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; - var coords = new Float32Array( numEdges * 2 * 3 ); + // Analytically subdivide a face to the required detail level. - for ( var i = 0, l = numTris; i < l; i ++ ) { + function subdivide( face, detail ) { - for ( var j = 0; j < 3; j ++ ) { + 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 index = 18 * i + 6 * j; + // Construct all of the vertices for this subdivision. - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; + for ( var i = 0 ; i <= cols; i ++ ) { - 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 ]; + v[ i ] = []; - } + var aj = prepare( a.clone().lerp( c, i / cols ) ); + var bj = prepare( b.clone().lerp( c, i / cols ) ); + var rows = cols - i; - } + for ( var j = 0; j <= rows; j ++ ) { - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + if ( j === 0 && i === cols ) { - } + v[ i ][ j ] = aj; - } + } else { -}; + v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); -THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry; + } -// File:src/extras/helpers/AxisHelper.js + } -/** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.AxisHelper = function ( size ) { + // Construct all of the faces. - size = size || 1; + for ( var i = 0; i < cols ; i ++ ) { - var vertices = new Float32Array( [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ] ); + for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - 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 k = Math.floor( j / 2 ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + if ( j % 2 === 0 ) { - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k ], + v[ i ][ k ] + ); - THREE.LineSegments.call( this, geometry, material ); + } else { -}; + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k + 1 ], + v[ i + 1 ][ k ] + ); -THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; + } -// File:src/extras/helpers/ArrowHelper.js + } -/** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://clara.io - * - * 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 lineGeometry = new THREE.BufferGeometry(); - lineGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - var coneGeometry = new THREE.CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.translate( 0, - 0.5, 0 ); + // Angle around the Y axis, counter-clockwise when looking from above. - return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { + function azimuth( vector ) { - // dir is assumed to be normalized + return Math.atan2( vector.z, - vector.x ); - THREE.Object3D.call( this ); + } - 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 ); + // Angle above the XZ plane. - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + function inclination( vector ) { - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + } - }; -}() ); + // Texture fixing helper. Spheres have some odd behaviours. -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; + function correctUV( uv, vector, azimuth ) { -THREE.ArrowHelper.prototype.setDirection = ( function () { + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); + return uv.clone(); - var axis = new THREE.Vector3(); - var radians; + } - return function setDirection( dir ) { - // dir is assumed to be normalized + }; - if ( dir.y > 0.99999 ) { + PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); + PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; - this.quaternion.set( 0, 0, 0, 1 ); + /** + * @author timothypratley / https://github.com/timothypratley + */ - } else if ( dir.y < - 0.99999 ) { + function TetrahedronGeometry ( radius, detail ) { + this.isTetrahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; - this.quaternion.set( 1, 0, 0, 0 ); + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - } else { + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - axis.set( dir.z, 0, - dir.x ).normalize(); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - radians = Math.acos( dir.y ); + this.type = 'TetrahedronGeometry'; - this.quaternion.setFromAxisAngle( axis, radians ); + this.parameters = { + radius: radius, + detail: detail + }; - } + }; - }; + TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; -}() ); + /** + * @author timothypratley / https://github.com/timothypratley + */ -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + function OctahedronGeometry ( radius, detail ) { + this.isOctahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); - this.line.updateMatrix(); + 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 + ]; - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); -}; + this.type = 'OctahedronGeometry'; -THREE.ArrowHelper.prototype.setColor = function ( color ) { + this.parameters = { + radius: radius, + detail: detail + }; - this.line.material.color.copy( color ); - this.cone.material.color.copy( color ); + }; -}; + OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + OctahedronGeometry.prototype.constructor = OctahedronGeometry; -// File:src/extras/helpers/BoxHelper.js + /** + * @author timothypratley / https://github.com/timothypratley + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + function IcosahedronGeometry ( radius, detail ) { + this.isIcosahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; -THREE.BoxHelper = function ( object, color ) { + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - if ( color === undefined ) color = 0xffff00; + 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 = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); - var positions = new Float32Array( 8 * 3 ); + 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 + ]; - var geometry = new THREE.BufferGeometry(); - geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.type = 'IcosahedronGeometry'; - if ( object !== undefined ) { + this.parameters = { + radius: radius, + detail: detail + }; - this.update( object ); + }; - } + IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; -}; + /** + * @author Abe Pazos / https://hamoid.com + */ -THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; + function DodecahedronGeometry ( radius, detail ) { + this.isDodecahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; -THREE.BoxHelper.prototype.update = ( function () { + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - var box = new THREE.Box3(); + var vertices = [ - return function update( object ) { + // (±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 ( object instanceof THREE.Box3 ) { + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, - box.copy( object ); + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - } else { + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - box.setFromObject( object ); + 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 + ]; - } + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - if ( box.isEmpty() ) return; + this.type = 'DodecahedronGeometry'; - var min = box.min; - var max = box.max; + this.parameters = { + radius: radius, + detail: detail + }; - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + }; - 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 - */ + DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; - var position = this.geometry.attributes.position; - var array = position.array; + /** + * @author Mugen87 / https://github.com/Mugen87 + * + * see: http://www.blackpawn.com/texts/pqtorus/ + */ + function TorusKnotBufferGeometry ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.isTorusKnotBufferGeometry = this.isBufferGeometry = true; - array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; - array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; - array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; - array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; - array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; - array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; - array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; - array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; + BufferGeometry.call( this ); - position.needsUpdate = true; + this.type = 'TorusKnotBufferGeometry'; - this.geometry.computeBoundingSphere(); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - }; + radius = radius || 100; + tube = tube || 40; + tubularSegments = Math.floor( tubularSegments ) || 64; + radialSegments = Math.floor( radialSegments ) || 8; + p = p || 2; + q = q || 3; -} )(); + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; -// File:src/extras/helpers/BoundingBoxHelper.js + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); -/** - * @author WestLangley / http://github.com/WestLangley - */ + // helper variables + var i, j, index = 0, indexOffset = 0; -// a helper to show the world-axis-aligned bounding box for an object + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); -THREE.BoundingBoxHelper = function ( object, hex ) { + var P1 = new Vector3(); + var P2 = new Vector3(); - var color = ( hex !== undefined ) ? hex : 0x888888; + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); - this.object = object; + // generate vertices, normals and uvs - this.box = new THREE.Box3(); + for ( i = 0; i <= tubularSegments; ++ i ) { - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); + // the radian "u" is used to calculate the position on the torus curve of the current tubular segement -}; + var u = i / tubularSegments * p * Math.PI * 2; -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions -THREE.BoundingBoxHelper.prototype.update = function () { + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - this.box.setFromObject( this.object ); + // calculate orthonormal basis - this.box.size( this.scale ); + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - this.box.center( this.position ); + // normalize B, N. T can be ignored, we don't use it -}; + B.normalize(); + N.normalize(); -// File:src/extras/helpers/CameraHelper.js + for ( j = 0; j <= radialSegments; ++ j ) { -/** - * @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 - */ + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. -THREE.CameraHelper = function ( camera ) { + var v = j / radialSegments * Math.PI * 2; + var cx = - tube * Math.cos( v ); + var cy = tube * Math.sin( v ); - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve - var pointMap = {}; + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); - // colors + // vertex + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) + normal.subVectors( vertex, P1 ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - // near + // uv + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.setXY( index, uv.x, uv.y ); - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); + // increase index + index ++; - // far + } - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); + } - // sides + // generate indices - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); + for ( j = 1; j <= tubularSegments; j ++ ) { - // cone + for ( i = 1; i <= radialSegments; i ++ ) { - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); + // indices + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - // up + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - // target + } - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); + } - // cross + // build geometry - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); + // this function calculates the current position on the torus curve - function addLine( a, b, hex ) { + function calculatePositionOnCurve( u, p, q, radius, position ) { - addPoint( a, hex ); - addPoint( b, hex ); + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = q / p * u; + var cs = Math.cos( quOverP ); - } + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - function addPoint( id, hex ) { + } - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); + }; - if ( pointMap[ id ] === undefined ) { + TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - pointMap[ id ] = []; + /** + * @author oosmoxiecode + */ - } + function TorusKnotGeometry ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + this.isTorusKnotGeometry = this.isGeometry = true; - pointMap[ id ].push( geometry.vertices.length - 1 ); + Geometry.call( this ); - } + this.type = 'TorusKnotGeometry'; - THREE.LineSegments.call( this, geometry, material ); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - this.camera = camera; - if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.mergeVertices(); - this.pointMap = pointMap; + }; - this.update(); + TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); + TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; -}; + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; + function TorusBufferGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusBufferGeometry = this.isBufferGeometry = true; -THREE.CameraHelper.prototype.update = function () { + BufferGeometry.call( this ); - var geometry, pointMap; + this.type = 'TorusBufferGeometry'; - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - function setPoint( point, x, y, z ) { + radius = radius || 100; + tube = tube || 40; + radialSegments = Math.floor( radialSegments ) || 8; + tubularSegments = Math.floor( tubularSegments ) || 6; + arc = arc || Math.PI * 2; - vector.set( x, y, z ).unproject( camera ); + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; - var points = pointMap[ point ]; + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); - if ( points !== undefined ) { + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; - for ( var i = 0, il = points.length; i < il; i ++ ) { + // helper variables + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); - geometry.vertices[ points[ i ] ].copy( vector ); + var j, i; - } + // generate vertices, normals and uvs - } + for ( j = 0; j <= radialSegments; j ++ ) { - } + for ( i = 0; i <= tubularSegments; i ++ ) { - return function update() { + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - geometry = this.geometry; - pointMap = this.pointMap; + // vertex + 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 ); - var w = 1, h = 1; + vertices[ vertexBufferOffset ] = vertex.x; + vertices[ vertexBufferOffset + 1 ] = vertex.y; + vertices[ vertexBufferOffset + 2 ] = vertex.z; - // we need just camera projection matrix - // world matrix must be identity + // this vector is used to calculate the normal + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); - camera.projectionMatrix.copy( this.camera.projectionMatrix ); + // normal + normal.subVectors( vertex, center ).normalize(); - // center / target + normals[ vertexBufferOffset ] = normal.x; + normals[ vertexBufferOffset + 1 ] = normal.y; + normals[ vertexBufferOffset + 2 ] = normal.z; - setPoint( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + // uv + uvs[ uvBufferOffset ] = i / tubularSegments; + uvs[ uvBufferOffset + 1 ] = j / radialSegments; - // near + // update offsets + vertexBufferOffset += 3; + uvBufferOffset += 2; - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + } - // far + } - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + // generate indices - // up + for ( j = 1; j <= radialSegments; j ++ ) { - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + for ( i = 1; i <= tubularSegments; i ++ ) { - // cross + // indices + 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; - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - geometry.verticesNeedUpdate = true; + // update offset + indexBufferOffset += 6; - }; + } -}(); + } -// File:src/extras/helpers/DirectionalLightHelper.js + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + }; -THREE.DirectionalLightHelper = function ( light, size ) { + TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - THREE.Object3D.call( this ); + /** + * @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 + */ - this.light = light; - this.light.updateMatrixWorld(); + function TorusGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusGeometry = this.isGeometry = true; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + Geometry.call( this ); - if ( size === undefined ) size = 1; + this.type = 'TorusGeometry'; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - var material = new THREE.LineBasicMaterial( { fog: false } ); + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); - this.add( new THREE.Line( geometry, material ) ); + }; - geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + TorusGeometry.prototype = Object.create( Geometry.prototype ); + TorusGeometry.prototype.constructor = TorusGeometry; - this.add( new THREE.Line( geometry, material )); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * Text = 3D Text + * + * parameters = { + * font: , // font + * + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: // how far from text outline is bevel + * } + */ - this.update(); + function TextGeometry ( text, parameters ) { + this.isTextGeometry = this.isExtrudeGeometry = this.isGeometry = true; -}; + parameters = parameters || {}; -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; + var font = parameters.font; -THREE.DirectionalLightHelper.prototype.dispose = function () { + if ( (font && font.isFont) === false ) { - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); + return new Geometry(); - lightPlane.geometry.dispose(); - lightPlane.material.dispose(); - targetLine.geometry.dispose(); - targetLine.material.dispose(); + } -}; + var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); -THREE.DirectionalLightHelper.prototype.update = function () { + // translate parameters to ExtrudeGeometry API - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); + parameters.amount = parameters.height !== undefined ? parameters.height : 50; - return function update() { + // defaults - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + ExtrudeGeometry.call( this, shapes, parameters ); - lightPlane.lookAt( v3 ); - lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.type = 'TextGeometry'; - targetLine.lookAt( v3 ); - targetLine.scale.z = v3.length(); + }; - }; + TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); + TextGeometry.prototype.constructor = TextGeometry; -}(); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ -// File:src/extras/helpers/EdgesHelper.js + function RingBufferGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingBufferGeometry = this.isBufferGeometry = true; -/** - * @author WestLangley / http://github.com/WestLangley - * @param object THREE.Mesh whose geometry will be used - * @param hex line color - * @param thresholdAngle the minimum 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. - */ + BufferGeometry.call( this ); -THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { + this.type = 'RingBufferGeometry'; - var color = ( hex !== undefined ) ? hex : 0xffffff; + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) ); + innerRadius = innerRadius || 20; + outerRadius = outerRadius || 50; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; -}; + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; -THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; + // these are used to calculate buffer length + var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); + var indexCount = thetaSegments * phiSegments * 2 * 3; -// File:src/extras/helpers/FaceNormalsHelper.js + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + // some helper variables + var index = 0, indexOffset = 0, segment; + var radius = innerRadius; + var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + var vertex = new Vector3(); + var uv = new Vector2(); + var j, i; -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { + // generate vertices, normals and uvs - // FaceNormalsHelper only supports THREE.Geometry + // values are generate from the inside of the ring to the outside - this.object = object; + for ( j = 0; j <= phiSegments; j ++ ) { - this.size = ( size !== undefined ) ? size : 1; + for ( i = 0; i <= thetaSegments; i ++ ) { - var color = ( hex !== undefined ) ? hex : 0xffff00; + segment = thetaStart + i / thetaSegments * thetaLength; - var width = ( linewidth !== undefined ) ? linewidth : 1; + // vertex + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - // + // normal + normals.setXYZ( index, 0, 0, 1 ); - var nNormals = 0; + // uv + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + uvs.setXY( index, uv.x, uv.y ); - var objGeometry = this.object.geometry; + // increase index + index++; - if ( objGeometry instanceof THREE.Geometry ) { + } - nNormals = objGeometry.faces.length; + // increase the radius for next row of vertices + radius += radiusStep; - } else { + } - console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); + // generate indices - } + for ( j = 0; j < phiSegments; j ++ ) { - // + var thetaSegmentLevel = j * ( thetaSegments + 1 ); - var geometry = new THREE.BufferGeometry(); + for ( i = 0; i < thetaSegments; i ++ ) { - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + segment = i + thetaSegmentLevel; - geometry.addAttribute( 'position', positions ); + // indices + var a = segment; + var b = segment + thetaSegments + 1; + var c = segment + thetaSegments + 2; + var d = segment + 1; - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; - // + // face two + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - this.matrixAutoUpdate = false; - this.update(); + } -}; + } -THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; + // build geometry -THREE.FaceNormalsHelper.prototype.update = ( function () { + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + }; - return function update() { + RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + RingBufferGeometry.prototype.constructor = RingBufferGeometry; - this.object.updateMatrixWorld( true ); + /** + * @author Kaleb Murphy + */ - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + function RingGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingGeometry = this.isGeometry = true; - var matrixWorld = this.object.matrixWorld; + Geometry.call( this ); - var position = this.geometry.attributes.position; + this.type = 'RingGeometry'; - // + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - var objGeometry = this.object.geometry; + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); - var vertices = objGeometry.vertices; + }; - var faces = objGeometry.faces; + RingGeometry.prototype = Object.create( Geometry.prototype ); + RingGeometry.prototype.constructor = RingGeometry; - var idx = 0; + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - for ( var i = 0, l = faces.length; i < l; i ++ ) { + function PlaneGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneGeometry = this.isGeometry = true; - var face = faces[ i ]; + Geometry.call( this ); - var normal = face.normal; + this.type = 'PlaneGeometry'; - v1.copy( vertices[ face.a ] ) - .add( vertices[ face.b ] ) - .add( vertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( matrixWorld ); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - position.setXYZ( idx, v1.x, v1.y, v1.z ); + }; - idx = idx + 1; + PlaneGeometry.prototype = Object.create( Geometry.prototype ); + PlaneGeometry.prototype.constructor = PlaneGeometry; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - idx = idx + 1; + // 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 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - } + function LatheBufferGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheBufferGeometry = this.isBufferGeometry = true; - position.needsUpdate = true; + BufferGeometry.call( this ); - return this; + this.type = 'LatheBufferGeometry'; - }; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; -}() ); + segments = Math.floor( segments ) || 12; + phiStart = phiStart || 0; + phiLength = phiLength || Math.PI * 2; -// File:src/extras/helpers/GridHelper.js + // clamp phiLength so it's in range of [ 0, 2PI ] + phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + // these are used to calculate buffer length + var vertexCount = ( segments + 1 ) * points.length; + var indexCount = segments * points.length * 2 * 3; -THREE.GridHelper = function ( size, divisions, color1, color2 ) { + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - divisions = divisions || 1; - color1 = new THREE.Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new THREE.Color( color2 !== undefined ? color2 : 0x888888 ); + // helper variables + var index = 0, indexOffset = 0, base; + var inversePointLength = 1.0 / ( points.length - 1 ); + var inverseSegments = 1.0 / segments; + var vertex = new Vector3(); + var uv = new Vector2(); + var i, j; - var center = divisions / 2; - var step = ( size * 2 ) / divisions; - var vertices = [], colors = []; + // generate vertices and uvs - for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { + for ( i = 0; i <= segments; i ++ ) { - vertices.push( - size, 0, k, size, 0, k ); - vertices.push( k, 0, - size, k, 0, size ); + var phi = phiStart + i * inverseSegments * phiLength; - var color = i === center ? color1 : color2; + var sin = Math.sin( phi ); + var cos = Math.cos( phi ); - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + for ( j = 0; j <= ( points.length - 1 ); j ++ ) { - } + // vertex + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.Float32Attribute( colors, 3 ) ); + // uv + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + uvs.setXY( index, uv.x, uv.y ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + // increase index + index ++; - THREE.LineSegments.call( this, geometry, material ); + } -}; + } -THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.GridHelper.prototype.constructor = THREE.GridHelper; + // generate indices -THREE.GridHelper.prototype.setColors = function () { + for ( i = 0; i < segments; i ++ ) { - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + for ( j = 0; j < ( points.length - 1 ); j ++ ) { -}; + base = j + i * points.length; -// File:src/extras/helpers/HemisphereLightHelper.js + // indices + var a = base; + var b = base + points.length; + var c = base + points.length + 1; + var d = base + 1; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; -THREE.HemisphereLightHelper = function ( light, sphereSize ) { + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - THREE.Object3D.call( this ); + } - this.light = light; - this.light.updateMatrixWorld(); + } - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + // build geometry - this.colors = [ new THREE.Color(), new THREE.Color() ]; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'uv', uvs ); - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); - geometry.rotateX( - Math.PI / 2 ); + // generate normals - for ( var i = 0, il = 8; i < il; i ++ ) { + this.computeVertexNormals(); - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; + // if the geometry is closed, we need to average the normals along the seam. + // because the corresponding vertices are identical (but still have different UVs). - } + if( phiLength === Math.PI * 2 ) { - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); + var normals = this.attributes.normal.array; + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); - this.lightSphere = new THREE.Mesh( geometry, material ); - this.add( this.lightSphere ); + // this is the buffer offset for the last line of vertices + base = segments * points.length * 3; - this.update(); + for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { -}; + // select the normal of the vertex in the first line + n1.x = normals[ j + 0 ]; + n1.y = normals[ j + 1 ]; + n1.z = normals[ j + 2 ]; -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; + // select the normal of the vertex in the last line + n2.x = normals[ base + j + 0 ]; + n2.y = normals[ base + j + 1 ]; + n2.z = normals[ base + j + 2 ]; -THREE.HemisphereLightHelper.prototype.dispose = function () { + // average normals + n.addVectors( n1, n2 ).normalize(); - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); + // assign the new values to both normals + normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; + normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; + normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; -}; + } // next row -THREE.HemisphereLightHelper.prototype.update = function () { + } - var vector = new THREE.Vector3(); + }; - return function update() { + LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); + /** + * @author astrodud / http://astrodud.isgreat.org/ + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://clara.io + */ - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; + // 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 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - }; + function LatheGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheGeometry = this.isGeometry = true; -}(); + Geometry.call( this ); -// File:src/extras/helpers/PointLightHelper.js + this.type = 'LatheGeometry'; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; -THREE.PointLightHelper = function ( light, sphereSize ) { + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.mergeVertices(); - this.light = light; - this.light.updateMatrixWorld(); + }; - var geometry = new THREE.SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + LatheGeometry.prototype = Object.create( Geometry.prototype ); + LatheGeometry.prototype.constructor = LatheGeometry; - THREE.Mesh.call( this, geometry, material ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + function CylinderGeometry ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderGeometry = this.isGeometry = true; - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + Geometry.call( this ); - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + this.type = 'CylinderGeometry'; - var d = light.distance; + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - if ( d === 0.0 ) { + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.mergeVertices(); - this.lightDistance.visible = false; + }; - } else { + CylinderGeometry.prototype = Object.create( Geometry.prototype ); + CylinderGeometry.prototype.constructor = CylinderGeometry; - this.lightDistance.scale.set( d, d, d ); + /** + * @author abelnation / http://github.com/abelnation + */ - } + function ConeGeometry ( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { + this.isConeGeometry = this.isCylinderGeometry = this.isGeometry = true; - this.add( this.lightDistance ); - */ + CylinderGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); -}; + this.type = 'ConeGeometry'; -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; -THREE.PointLightHelper.prototype.dispose = function () { + }; - this.geometry.dispose(); - this.material.dispose(); + ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); + ConeGeometry.prototype.constructor = ConeGeometry; -}; + /* + * @author: abelnation / http://github.com/abelnation + */ -THREE.PointLightHelper.prototype.update = function () { + function ConeBufferGeometry ( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { + this.isConeBufferGeometry = this.isBufferGeometry = true; - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + CylinderBufferGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); - /* - var d = this.light.distance; + this.type = 'ConeBufferGeometry'; - if ( d === 0.0 ) { + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.lightDistance.visible = false; + }; - } else { + ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - } - */ + function CircleBufferGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleBufferGeometry = this.isBufferGeometry = true; -}; + BufferGeometry.call( this ); -// File:src/extras/helpers/SkeletonHelper.js + this.type = 'CircleBufferGeometry'; -/** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - */ + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; -THREE.SkeletonHelper = function ( object ) { + radius = radius || 50; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; - this.bones = this.getBoneList( object ); + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - var geometry = new THREE.Geometry(); + var vertices = segments + 2; - for ( var i = 0; i < this.bones.length; i ++ ) { + var positions = new Float32Array( vertices * 3 ); + var normals = new Float32Array( vertices * 3 ); + var uvs = new Float32Array( vertices * 2 ); - var bone = this.bones[ i ]; + // center data is already zero, but need to set a few extras + normals[ 2 ] = 1.0; + uvs[ 0 ] = 0.5; + uvs[ 1 ] = 0.5; - if ( bone.parent instanceof THREE.Bone ) { + for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { - 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 ) ); + var segment = thetaStart + s / segments * thetaLength; - } + positions[ i ] = radius * Math.cos( segment ); + positions[ i + 1 ] = radius * Math.sin( segment ); - } + normals[ i + 2 ] = 1; // normal z - geometry.dynamic = true; + uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; + uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + } - THREE.LineSegments.call( this, geometry, material ); + var indices = []; - this.root = object; + for ( var i = 1; i <= segments; i ++ ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + indices.push( i, i + 1, 0 ); - this.update(); + } -}; + this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + this.boundingSphere = new Sphere( new Vector3(), radius ); -THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; + }; -THREE.SkeletonHelper.prototype.getBoneList = function( object ) { + CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; - var boneList = []; + /** + * @author hughes + */ - if ( object instanceof THREE.Bone ) { + function CircleGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleGeometry = this.isGeometry = true; - boneList.push( object ); + Geometry.call( this ); - } + this.type = 'CircleGeometry'; - for ( var i = 0; i < object.children.length; i ++ ) { + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); - } + }; - return boneList; + CircleGeometry.prototype = Object.create( Geometry.prototype ); + CircleGeometry.prototype.constructor = CircleGeometry; -}; + /** + * @author zz85 https://github.com/zz85 + * + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ -THREE.SkeletonHelper.prototype.update = function () { + exports.CatmullRomCurve3 = ( function() { - var geometry = this.geometry; + var + tmp = new Vector3(), + px = new CubicPoly(), + py = new CubicPoly(), + pz = new CubicPoly(); - var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + /* + Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM - var boneMatrix = new THREE.Matrix4(); + This CubicPoly class could be used for reusing some variables and calculations, + but for three.js curve use, it could be possible inlined and flatten into a single function call + which can be placed in CurveUtils. + */ - var j = 0; + function CubicPoly() { - for ( var i = 0; i < this.bones.length; i ++ ) { + } - var bone = this.bones[ i ]; + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { - if ( bone.parent instanceof THREE.Bone ) { + this.c0 = x0; + this.c1 = t0; + this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + this.c3 = 2 * x0 - 2 * x1 + t0 + t1; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); - geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + }; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); + CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { - j += 2; + // compute tangents when parameterized in [t1,t2] + var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - } + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - } + // initCubicPoly + this.init( x1, x2, t1, t2 ); - geometry.verticesNeedUpdate = true; + }; - geometry.computeBoundingSphere(); + // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 + CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { -}; + this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); -// File:src/extras/helpers/SpotLightHelper.js + }; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + CubicPoly.prototype.calc = function( t ) { -THREE.SpotLightHelper = function ( light ) { + var t2 = t * t; + var t3 = t2 * t; + return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; - THREE.Object3D.call( this ); + }; - this.light = light; - this.light.updateMatrixWorld(); + // Subclass Three.js curve + return Curve.create( - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + function ( p /* array of Vector3 */ ) { - var geometry = new THREE.BufferGeometry(); + this.points = p || []; + this.closed = false; - var positions = [ - 0, 0, 0, 0, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, - 1, 0, 1, - 0, 0, 0, 0, 1, 1, - 0, 0, 0, 0, - 1, 1 - ]; + }, - for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + function ( t ) { - var p1 = ( i / l ) * Math.PI * 2; - var p2 = ( j / l ) * Math.PI * 2; + var points = this.points, + point, intPoint, weight, l; - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + l = points.length; - } + if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); - geometry.addAttribute( 'position', new THREE.Float32Attribute( positions, 3 ) ); + point = ( l - ( this.closed ? 0 : 1 ) ) * t; + intPoint = Math.floor( point ); + weight = point - intPoint; - var material = new THREE.LineBasicMaterial( { fog: false } ); + if ( this.closed ) { - this.cone = new THREE.LineSegments( geometry, material ); - this.add( this.cone ); + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - this.update(); + } else if ( weight === 0 && intPoint === l - 1 ) { -}; + intPoint = l - 2; + weight = 1; -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; + } -THREE.SpotLightHelper.prototype.dispose = function () { + var p0, p1, p2, p3; // 4 points - this.cone.geometry.dispose(); - this.cone.material.dispose(); + if ( this.closed || intPoint > 0 ) { -}; + p0 = points[ ( intPoint - 1 ) % l ]; -THREE.SpotLightHelper.prototype.update = function () { + } else { - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - return function update() { + } - var coneLength = this.light.distance ? this.light.distance : 1000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + p1 = points[ intPoint % l ]; + p2 = points[ ( intPoint + 1 ) % l ]; - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + if ( this.closed || intPoint + 2 < l ) { - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + p3 = points[ ( intPoint + 2 ) % l ]; - this.cone.lookAt( vector2.sub( vector ) ); + } else { - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - }; + } -}(); + if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { -// File:src/extras/helpers/VertexNormalsHelper.js + // init Centripetal / Chordal Catmull-Rom + var pow = this.type === 'chordal' ? 0.5 : 0.25; + var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley -*/ + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - this.object = object; + } else if ( this.type === 'catmullrom' ) { - this.size = ( size !== undefined ) ? size : 1; + var tension = this.tension !== undefined ? this.tension : 0.5; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); - var color = ( hex !== undefined ) ? hex : 0xff0000; + } - var width = ( linewidth !== undefined ) ? linewidth : 1; + var v = new Vector3( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - // + return v; - var nNormals = 0; + } - var objGeometry = this.object.geometry; + ); - if ( objGeometry instanceof THREE.Geometry ) { + } )(); - nNormals = objGeometry.faces.length * 3; + /************************************************************** + * Closed Spline 3D curve + **************************************************************/ - } else if ( objGeometry instanceof THREE.BufferGeometry ) { - nNormals = objGeometry.attributes.normal.count; + function ClosedSplineCurve3 ( points ) { + this.isClosedSplineCurve3 = this.isCatmullRomCurve3 = true; - } + console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); - // + exports.CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; + this.closed = true; - var geometry = new THREE.BufferGeometry(); + }; - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype ); - geometry.addAttribute( 'position', positions ); + /************************************************************** + * Spline 3D curve + **************************************************************/ - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); - // + exports.SplineCurve3 = Curve.create( - this.matrixAutoUpdate = false; + function ( points /* array of Vector3 */ ) { - this.update(); + console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); + this.points = ( points == undefined ) ? [] : points; -}; + }, -THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; + function ( t ) { -THREE.VertexNormalsHelper.prototype.update = ( function () { + var points = this.points; + var point = ( points.length - 1 ) * t; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var intPoint = Math.floor( point ); + var weight = point - intPoint; - return function update() { + 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 keys = [ 'a', 'b', 'c' ]; + var interpolate = exports.CurveUtils.interpolate; - this.object.updateMatrixWorld( true ); + return new Vector3( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ), + interpolate( point0.z, point1.z, point2.z, point3.z, weight ) + ); - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + } - var matrixWorld = this.object.matrixWorld; + ); - var position = this.geometry.attributes.position; + /************************************************************** + * Cubic Bezier 3D curve + **************************************************************/ - // + exports.CubicBezierCurve3 = Curve.create( - var objGeometry = this.object.geometry; + function ( v0, v1, v2, v3 ) { - if ( objGeometry instanceof THREE.Geometry ) { + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - var vertices = objGeometry.vertices; + }, - var faces = objGeometry.faces; + function ( t ) { - var idx = 0; + var b3 = exports.ShapeUtils.b3; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + return new Vector3( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), + b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) + ); - var face = faces[ i ]; + } - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + ); - var vertex = vertices[ face[ keys[ j ] ] ]; + /************************************************************** + * Quadratic Bezier 3D curve + **************************************************************/ - var normal = face.vertexNormals[ j ]; + exports.QuadraticBezierCurve3 = Curve.create( - v1.copy( vertex ).applyMatrix4( matrixWorld ); + function ( v0, v1, v2 ) { - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - position.setXYZ( idx, v1.x, v1.y, v1.z ); + }, - idx = idx + 1; + function ( t ) { - position.setXYZ( idx, v2.x, v2.y, v2.z ); + var b2 = exports.ShapeUtils.b2; - idx = idx + 1; + return new Vector3( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ), + b2( t, this.v0.z, this.v1.z, this.v2.z ) + ); - } + } - } + ); - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + /************************************************************** + * Line3D + **************************************************************/ - var objPos = objGeometry.attributes.position; + exports.LineCurve3 = Curve.create( - var objNorm = objGeometry.attributes.normal; + function ( v1, v2 ) { - var idx = 0; + this.v1 = v1; + this.v2 = v2; - // for simplicity, ignore index and drawcalls, and render every normal + }, - for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { + function ( t ) { - v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); + if ( t === 1 ) { - v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); + return this.v2.clone(); - v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } - position.setXYZ( idx, v1.x, v1.y, v1.z ); + var vector = new Vector3(); - idx = idx + 1; + vector.subVectors( this.v2, this.v1 ); // diff + vector.multiplyScalar( t ); + vector.add( this.v1 ); - position.setXYZ( idx, v2.x, v2.y, v2.z ); + return vector; - idx = idx + 1; + } - } + ); - } + /************************************************************** + * Arc curve + **************************************************************/ - position.needsUpdate = true; + function ArcCurve ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.isArcCurve = this.isEllipseCurve = this.isCurve = true; - return this; + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - }; + }; -}() ); + ArcCurve.prototype = Object.create( EllipseCurve.prototype ); + ArcCurve.prototype.constructor = ArcCurve; -// File:src/extras/helpers/WireframeHelper.js + /** + * @author alteredq / http://alteredqualia.com/ + */ -/** - * @author mrdoob / http://mrdoob.com/ - */ + exports.SceneUtils = { -THREE.WireframeHelper = function ( object, hex ) { + createMultiMaterialObject: function ( geometry, materials ) { - var color = ( hex !== undefined ) ? hex : 0xffffff; + var group = new Group(); - THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) ); + for ( var i = 0, l = materials.length; i < l; i ++ ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + group.add( new Mesh( geometry, materials[ i ] ) ); -}; + } -THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; + return group; -// File:src/extras/objects/ImmediateRenderObject.js + }, + detach: function ( child, parent, scene ) { + + child.applyMatrix( parent.matrixWorld ); + parent.remove( child ); + scene.add( child ); + + }, + + attach: function ( child, scene, parent ) { + + var matrixWorldInverse = new Matrix4(); + matrixWorldInverse.getInverse( parent.matrixWorld ); + child.applyMatrix( matrixWorldInverse ); + + scene.remove( child ); + parent.add( child ); + + } + + }; + + Object.defineProperty( exports, 'AudioContext', { + get: function () { + return exports.getAudioContext(); + } + }); + + exports.SpritePlugin = SpritePlugin; + exports.LensFlarePlugin = LensFlarePlugin; + exports.WebGLTextures = WebGLTextures; + exports.WebGLStencilBuffer = WebGLStencilBuffer; + exports.WebGLDepthBuffer = WebGLDepthBuffer; + exports.WebGLColorBuffer = WebGLColorBuffer; + exports.WebGLState = WebGLState; + exports.WebGLShadowMap = WebGLShadowMap; + exports.WebGLProperties = WebGLProperties; + exports.WebGLPrograms = WebGLPrograms; + exports.WebGLObjects = WebGLObjects; + exports.WebGLLights = WebGLLights; + exports.WebGLGeometries = WebGLGeometries; + exports.WebGLCapabilities = WebGLCapabilities; + exports.WebGLExtensions = WebGLExtensions; + exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer; + exports.WebGLClipping = WebGLClipping; + exports.WebGLBufferRenderer = WebGLBufferRenderer; + exports.WebGLRenderTargetCube = WebGLRenderTargetCube; + exports.WebGLRenderTarget = WebGLRenderTarget; + exports.WebGLRenderer = WebGLRenderer; + exports.ShaderChunk = ShaderChunk; + exports.FogExp2 = FogExp2; + exports.Fog = Fog; + exports.Scene = Scene; + exports.LensFlare = LensFlare; + exports.Sprite = Sprite; + exports.LOD = LOD; + exports.SkinnedMesh = SkinnedMesh; + exports.Skeleton = Skeleton; + exports.Bone = Bone; + exports.Mesh = Mesh; + exports.LineSegments = LineSegments; + exports.Line = Line; + exports.Points = Points; + exports.Group = Group; + exports.VideoTexture = VideoTexture; + exports.DataTexture = DataTexture; + exports.CompressedTexture = CompressedTexture; + exports.CubeTexture = CubeTexture; + exports.CanvasTexture = CanvasTexture; + exports.DepthTexture = DepthTexture; + exports.TextureIdCount = TextureIdCount; + exports.Texture = Texture; + exports.ShadowMaterial = ShadowMaterial; + exports.SpriteMaterial = SpriteMaterial; + exports.RawShaderMaterial = RawShaderMaterial; + exports.ShaderMaterial = ShaderMaterial; + exports.PointsMaterial = PointsMaterial; + exports.MultiMaterial = MultiMaterial; + exports.MeshPhysicalMaterial = MeshPhysicalMaterial; + exports.MeshStandardMaterial = MeshStandardMaterial; + exports.MeshPhongMaterial = MeshPhongMaterial; + exports.MeshNormalMaterial = MeshNormalMaterial; + exports.MeshLambertMaterial = MeshLambertMaterial; + exports.MeshDepthMaterial = MeshDepthMaterial; + exports.MeshBasicMaterial = MeshBasicMaterial; + exports.LineDashedMaterial = LineDashedMaterial; + exports.LineBasicMaterial = LineBasicMaterial; + exports.MaterialIdCount = MaterialIdCount; + exports.Material = Material; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.BinaryTextureLoader = BinaryTextureLoader; + exports.DataTextureLoader = DataTextureLoader; + exports.CubeTextureLoader = CubeTextureLoader; + exports.TextureLoader = TextureLoader; + exports.ObjectLoader = ObjectLoader; + exports.MaterialLoader = MaterialLoader; + exports.BufferGeometryLoader = BufferGeometryLoader; + exports.LoadingManager = LoadingManager; + exports.JSONLoader = JSONLoader; + exports.ImageLoader = ImageLoader; + exports.FontLoader = FontLoader; + exports.XHRLoader = XHRLoader; + exports.Loader = Loader; + exports.AudioLoader = AudioLoader; + exports.SpotLightShadow = SpotLightShadow; + exports.SpotLight = SpotLight; + exports.PointLight = PointLight; + exports.HemisphereLight = HemisphereLight; + exports.DirectionalLightShadow = DirectionalLightShadow; + exports.DirectionalLight = DirectionalLight; + exports.AmbientLight = AmbientLight; + exports.LightShadow = LightShadow; + exports.Light = Light; + exports.StereoCamera = StereoCamera; + exports.PerspectiveCamera = PerspectiveCamera; + exports.OrthographicCamera = OrthographicCamera; + exports.CubeCamera = CubeCamera; + exports.Camera = Camera; + exports.AudioListener = AudioListener; + exports.PositionalAudio = PositionalAudio; + exports.getAudioContext = getAudioContext; + exports.AudioAnalyser = AudioAnalyser; + exports.Audio = Audio; + exports.VectorKeyframeTrack = VectorKeyframeTrack; + exports.StringKeyframeTrack = StringKeyframeTrack; + exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; + exports.NumberKeyframeTrack = NumberKeyframeTrack; + exports.ColorKeyframeTrack = ColorKeyframeTrack; + exports.BooleanKeyframeTrack = BooleanKeyframeTrack; + exports.PropertyMixer = PropertyMixer; + exports.PropertyBinding = PropertyBinding; + exports.KeyframeTrack = KeyframeTrack; + exports.AnimationObjectGroup = AnimationObjectGroup; + exports.AnimationMixer = AnimationMixer; + exports.AnimationClip = AnimationClip; + exports.AnimationAction = AnimationAction; + exports.Uniform = Uniform; + exports.InstancedBufferGeometry = InstancedBufferGeometry; + exports.BufferGeometry = BufferGeometry; + exports.DirectGeometry = DirectGeometry; + exports.GeometryIdCount = GeometryIdCount; + exports.Geometry = Geometry; + exports.InterleavedBufferAttribute = InterleavedBufferAttribute; + exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; + exports.InterleavedBuffer = InterleavedBuffer; + exports.InstancedBufferAttribute = InstancedBufferAttribute; + exports.DynamicBufferAttribute = DynamicBufferAttribute; + exports.Float64Attribute = Float64Attribute; + exports.Float32Attribute = Float32Attribute; + exports.Uint32Attribute = Uint32Attribute; + exports.Int32Attribute = Int32Attribute; + exports.Uint16Attribute = Uint16Attribute; + exports.Int16Attribute = Int16Attribute; + exports.Uint8ClampedAttribute = Uint8ClampedAttribute; + exports.Uint8Attribute = Uint8Attribute; + exports.Int8Attribute = Int8Attribute; + exports.BufferAttribute = BufferAttribute; + exports.Face3 = Face3; + exports.Object3DIdCount = Object3DIdCount; + exports.Object3D = Object3D; + exports.Raycaster = Raycaster; + exports.Layers = Layers; + exports.EventDispatcher = EventDispatcher; + exports.Clock = Clock; + exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; + exports.LinearInterpolant = LinearInterpolant; + exports.DiscreteInterpolant = DiscreteInterpolant; + exports.CubicInterpolant = CubicInterpolant; + exports.Interpolant = Interpolant; + exports.Triangle = Triangle; + exports.Spline = Spline; + exports.Spherical = Spherical; + exports.Plane = Plane; + exports.Frustum = Frustum; + exports.Sphere = Sphere; + exports.Ray = Ray; + exports.Matrix4 = Matrix4; + exports.Matrix3 = Matrix3; + exports.Box3 = Box3; + exports.Box2 = Box2; + exports.Line3 = Line3; + exports.Euler = Euler; + exports.Vector4 = Vector4; + exports.Vector3 = Vector3; + exports.Vector2 = Vector2; + exports.Quaternion = Quaternion; + exports.Color = Color; + exports.MorphBlendMesh = MorphBlendMesh; + exports.ImmediateRenderObject = ImmediateRenderObject; + exports.WireframeHelper = WireframeHelper; + exports.VertexNormalsHelper = VertexNormalsHelper; + exports.SpotLightHelper = SpotLightHelper; + exports.SkeletonHelper = SkeletonHelper; + exports.PointLightHelper = PointLightHelper; + exports.HemisphereLightHelper = HemisphereLightHelper; + exports.GridHelper = GridHelper; + exports.FaceNormalsHelper = FaceNormalsHelper; + exports.EdgesHelper = EdgesHelper; + exports.DirectionalLightHelper = DirectionalLightHelper; + exports.CameraHelper = CameraHelper; + exports.BoundingBoxHelper = BoundingBoxHelper; + exports.BoxHelper = BoxHelper; + exports.AxisHelper = AxisHelper; + exports.WireframeGeometry = WireframeGeometry; + exports.ParametricGeometry = ParametricGeometry; + exports.TetrahedronGeometry = TetrahedronGeometry; + exports.OctahedronGeometry = OctahedronGeometry; + exports.IcosahedronGeometry = IcosahedronGeometry; + exports.DodecahedronGeometry = DodecahedronGeometry; + exports.PolyhedronGeometry = PolyhedronGeometry; + exports.TubeGeometry = TubeGeometry; + exports.TorusKnotGeometry = TorusKnotGeometry; + exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; + exports.TorusGeometry = TorusGeometry; + exports.TorusBufferGeometry = TorusBufferGeometry; + exports.TextGeometry = TextGeometry; + exports.SphereBufferGeometry = SphereBufferGeometry; + exports.SphereGeometry = SphereGeometry; + exports.RingGeometry = RingGeometry; + exports.RingBufferGeometry = RingBufferGeometry; + exports.PlaneBufferGeometry = PlaneBufferGeometry; + exports.PlaneGeometry = PlaneGeometry; + exports.LatheGeometry = LatheGeometry; + exports.LatheBufferGeometry = LatheBufferGeometry; + exports.ShapeGeometry = ShapeGeometry; + exports.ExtrudeGeometry = ExtrudeGeometry; + exports.EdgesGeometry = EdgesGeometry; + exports.ConeGeometry = ConeGeometry; + exports.ConeBufferGeometry = ConeBufferGeometry; + exports.CylinderGeometry = CylinderGeometry; + exports.CylinderBufferGeometry = CylinderBufferGeometry; + exports.CircleBufferGeometry = CircleBufferGeometry; + exports.CircleGeometry = CircleGeometry; + exports.BoxBufferGeometry = BoxBufferGeometry; + exports.BoxGeometry = BoxGeometry; + exports.ClosedSplineCurve3 = ClosedSplineCurve3; + exports.ArcCurve = ArcCurve; + exports.EllipseCurve = EllipseCurve; + exports.SplineCurve = SplineCurve; + exports.CubicBezierCurve = CubicBezierCurve; + exports.QuadraticBezierCurve = QuadraticBezierCurve; + exports.LineCurve = LineCurve; + exports.Shape = Shape; + exports.ShapePath = ShapePath; + exports.Path = Path; + exports.Font = Font; + exports.CurvePath = CurvePath; + exports.Curve = Curve; + exports.MOUSE = MOUSE; + exports.CullFaceNone = CullFaceNone; + exports.CullFaceBack = CullFaceBack; + exports.CullFaceFront = CullFaceFront; + exports.CullFaceFrontBack = CullFaceFrontBack; + exports.FrontFaceDirectionCW = FrontFaceDirectionCW; + exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; + exports.BasicShadowMap = BasicShadowMap; + exports.PCFShadowMap = PCFShadowMap; + exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.FrontSide = FrontSide; + exports.BackSide = BackSide; + exports.DoubleSide = DoubleSide; + exports.FlatShading = FlatShading; + exports.SmoothShading = SmoothShading; + exports.NoColors = NoColors; + exports.FaceColors = FaceColors; + exports.VertexColors = VertexColors; + exports.NoBlending = NoBlending; + exports.NormalBlending = NormalBlending; + exports.AdditiveBlending = AdditiveBlending; + exports.SubtractiveBlending = SubtractiveBlending; + exports.MultiplyBlending = MultiplyBlending; + exports.CustomBlending = CustomBlending; + exports.AddEquation = AddEquation; + exports.SubtractEquation = SubtractEquation; + exports.ReverseSubtractEquation = ReverseSubtractEquation; + exports.MinEquation = MinEquation; + exports.MaxEquation = MaxEquation; + exports.ZeroFactor = ZeroFactor; + exports.OneFactor = OneFactor; + exports.SrcColorFactor = SrcColorFactor; + exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; + exports.SrcAlphaFactor = SrcAlphaFactor; + exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; + exports.DstAlphaFactor = DstAlphaFactor; + exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; + exports.DstColorFactor = DstColorFactor; + exports.OneMinusDstColorFactor = OneMinusDstColorFactor; + exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; + exports.NeverDepth = NeverDepth; + exports.AlwaysDepth = AlwaysDepth; + exports.LessDepth = LessDepth; + exports.LessEqualDepth = LessEqualDepth; + exports.EqualDepth = EqualDepth; + exports.GreaterEqualDepth = GreaterEqualDepth; + exports.GreaterDepth = GreaterDepth; + exports.NotEqualDepth = NotEqualDepth; + exports.MultiplyOperation = MultiplyOperation; + exports.MixOperation = MixOperation; + exports.AddOperation = AddOperation; + exports.NoToneMapping = NoToneMapping; + exports.LinearToneMapping = LinearToneMapping; + exports.ReinhardToneMapping = ReinhardToneMapping; + exports.Uncharted2ToneMapping = Uncharted2ToneMapping; + exports.CineonToneMapping = CineonToneMapping; + exports.UVMapping = UVMapping; + exports.CubeReflectionMapping = CubeReflectionMapping; + exports.CubeRefractionMapping = CubeRefractionMapping; + exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; + exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; + exports.SphericalReflectionMapping = SphericalReflectionMapping; + exports.CubeUVReflectionMapping = CubeUVReflectionMapping; + exports.CubeUVRefractionMapping = CubeUVRefractionMapping; + exports.RepeatWrapping = RepeatWrapping; + exports.ClampToEdgeWrapping = ClampToEdgeWrapping; + exports.MirroredRepeatWrapping = MirroredRepeatWrapping; + exports.NearestFilter = NearestFilter; + exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; + exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; + exports.LinearFilter = LinearFilter; + exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; + exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; + exports.UnsignedByteType = UnsignedByteType; + exports.ByteType = ByteType; + exports.ShortType = ShortType; + exports.UnsignedShortType = UnsignedShortType; + exports.IntType = IntType; + exports.UnsignedIntType = UnsignedIntType; + exports.FloatType = FloatType; + exports.HalfFloatType = HalfFloatType; + exports.UnsignedShort4444Type = UnsignedShort4444Type; + exports.UnsignedShort5551Type = UnsignedShort5551Type; + exports.UnsignedShort565Type = UnsignedShort565Type; + exports.AlphaFormat = AlphaFormat; + exports.RGBFormat = RGBFormat; + exports.RGBAFormat = RGBAFormat; + exports.LuminanceFormat = LuminanceFormat; + exports.LuminanceAlphaFormat = LuminanceAlphaFormat; + exports.RGBEFormat = RGBEFormat; + exports.DepthFormat = DepthFormat; + exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; + exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; + exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; + exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; + exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; + exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; + exports.RGB_ETC1_Format = RGB_ETC1_Format; + exports.LoopOnce = LoopOnce; + exports.LoopRepeat = LoopRepeat; + exports.LoopPingPong = LoopPingPong; + exports.InterpolateDiscrete = InterpolateDiscrete; + exports.InterpolateLinear = InterpolateLinear; + exports.InterpolateSmooth = InterpolateSmooth; + exports.ZeroCurvatureEnding = ZeroCurvatureEnding; + exports.ZeroSlopeEnding = ZeroSlopeEnding; + exports.WrapAroundEnding = WrapAroundEnding; + exports.TrianglesDrawMode = TrianglesDrawMode; + exports.TriangleStripDrawMode = TriangleStripDrawMode; + exports.TriangleFanDrawMode = TriangleFanDrawMode; + exports.LinearEncoding = LinearEncoding; + exports.sRGBEncoding = sRGBEncoding; + exports.GammaEncoding = GammaEncoding; + exports.RGBEEncoding = RGBEEncoding; + exports.LogLuvEncoding = LogLuvEncoding; + exports.RGBM7Encoding = RGBM7Encoding; + exports.RGBM16Encoding = RGBM16Encoding; + exports.RGBDEncoding = RGBDEncoding; + exports.BasicDepthPacking = BasicDepthPacking; + exports.RGBADepthPacking = RGBADepthPacking; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); /** - * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ */ -THREE.ImmediateRenderObject = function ( material ) { - - THREE.Object3D.call( this ); - - this.material = material; - this.render = function ( renderCallback ) {}; +Object.assign( THREE, { + Face4: function ( a, b, c, d, normal, color, materialIndex ) { + console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); + return new THREE.Face3( a, b, c, normal, color, materialIndex ); + }, + LineStrip: 0, + LinePieces: 1, + MeshFaceMaterial: THREE.MultiMaterial, + PointCloud: function ( geometry, material ) { + console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); + return new THREE.Points( geometry, material ); + }, + Particle: THREE.Sprite, + ParticleSystem: function ( geometry, material ) { + console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); + return new THREE.Points( geometry, material ); + }, + PointCloudMaterial: function ( parameters ) { + console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + ParticleBasicMaterial: function ( parameters ) { + console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + ParticleSystemMaterial: function ( parameters ) { + console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); + return new THREE.PointsMaterial( parameters ); + }, + Vertex: function ( x, y, z ) { + console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); + return new THREE.Vector3( x, y, z ); + } +} ); -}; +// -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; +Object.assign( THREE.Box2.prototype, { + empty: function () { + console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); + }, + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + } +} ); -// File:src/extras/objects/MorphBlendMesh.js +Object.assign( THREE.Box3.prototype, { + empty: function () { + console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); + }, + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + }, + isIntersectionSphere: function ( sphere ) { + console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); + } +} ); -/** - * @author alteredq / http://alteredqualia.com/ - */ +Object.assign( THREE.Matrix3.prototype, { + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); + return vector.applyMatrix3( this ); + }, + multiplyVector3Array: function ( a ) { + console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); + } +} ); -THREE.MorphBlendMesh = function( geometry, material ) { +Object.assign( THREE.Matrix4.prototype, { + extractPosition: function ( m ) { + console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); + return this.copyPosition( m ); + }, + setRotationFromQuaternion: function ( q ) { + console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); + return this.makeRotationFromQuaternion( q ); + }, + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); + return vector.applyProjection( this ); + }, + multiplyVector4: function ( vector ) { + console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); + }, + multiplyVector3Array: function ( a ) { + console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); + return this.applyToVector3Array( a ); + }, + rotateAxis: function ( v ) { + console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + v.transformDirection( this ); + }, + crossVector: function ( vector ) { + console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); + }, + translate: function ( v ) { + console.error( 'THREE.Matrix4: .translate() has been removed.' ); + }, + rotateX: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + }, + rotateY: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); + }, + rotateZ: function ( angle ) { + console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + }, + rotateByAxis: function ( axis, angle ) { + console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + } +} ); - THREE.Mesh.call( this, geometry, material ); +Object.assign( THREE.Plane.prototype, { + isIntersectionLine: function ( line ) { + console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); + return this.intersectsLine( line ); + } +} ); - this.animationsMap = {}; - this.animationsList = []; +Object.assign( THREE.Quaternion.prototype, { + multiplyVector3: function ( vector ) { + console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + return vector.applyQuaternion( this ); + } +} ); - // prepare default animation - // (all frames played together in 1 second) +Object.assign( THREE.Ray.prototype, { + isIntersectionBox: function ( box ) { + console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + }, + isIntersectionPlane: function ( plane ) { + console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); + return this.intersectsPlane( plane ); + }, + isIntersectionSphere: function ( sphere ) { + console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); + } +} ); - var numFrames = this.geometry.morphTargets.length; +Object.assign( THREE.Vector3.prototype, { + setEulerFromRotationMatrix: function () { + console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + }, + setEulerFromQuaternion: function () { + console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + }, + getPositionFromMatrix: function ( m ) { + console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); + return this.setFromMatrixPosition( m ); + }, + getScaleFromMatrix: function ( m ) { + console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); + return this.setFromMatrixScale( m ); + }, + getColumnFromMatrix: function ( index, matrix ) { + console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); + return this.setFromMatrixColumn( matrix, index ); + } +} ); - var name = "__default"; +// - var startFrame = 0; - var endFrame = numFrames - 1; +Object.assign( THREE.Object3D.prototype, { + getChildByName: function ( name ) { + console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); + return this.getObjectByName( name ); + }, + renderDepth: function ( value ) { + console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + }, + translate: function ( distance, axis ) { + console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); + return this.translateOnAxis( axis, distance ); + } +} ); - var fps = numFrames / 1; +Object.defineProperties( THREE.Object3D.prototype, { + eulerOrder: { + get: function () { + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + return this.rotation.order; + }, + set: function ( value ) { + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + this.rotation.order = value; + } + }, + useQuaternion: { + get: function () { + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + }, + set: function ( value ) { + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + } + } +} ); - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); +Object.defineProperties( THREE.LOD.prototype, { + objects: { + get: function () { + console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); + return this.levels; + } + } +} ); -}; +// -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; +THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + + "Use .setFocalLength and .filmGauge for a photographic setup." ); - var animation = { + if ( filmGauge !== undefined ) this.filmGauge = filmGauge; + this.setFocalLength( focalLength ); - start: start, - end: end, +}; - length: end - start + 1, +// - fps: fps, - duration: ( end - start ) / fps, +Object.defineProperties( THREE.Light.prototype, { + onlyShadow: { + set: function ( value ) { + console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + } + }, + shadowCameraFov: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); + this.shadow.camera.fov = value; + } + }, + shadowCameraLeft: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); + this.shadow.camera.left = value; + } + }, + shadowCameraRight: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); + this.shadow.camera.right = value; + } + }, + shadowCameraTop: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); + this.shadow.camera.top = value; + } + }, + shadowCameraBottom: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); + this.shadow.camera.bottom = value; + } + }, + shadowCameraNear: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); + this.shadow.camera.near = value; + } + }, + shadowCameraFar: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); + this.shadow.camera.far = value; + } + }, + shadowCameraVisible: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); + } + }, + shadowBias: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); + this.shadow.bias = value; + } + }, + shadowDarkness: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + } + }, + shadowMapWidth: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); + this.shadow.mapSize.width = value; + } + }, + shadowMapHeight: { + set: function ( value ) { + console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); + this.shadow.mapSize.height = value; + } + } +} ); - lastFrame: 0, - currentFrame: 0, +// - active: false, +Object.defineProperties( THREE.BufferAttribute.prototype, { + length: { + get: function () { + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); + return this.array.length; + } + } +} ); - time: 0, - direction: 1, - weight: 1, +Object.assign( THREE.BufferGeometry.prototype, { + addIndex: function ( index ) { + console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); + this.setIndex( index ); + }, + addDrawCall: function ( start, count, indexOffset ) { + if ( indexOffset !== undefined ) { + console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + } + console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); + this.addGroup( start, count ); + }, + clearDrawCalls: function () { + console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); + this.clearGroups(); + }, + computeTangents: function () { + console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); + }, + computeOffsets: function () { + console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + } +} ); - directionBackwards: false, - mirroredLoop: false +Object.defineProperties( THREE.BufferGeometry.prototype, { + drawcalls: { + get: function () { + console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); + return this.groups; + } + }, + offsets: { + get: function () { + console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); + return this.groups; + } + } +} ); - }; +// - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); +Object.defineProperties( THREE.Material.prototype, { + wrapAround: { + get: function () { + console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + }, + set: function ( value ) { + console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + } + }, + wrapRGB: { + get: function () { + console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' ); + return new THREE.Color(); + } + } +} ); -}; +Object.defineProperties( THREE.MeshPhongMaterial.prototype, { + metal: { + get: function () { + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); + return false; + }, + set: function ( value ) { + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); + } + } +} ); -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { +Object.defineProperties( THREE.ShaderMaterial.prototype, { + derivatives: { + get: function () { + console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + return this.extensions.derivatives; + }, + set: function ( value ) { + console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + this.extensions.derivatives = value; + } + } +} ); - var pattern = /([a-z]+)_?(\d+)/i; +// - var firstAnimation, frameRanges = {}; +THREE.EventDispatcher.prototype = Object.assign( Object.create( { - var geometry = this.geometry; + // Note: Extra base ensures these properties are not 'assign'ed. - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + constructor: THREE.EventDispatcher, - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); + apply: function ( target ) { - if ( chunks && chunks.length > 1 ) { + console.warn( "THREE.EventDispatcher: .apply is deprecated, " + + "just inherit or Object.assign the prototype to mix-in." ); - var name = chunks[ 1 ]; + Object.assign( target, this ); - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + } - var range = frameRanges[ name ]; +} ), THREE.EventDispatcher.prototype ); - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; +// - if ( ! firstAnimation ) firstAnimation = name; +Object.assign( THREE.WebGLRenderer.prototype, { + supportsFloatTextures: function () { + console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); + return this.extensions.get( 'OES_texture_float' ); + }, + supportsHalfFloatTextures: function () { + console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); + return this.extensions.get( 'OES_texture_half_float' ); + }, + supportsStandardDerivatives: function () { + console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); + return this.extensions.get( 'OES_standard_derivatives' ); + }, + supportsCompressedTextureS3TC: function () { + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); + }, + supportsCompressedTexturePVRTC: function () { + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + }, + supportsBlendMinMax: function () { + console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); + return this.extensions.get( 'EXT_blend_minmax' ); + }, + supportsVertexTextures: function () { + return this.capabilities.vertexTextures; + }, + supportsInstancedArrays: function () { + console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); + return this.extensions.get( 'ANGLE_instanced_arrays' ); + }, + enableScissorTest: function ( boolean ) { + console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); + this.setScissorTest( boolean ); + }, + initMaterial: function () { + console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); + }, + addPrePlugin: function () { + console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); + }, + addPostPlugin: function () { + console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); + }, + updateShadowMap: function () { + console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + } +} ); +Object.defineProperties( THREE.WebGLRenderer.prototype, { + shadowMapEnabled: { + get: function () { + return this.shadowMap.enabled; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); + this.shadowMap.enabled = value; + } + }, + shadowMapType: { + get: function () { + return this.shadowMap.type; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); + this.shadowMap.type = value; + } + }, + shadowMapCullFace: { + get: function () { + return this.shadowMap.cullFace; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); + this.shadowMap.cullFace = value; } - } +} ); - for ( var name in frameRanges ) { - - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); - +Object.defineProperties( THREE.WebGLShadowMap.prototype, { + cullFace: { + get: function () { + return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack; + }, + set: function ( cullFace ) { + var value = ( cullFace !== THREE.CullFaceBack ); + console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); + this.renderReverseSided = value; + } } +} ); - this.firstAnimation = firstAnimation; - -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = 1; - animation.directionBackwards = false; +// +Object.defineProperties( THREE.WebGLRenderTarget.prototype, { + wrapS: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + return this.texture.wrapS; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + this.texture.wrapS = value; + } + }, + wrapT: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + return this.texture.wrapT; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + this.texture.wrapT = value; + } + }, + magFilter: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + return this.texture.magFilter; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + this.texture.magFilter = value; + } + }, + minFilter: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + return this.texture.minFilter; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + this.texture.minFilter = value; + } + }, + anisotropy: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + return this.texture.anisotropy; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + this.texture.anisotropy = value; + } + }, + offset: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + return this.texture.offset; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + this.texture.offset = value; + } + }, + repeat: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + return this.texture.repeat; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + this.texture.repeat = value; + } + }, + format: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + return this.texture.format; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + this.texture.format = value; + } + }, + type: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + return this.texture.type; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + this.texture.type = value; + } + }, + generateMipmaps: { + get: function () { + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + return this.texture.generateMipmaps; + }, + set: function ( value ) { + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + this.texture.generateMipmaps = value; + } } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = - 1; - animation.directionBackwards = true; +// +Object.assign( THREE.Audio.prototype, { + load: function ( file ) { + console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' ); + var scope = this; + var audioLoader = new THREE.AudioLoader(); + audioLoader.load( file, function ( buffer ) { + scope.setBuffer( buffer ); + } ); + return this; } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; - +Object.assign( THREE.AudioAnalyser.prototype, { + getData: function ( file ) { + console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); + return this.getFrequencyData(); } +} ); -}; - -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; +// - } +THREE.GeometryUtils = { -}; + merge: function ( geometry1, geometry2, materialIndexOffset ) { -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - var animation = this.animationsMap[ name ]; + var matrix; - if ( animation ) { + if ( geometry2 instanceof THREE.Mesh ) { - animation.weight = weight; + geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - } + matrix = geometry2.matrix; + geometry2 = geometry2.geometry; -}; + } -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + geometry1.merge( geometry2, matrix, materialIndexOffset ); - var animation = this.animationsMap[ name ]; + }, - if ( animation ) { + center: function ( geometry ) { - animation.time = time; + console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); + return geometry.center(); } }; -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - - var time = 0; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - time = animation.time; - - } - - return time; - -}; +THREE.ImageUtils = { -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + crossOrigin: undefined, - var duration = - 1; + loadTexture: function ( url, mapping, onLoad, onError ) { - var animation = this.animationsMap[ name ]; + console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - if ( animation ) { + var loader = new THREE.TextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - duration = animation.duration; + var texture = loader.load( url, onLoad, undefined, onError ); - } + if ( mapping ) texture.mapping = mapping; - return duration; + return texture; -}; + }, -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { + loadTextureCube: function ( urls, mapping, onLoad, onError ) { - var animation = this.animationsMap[ name ]; + console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - if ( animation ) { + var loader = new THREE.CubeTextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - animation.time = 0; - animation.active = true; + var texture = loader.load( urls, onLoad, undefined, onError ); - } else { + if ( mapping ) texture.mapping = mapping; - console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + return texture; - } + }, -}; + loadCompressedTexture: function () { -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { + console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - var animation = this.animationsMap[ name ]; + }, - if ( animation ) { + loadCompressedTextureCube: function () { - animation.active = false; + console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); } }; -THREE.MorphBlendMesh.prototype.update = function ( delta ) { - - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - - var animation = this.animationsList[ i ]; - - if ( ! animation.active ) continue; - - var frameTime = animation.duration / animation.length; - - animation.time += animation.direction * delta; - - if ( animation.mirroredLoop ) { - - if ( animation.time > animation.duration || animation.time < 0 ) { - - animation.direction *= - 1; - - if ( animation.time > animation.duration ) { - - animation.time = animation.duration; - animation.directionBackwards = true; - - } - - if ( animation.time < 0 ) { - - animation.time = 0; - animation.directionBackwards = false; - - } - - } - - } else { - - animation.time = animation.time % animation.duration; +// - if ( animation.time < 0 ) animation.time += animation.duration; +THREE.Projector = function () { - } + console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); - var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; + this.projectVector = function ( vector, camera ) { - if ( keyframe !== animation.currentFrame ) { + console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); + vector.project( camera ); - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + }; - this.morphTargetInfluences[ keyframe ] = 0; + this.unprojectVector = function ( vector, camera ) { - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; + console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); + vector.unproject( camera ); - } + }; - var mix = ( animation.time % frameTime ) / frameTime; + this.pickingRay = function ( vector, camera ) { - if ( animation.directionBackwards ) mix = 1 - mix; + console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); - if ( animation.currentFrame !== animation.lastFrame ) { + }; - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; +}; - } else { +// - this.morphTargetInfluences[ animation.currentFrame ] = weight; +THREE.CanvasRenderer = function () { - } + console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); - } + this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + this.clear = function () {}; + this.render = function () {}; + this.setClearColor = function () {}; + this.setSize = function () {}; }; - diff --git a/build/three.min.js b/build/three.min.js index a955ba13d67da5..05d0bd00836370 100644 --- a/build/three.min.js +++ b/build/three.min.js @@ -1,993 +1,14 @@ -// threejs.org/license -'use strict';var THREE={REVISION:"79"};"function"===typeof define&&define.amd?define("three",THREE):"undefined"!==typeof exports&&"undefined"!==typeof module&&(module.exports=THREE);void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=THREE.Math.euclideanModulo(b,1);c=THREE.Math.clamp(c,0,1);d=THREE.Math.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c= -/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d= -parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-d)/k+(cf&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y= -.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector3);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*= --1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this}, -multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,l=b._w;this._x=c*l+f*g+d*k-e*h;this._y=d*l+f*h+e*g-c*k;this._z=e*l+f*k+c*h-d*g;this._w=f*l-c*g-d*h-e*k;this.onChangeCallback(); -return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b* -k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback= -a;return this},onChangeCallback:function(){}}; -Object.assign(THREE.Quaternion,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],l=c[d+2];c=c[d+3];d=e[f+0];var m=e[f+1],p=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==m||l!==p){f=1-g;var n=h*d+k*m+l*p+c*e,q=0<=n?1:-1,r=1-n*n;r>Number.EPSILON&&(r=Math.sqrt(r),n=Math.atan2(r,n*q),f=Math.sin(f*n)/r,g=Math.sin(g*n)/r);q*=g;h=h*f+d*q;k=k*f+m*q;l=l*f+p*q;c=c*f+e*q;f===1-g&&(g=1/Math.sqrt(h*h+k*k+l*l+c*c),h*=g,k*=g,l*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=l; -a[b+3]=c}});THREE.Vector2=function(a,b){this.x=a||0;this.y=b||0}; -THREE.Vector2.prototype={constructor:THREE.Vector2,get width(){return this.x},set width(a){this.x=a},get height(){return this.y},set height(a){this.y=a},set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}},getComponent:function(a){switch(a){case 0:return this.x; -case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this}, -addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a, -this.y*=a):this.y=this.x=0;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a,b;return function(c,d){void 0=== -a&&(a=new THREE.Vector2,b=new THREE.Vector2);a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x); -this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a}, -distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y}, -fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}};THREE.Vector3=function(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}; -THREE.Vector3.prototype={constructor:THREE.Vector3,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y; -case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a, -b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this}, -multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a):this.z=this.y=this.x=0;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a;return function(b){!1===b instanceof THREE.Euler&& -console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");void 0===a&&(a=new THREE.Quaternion);return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new THREE.Quaternion);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this}, -applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];return this},applyProjection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a= -a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,l=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-l*-f;this.y=k*a+b*-f+l*-e-h*-g;this.z=l*a+b*-g+h*-f-k*-e;return this},project:function(){var a;return function(b){void 0===a&&(a=new THREE.Matrix4);a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new THREE.Matrix4);a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyProjection(a)}}(), -transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z= -Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector3,b=new THREE.Vector3);a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y= -Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y= --this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+= -(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h; -this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(THREE.Math.clamp(a, --1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){return this.setFromMatrixColumn(a,3)}, -setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){if("number"===typeof a){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var c=a;a=b;b=c}return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0); -this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];return this}};THREE.Vector4=function(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}; -THREE.Vector4.prototype={constructor:THREE.Vector4,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+ -a);}},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b); -this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-= -a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a,this.w*=a):this.w=this.z=this.y=this.x=0;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z= -a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var l=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01> -Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+l-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;l=(l+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>l?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>l?.01>h?(b=.707106781,c=0,d=.707106781):(c=Math.sqrt(h),b=d/c,d=k/c):.01>l?(c=b=.707106781,d=0):(d=Math.sqrt(l),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/ -a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+l-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z)); -this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new THREE.Vector4,b=new THREE.Vector4);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil: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);return this},round:function(){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},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z* -a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z- -this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromAttribute:function(a,b,c){void 0===c&&(c=0);b=b*a.itemSize+ -c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];this.w=a.array[b+3];return this}};THREE.Euler=function(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||THREE.Euler.DefaultOrder};THREE.Euler.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");THREE.Euler.DefaultOrder="XYZ"; -THREE.Euler.prototype={constructor:THREE.Euler,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get order(){return this._order},set order(a){this._order=a;this.onChangeCallback()},set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x, -this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=THREE.Math.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],l=e[9],m=e[2],p=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-l,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(p,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)? -(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-m,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(p,-1,1)),.99999>Math.abs(p)?(this._y=Math.atan2(-m,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._x=Math.atan2(p,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-l,k),this._y=Math.atan2(-m,a)):(this._x= -0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(p,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-l,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new THREE.Matrix4);a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a, -b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new THREE.Quaternion;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z; -a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new THREE.Vector3(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};THREE.Line3=function(a,b){this.start=void 0!==a?a:new THREE.Vector3;this.end=void 0!==b?b:new THREE.Vector3}; -THREE.Line3.prototype={constructor:THREE.Line3,set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},center:function(a){return(a||new THREE.Vector3).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new THREE.Vector3).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)}, -at:function(a,b){var c=b||new THREE.Vector3;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=THREE.Math.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new THREE.Vector3;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a); -this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}};THREE.Box2=function(a,b){this.min=void 0!==a?a:new THREE.Vector2(Infinity,Infinity);this.max=void 0!==b?b:new THREE.Vector2(-Infinity,-Infinity)}; -THREE.Box2.prototype={constructor:THREE.Box2,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y?!0:!1},getParameter:function(a,b){return(b||new THREE.Vector2).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.y -this.max.y?!1:!0},clampPoint:function(a,b){return(b||new THREE.Vector2).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new THREE.Vector2;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&& -a.max.equals(this.max)}};THREE.Box3=function(a,b){this.min=void 0!==a?a:new THREE.Vector3(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new THREE.Vector3(-Infinity,-Infinity,-Infinity)}; -THREE.Box3.prototype={constructor:THREE.Box3,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;he&&(e=l);m>f&&(f=m);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z?!0:!1},getParameter:function(a,b){return(b||new THREE.Vector3).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x|| -a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},intersectsSphere:function(){var a;return function(b){void 0===a&&(a=new THREE.Vector3);this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0=a.constant},clampPoint:function(a,b){return(b||new THREE.Vector3).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new THREE.Vector3;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new THREE.Vector3;return function(b){b=b||new THREE.Sphere;b.center= -this.center();b.radius=.5*this.size(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b); -a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a); -return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};THREE.Matrix3=function(){this.elements=new Float32Array([1,0,0,0,1,0,0,0,1]);0this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.elements.set(this.elements);c=1/g;var f=1/h,l=1/k;b.elements[0]*=c;b.elements[1]*=c; -b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=l;b.elements[9]*=l;b.elements[10]*=l;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makeFrustum:function(a,b,c,d,e,f){var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(d-c);g[9]=(d+c)/(d-c);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(THREE.Math.DEG2RAD*a*.5);var e= --a;return this.makeFrustum(e*b,a*b,e,a,c,d)},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),l=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*l;g[14]=-((f+e)*l);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a){this.elements.set(a);return this},toArray:function(a,b){void 0===a&&(a=[]); -void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}};THREE.Ray=function(a,b){this.origin=void 0!==a?a:new THREE.Vector3;this.direction=void 0!==b?b:new THREE.Vector3}; -THREE.Ray.prototype={constructor:THREE.Ray,set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new THREE.Vector3).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new THREE.Vector3;return function(b){this.origin.copy(this.at(b, -a));return this}}(),closestPointToPoint:function(a,b){var c=b||new THREE.Vector3;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new THREE.Vector3;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin); -return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Vector3;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),l=c.dot(this.direction),m=-c.dot(b),p=c.lengthSq(),n=Math.abs(1-k*k),q;0=-q?e<=q?(h=1/n,d*=h,e*=h,k=d*(d+k*e+2*l)+e*(k*d+e+2*m)+p):(e=h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2* -m)+p):(e=-h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*m)+p):e<=-q?(d=Math.max(0,-(-k*h+l)),e=0f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c= -this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(fg||e>d)return null;if(e>c||c!==c)c=e;if(gd?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new THREE.Vector3;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Vector3,d=new THREE.Vector3;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d); -if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.direction.add(this.origin).applyMatrix4(a);this.origin.applyMatrix4(a);this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}}; -THREE.Sphere=function(a,b){this.center=void 0!==a?a:new THREE.Vector3;this.radius=void 0!==b?b:0}; -THREE.Sphere.prototype={constructor:THREE.Sphere,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new THREE.Box3;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).center(d);for(var e=0,f=0,g=b.length;f=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c= -this.center.distanceToSquared(a),d=b||new THREE.Vector3;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=a||new THREE.Box3;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&& -a.radius===this.radius}};THREE.Frustum=function(a,b,c,d,e,f){this.planes=[void 0!==a?a:new THREE.Plane,void 0!==b?b:new THREE.Plane,void 0!==c?c:new THREE.Plane,void 0!==d?d:new THREE.Plane,void 0!==e?e:new THREE.Plane,void 0!==f?f:new THREE.Plane]}; -THREE.Frustum.prototype={constructor:THREE.Frustum,set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],l=c[7],m=c[8],p=c[9],n=c[10],q=c[11],r=c[12],s=c[13],v=c[14], -c=c[15];b[0].setComponents(f-a,l-g,q-m,c-r).normalize();b[1].setComponents(f+a,l+g,q+m,c+r).normalize();b[2].setComponents(f+d,l+h,q+p,c+s).normalize();b[3].setComponents(f-d,l-h,q-p,c-s).normalize();b[4].setComponents(f-e,l-k,q-n,c-v).normalize();b[5].setComponents(f+e,l+k,q+n,c+v).normalize();return this},intersectsObject:function(){var a=new THREE.Sphere;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(), -intersectsSprite:function(){var a=new THREE.Sphere;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}};THREE.Plane=function(a,b){this.normal=void 0!==a?a:new THREE.Vector3(1,0,0);this.constant=void 0!==b?b:0}; -THREE.Plane.prototype={constructor:THREE.Plane,set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d, -c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a, -b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new THREE.Vector3).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new THREE.Vector3;return function(b,c){var d=c||new THREE.Vector3,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/f,0>f||1b&&0a&&0e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c, -d,e){return d+(a-b)*(e-d)/(c-b)},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},random16:function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a* -(.5-Math.random())},degToRad:function(a){return a*THREE.Math.DEG2RAD},radToDeg:function(a){return a*THREE.Math.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}}; -THREE.Spline=function(a){function b(a,b,c,d,e,f,g){a=.5*(c-a);d=.5*(d-b);return(2*(b-c)+a+d)*g+(-3*(b-c)-2*a-d)*f+a*e+b}this.points=a;var c=[],d={x:0,y:0,z:0},e,f,g,h,k,l,m,p,n;this.initFromArray=function(a){this.points=[];for(var b=0;bthis.points.length-2?this.points.length-1:f+1;c[3]=f>this.points.length-3?this.points.length-1:f+ -2;l=this.points[c[0]];m=this.points[c[1]];p=this.points[c[2]];n=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,m.x,p.x,n.x,g,h,k);d.y=b(l.y,m.y,p.y,n.y,g,h,k);d.z=b(l.z,m.z,p.z,n.z,g,h,k);return d};this.getControlPointsArray=function(){var a,b,c=this.points.length,d=[];for(a=0;a=b.x+b.y}}(); -THREE.Triangle.prototype={constructor:THREE.Triangle,set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a, -this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new THREE.Vector3).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return THREE.Triangle.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new THREE.Plane).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return THREE.Triangle.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return THREE.Triangle.containsPoint(a,this.a,this.b,this.c)}, -closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new THREE.Plane,b=[new THREE.Line3,new THREE.Line3,new THREE.Line3],c=new THREE.Vector3,d=new THREE.Vector3);var g=f||new THREE.Vector3,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k=e)break a;else{f=b[1];a=e)break b}d= -c;c=0}}for(;c>>1,ad;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e, -1),c=0,g=this.faceVertexUvs.length;cb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0: -this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(d===THREE.LoopOnce)a:{if(-1===e&&(this.loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=d===THREE.LoopPingPong;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions, -d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a, -b,c){var d=this._interpolantSettings;c?(d.endingStart=THREE.ZeroSlopeEnding,d.endingEnd=THREE.ZeroSlopeEnding):(d.endingStart=a?this.zeroSlopeAtStart?THREE.ZeroSlopeEnding:THREE.ZeroCurvatureEnding:THREE.WrapAroundEnding,d.endingEnd=b?this.zeroSlopeAtEnd?THREE.ZeroSlopeEnding:THREE.ZeroCurvatureEnding:THREE.WrapAroundEnding)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions; -f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}};THREE.AnimationClip=function(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=THREE.Math.generateUUID();0>this.duration&&this.resetDuration();this.trim();this.optimize()}; -THREE.AnimationClip.prototype={constructor:THREE.AnimationClip,resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a=c){var p=c++,n=b[p];d[n.uuid]= -m;b[m]=n;d[l]=p;b[p]=k;k=0;for(l=f;k!==l;++k){var n=e[k],q=n[m];n[m]=n[p];n[p]=q}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,m=e[l];if(void 0!==m)if(delete e[l],mb;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),d=this.getValueSize(),this.times=THREE.AnimationUtils.arraySlice(c,e,f),this.values=THREE.AnimationUtils.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track", -this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&THREE.AnimationUtils.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a= -this.times,b=this.values,c=this.getValueSize(),d=1,e=1,f=a.length-1;e<=f;++e){var g=!1,h=a[e];if(h!==a[e+1]&&(1!==e||h!==h[0]))for(var k=e*c,l=k-c,m=k+c,h=0;h!==c;++h){var p=b[k+h];if(p!==b[l+h]||p!==b[m+h]){g=!0;break}}if(g){if(e!==d)for(a[d]=a[e],g=e*c,k=d*c,h=0;h!==c;++h)b[k+h]=b[g+h];++d}}d!==a.length&&(this.times=THREE.AnimationUtils.arraySlice(a,0,d),this.values=THREE.AnimationUtils.arraySlice(b,0,d*c));return this}}; -Object.assign(THREE.KeyframeTrack,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=THREE.KeyframeTrack._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];THREE.AnimationUtils.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:THREE.AnimationUtils.convertArray(a.times, -Array),values:THREE.AnimationUtils.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return THREE.NumberKeyframeTrack;case "vector":case "vector2":case "vector3":case "vector4":return THREE.VectorKeyframeTrack;case "color":return THREE.ColorKeyframeTrack;case "quaternion":return THREE.QuaternionKeyframeTrack; -case "bool":case "boolean":return THREE.BooleanKeyframeTrack;case "string":return THREE.StringKeyframeTrack}throw Error("Unsupported typeName: "+a);}});THREE.PropertyBinding=function(a,b,c){this.path=b;this.parsedPath=c||THREE.PropertyBinding.parseTrackName(b);this.node=THREE.PropertyBinding.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}; -THREE.PropertyBinding.prototype={constructor:THREE.PropertyBinding,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=THREE.PropertyBinding.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error(" can not bind to material as node does not have a material", -this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;cd&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a); -break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d,e){THREE.Quaternion.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}}; -THREE.BooleanKeyframeTrack=function(a,b,c){THREE.KeyframeTrack.call(this,a,b,c)};THREE.BooleanKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.BooleanKeyframeTrack,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:THREE.InterpolateDiscrete,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});THREE.ColorKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.ColorKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.ColorKeyframeTrack,ValueTypeName:"color"});THREE.NumberKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)};THREE.NumberKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.NumberKeyframeTrack,ValueTypeName:"number"});THREE.QuaternionKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.QuaternionKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.QuaternionKeyframeTrack,ValueTypeName:"quaternion",DefaultInterpolation:THREE.InterpolateLinear,InterpolantFactoryMethodLinear:function(a){return new THREE.QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});THREE.StringKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.StringKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.StringKeyframeTrack,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:THREE.InterpolateDiscrete,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});THREE.VectorKeyframeTrack=function(a,b,c,d){THREE.KeyframeTrack.call(this,a,b,c,d)}; -THREE.VectorKeyframeTrack.prototype=Object.assign(Object.create(THREE.KeyframeTrack.prototype),{constructor:THREE.VectorKeyframeTrack,ValueTypeName:"vector"}); -THREE.Audio=function(a){THREE.Object3D.call(this);this.type="Audio";this.context=a.context;this.source=this.context.createBufferSource();this.source.onended=this.onEnded.bind(this);this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}; -THREE.Audio.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Audio,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.source.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control."); -else{var a=this.context.createBufferSource();a.buffer=this.source.buffer;a.loop=this.source.loop;a.onended=this.source.onended;a.start(0,this.startTime);a.playbackRate.value=this.playbackRate;this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control."); -else return this.source.stop(),this.startTime=0,this.isPlaying=!1,this},connect:function(){if(0k.opacity&&(k.transparent=!0);c.setTextures(h); -return c.parse(k)}}()};THREE.Loader.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;cg;g++)n=u[k++],t=v[2*n],n=v[2*n+1],t=new THREE.Vector2(t,n),2!==g&&c.faceVertexUvs[d][h].push(t), -0!==g&&c.faceVertexUvs[d][h+1].push(t);p&&(p=3*u[k++],q.normal.set(D[p++],D[p++],D[p]),s.normal.copy(q.normal));if(r)for(d=0;4>d;d++)p=3*u[k++],r=new THREE.Vector3(D[p++],D[p++],D[p]),2!==d&&q.vertexNormals.push(r),0!==d&&s.vertexNormals.push(r);m&&(m=u[k++],m=w[m],q.color.setHex(m),s.color.setHex(m));if(b)for(d=0;4>d;d++)m=u[k++],m=w[m],2!==d&&q.vertexColors.push(new THREE.Color(m)),0!==d&&s.vertexColors.push(new THREE.Color(m));c.faces.push(q);c.faces.push(s)}else{q=new THREE.Face3;q.a=u[k++];q.b= -u[k++];q.c=u[k++];h&&(h=u[k++],q.materialIndex=h);h=c.faces.length;if(d)for(d=0;dg;g++)n=u[k++],t=v[2*n],n=v[2*n+1],t=new THREE.Vector2(t,n),c.faceVertexUvs[d][h].push(t);p&&(p=3*u[k++],q.normal.set(D[p++],D[p++],D[p]));if(r)for(d=0;3>d;d++)p=3*u[k++],r=new THREE.Vector3(D[p++],D[p++],D[p]),q.vertexNormals.push(r);m&&(m=u[k++],q.color.setHex(w[m]));if(b)for(d=0;3>d;d++)m=u[k++],q.vertexColors.push(new THREE.Color(w[m]));c.faces.push(q)}})(d);(function(){var b= -void 0!==a.influencesPerVertex?a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;dthis.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);0a.x||1a.x?0:1;break;case THREE.MirroredRepeatWrapping:1===Math.abs(Math.floor(a.x)%2)?a.x=Math.ceil(a.x)-a.x:a.x-=Math.floor(a.x)}if(0>a.y||1a.y?0:1;break;case THREE.MirroredRepeatWrapping:1=== -Math.abs(Math.floor(a.y)%2)?a.y=Math.ceil(a.y)-a.y:a.y-=Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}};Object.assign(THREE.Texture.prototype,THREE.EventDispatcher.prototype);THREE.TextureIdCount=0; -THREE.DepthTexture=function(a,b,c,d,e,f,g,h,k){THREE.Texture.call(this,null,d,e,f,g,h,THREE.DepthFormat,c,k);this.image={width:a,height:b};this.type=void 0!==c?c:THREE.UnsignedShortType;this.magFilter=void 0!==g?g:THREE.NearestFilter;this.minFilter=void 0!==h?h:THREE.NearestFilter;this.generateMipmaps=this.flipY=!1};THREE.DepthTexture.prototype=Object.create(THREE.Texture.prototype);THREE.DepthTexture.prototype.constructor=THREE.DepthTexture; -THREE.CanvasTexture=function(a,b,c,d,e,f,g,h,k){THREE.Texture.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0};THREE.CanvasTexture.prototype=Object.create(THREE.Texture.prototype);THREE.CanvasTexture.prototype.constructor=THREE.CanvasTexture;THREE.CubeTexture=function(a,b,c,d,e,f,g,h,k,l){a=void 0!==a?a:[];b=void 0!==b?b:THREE.CubeReflectionMapping;THREE.Texture.call(this,a,b,c,d,e,f,g,h,k,l);this.flipY=!1};THREE.CubeTexture.prototype=Object.create(THREE.Texture.prototype); -THREE.CubeTexture.prototype.constructor=THREE.CubeTexture;Object.defineProperty(THREE.CubeTexture.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});THREE.CompressedTexture=function(a,b,c,d,e,f,g,h,k,l,m,p){THREE.Texture.call(this,null,f,g,h,k,l,d,e,m,p);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1};THREE.CompressedTexture.prototype=Object.create(THREE.Texture.prototype);THREE.CompressedTexture.prototype.constructor=THREE.CompressedTexture; -THREE.DataTexture=function(a,b,c,d,e,f,g,h,k,l,m,p){THREE.Texture.call(this,null,f,g,h,k,l,d,e,m,p);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:THREE.NearestFilter;this.minFilter=void 0!==l?l:THREE.NearestFilter;this.generateMipmaps=this.flipY=!1};THREE.DataTexture.prototype=Object.create(THREE.Texture.prototype);THREE.DataTexture.prototype.constructor=THREE.DataTexture; -THREE.VideoTexture=function(a,b,c,d,e,f,g,h,k){function l(){requestAnimationFrame(l);a.readyState>=a.HAVE_CURRENT_DATA&&(m.needsUpdate=!0)}THREE.Texture.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var m=this;l()};THREE.VideoTexture.prototype=Object.create(THREE.Texture.prototype);THREE.VideoTexture.prototype.constructor=THREE.VideoTexture;THREE.Group=function(){THREE.Object3D.call(this);this.type="Group"};THREE.Group.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Group}); -THREE.Points=function(a,b){THREE.Object3D.call(this);this.type="Points";this.geometry=void 0!==a?a:new THREE.BufferGeometry;this.material=void 0!==b?b:new THREE.PointsMaterial({color:16777215*Math.random()})}; -THREE.Points.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Points,raycast:function(){var a=new THREE.Matrix4,b=new THREE.Ray,c=new THREE.Sphere;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(fd.far||e.push({distance:l,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,l=d.params.Points.threshold; -null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var l=l/((this.scale.x+this.scale.y+this.scale.z)/3),m=l*l,l=new THREE.Vector3;if(h instanceof THREE.BufferGeometry){var p=h.index,h=h.attributes.position.array;if(null!==p)for(var n=p.array,p=0,q=n.length;pf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far||e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,r= -q.length/3-1;gf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far||e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g instanceof THREE.Geometry)for(k=g.vertices,l=k.length,g=0;gf||(m.applyMatrix4(this.matrixWorld),s=d.ray.origin.distanceTo(m),sd.far|| -e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});THREE.LineSegments=function(a,b){THREE.Line.call(this,a,b);this.type="LineSegments"};THREE.LineSegments.prototype=Object.assign(Object.create(THREE.Line.prototype),{constructor:THREE.LineSegments}); -THREE.Mesh=function(a,b){THREE.Object3D.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new THREE.BufferGeometry;this.material=void 0!==b?b:new THREE.MeshBasicMaterial({color:16777215*Math.random()});this.drawMode=THREE.TrianglesDrawMode;this.updateMorphTargets()}; -THREE.Mesh.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.Mesh,setDrawMode:function(a){this.drawMode=a},copy:function(a){THREE.Object3D.prototype.copy.call(this,a);this.drawMode=a.drawMode;return this},updateMorphTargets:function(){if(void 0!==this.geometry.morphTargets&&0b.far?null:{distance:c,point:t.clone(),object:a}}function c(c,d,e,f,l,p,m,s){g.fromArray(f,3*p);h.fromArray(f,3*m);k.fromArray(f,3*s);if(c=b(c,d,e,g,h,k,v))l&&(n.fromArray(l,2*p),q.fromArray(l,2*m),r.fromArray(l,2*s),c.uv=a(v,g,h,k,n,q,r)),c.face=new THREE.Face3(p, -m,s,THREE.Triangle.normal(g,h,k)),c.faceIndex=p;return c}var d=new THREE.Matrix4,e=new THREE.Ray,f=new THREE.Sphere,g=new THREE.Vector3,h=new THREE.Vector3,k=new THREE.Vector3,l=new THREE.Vector3,m=new THREE.Vector3,p=new THREE.Vector3,n=new THREE.Vector2,q=new THREE.Vector2,r=new THREE.Vector2,s=new THREE.Vector3,v=new THREE.Vector3,t=new THREE.Vector3;return function(u,s){var w=this.geometry,t=this.material,z=this.matrixWorld;if(void 0!==t&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere), -f.applyMatrix4(z),!1!==u.ray.intersectsSphere(f)&&(d.getInverse(z),e.copy(u.ray).applyMatrix4(d),null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var y,A;if(w instanceof THREE.BufferGeometry){var G,B,t=w.index,z=w.attributes,w=z.position.array;void 0!==z.uv&&(y=z.uv.array);if(null!==t)for(var z=t.array,F=0,J=z.length;F= -d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;ethis.scale.x*this.scale.y/4||c.push({distance:Math.sqrt(d),point:this.position,face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}}); -THREE.LensFlare=function(a,b,c,d,e){THREE.Object3D.call(this);this.lensFlares=[];this.positionScreen=new THREE.Vector3;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}; -THREE.LensFlare.prototype=Object.assign(Object.create(THREE.Object3D.prototype),{constructor:THREE.LensFlare,copy:function(a){THREE.Object3D.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b=ca.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ca.maxTextures); -ga+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b instanceof THREE.WebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);la.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);la.setTexture2D(b,c)}}();this.setTextureCube=function(){var a= -!1;return function(b,c){b instanceof THREE.WebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b instanceof THREE.CubeTexture||Array.isArray(b.image)&&6===b.image.length?la.setTextureCube(b,c):la.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return C};this.setRenderTarget=function(a){(C=a)&&void 0===Y.get(a).__webglFramebuffer&&la.setupRenderTarget(a); -var b=a instanceof THREE.WebGLRenderTargetCube,c;a?(c=Y.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),ea=a.scissorTest,fa.copy(a.viewport)):(c=null,X.copy(ua).multiplyScalar(Z),ea=xa,fa.copy(na).multiplyScalar(Z));L!==c&&(x.bindFramebuffer(x.FRAMEBUFFER,c),L=c);R.scissor(X);R.setScissorTest(ea);R.viewport(fa);b&&(b=Y.get(a.texture),x.framebufferTexture2D(x.FRAMEBUFFER,x.COLOR_ATTACHMENT0,x.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))}; -this.readRenderTargetPixels=function(a,b,c,d,e,g){if(!1===a instanceof THREE.WebGLRenderTarget)console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var f=Y.get(a).__webglFramebuffer;if(f){var h=!1;f!==L&&(x.bindFramebuffer(x.FRAMEBUFFER,f),h=!0);try{var k=a.texture;k.format!==THREE.RGBAFormat&&t(k.format)!==x.getParameter(x.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."): -k.type===THREE.UnsignedByteType||t(k.type)===x.getParameter(x.IMPLEMENTATION_COLOR_READ_TYPE)||k.type===THREE.FloatType&&U.get("WEBGL_color_buffer_float")||k.type===THREE.HalfFloatType&&U.get("EXT_color_buffer_half_float")?x.checkFramebufferStatus(x.FRAMEBUFFER)===x.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&x.readPixels(b,c,d,e,t(k.format),t(k.type),g):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&& -x.bindFramebuffer(x.FRAMEBUFFER,L)}}}}}; -THREE.WebGLRenderTarget=function(a,b,c){this.uuid=THREE.Math.generateUUID();this.width=a;this.height=b;this.scissor=new THREE.Vector4(0,0,a,b);this.scissorTest=!1;this.viewport=new THREE.Vector4(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=THREE.LinearFilter);this.texture=new THREE.Texture(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer: -!0;this.depthTexture=null}; -Object.assign(THREE.WebGLRenderTarget.prototype,THREE.EventDispatcher.prototype,{setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture; -return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});THREE.WebGLRenderTargetCube=function(a,b,c){THREE.WebGLRenderTarget.call(this,a,b,c);this.activeMipMapLevel=this.activeCubeFace=0};THREE.WebGLRenderTargetCube.prototype=Object.create(THREE.WebGLRenderTarget.prototype);THREE.WebGLRenderTargetCube.prototype.constructor=THREE.WebGLRenderTargetCube; -THREE.WebGLBufferRenderer=function(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=f/3)};this.renderInstances=function(e){var f=b.get("ANGLE_instanced_arrays");if(null===f)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{var g=e.attributes.position,h=0,h=g instanceof THREE.InterleavedBufferAttribute?g.data.count: -g.count;f.drawArraysInstancedANGLE(d,0,h,e.maxInstancedCount);c.calls++;c.vertices+=h*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*h/3)}}}; -THREE.WebGLClipping=function(){function a(){l.value!==d&&(l.value=d,l.needsUpdate=0c){var d=b;b=c;c=d}d=a[b];return void 0===d?(a[b]=[c],!0):-1===d.indexOf(c)?(d.push(c),!0):!1}var f=new THREE.WebGLGeometries(a,b,c);this.getAttributeBuffer=function(a){return a instanceof THREE.InterleavedBufferAttribute?b.get(a.data).__webglBuffer:b.get(a).__webglBuffer};this.getWireframeAttribute= -function(c){var f=b.get(c);if(void 0!==f.wireframe)return f.wireframe;var k=[],l=c.index,m=c.attributes;c=m.position;if(null!==l)for(var m={},l=l.array,p=0,n=l.length;p/g,function(a,b){var c=THREE.ShaderChunk[b];if(void 0===c)throw Error("Can not resolve #include <"+ -b+">");return k(c)})}function l(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,b,c,d){a="";for(b=parseInt(b);bb||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return THREE.Math.isPowerOfTwo(a.width)&&THREE.Math.isPowerOfTwo(a.height)} -function l(b){return b===THREE.NearestFilter||b===THREE.NearestMipMapNearestFilter||b===THREE.NearestMipMapLinearFilter?a.NEAREST:a.LINEAR}function m(b){b=b.target;b.removeEventListener("dispose",m);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.delete(b)}v.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!== -e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b instanceof THREE.WebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.delete(b.texture);d.delete(b)}v.textures--}function n(b,g){var l=d.get(b);if(0s;s++)r[s]= -n||p?p?b.image[s].image:b.image[s]:h(b.image[s],e.maxCubemapSize);var t=k(r[0]),B=f(b.format),F=f(b.type);q(a.TEXTURE_CUBE_MAP,b,t);for(s=0;6>s;s++)if(n)for(var J,P=r[s].mipmaps,K=0,H=P.length;Kl;l++)e.__webglFramebuffer[l]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(g){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);q(a.TEXTURE_CUBE_MAP,b.texture,h);for(l= -0;6>l;l++)r(e.__webglFramebuffer[l],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+l);b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),q(a.TEXTURE_2D,b.texture,h),r(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=b instanceof THREE.WebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets"); -if(b instanceof THREE.WebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!(b.depthTexture instanceof THREE.DepthTexture))throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate= -!0);n(b.depthTexture,0);b=d.get(b.depthTexture).__webglTexture;a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,b,0)}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),s(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),s(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap= -function(b){var e=b.texture;e.generateMipmaps&&k(b)&&e.minFilter!==THREE.NearestFilter&&e.minFilter!==THREE.LinearFilter&&(b=b instanceof THREE.WebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}; -THREE.WebGLUniforms=function(){var a=new THREE.Texture,b=new THREE.CubeTexture,c=[],d=[],e=function(a,b,d){var e=a[0];if(0>=e||0 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n")); -w.compileShader(M);w.compileShader(O);w.attachShader(H,M);w.attachShader(H,O);w.linkProgram(H);A=H;t=w.getAttribLocation(A,"position");u=w.getAttribLocation(A,"uv");c=w.getUniformLocation(A,"uvOffset");d=w.getUniformLocation(A,"uvScale");e=w.getUniformLocation(A,"rotation");f=w.getUniformLocation(A,"scale");g=w.getUniformLocation(A,"color");h=w.getUniformLocation(A,"map");k=w.getUniformLocation(A,"opacity");l=w.getUniformLocation(A,"modelViewMatrix");m=w.getUniformLocation(A,"projectionMatrix");p= -w.getUniformLocation(A,"fogType");n=w.getUniformLocation(A,"fogDensity");q=w.getUniformLocation(A,"fogNear");r=w.getUniformLocation(A,"fogFar");s=w.getUniformLocation(A,"fogColor");v=w.getUniformLocation(A,"alphaTest");H=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");H.width=8;H.height=8;M=H.getContext("2d");M.fillStyle="white";M.fillRect(0,0,8,8);G=new THREE.Texture(H);G.needsUpdate=!0}w.useProgram(A);I.initAttributes();I.enableAttribute(t);I.enableAttribute(u);I.disableUnusedAttributes(); -I.disable(w.CULL_FACE);I.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,z);w.vertexAttribPointer(t,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(u,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,y);w.uniformMatrix4fv(m,!1,K.projectionMatrix.elements);I.activeTexture(w.TEXTURE0);w.uniform1i(h,0);M=H=0;(O=P.fog)?(w.uniform3f(s,O.color.r,O.color.g,O.color.b),O instanceof THREE.Fog?(w.uniform1f(q,O.near),w.uniform1f(r,O.far),w.uniform1i(p,1),M=H=1):O instanceof THREE.FogExp2&&(w.uniform1f(n,O.density), -w.uniform1i(p,2),M=H=2)):(w.uniform1i(p,0),M=H=0);for(var O=0,N=b.length;Oc)return null;var d=[],e=[],f=[],g,h,k;if(0=l--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var m;a:{var p= -m=void 0,n=void 0,q=void 0,r=void 0,s=void 0,v=void 0,t=void 0,u=void 0,p=a[e[g]].x,n=a[e[g]].y,q=a[e[h]].x,r=a[e[h]].y,s=a[e[k]].x,v=a[e[k]].y;if(Number.EPSILON>(q-p)*(v-n)-(r-n)*(s-p))m=!1;else{var D=void 0,w=void 0,I=void 0,z=void 0,y=void 0,A=void 0,G=void 0,B=void 0,F=void 0,J=void 0,F=B=G=u=t=void 0,D=s-q,w=v-r,I=p-s,z=n-v,y=q-p,A=r-n;for(m=0;m=-Number.EPSILON&& -B>=-Number.EPSILON&&G>=-Number.EPSILON)){m=!1;break a}m=!0}}if(m){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;kNumber.EPSILON){if(0G||G>p)return[];k=l*m-k*n;if(0>k||k>p)return[]}else{if(0c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,l]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;cH){console.log("Infinite Loop! Holes left:"+l.length+", Probably Hole outside Shape!");break}for(n=F;nk;k++)m=l[k].x+":"+l[k].y,m=p[m],void 0!==m&&(l[k]=m);return n.concat()},isClockWise:function(a){return 0>THREE.ShapeUtils.area(a)},b2:function(){return function(a,b,c,d){var e= -1-a;return e*e*b+2*(1-a)*a*c+a*a*d}}(),b3:function(){return function(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}}()};THREE.Curve=function(){}; -THREE.Curve.prototype={constructor:THREE.Curve,getPoint:function(a){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){a|| -(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d=0,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e- -1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0b&&(b=0);1=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a= -this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;cNumber.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.yh.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=THREE.ShapeUtils.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g, -h,k,l=[];if(1===f.length)return h=f[0],k=new THREE.Shape,k.curves=h.curves,l.push(k),l;var m=!e(f[0].getPoints()),m=a?!m:m;k=[];var p=[],n=[],q=0,r;p[q]=void 0;n[q]=[];for(var s=0,v=f.length;sb.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=THREE.CurveUtils.interpolate;return new THREE.Vector2(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))}; -THREE.EllipseCurve=function(a,b,c,d,e,f,g,h){this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0};THREE.EllipseCurve.prototype=Object.create(THREE.Curve.prototype);THREE.EllipseCurve.prototype.constructor=THREE.EllipseCurve; -THREE.EllipseCurve.prototype.getPoint=function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)c;)c+=b;for(;c>b;)c-=b;cb.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=THREE.CurveUtils.interpolate;return new THREE.Vector3(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a),c(d.z,e.z,f.z,b.z,a))}); -THREE.CatmullRomCurve3=function(){function a(){}var b=new THREE.Vector3,c=new a,d=new a,e=new a;a.prototype.init=function(a,b,c,d){this.c0=a;this.c1=c;this.c2=-3*a+3*b-2*c-d;this.c3=2*a-2*b+c+d};a.prototype.initNonuniformCatmullRom=function(a,b,c,d,e,m,p){a=((b-a)/e-(c-a)/(e+m)+(c-b)/m)*m;d=((c-b)/m-(d-b)/(m+p)+(d-c)/p)*m;this.init(b,c,a,d)};a.prototype.initCatmullRom=function(a,b,c,d,e){this.init(b,c,e*(c-a),e*(d-b))};a.prototype.calc=function(a){var b=a*a;return this.c0+this.c1*a+this.c2*b+this.c3* -b*a};return THREE.Curve.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=this.points,h,k;k=g.length;2>k&&console.log("duh, you need at least 2 points");a*=k-(this.closed?0:1);h=Math.floor(a);a-=h;this.closed?h+=0h&&(h=1);1E-4>k&&(k=h);1E-4>n&&(n=h);c.initNonuniformCatmullRom(l.x,m.x,p.x,g.x,k,h,n);d.initNonuniformCatmullRom(l.y,m.y,p.y,g.y,k,h,n);e.initNonuniformCatmullRom(l.z,m.z,p.z,g.z,k,h,n)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,m.x,p.x,g.x, -k),d.initCatmullRom(l.y,m.y,p.y,g.y,k),e.initCatmullRom(l.z,m.z,p.z,g.z,k));return new THREE.Vector3(c.calc(a),d.calc(a),e.calc(a))})}();THREE.ClosedSplineCurve3=function(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.");THREE.CatmullRomCurve3.call(this,a);this.type="catmullrom";this.closed=!0};THREE.ClosedSplineCurve3.prototype=Object.create(THREE.CatmullRomCurve3.prototype); -THREE.BoxGeometry=function(a,b,c,d,e,f){THREE.Geometry.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new THREE.BoxBufferGeometry(a,b,c,d,e,f));this.mergeVertices()};THREE.BoxGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.BoxGeometry.prototype.constructor=THREE.BoxGeometry;THREE.CubeGeometry=THREE.BoxGeometry; -THREE.BoxBufferGeometry=function(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,k,l,J,P){var K=f/l,H=g/J,M=f/2,O=g/2,N=k/2;g=l+1;for(var Q=J+1,C=f=0,L=new THREE.Vector3,E=0;En;n++){e[0]=p[g[n]];e[1]=p[g[(n+1)%3]];e.sort(c);var q=e.toString();void 0===f[q]?f[q]={vert1:e[0],vert2:e[1],face1:l, -face2:void 0}:f[q].face2=l}e=[];for(q in f)if(g=f[q],void 0===g.face2||h[g.face1].normal.dot(h[g.face2].normal)<=d)l=k[g.vert1],e.push(l.x),e.push(l.y),e.push(l.z),l=k[g.vert2],e.push(l.x),e.push(l.y),e.push(l.z);this.addAttribute("position",new THREE.BufferAttribute(new Float32Array(e),3))};THREE.EdgesGeometry.prototype=Object.create(THREE.BufferGeometry.prototype);THREE.EdgesGeometry.prototype.constructor=THREE.EdgesGeometry; -THREE.ExtrudeGeometry=function(a,b){"undefined"!==typeof a&&(THREE.Geometry.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())};THREE.ExtrudeGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.ExtrudeGeometry.prototype.constructor=THREE.ExtrudeGeometry;THREE.ExtrudeGeometry.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;dNumber.EPSILON){var k=Math.sqrt(h),l=Math.sqrt(f*f+g*g),h=b.x-e/k;b=b.y+d/k;f=((c.x-g/l-h)*g-(c.y+f/l-b)*f)/(d*g-e*f);c=h+d*f-a.x;a=b+e*f-a.y;d=c*c+a*a;if(2>=d)return new THREE.Vector2(c,a);d=Math.sqrt(d/2)}else a=!1,d>Number.EPSILON? -f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(c=-e,a=d,d=Math.sqrt(h)):(c=d,a=e,d=Math.sqrt(h/2));return new THREE.Vector2(c/d,a/d)}function e(a,b){var c,d;for(E=a.length;0<=--E;){c=E;d=E-1;0>d&&(d=a.length-1);for(var e=0,f=q+2*m,e=0;eMath.abs(b.y-c.y)?[new THREE.Vector2(b.x,1-b.z),new THREE.Vector2(c.x,1-c.z),new THREE.Vector2(d.x,1-d.z),new THREE.Vector2(e.x,1-e.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),new THREE.Vector2(e.y,1-e.z)]}};THREE.ShapeGeometry=function(a,b){THREE.Geometry.call(this);this.type="ShapeGeometry";!1===Array.isArray(a)&&(a=[a]);this.addShapeList(a,b);this.computeFaceNormals()};THREE.ShapeGeometry.prototype=Object.create(THREE.Geometry.prototype);THREE.ShapeGeometry.prototype.constructor=THREE.ShapeGeometry;THREE.ShapeGeometry.prototype.addShapeList=function(a,b){for(var c=0,d=a.length;cNumber.EPSILON&&(h.normalize(),d=Math.acos(THREE.Math.clamp(e[l-1].dot(e[l]),-1,1)),f[l].applyMatrix4(k.makeRotationAxis(h,d))),g[l].crossVectors(e[l],f[l]);if(c)for(d=Math.acos(THREE.Math.clamp(f[0].dot(f[b-1]),-1,1)),d/=b-1,0c&&1===a.x&&(a=new THREE.Vector2(a.x-1,a.y));0===b.x&&0===b.z&&(a=new THREE.Vector2(c/2/Math.PI+.5,a.y)); -return a.clone()}THREE.Geometry.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;for(var k=this,l=0,m=a.length;lq&&(.2>d&&(b[0].x+=1),.2>a&&(b[1].x+=1),.2>p&&(b[2].x+=1));l=0;for(m=this.vertices.length;lp;p++){c[0]=m[e[p]];c[1]=m[e[(p+1)%3]];c.sort(b);var n=c.toString();void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(l=h;ap;p++)d=f[k[2*a+p]],h=6*a+3*p,c[h+0]=d.x,c[h+1]=d.y, -c[h+2]=d.z;this.addAttribute("position",new THREE.BufferAttribute(c,3))}else if(a instanceof THREE.BufferGeometry){if(null!==a.index){l=a.index.array;f=a.attributes.position;e=a.groups;h=0;0===e.length&&a.addGroup(0,l.length);k=new Uint32Array(2*l.length);g=0;for(m=e.length;gp;p++)c[0]=l[a+p],c[1]=l[a+(p+1)%3],c.sort(b),n=c.toString(),void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(l=h;a< -l;a++)for(p=0;2>p;p++)h=6*a+3*p,d=k[2*a+p],c[h+0]=f.getX(d),c[h+1]=f.getY(d),c[h+2]=f.getZ(d)}else for(f=a.attributes.position.array,h=f.length/3,k=h/3,c=new Float32Array(6*h),a=0,l=k;ap;p++)h=18*a+6*p,k=9*a+3*p,c[h+0]=f[k],c[h+1]=f[k+1],c[h+2]=f[k+2],d=9*a+(p+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new THREE.BufferAttribute(c,3))}};THREE.WireframeGeometry.prototype=Object.create(THREE.BufferGeometry.prototype); -THREE.WireframeGeometry.prototype.constructor=THREE.WireframeGeometry;THREE.AxisHelper=function(a){a=a||1;var b=new Float32Array([0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a]),c=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]);a=new THREE.BufferGeometry;a.addAttribute("position",new THREE.BufferAttribute(b,3));a.addAttribute("color",new THREE.BufferAttribute(c,3));b=new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});THREE.LineSegments.call(this,a,b)};THREE.AxisHelper.prototype=Object.create(THREE.LineSegments.prototype); -THREE.AxisHelper.prototype.constructor=THREE.AxisHelper; -THREE.ArrowHelper=function(){var a=new THREE.BufferGeometry;a.addAttribute("position",new THREE.Float32Attribute([0,0,0,0,1,0],3));var b=new THREE.CylinderBufferGeometry(0,.5,1,5,1);b.translate(0,-.5,0);return function(c,d,e,f,g,h){THREE.Object3D.call(this);void 0===f&&(f=16776960);void 0===e&&(e=1);void 0===g&&(g=.2*e);void 0===h&&(h=.2*g);this.position.copy(d);this.line=new THREE.Line(a,new THREE.LineBasicMaterial({color:f}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new THREE.Mesh(b, -new THREE.MeshBasicMaterial({color:f}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(c);this.setLength(e,g,h)}}();THREE.ArrowHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.ArrowHelper.prototype.constructor=THREE.ArrowHelper; -THREE.ArrowHelper.prototype.setDirection=function(){var a=new THREE.Vector3,b;return function(c){.99999c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();THREE.ArrowHelper.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()}; -THREE.ArrowHelper.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};THREE.BoxHelper=function(a,b){void 0===b&&(b=16776960);var c=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),d=new Float32Array(24),e=new THREE.BufferGeometry;e.setIndex(new THREE.BufferAttribute(c,1));e.addAttribute("position",new THREE.BufferAttribute(d,3));THREE.LineSegments.call(this,e,new THREE.LineBasicMaterial({color:b}));void 0!==a&&this.update(a)}; -THREE.BoxHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.BoxHelper.prototype.constructor=THREE.BoxHelper; -THREE.BoxHelper.prototype.update=function(){var a=new THREE.Box3;return function(b){b instanceof THREE.Box3?a.copy(b):a.setFromObject(b);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}(); -THREE.BoundingBoxHelper=function(a,b){var c=void 0!==b?b:8947848;this.object=a;this.box=new THREE.Box3;THREE.Mesh.call(this,new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color:c,wireframe:!0}))};THREE.BoundingBoxHelper.prototype=Object.create(THREE.Mesh.prototype);THREE.BoundingBoxHelper.prototype.constructor=THREE.BoundingBoxHelper;THREE.BoundingBoxHelper.prototype.update=function(){this.box.setFromObject(this.object);this.box.size(this.scale);this.box.center(this.position)}; -THREE.CameraHelper=function(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){d.vertices.push(new THREE.Vector3);d.colors.push(new THREE.Color(b));void 0===f[a]&&(f[a]=[]);f[a].push(d.vertices.length-1)}var d=new THREE.Geometry,e=new THREE.LineBasicMaterial({color:16777215,vertexColors:THREE.FaceColors}),f={};b("n1","n2",16755200);b("n2","n4",16755200);b("n4","n3",16755200);b("n3","n1",16755200);b("f1","f2",16755200);b("f2","f4",16755200);b("f4","f3",16755200);b("f3","f1",16755200);b("n1","f1",16755200); -b("n2","f2",16755200);b("n3","f3",16755200);b("n4","f4",16755200);b("p","n1",16711680);b("p","n2",16711680);b("p","n3",16711680);b("p","n4",16711680);b("u1","u2",43775);b("u2","u3",43775);b("u3","u1",43775);b("c","t",16777215);b("p","c",3355443);b("cn1","cn2",3355443);b("cn3","cn4",3355443);b("cf1","cf2",3355443);b("cf3","cf4",3355443);THREE.LineSegments.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate= -!1;this.pointMap=f;this.update()};THREE.CameraHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.CameraHelper.prototype.constructor=THREE.CameraHelper; -THREE.CameraHelper.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=0,h=a.length;gd;d++)c.faces[d].color=this.colors[4>d?0:1];d=new THREE.MeshBasicMaterial({vertexColors:THREE.FaceColors,wireframe:!0});this.lightSphere=new THREE.Mesh(c,d);this.add(this.lightSphere);this.update()}; -THREE.HemisphereLightHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.HemisphereLightHelper.prototype.constructor=THREE.HemisphereLightHelper;THREE.HemisphereLightHelper.prototype.dispose=function(){this.lightSphere.geometry.dispose();this.lightSphere.material.dispose()}; -THREE.HemisphereLightHelper.prototype.update=function(){var a=new THREE.Vector3;return function(){this.colors[0].copy(this.light.color).multiplyScalar(this.light.intensity);this.colors[1].copy(this.light.groundColor).multiplyScalar(this.light.intensity);this.lightSphere.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());this.lightSphere.geometry.colorsNeedUpdate=!0}}(); -THREE.PointLightHelper=function(a,b){this.light=a;this.light.updateMatrixWorld();var c=new THREE.SphereBufferGeometry(b,4,2),d=new THREE.MeshBasicMaterial({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);THREE.Mesh.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1};THREE.PointLightHelper.prototype=Object.create(THREE.Mesh.prototype);THREE.PointLightHelper.prototype.constructor=THREE.PointLightHelper; -THREE.PointLightHelper.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};THREE.PointLightHelper.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}; -THREE.SkeletonHelper=function(a){this.bones=this.getBoneList(a);for(var b=new THREE.Geometry,c=0;cc;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new THREE.Float32Attribute(b,3));b=new THREE.LineBasicMaterial({fog:!1});this.cone=new THREE.LineSegments(a, -b);this.add(this.cone);this.update()};THREE.SpotLightHelper.prototype=Object.create(THREE.Object3D.prototype);THREE.SpotLightHelper.prototype.constructor=THREE.SpotLightHelper;THREE.SpotLightHelper.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()}; -THREE.SpotLightHelper.prototype.update=function(){var a=new THREE.Vector3,b=new THREE.Vector3;return function(){var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}(); -THREE.VertexNormalsHelper=function(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;c=this.object.geometry;c instanceof THREE.Geometry?b=3*c.faces.length:c instanceof THREE.BufferGeometry&&(b=c.attributes.normal.count);c=new THREE.BufferGeometry;b=new THREE.Float32Attribute(6*b,3);c.addAttribute("position",b);THREE.LineSegments.call(this,c,new THREE.LineBasicMaterial({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}; -THREE.VertexNormalsHelper.prototype=Object.create(THREE.LineSegments.prototype);THREE.VertexNormalsHelper.prototype.constructor=THREE.VertexNormalsHelper; -THREE.VertexNormalsHelper.prototype.update=function(){var a=new THREE.Vector3,b=new THREE.Vector3,c=new THREE.Matrix3;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g instanceof THREE.Geometry)for(var h=g.vertices,k=g.faces,l=g=0,m=k.length;lh.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c}; -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};THREE.MorphBlendMesh.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)}; -THREE.MorphBlendMesh.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};THREE.MorphBlendMesh.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};THREE.MorphBlendMesh.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};THREE.MorphBlendMesh.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b}; -THREE.MorphBlendMesh.prototype.getAnimationDuration=function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};THREE.MorphBlendMesh.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};THREE.MorphBlendMesh.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1}; -THREE.MorphBlendMesh.prototype.update=function(a){for(var b=0,c=this.animationsList.length;bd.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+THREE.Math.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&& -(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}}; +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.THREE=t.THREE||{})}(this,function(t){"use strict";function e(){this.isEventDispatcher=!0}function i(t,e){this.isVector2=!0,this.x=t||0,this.y=e||0}function n(e,a,o,s,h,c,l,u,p,d){this.isTexture=!0,Object.defineProperty(this,"id",{value:r()}),this.uuid=t.Math.generateUUID(),this.name="",this.sourceFile="",this.image=void 0!==e?e:n.DEFAULT_IMAGE,this.mipmaps=[],this.mapping=void 0!==a?a:n.DEFAULT_MAPPING,this.wrapS=void 0!==o?o:yr,this.wrapT=void 0!==s?s:yr,this.magFilter=void 0!==h?h:Mr,this.minFilter=void 0!==c?c:Tr,this.anisotropy=void 0!==p?p:1,this.format=void 0!==l?l:zr,this.type=void 0!==u?u:Sr,this.offset=new i(0,0),this.repeat=new i(1,1),this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=void 0!==d?d:ua,this.version=0,this.onUpdate=null}function r(){return _a++}function a(){this.isMatrix4=!0,this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function o(t,e,i,n){this.isQuaternion=!0,this._x=t||0,this._y=e||0,this._z=i||0,this._w=void 0!==n?n:1}function s(t,e,i){this.isVector3=!0,this.x=t||0,this.y=e||0,this.z=i||0}function h(t,e){function i(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);h=f.createBuffer(),c=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,h),f.bufferData(f.ARRAY_BUFFER,t,f.STATIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.bufferData(f.ELEMENT_ARRAY_BUFFER,e,f.STATIC_DRAW),l=r(),u={position:f.getAttribLocation(l,"position"),uv:f.getAttribLocation(l,"uv")},p={uvOffset:f.getUniformLocation(l,"uvOffset"),uvScale:f.getUniformLocation(l,"uvScale"),rotation:f.getUniformLocation(l,"rotation"),scale:f.getUniformLocation(l,"scale"),color:f.getUniformLocation(l,"color"),map:f.getUniformLocation(l,"map"),opacity:f.getUniformLocation(l,"opacity"),modelViewMatrix:f.getUniformLocation(l,"modelViewMatrix"),projectionMatrix:f.getUniformLocation(l,"projectionMatrix"),fogType:f.getUniformLocation(l,"fogType"),fogDensity:f.getUniformLocation(l,"fogDensity"),fogNear:f.getUniformLocation(l,"fogNear"),fogFar:f.getUniformLocation(l,"fogFar"),fogColor:f.getUniformLocation(l,"fogColor"),alphaTest:f.getUniformLocation(l,"alphaTest")};var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=8,i.height=8;var a=i.getContext("2d");a.fillStyle="white",a.fillRect(0,0,8,8),d=new n(i),d.needsUpdate=!0}function r(){var e=f.createProgram(),i=f.createShader(f.VERTEX_SHADER),n=f.createShader(f.FRAGMENT_SHADER);return f.shaderSource(i,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),f.shaderSource(n,["precision "+t.getPrecision()+" float;","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() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),f.compileShader(i),f.compileShader(n),f.attachShader(e,i),f.attachShader(e,n),f.linkProgram(e),e}function a(t,e){return t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:e.id-t.id}this.isSpritePlugin=!0;var h,c,l,u,p,d,f=t.context,m=t.state,g=new s,v=new o,y=new s;this.render=function(n,r){if(0!==e.length){void 0===l&&i(),f.useProgram(l),m.initAttributes(),m.enableAttribute(u.position),m.enableAttribute(u.uv),m.disableUnusedAttributes(),m.disable(f.CULL_FACE),m.enable(f.BLEND),f.bindBuffer(f.ARRAY_BUFFER,h),f.vertexAttribPointer(u.position,2,f.FLOAT,!1,16,0),f.vertexAttribPointer(u.uv,2,f.FLOAT,!1,16,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,c),f.uniformMatrix4fv(p.projectionMatrix,!1,r.projectionMatrix.elements),m.activeTexture(f.TEXTURE0),f.uniform1i(p.map,0);var o=0,s=0,x=n.fog;x?(f.uniform3f(p.fogColor,x.color.r,x.color.g,x.color.b),x&&x.isFog?(f.uniform1f(p.fogNear,x.near),f.uniform1f(p.fogFar,x.far),f.uniform1i(p.fogType,1),o=1,s=1):x&&x.isFogExp2&&(f.uniform1f(p.fogDensity,x.density),f.uniform1i(p.fogType,2),o=2,s=2)):(f.uniform1i(p.fogType,0),o=0,s=0);for(var b=0,_=e.length;b<_;b++){var w=e[b];w.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,w.matrixWorld),w.z=-w.modelViewMatrix.elements[14]}e.sort(a);for(var M=[],b=0,_=e.length;b<_;b++){var w=e[b],E=w.material;if(E.visible!==!1){f.uniform1f(p.alphaTest,E.alphaTest),f.uniformMatrix4fv(p.modelViewMatrix,!1,w.modelViewMatrix.elements),w.matrixWorld.decompose(g,v,y),M[0]=y.x,M[1]=y.y;var T=0;n.fog&&E.fog&&(T=s),o!==T&&(f.uniform1i(p.fogType,T),o=T),null!==E.map?(f.uniform2f(p.uvOffset,E.map.offset.x,E.map.offset.y),f.uniform2f(p.uvScale,E.map.repeat.x,E.map.repeat.y)):(f.uniform2f(p.uvOffset,0,0),f.uniform2f(p.uvScale,1,1)),f.uniform1f(p.opacity,E.opacity),f.uniform3f(p.color,E.color.r,E.color.g,E.color.b),f.uniform1f(p.rotation,E.rotation),f.uniform2fv(p.scale,M),m.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),m.setDepthTest(E.depthTest),m.setDepthWrite(E.depthWrite),E.map?t.setTexture2D(E.map,0):t.setTexture2D(d,0),f.drawElements(f.TRIANGLES,6,f.UNSIGNED_SHORT,0)}}m.enable(f.CULL_FACE),t.resetGLState()}}}function c(t,e){this.isBox2=!0,this.min=void 0!==t?t:new i((+(1/0)),(+(1/0))),this.max=void 0!==e?e:new i((-(1/0)),(-(1/0)))}function l(t,e){function n(){var t=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),e=new Uint16Array([0,1,2,0,2,3]);a=m.createBuffer(),o=m.createBuffer(),m.bindBuffer(m.ARRAY_BUFFER,a),m.bufferData(m.ARRAY_BUFFER,t,m.STATIC_DRAW),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),m.bufferData(m.ELEMENT_ARRAY_BUFFER,e,m.STATIC_DRAW),d=m.createTexture(),f=m.createTexture(),g.bindTexture(m.TEXTURE_2D,d),m.texImage2D(m.TEXTURE_2D,0,m.RGB,16,16,0,m.RGB,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),g.bindTexture(m.TEXTURE_2D,f),m.texImage2D(m.TEXTURE_2D,0,m.RGBA,16,16,0,m.RGBA,m.UNSIGNED_BYTE,null),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,m.CLAMP_TO_EDGE),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,m.NEAREST),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,m.NEAREST),h={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if ( renderType == 2 ) {","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 ) );","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;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if ( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if ( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")},l=r(h),u={vertex:m.getAttribLocation(l,"position"),uv:m.getAttribLocation(l,"uv")},p={renderType:m.getUniformLocation(l,"renderType"),map:m.getUniformLocation(l,"map"),occlusionMap:m.getUniformLocation(l,"occlusionMap"),opacity:m.getUniformLocation(l,"opacity"),color:m.getUniformLocation(l,"color"),scale:m.getUniformLocation(l,"scale"),rotation:m.getUniformLocation(l,"rotation"),screenPosition:m.getUniformLocation(l,"screenPosition")}}function r(e){var i=m.createProgram(),n=m.createShader(m.FRAGMENT_SHADER),r=m.createShader(m.VERTEX_SHADER),a="precision "+t.getPrecision()+" float;\n";return m.shaderSource(n,a+e.fragmentShader),m.shaderSource(r,a+e.vertexShader),m.compileShader(n),m.compileShader(r),m.attachShader(i,n),m.attachShader(i,r),m.linkProgram(i),i}this.isLensFlarePlugin=!0;var a,o,h,l,u,p,d,f,m=t.context,g=t.state;this.render=function(r,h,v){if(0!==e.length){var y=new s,x=v.w/v.z,b=.5*v.z,_=.5*v.w,w=16/v.w,M=new i(w*x,w),E=new s(1,1,0),T=new i(1,1),S=new c;S.min.set(0,0),S.max.set(v.z-16,v.w-16),void 0===l&&n(),m.useProgram(l),g.initAttributes(),g.enableAttribute(u.vertex),g.enableAttribute(u.uv),g.disableUnusedAttributes(),m.uniform1i(p.occlusionMap,0),m.uniform1i(p.map,1),m.bindBuffer(m.ARRAY_BUFFER,a),m.vertexAttribPointer(u.vertex,2,m.FLOAT,!1,16,0),m.vertexAttribPointer(u.uv,2,m.FLOAT,!1,16,8),m.bindBuffer(m.ELEMENT_ARRAY_BUFFER,o),g.disable(m.CULL_FACE),g.setDepthWrite(!1);for(var A=0,L=e.length;A.001&&U.scale>.001&&(E.x=U.x,E.y=U.y,E.z=U.z,w=U.size*U.scale/v.w,M.x=w*x,M.y=w,m.uniform3f(p.screenPosition,E.x,E.y,E.z),m.uniform2f(p.scale,M.x,M.y),m.uniform1f(p.rotation,U.rotation),m.uniform1f(p.opacity,U.opacity),m.uniform3f(p.color,U.color.r,U.color.g,U.color.b),g.setBlending(U.blending,U.blendEquation,U.blendSrc,U.blendDst),t.setTexture2D(U.texture,1),m.drawElements(m.TRIANGLES,6,m.UNSIGNED_SHORT,0))}}}g.enable(m.CULL_FACE),g.enable(m.DEPTH_TEST),g.setDepthWrite(!0),t.resetGLState()}}}function u(t,e,i,r,a,o,s,h,c,l){this.isCubeTexture=this.isTexture=!0,t=void 0!==t?t:[],e=void 0!==e?e:lr,n.call(this,t,e,i,r,a,o,s,h,c,l),this.flipY=!1}function p(e,i,n,r,a,o,s){function h(t,e){if(t.width>e||t.height>e){var i=e/Math.max(t.width,t.height),n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=Math.floor(t.width*i),n.height=Math.floor(t.height*i);var r=n.getContext("2d");return r.drawImage(t,0,0,t.width,t.height,0,0,n.width,n.height),console.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+n.width+"x"+n.height,t),n}return t}function c(e){return t.Math.isPowerOfTwo(e.width)&&t.Math.isPowerOfTwo(e.height)}function l(e){if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement){var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=t.Math.nearestPowerOfTwo(e.width),i.height=t.Math.nearestPowerOfTwo(e.height);var n=i.getContext("2d");return n.drawImage(e,0,0,i.width,i.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+e.width+"x"+e.height+"). Resized to "+i.width+"x"+i.height,e),i}return e}function u(t){return t.wrapS!==yr||t.wrapT!==yr||t.minFilter!==br&&t.minFilter!==Mr}function p(t){return t===br||t===_r||t===wr?e.NEAREST:e.LINEAR}function d(t){var e=t.target;e.removeEventListener("dispose",d),m(e),L.textures--}function f(t){var e=t.target;e.removeEventListener("dispose",f),g(e),L.textures--}function m(t){var i=r.get(t);if(t.image&&i.__image__webglTextureCube)e.deleteTexture(i.__image__webglTextureCube);else{if(void 0===i.__webglInit)return;e.deleteTexture(i.__webglTexture)}r.delete(t)}function g(t){var i=r.get(t),n=r.get(t.texture);if(t){if(void 0!==n.__webglTexture&&e.deleteTexture(n.__webglTexture),t.depthTexture&&t.depthTexture.dispose(),t&&t.isWebGLRenderTargetCube)for(var a=0;a<6;a++)e.deleteFramebuffer(i.__webglFramebuffer[a]),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[a]);else e.deleteFramebuffer(i.__webglFramebuffer),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer);r.delete(t.texture),r.delete(t)}}function v(t,i){var a=r.get(t);if(t.version>0&&a.__version!==t.version){var o=t.image;if(void 0===o)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",t);else{if(o.complete!==!1)return void _(a,t,i);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",t)}}n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_2D,a.__webglTexture)}function y(t,i){var s=r.get(t);if(6===t.image.length)if(t.version>0&&s.__version!==t.version){s.__image__webglTextureCube||(t.addEventListener("dispose",d),s.__image__webglTextureCube=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var l=t&&t.isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,p=[],f=0;f<6;f++)l||u?p[f]=u?t.image[f].image:t.image[f]:p[f]=h(t.image[f],a.maxCubemapSize);var m=p[0],g=c(m),v=o(t.format),y=o(t.type);b(e.TEXTURE_CUBE_MAP,t,g);for(var f=0;f<6;f++)if(l)for(var x,_=p[f].mipmaps,w=0,M=_.length;w-1?n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,v,x.width,x.height,0,v,y,x.data);else u?n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,p[f].width,p[f].height,0,v,y,p[f].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,v,v,y,p[f]);t.generateMipmaps&&g&&e.generateMipmap(e.TEXTURE_CUBE_MAP),s.__version=t.version,t.onUpdate&&t.onUpdate(t)}else n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube)}function x(t,i){n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,r.get(t).__webglTexture)}function b(t,n,s){var h;if(s?(e.texParameteri(t,e.TEXTURE_WRAP_S,o(n.wrapS)),e.texParameteri(t,e.TEXTURE_WRAP_T,o(n.wrapT)),e.texParameteri(t,e.TEXTURE_MAG_FILTER,o(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,o(n.minFilter))):(e.texParameteri(t,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(t,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),n.wrapS===yr&&n.wrapT===yr||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",n),e.texParameteri(t,e.TEXTURE_MAG_FILTER,p(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,p(n.minFilter)),n.minFilter!==br&&n.minFilter!==Mr&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",n)),h=i.get("EXT_texture_filter_anisotropic")){if(n.type===Ur&&null===i.get("OES_texture_float_linear"))return;if(n.type===Ir&&null===i.get("OES_texture_half_float_linear"))return;(n.anisotropy>1||r.get(n).__currentAnisotropy)&&(e.texParameterf(t,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n.anisotropy,a.getMaxAnisotropy())),r.get(n).__currentAnisotropy=n.anisotropy)}}function _(t,i,r){void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",d),t.__webglTexture=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+r),n.bindTexture(e.TEXTURE_2D,t.__webglTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,i.unpackAlignment);var s=h(i.image,a.maxTextureSize);u(i)&&c(s)===!1&&(s=l(s));var p=c(s),f=o(i.format),m=o(i.type);b(e.TEXTURE_2D,i,p);var g,v=i.mipmaps;if(i&&i.isDepthTexture){var y=e.DEPTH_COMPONENT;if(i.type===Ur){if(!R)throw new Error("Float Depth Texture only supported in WebGL2.0");y=e.DEPTH_COMPONENT32F}else R&&(y=e.DEPTH_COMPONENT16);n.texImage2D(e.TEXTURE_2D,0,y,s.width,s.height,0,f,m,null)}else if(i&&i.isDataTexture)if(v.length>0&&p){for(var x=0,_=v.length;x<_;x++)g=v[x],n.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);i.generateMipmaps=!1}else n.texImage2D(e.TEXTURE_2D,0,f,s.width,s.height,0,f,m,s.data);else if(i&&i.isCompressedTexture)for(var x=0,_=v.length;x<_;x++)g=v[x],i.format!==zr&&i.format!==Br?n.getCompressedTextureFormats().indexOf(f)>-1?n.compressedTexImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,g.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texImage2D(e.TEXTURE_2D,x,f,g.width,g.height,0,f,m,g.data);else if(v.length>0&&p){for(var x=0,_=v.length;x<_;x++)g=v[x],n.texImage2D(e.TEXTURE_2D,x,f,f,m,g);i.generateMipmaps=!1}else n.texImage2D(e.TEXTURE_2D,0,f,f,m,s);i.generateMipmaps&&p&&e.generateMipmap(e.TEXTURE_2D),t.__version=i.version,i.onUpdate&&i.onUpdate(i)}function w(t,i,a,s){var h=o(i.texture.format),c=o(i.texture.type);n.texImage2D(s,0,h,i.width,i.height,0,h,c,null),e.bindFramebuffer(e.FRAMEBUFFER,t),e.framebufferTexture2D(e.FRAMEBUFFER,a,s,r.get(i.texture).__webglTexture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}function M(t,i){e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer&&!i.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)):i.depthBuffer&&i.stencilBuffer?(e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,t)):e.renderbufferStorage(e.RENDERBUFFER,e.RGBA4,i.width,i.height),e.bindRenderbuffer(e.RENDERBUFFER,null)}function E(t,i){var n=i&&i.isWebGLRenderTargetCube;if(n)throw new Error("Depth Texture with cube render targets is not supported!");if(e.bindFramebuffer(e.FRAMEBUFFER,t),!i.depthTexture||!i.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");r.get(i.depthTexture).__webglTexture&&i.depthTexture.image.width===i.width&&i.depthTexture.image.height===i.height||(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),v(i.depthTexture,0);var a=r.get(i.depthTexture).__webglTexture;e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0)}function T(t){var i=r.get(t),n=t&&t.isWebGLRenderTargetCube;if(t.depthTexture){if(n)throw new Error("target.depthTexture not supported in Cube render targets");E(i.__webglFramebuffer,t)}else if(n){i.__webglDepthbuffer=[];for(var a=0;a<6;a++)e.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[a]),i.__webglDepthbuffer[a]=e.createRenderbuffer(),M(i.__webglDepthbuffer[a],t)}else e.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer=e.createRenderbuffer(),M(i.__webglDepthbuffer,t);e.bindFramebuffer(e.FRAMEBUFFER,null)}function S(t){var i=r.get(t),a=r.get(t.texture);t.addEventListener("dispose",f),a.__webglTexture=e.createTexture(),L.textures++;var o=t&&t.isWebGLRenderTargetCube,s=c(t);if(o){i.__webglFramebuffer=[];for(var h=0;h<6;h++)i.__webglFramebuffer[h]=e.createFramebuffer()}else i.__webglFramebuffer=e.createFramebuffer();if(o){n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture),b(e.TEXTURE_CUBE_MAP,t.texture,s);for(var h=0;h<6;h++)w(i.__webglFramebuffer[h],t,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+h);t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_CUBE_MAP),n.bindTexture(e.TEXTURE_CUBE_MAP,null)}else n.bindTexture(e.TEXTURE_2D,a.__webglTexture),b(e.TEXTURE_2D,t.texture,s),w(i.__webglFramebuffer,t,e.COLOR_ATTACHMENT0,e.TEXTURE_2D),t.texture.generateMipmaps&&s&&e.generateMipmap(e.TEXTURE_2D),n.bindTexture(e.TEXTURE_2D,null);t.depthBuffer&&T(t)}function A(t){var i=t.texture;if(i.generateMipmaps&&c(t)&&i.minFilter!==br&&i.minFilter!==Mr){var a=t&&t.isWebGLRenderTargetCube?e.TEXTURE_CUBE_MAP:e.TEXTURE_2D,o=r.get(i).__webglTexture;n.bindTexture(a,o),e.generateMipmap(a),n.bindTexture(a,null)}}this.isWebGLTextures=!0;var L=s.memory,R="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext;this.setTexture2D=v,this.setTextureCube=y,this.setTextureCubeDynamic=x,this.setupRenderTarget=S,this.updateRenderTargetMipmap=A}function d(t,e,i,n){this.isVector4=!0,this.x=t||0,this.y=e||0,this.z=i||0,this.w=void 0!==n?n:1}function f(t,e,i){function n(e,i,n){var r=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(var o=0;o0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.isPlane=!0,this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,i,n,r,a){this.isFrustum=!0,this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==i?i:new A,void 0!==n?n:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,n,r,o){function h(t,i,n,r){var a=t.geometry,o=null,s=A,h=t.customDepthMaterial;if(n&&(s=R,h=t.customDistanceMaterial),h)o=h;else{var c=!1;i.morphTargets&&(a&&a.isBufferGeometry?c=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(c=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&i.skinning,u=0;c&&(u|=E),l&&(u|=T),o=s[u]}if(e.localClippingEnabled&&i.clipShadows===!0&&0!==i.clippingPlanes.length){var p=o.uuid,d=i.uuid,f=P[p];void 0===f&&(f={},P[p]=f);var m=f[d];void 0===m&&(m=o.clone(),f[d]=m),o=m}o.visible=i.visible,o.wireframe=i.wireframe;var g=i.side;return V.renderSingleSided&&g==xn&&(g=vn),V.renderReverseSided&&(g===vn?g=yn:g===yn&&(g=vn)),o.side=g,o.clipShadows=i.clipShadows,o.clippingPlanes=i.clippingPlanes,o.wireframeLinewidth=i.wireframeLinewidth,o.linewidth=i.linewidth,n&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function c(t,e,i){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||p.intersectsObject(t)===!0)){var n=t.material;n.visible===!0&&(t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===xn,flipSided:t.side===yn,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var i=[];if(e.shaderID?i.push(e.shaderID):(i.push(t.fragmentShader),i.push(t.vertexShader)),void 0!==t.defines)for(var n in t.defines)i.push(n),i.push(t.defines[n]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new v(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),n.wireframe=y,y}function c(t,e,i){if(e>i){var n=e;e=i,i=n}var r=t[e];return void 0===r?(t[e]=[i],!0):r.indexOf(i)===-1&&(r.push(i),!0)}this.isWebGLObjects=!0;var l=new K(t,e,i);this.getAttributeBuffer=s,this.getWireframeAttribute=h,this.update=n}function tt(){this.isWebGLLights=!0;var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var n;switch(e.type){case"DirectionalLight":n={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"SpotLight":n={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"PointLight":n={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"HemisphereLight":n={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=n,n}}function et(t,e,i){function n(){if(void 0!==a)return a;var i=e.get("EXT_texture_filter_anisotropic");return a=null!==i?t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}this.isWebGLCapabilities=!0;var a;this.getMaxAnisotropy=n,this.getMaxPrecision=r,this.precision=void 0!==i.precision?i.precision:"highp",this.logarithmicDepthBuffer=void 0!==i.logarithmicDepthBuffer&&i.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function it(t){this.isWebGLExtensions=!0;var e={};this.get=function(i){if(void 0!==e[i])return e[i];var n;switch(i){case"WEBGL_depth_texture":n=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":n=t.getExtension("WEBGL_compressed_texture_etc1");break;default:n=t.getExtension(i)}return null===n&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),e[i]=n,n}}function nt(t,e,i){function n(t){s=t}function r(i){i.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(h=t.UNSIGNED_INT,c=4):(h=t.UNSIGNED_SHORT,c=2)}function a(e,n){t.drawElements(s,n,h,e*c),i.calls++,i.vertices+=n,s===t.TRIANGLES&&(i.faces+=n/3)}function o(n,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,h,r*c,n.maxInstancedCount),i.calls++,i.vertices+=a*n.maxInstancedCount,void(s===t.TRIANGLES&&(i.faces+=n.maxInstancedCount*a/3)))}this.isWebGLIndexedBufferRenderer=!0;var s,h,c;this.setMode=n,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),i.numPlanes=r}function e(t,e,n,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=c.value,r!==!0||null===o){var l=n+4*a,u=e.matrixWorldInverse;h.getNormalMatrix(u),(null===o||o.length0?1:-1,m[v]=C.x,m[v+1]=C.y,m[v+2]=C.z,g[y]=D/c,g[y+1]=1-U/u,v+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(p),f=new Float32Array(3*u),m=new Float32Array(3*u),g=new Float32Array(2*u),v=0,y=0,x=0,b=0,_=0;c("z","y","x",-1,-1,i,e,t,a,r,0),c("z","y","x",1,-1,i,e,-t,a,r,1),c("x","z","y",1,1,t,i,e,n,a,2),c("x","z","y",1,-1,t,i,-e,n,a,3),c("x","y","z",1,-1,t,e,i,n,r,4),c("x","y","z",-1,-1,t,e,-i,n,r,5),this.setIndex(new U(d,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(g,2))}function ht(t,e){this.isRay=!0,this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ct(t,e){this.isLine3=!0,this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,i){this.isTriangle=!0,this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==i?i:new s}function ut(t){this.isMeshBasicMaterial=this.isMaterial=!0,x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function pt(t,e){this.isMesh=!0,X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ha,this.updateMorphTargets()}function dt(t,e,i,n){this.isPlaneBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};for(var r=t/2,a=e/2,o=Math.floor(i)||1,s=Math.floor(n)||1,h=o+1,c=s+1,l=t/o,u=e/s,p=new Float32Array(h*c*3),d=new Float32Array(h*c*3),f=new Float32Array(h*c*2),m=0,g=0,v=0;v65535?Uint32Array:Uint16Array)(o*s*6),v=0;v=0){var l=a[h];if(void 0!==l){var u=ee.FLOAT,p=l.array,d=l.normalized;p instanceof Float32Array?u=ee.FLOAT:p instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):p instanceof Uint16Array?u=ee.UNSIGNED_SHORT:p instanceof Int16Array?u=ee.SHORT:p instanceof Uint32Array?u=ee.UNSIGNED_INT:p instanceof Int32Array?u=ee.INT:p instanceof Int8Array?u=ee.BYTE:p instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=he.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var g=l.data,v=g.stride,y=l.offset;g&&g.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(c,g.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=g.meshPerAttribute*g.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,v*g.array.BYTES_PER_ELEMENT,(n*v+y)*g.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(c,l.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(c),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(c,f,u,d,0,n*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[h];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(c,x);break;case 3:ee.vertexAttrib3fv(c,x);break;case 4:ee.vertexAttrib4fv(c,x);break;default:ee.vertexAttrib1fv(c,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function b(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,i,n,r){var a,o;i.transparent?(a=wt,o=++Mt):(a=bt,o=++_t);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=i,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:i,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function S(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var i=At.clippingPlanes,n=t.center,r=-t.radius,a=0;do if(i[a].distanceToPoint(n)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var p=0;p=0&&e.numSupportedMorphNormals++}var d=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,d.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,d.ambientLightColor.value=$t.ambient,d.directionalLights.value=$t.directional,d.spotLights.value=$t.spot,d.pointLights.value=$t.point,d.hemisphereLights.value=$t.hemi,d.directionalShadowMap.value=$t.directionalShadowMap,d.directionalShadowMatrix.value=$t.directionalShadowMatrix,d.spotShadowMap.value=$t.spotShadowMap, +d.spotShadowMatrix.value=$t.spotShadowMatrix,d.pointShadowMap.value=$t.pointShadowMap,d.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,d);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,d)}function N(t){t.side!==xn?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===yn),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Tn),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,i,n,r){Ft=0;var a=oe.get(n);if(qt){if(Zt||e!==It){var o=e===It&&n.id===Ct;Yt.setState(n.clippingPlanes,n.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(n.needsUpdate=!0)}void 0===a.program&&(n.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(n.needsUpdate=!0),n.needsUpdate&&(D(n,i,r),n.needsUpdate=!1);var s=!1,h=!1,c=!1,l=a.program,u=l.getUniforms(),p=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,h=!0,c=!0),n.id!==Ct&&(Ct=n.id,h=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,h=!0,c=!0),n&&n.isShaderMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n.envMap){var d=u.map.cameraPosition;void 0!==d&&d.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(n&&n.isMeshPhongMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshBasicMaterial||n&&n.isMeshStandardMaterial||n&&n.isShaderMaterial||n.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(n.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}h&&(n.lights&&X(p,c),i&&n.fog&&H(p,i),(n&&n.isMeshBasicMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n&&n.isMeshDepthMaterial)&&F(p,n),n&&n.isLineBasicMaterial?B(p,n):n&&n.isLineDashedMaterial?(B(p,n),z(p,n)):n&&n.isPointsMaterial?G(p,n):n&&n.isMeshLambertMaterial?V(p,n):n&&n.isMeshPhongMaterial?k(p,n):n&&n.isMeshPhysicalMaterial?W(p,n):n&&n.isMeshStandardMaterial?j(p,n):n&&n.isMeshDepthMaterial?n.displacementMap&&(p.displacementMap.value=n.displacementMap,p.displacementScale.value=n.displacementScale,p.displacementBias.value=n.displacementBias):n&&n.isMeshNormalMaterial&&(p.opacity.value=n.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,p,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,p,r,e),t.WebGLUniforms.upload(ee,m,p,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var i;if(e.map?i=e.map:e.specularMap?i=e.specularMap:e.displacementMap?i=e.displacementMap:e.normalMap?i=e.normalMap:e.bumpMap?i=e.bumpMap:e.roughnessMap?i=e.roughnessMap:e.metalnessMap?i=e.metalnessMap:e.alphaMap?i=e.alphaMap:e.emissiveMap&&(i=e.emissiveMap),void 0!==i){i&&i.isWebGLRenderTarget&&(i=i.texture);var n=i.offset,r=i.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Vt,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var i=e.map.offset,n=e.map.repeat;t.offsetRepeat.value.set(i.x,i.y,n.x,n.y)}}function H(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function V(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function k(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,i=0,n=t.length;i=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===vr)return ee.REPEAT;if(t===yr)return ee.CLAMP_TO_EDGE;if(t===xr)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===_r)return ee.NEAREST_MIPMAP_NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Mr)return ee.LINEAR;if(t===Er)return ee.LINEAR_MIPMAP_NEAREST;if(t===Tr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Sr)return ee.UNSIGNED_BYTE;if(t===Dr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Nr)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Or)return ee.UNSIGNED_SHORT_5_6_5;if(t===Ar)return ee.BYTE;if(t===Lr)return ee.SHORT;if(t===Rr)return ee.UNSIGNED_SHORT;if(t===Pr)return ee.INT;if(t===Cr)return ee.UNSIGNED_INT;if(t===Ur)return ee.FLOAT;if(e=ne.get("OES_texture_half_float"),null!==e&&t===Ir)return e.HALF_FLOAT_OES;if(t===Fr)return ee.ALPHA;if(t===Br)return ee.RGB;if(t===zr)return ee.RGBA;if(t===Gr)return ee.LUMINANCE;if(t===Hr)return ee.LUMINANCE_ALPHA;if(t===kr)return ee.DEPTH_COMPONENT;if(t===Cn)return ee.FUNC_ADD;if(t===Un)return ee.FUNC_SUBTRACT;if(t===In)return ee.FUNC_REVERSE_SUBTRACT;if(t===On)return ee.ZERO;if(t===Fn)return ee.ONE;if(t===Bn)return ee.SRC_COLOR;if(t===zn)return ee.ONE_MINUS_SRC_COLOR;if(t===Gn)return ee.SRC_ALPHA;if(t===Hn)return ee.ONE_MINUS_SRC_ALPHA;if(t===Vn)return ee.DST_ALPHA;if(t===kn)return ee.ONE_MINUS_DST_ALPHA;if(t===jn)return ee.DST_COLOR;if(t===Wn)return ee.ONE_MINUS_DST_COLOR;if(t===Xn)return ee.SRC_ALPHA_SATURATE;if(e=ne.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===jr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===Wr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Xr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Yr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ne.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Zr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===Jr)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===Qr)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ne.get("WEBGL_compressed_texture_etc1"),null!==e&&t===Kr)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ne.get("EXT_blend_minmax"),null!==e){if(t===Dn)return e.MIN_EXT;if(t===Nn)return e.MAX_EXT}return 0}this.isWebGLRenderer=!0,console.log("THREE.WebGLRenderer","80dev"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ht=void 0!==e.alpha&&e.alpha,ct=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,vt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],bt=[],_t=-1,wt=[],Mt=-1,Et=new Float32Array(8),Tt=[],St=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=ar,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Pt=null,Ct=-1,Ut="",It=null,Dt=new d,Nt=null,Ot=new d,Ft=0,Bt=new w(0),zt=0,Gt=K.width,Ht=K.height,Vt=1,kt=new d(0,0,Gt,Ht),jt=!1,Wt=new d(0,0,Gt,Ht),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new T,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ie={alpha:ht,depth:ct,stencil:lt,antialias:ft,premultipliedAlpha:vt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ie)||K.getContext("experimental-webgl",ie),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",c,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ne=new it(ee);ne.get("WEBGL_depth_texture"),ne.get("OES_texture_float"),ne.get("OES_texture_float_linear"),ne.get("OES_texture_half_float"),ne.get("OES_texture_half_float_linear"),ne.get("OES_standard_derivatives"),ne.get("ANGLE_instanced_arrays"),ne.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ne,e),ae=new f(ee,ne,J),oe=new P,se=new p(ee,ne,ae,oe,re,J,this.info),he=new $(ee,oe,this.info),ce=new C(this,re),le=new tt;this.info.programs=ce.programs;var ue=new at(ee,ne,te),pe=new nt(ee,ne,te),de=new gt((-1),1,1,(-1),0,1),fe=new mt,me=new pt(new dt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ge=t.ShaderLib.cube,ve=new pt(new st(5,5,5),new _({uniforms:ge.uniforms,vertexShader:ge.vertexShader,fragmentShader:ge.fragmentShader,side:yn,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ne,this.properties=oe,this.state=ae;var ye=new R(this,$t,he,re);this.shadowMap=ye;var xe=new h(this,Tt),be=new l(this,St);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ne.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Vt},this.setPixelRatio=function(t){void 0!==t&&(Vt=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:Ht}},this.setSize=function(t,e,i){Gt=t,Ht=e,K.width=t*Vt,K.height=e*Vt,i!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,i,n){ae.viewport(Wt.set(t,e,i,n))},this.setScissor=function(t,e,i,n){ae.scissor(kt.set(t,e,i,n))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,n(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,n(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,i){var n=0;(void 0===t||t)&&(n|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(n|=ee.DEPTH_BUFFER_BIT),(void 0===i||i)&&(n|=ee.STENCIL_BUFFER_BIT),ee.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,i,n){this.setRenderTarget(t),this.clear(e,i,n)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,bt=[],_t=-1,K.removeEventListener("webglcontextlost",c,!1)},this.renderBufferImmediate=function(t,e,i){ae.initAttributes();var n=oe.get(t);t.hasPositions&&!n.position&&(n.position=ee.createBuffer()),t.hasNormals&&!n.normal&&(n.normal=ee.createBuffer()),t.hasUvs&&!n.uv&&(n.uv=ee.createBuffer()),t.hasColors&&!n.color&&(n.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,n.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,n.normal),"MeshPhongMaterial"!==i.type&&"MeshStandardMaterial"!==i.type&&"MeshPhysicalMaterial"!==i.type&&i.shading===bn)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=n.morphAttributes,p=0,d=u.length;p0&&b.renderInstances(n,A,R):b.render(A,R)},this.render=function(t,e,i,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Ct=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,_t=-1,Mt=-1,Tt.length=0,St.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),bt.length=_t+1,wt.length=Mt+1,At.sortObjects===!0&&(bt.sort(x),wt.sort(b)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===i&&(i=null),this.setRenderTarget(i);var o=t.background;if(null===o?n(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&n(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ve.material.uniforms.tCube.value=o,ve.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ve.matrixWorld),he.update(ve),At.renderBufferDirect(fe,null,ve.geometry,ve.material,ve,null)):o&&o.isTexture&&(me.material.map=o,he.update(me),At.renderBufferDirect(de,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(bt,e,a,s),I(wt,e,a,s)}else ae.setBlending(Tn),I(bt,e,a),I(wt,e,a);xe.render(t,e),be.render(t,e,Ot),i&&se.updateRenderTargetMipmap(i),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===pn)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,i)}}(),this.setTexture=function(){var t=!1;return function(e,i){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,i)}}(),this.setTextureCube=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,i):se.setTextureCubeDynamic(e,i)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,i=t&&t.isWebGLRenderTargetCube;if(t){var n=oe.get(t);e=i?n.__webglFramebuffer[t.activeCubeFace]:n.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(kt).multiplyScalar(Vt),Nt=jt,Ot.copy(Wt).multiplyScalar(Vt);if(Pt!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Pt=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),i){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,i,n,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Pt&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var h=t.texture;if(h.format!==zr&&J(h.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(h.type===Sr||J(h.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||h.type===Ur&&ne.get("WEBGL_color_buffer_float")||h.type===Ir&&ne.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&ee.readPixels(e,i,n,r,J(h.format),J(h.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Pt)}}}}function yt(t,e){this.isFogExp2=!0,this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,i){this.isFog=!0,this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==i?i:1e3}function bt(){this.isScene=this.isObject3D=!0,X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function _t(t,e,i,n,r){this.isLensFlare=!0,X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,i,n,r)}function wt(t){this.isSpriteMaterial=this.isMaterial=!0,x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){this.isSprite=!0,X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){this.isLOD=!0,X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Tt(t,e,i,r,a,o,s,h,c,l,u,p){this.isDataTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={data:t,width:e,height:i},this.magFilter=void 0!==c?c:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function St(e,i,n){if(this.isSkeleton=!0,this.useVertexTexture=void 0===n||n,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new Tt(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,zr,Ur)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===i)this.calculateInverses();else if(this.bones.length===i.length)this.boneInverses=i.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}this.isVideoTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,i,r,a,o,s,h,c,l,u,p){this.isCompressedTexture=this.isTexture=!0,n.call(this,null,o,s,h,c,l,r,a,u,p),this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,i,r,a,o,s,h,c){this.isCanvasTexture=this.isTexture=!0,n.call(this,t,e,i,r,a,o,s,h,c),this.needsUpdate=!0}function Bt(t,e,i,r,a,o,s,h,c){this.isDepthTexture=this.isTexture=!0,n.call(this,null,r,a,o,s,h,kr,i,c),this.image={width:t,height:e},this.type=void 0!==i?i:Rr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==h?h:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){this.isShadowMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:ws.shadow_vert,fragmentShader:ws.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){this.isRawShaderMaterial=this.isShaderMaterial=this.isMaterial=!0,_.call(this,t),this.type="RawShaderMaterial"}function Ht(e){this.isMultiMaterial=!0,this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Vt(t){this.isMeshStandardMaterial=this.isMaterial=!0,x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function kt(t){this.isMeshPhysicalMaterial=this.isMeshStandardMaterial=this.isMaterial=!0,Vt.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){this.isMeshPhongMaterial=this.isMaterial=!0,x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){this.isMeshNormalMaterial=this.isMaterial=!0,x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){this.isMeshLambertMaterial=this.isMaterial=!0,x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=er,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){this.isLineDashedMaterial=this.isMaterial=!0,x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,i){this.isLoadingManager=!0;var n=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this.itemStart=function(t){o++,r===!1&&void 0!==n.onStart&&n.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==n.onProgress&&n.onProgress(t,a,o),a===o&&(r=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(t){void 0!==n.onError&&n.onError(t)}}function Zt(e){this.isXHRLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.isCompressedTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){this.isImageLoader=!0, +this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.isCubeTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.isTextureLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){this.isLight=!0,X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ie(t,e,i){this.isHemisphereLight=!0,ee.call(this,t,i),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ne(t){this.isLightShadow=!0,this.camera=t,this.bias=0,this.radius=1,this.mapSize=new i(512,512),this.map=null,this.matrix=new a}function re(){this.isSpotLightShadow=!0,ne.call(this,new mt(50,1,.5,500))}function ae(t,e,i,n,r,a){this.isSpotLight=!0,ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==i?i:0,this.angle=void 0!==n?n:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,i,n){this.isPointLight=!0,ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==i?i:0,this.decay=void 0!==n?n:1,this.shadow=new ne(new mt(90,1,.5,500))}function se(t){this.isDirectionalLightShadow=!0,ne.call(this,new gt((-5),5,5,(-5),.5,500))}function he(t,e){this.isDirectionalLight=!0,ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function ce(t,e){this.isAmbientLight=!0,ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,i,n){this.isInterpolant=!0,this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i}function ue(t,e,i,n){this.isCubicInterpolant=!0,le.call(this,t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function pe(t,e,i,n){this.isLinearInterpolant=!0,le.call(this,t,e,i,n)}function de(t,e,i,n){this.isDiscreteInterpolant=!0,le.call(this,t,e,i,n)}function fe(e,i,n,r){if(this.isKeyframeTrack=!0,void 0===e)throw new Error("track name is undefined");if(void 0===i||0===i.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(i,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,i,n){this.isVectorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ge(t,e,i,n){this.isQuaternionLinearInterpolant=!0,le.call(this,t,e,i,n)}function ve(t,e,i,n){this.isQuaternionKeyframeTrack=!0,fe.call(this,t,e,i,n)}function ye(t,e,i,n){this.isNumberKeyframeTrack=!0,fe.call(this,t,e,i,n)}function xe(t,e,i,n){this.isStringKeyframeTrack=!0,fe.call(this,t,e,i,n)}function be(t,e,i){this.isBooleanKeyframeTrack=!0,fe.call(this,t,e,i)}function _e(t,e,i,n){this.isColorKeyframeTrack=!0,fe.call(this,t,e,i,n)}function we(t,e,i,n){fe.apply(this,arguments)}function Me(e,i,n){this.isAnimationClip=!0,this.name=e,this.tracks=n,this.duration=void 0!==i?i:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.isMaterialLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Te(e){this.isBufferGeometryLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager}function Se(){this.isLoader=!0,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){this.isJSONLoader=!0,"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.isObjectLoader=!0,this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){this.isCurve=!0}function Pe(t,e){this.isLineCurve=this.isCurve=!0,this.v1=t,this.v2=e}function Ce(){this.isCurvePath=!0,this.curves=[],this.autoClose=!1}function Ue(t,e,i,n,r,a,o,s){this.isEllipseCurve=this.isCurve=!0,this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.isSplineCurve=this.isCurve=!0,this.points=void 0==t?[]:t}function De(t,e,i,n){this.isCubicBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i,this.v3=n}function Ne(t,e,i){this.isQuadraticBezierCurve=this.isCurve=!0,this.v0=t,this.v1=e,this.v2=i}function Oe(t,e,n,r,a,o){function h(t,e,i){return C.vertices.push(new s(t,e,i))-1}this.isTubeGeometry=this.isGeometry=!0,q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:a,taper:o},e=e||64,n=n||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var c,l,u,p,d,f,m,g,v,y,x,b,_,w,M,E,T,S,A,L,R,P=[],C=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:n+1,p[3]=n>this.points.length-3?this.points.length-1:n+2,h=this.points[p[0]],c=this.points[p[1]],l=this.points[p[2]],u=this.points[p[3]],a=r*r,o=r*a,d.x=e(h.x,c.x,l.x,u.x,r,a,o),d.y=e(h.y,c.y,l.y,u.y,r,a,o),d.z=e(h.z,c.z,l.z,u.z,r,a,o),d},this.getControlPointsArray=function(){var t,e,i=this.points.length,n=[];for(t=0;t0)&&E.push(S,A,R),(g!==i-1||h65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",p),this.boundingSphere=new T(new s,t)}function Mi(t,e){this.isPointLightHelper=this.isMesh=!0,this.light=t,this.light.updateMatrixWorld();var i=new wi(e,4,2),n=new ut({wireframe:!0,fog:!1});n.color.copy(this.light.color).multiplyScalar(this.light.intensity),pt.call(this,i,n),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Ei(t,e,i,n,r,a,o){this.isSphereGeometry=this.isGeometry=!0,q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new wi(t,e,i,n,r,a,o))}function Ti(t,e){this.isHemisphereLightHelper=this.isObject3D=!0,X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var i=new Ei(e,4,2);i.rotateX(-Math.PI/2);for(var n=0,r=8;n0&&m++,e>0&&m++);var g=l(),v=u(),y=new U(new(v>65535?Uint32Array:Uint16Array)(v),1),x=new U(new Float32Array(3*g),3),b=new U(new Float32Array(3*g),3),_=new U(new Float32Array(2*g),2),w=0,M=0,E=[],T=n/2,S=0;p(),o===!1&&(t>0&&d(!0),e>0&&d(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",b),this.addAttribute("uv",_)}function Oi(t){this.isAxisHelper=this.isLineSegments=!0,t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),i=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),n=new Q;n.addAttribute("position",new U(e,3)),n.addAttribute("color",new U(i,3));var r=new Rt({vertexColors:En});Ct.call(this,n,r)}function Fi(t,e,n){this.isParametricGeometry=this.isGeometry=!0,q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,a,o,s,h,c=this.vertices,l=this.faces,u=this.faceVertexUvs[0],p=e+1;for(r=0;r<=n;r++)for(h=r/n,a=0;a<=e;a++)s=a/e,o=t(s,h),c.push(o);var d,f,m,g,v,y,x,b;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),S<.2&&(w[2].x+=1))}for(var d=0,f=this.vertices.length;d65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=new s,b=new s,_=new i,w=new s,M=new s,E=new s,T=new s,S=new s;for(c=0;c<=n;++c){var A=c/n*a*Math.PI*2;for(h(A,a,o,t,w),h(A+.01,a,o,t,M),T.subVectors(M,w),S.addVectors(M,w),E.crossVectors(T,S),S.crossVectors(E,T),E.normalize(),S.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),P=e*Math.sin(L);x.x=w.x+(R*S.x+P*E.x),x.y=w.y+(R*S.y+P*E.y),x.z=w.z+(R*S.z+P*E.z),f.setXYZ(v,x.x,x.y,x.z),b.subVectors(x,w).normalize(),m.setXYZ(v,b.x,b.y,b.z),_.x=c/n,_.y=l/r,g.setXY(v,_.x,_.y),v++}}for(l=1;l<=n;l++)for(c=1;c<=r;c++){var C=(r+1)*(l-1)+(c-1),I=(r+1)*l+(c-1),D=(r+1)*l+c,N=(r+1)*(l-1)+c;d.setX(y,C),y++,d.setX(y,I),y++,d.setX(y,N),y++,d.setX(y,I),y++,d.setX(y,D),y++,d.setX(y,N),y++}this.setIndex(d),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",g)}function ji(t,e,i,n,r,a,o){this.isTorusKnotGeometry=this.isGeometry=!0,q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:i,radialSegments:n,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new ki(t,e,i,n,r,a)),this.mergeVertices()}function Wi(t,e,i,n,r){this.isTorusBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},t=t||100,e=e||40,i=Math.floor(i)||8,n=Math.floor(n)||6,r=r||2*Math.PI;var a,o,h=(i+1)*(n+1),c=i*n*2*3,l=new(c>65535?Uint32Array:Uint16Array)(c),u=new Float32Array(3*h),p=new Float32Array(3*h),d=new Float32Array(2*h),f=0,m=0,g=0,v=new s,y=new s,x=new s;for(a=0;a<=i;a++)for(o=0;o<=n;o++){var b=o/n*r,_=a/i*Math.PI*2;y.x=(t+e*Math.cos(_))*Math.cos(b),y.y=(t+e*Math.cos(_))*Math.sin(b),y.z=e*Math.sin(_),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,v.x=t*Math.cos(b),v.y=t*Math.sin(b),x.subVectors(y,v).normalize(),p[f]=x.x,p[f+1]=x.y,p[f+2]=x.z,d[m]=o/n,d[m+1]=a/i,f+=3,m+=2}for(a=1;a<=i;a++)for(o=1;o<=n;o++){var w=(n+1)*a+o-1,M=(n+1)*(a-1)+o-1,E=(n+1)*(a-1)+o,T=(n+1)*a+o;l[g]=w,l[g+1]=M,l[g+2]=T,l[g+3]=M,l[g+4]=E,l[g+5]=T,g+=6}this.setIndex(new U(l,1)), +this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(p,3)),this.addAttribute("uv",new U(d,2))}function Xi(t,e,i,n,r){this.isTorusGeometry=this.isGeometry=!0,q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},this.fromBufferGeometry(new Wi(t,e,i,n,r))}function Yi(t,e){this.isTextGeometry=this.isExtrudeGeometry=this.isGeometry=!0,e=e||{};var i=e.font;if((i&&i.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var n=i.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,n,e),this.type="TextGeometry"}function qi(t,e,n,r,a,o){this.isRingBufferGeometry=this.isBufferGeometry=!0,Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):1;var h,c,l,u=(n+1)*(r+1),p=n*r*2*3,d=new U(new(p>65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),g=new U(new Float32Array(2*u),2),v=0,y=0,x=t,b=(e-t)/r,_=new s,w=new i;for(c=0;c<=r;c++){for(l=0;l<=n;l++)h=a+l/n*o,_.x=x*Math.cos(h),_.y=x*Math.sin(h),f.setXYZ(v,_.x,_.y,_.z),m.setXYZ(v,0,0,1),w.x=(_.x/e+1)/2,w.y=(_.y/e+1)/2,g.setXY(v,w.x,w.y),v++;x+=b}for(c=0;c65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,g=0,v=(1/(e.length-1),1/n),y=new s,x=new i;for(h=0;h<=n;h++){var b=r+h*v*a,_=Math.sin(b),w=Math.cos(b);for(c=0;c<=e.length-1;c++)y.x=e[c].x*_,y.y=e[c].y,y.z=e[c].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=h/n,x.y=c/(e.length-1),f.setXY(m,x.x,x.y),m++}for(h=0;h0?1:+t}),void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]}}),void 0===Object.assign&&!function(){Object.assign=function(t){if(void 0===t||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),i=1;i>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return 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},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=cr,n.prototype={constructor:n,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===cr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case vr:t.x=t.x-Math.floor(t.x);break;case yr:t.x=t.x<0?0:1;break;case xr:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case vr:t.y=t.y-Math.floor(t.y);break;case yr:t.y=t.y<0?0:1;break;case xr:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var _a=0;a.prototype={constructor:a,set:function(t,e,i,n,r,a,o,s,h,c,l,u,p,d,f,m){var g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=n,g[1]=r,g[5]=a,g[9]=o,g[13]=s,g[2]=h,g[6]=c,g[10]=l,g[14]=u,g[3]=p,g[7]=d,g[11]=f,g[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),h=Math.sin(n),c=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=-s*l,e[8]=h,e[1]=p+d*h,e[5]=u-f*h,e[9]=-o*s,e[2]=f-u*h,e[6]=d+p*h,e[10]=a*s}else if("YXZ"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m+y*o,e[4]=v*o-g,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=g*o-v,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*c,g=s*l,v=h*c,y=h*l;e[0]=m-y*o,e[4]=-a*l,e[8]=v+g*o,e[1]=g+v*o,e[5]=a*c,e[9]=y-m*o,e[2]=-a*h,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*c,p=a*l,d=o*c,f=o*l;e[0]=s*c,e[4]=d*h-p,e[8]=u*h+f,e[1]=s*l,e[5]=f*h+u,e[9]=p*h-d,e[2]=-h,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=w-x*l,e[8]=_*l+b,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=b*l+_,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,b=a*h,_=o*s,w=o*h;e[0]=s*c,e[4]=-l,e[8]=h*c,e[1]=x*l+w,e[5]=a*c,e[9]=b*l-_,e[2]=_*l-b,e[6]=o*c,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,h=r+r,c=i*o,l=i*s,u=i*h,p=n*s,d=n*h,f=r*h,m=a*o,g=a*s,v=a*h;return e[0]=1-(p+f),e[4]=l-v,e[8]=u+g,e[1]=l+v,e[5]=1-(c+f),e[9]=d-m,e[2]=u-g,e[6]=d+m,e[10]=1-(c+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],h=i[12],c=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],g=i[14],v=i[3],y=i[7],x=i[11],b=i[15],_=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*_+o*T+s*R+h*I,r[4]=a*w+o*S+s*P+h*D,r[8]=a*M+o*A+s*C+h*N,r[12]=a*E+o*L+s*U+h*O,r[1]=c*_+l*T+u*R+p*I,r[5]=c*w+l*S+u*P+p*D,r[9]=c*M+l*A+u*C+p*N,r[13]=c*E+l*L+u*U+p*O,r[2]=d*_+f*T+m*R+g*I,r[6]=d*w+f*S+m*P+g*D,r[10]=d*M+f*A+m*C+g*N,r[14]=d*E+f*L+m*U+g*O,r[3]=v*_+y*T+x*R+b*I,r[7]=v*w+y*S+x*P+b*D,r[11]=v*M+y*A+x*C+b*N,r[15]=v*E+y*L+x*U+b*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-h)*e,this._y=(a-c)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-h)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+c)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-c)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(h+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+c)/e,this._y=(h+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,h=e._z,c=e._w;return this._x=i*c+a*o+n*h-r*s,this._y=n*c+a*s+r*o-i*h,this._z=r*c+a*h+i*s-n*o,this._w=a*c-i*o-n*s-r*h,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var h=Math.atan2(s,o),c=Math.sin((1-e)*h)/s,l=Math.sin(e*h)/s;return this._w=a*c+this._w*l,this._x=i*c+this._x*l,this._y=n*c+this._y*l,this._z=r*c+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],h=i[n+1],c=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||h!==p||c!==d){var m=1-o,g=s*u+h*p+c*d+l*f,v=g>=0?1:-1,y=1-g*g;if(y>Number.EPSILON){var x=Math.sqrt(y),b=Math.atan2(x,g*v);m=Math.sin(m*b)/x,o=Math.sin(o*b)/x}var _=o*v;if(s=s*m+u*_,h=h*m+p*_,c=c*m+d*_,l=l*m+f*_,m===1-o){var w=1/Math.sqrt(s*s+h*h+c*c+l*l);s*=w,h*=w,c*=w,l*=w}}t[e]=s,t[e+1]=h,t[e+2]=c,t[e+3]=l}}),s.prototype={constructor:s,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x, +this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i))}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,h=s*e+a*n-o*i,c=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=h*s+u*-r+c*-o-l*-a,this.y=c*s+u*-a+l*-r-h*-o,this.z=l*s+u*-o+h*-a-c*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return 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},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},c.prototype={constructor:c,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,h=0;s!==e;++s)h+=i,t[s].toArray(o,h)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},h=function(t,e){t.uniform1f(this.addr,e)},c=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},g=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},v=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},b=function(t,e){t.uniform3iv(this.addr,e)},_=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return h;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return g;case 35678:return v;case 35680:return y;case 5124:case 35670:return c;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return b;case 35669:case 35673:return _}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],h="]"===a[2],c=a[3];if(h&&(s=0|s),void 0===c||"["===c&&o+2===r){B(i,void 0===c?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),B(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,h=t.getUniformLocation(e,s);z(o,h,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&v>x?vx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var wa=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,i){return this.r=t,this.g=e,this.b=i,this},setHSL:function(){function e(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}return function(i,n,r){if(i=t.Math.euclideanModulo(i,1),n=t.Math.clamp(n,0,1),r=t.Math.clamp(r,0,1),0===n)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+n):r+n-r*n,o=2*r-a;this.r=e(o,a,i+1/3),this.g=e(o,a,i),this.b=e(o,a,i-1/3)}return this}}(),setStyle:function(e){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var n;if(n=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,i(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,i(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,h=parseInt(r[2],10)/100,c=parseInt(r[3],10)/100;return i(r[5]),this.setHSL(s,h,c)}}}else if(n=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=n[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var i=e>0?1/e:1;return this.r=Math.pow(t.r,i),this.g=Math.pow(t.g,i),this.b=Math.pow(t.b,i),this},convertGammaToLinear:function(){var t=this.r,e=this.g,i=this.b;return this.r=t*t,this.g=e*e,this.b=i*i,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,i,n=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),h=Math.min(r,a,o),c=(h+s)/2;if(h===s)e=0,i=0;else{var l=s-h;switch(i=c<=.5?l/(s+h):l/(2-s-h),s){case r:e=(a-o)/l+(ar&&(r=c),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,i,n),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var i=e||new s;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=t.constant&&i>=t.constant},clampPoint:function(t,e){var i=e||new s;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var i=e||new T;return i.center=this.center(),i.radius=.5*this.size(t).length(),i}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},T.prototype={constructor:T,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,i){var n=this.center;void 0!==i?n.copy(i):t.setFromPoints(e).center(n);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},S.prototype={constructor:S,set:function(t,e,i,n,r,a,o,s,h){var c=this.elements;return c[0]=t,c[1]=n,c[2]=o,c[3]=e,c[4]=r,c[5]=s,c[6]=i,c[7]=a,c[8]=h,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r1))return n.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return n.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new S;return function(i,n){var r=this.coplanarPoint(t).applyMatrix4(i),a=n||e.getNormalMatrix(i),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,i,n,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,i=0;i<6;i++)e[i].copy(t.planes[i]);return this},setFromMatrix:function(t){var e=this.planes,i=t.elements,n=i[0],r=i[1],a=i[2],o=i[3],s=i[4],h=i[5],c=i[6],l=i[7],u=i[8],p=i[9],d=i[10],f=i[11],m=i[12],g=i[13],v=i[14],y=i[15];return e[0].setComponents(o-n,l-s,f-u,y-m).normalize(),e[1].setComponents(o+n,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+h,f+p,y+g).normalize(),e[3].setComponents(o-r,l-h,f-p,y-g).normalize(),e[4].setComponents(o-a,l-c,f-d,y-v).normalize(),e[5].setComponents(o+a,l+c,f+d,y+v).normalize(),this},intersectsObject:function(){var t=new T;return function(e){var i=e.geometry;return null===i.boundingSphere&&i.computeBoundingSphere(),t.copy(i.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new T;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,i=t.center,n=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(i);if(a0?i.min.x:i.max.x,e.x=a.normal.x>0?i.max.x:i.min.x,t.y=a.normal.y>0?i.min.y:i.max.y,e.y=a.normal.y>0?i.max.y:i.min.y,t.z=a.normal.z>0?i.min.z:i.max.z,e.z=a.normal.z>0?i.max.z:i.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),i=0;i");return l(i)}var i=/#include +<([\w\d.]+)>/g;return t.replace(i,e)}function u(t){function e(t,e,i,n){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(v,m,e.extensions),R=o(y),P=g.createProgram();f&&f.isRawShaderMaterial?(T=[R].filter(h).join("\n"),S=[R].filter(h).join("\n")):(T=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(h).join("\n"), +S=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+_:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==rr?"#define TONE_MAPPING":"",m.toneMapping!==rr?ws.tonemapping_pars_fragment:"",m.toneMapping!==rr?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?ws.encodings_pars_fragment:"",m.mapEncoding?i("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?i("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?i("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?n("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(h).join("\n")),x=l(x,m),x=c(x,m),b=l(b,m),b=c(b,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),b=u(b));var C=T+x,U=S+b,I=t.WebGLShader(g,g.VERTEX_SHADER,C),D=t.WebGLShader(g,g.FRAGMENT_SHADER,U);g.attachShader(P,I),g.attachShader(P,D),void 0!==f.index0AttributeName?g.bindAttribLocation(P,0,f.index0AttributeName):m.morphTargets===!0&&g.bindAttribLocation(P,0,"position"),g.linkProgram(P);var N=g.getProgramInfoLog(P),O=g.getShaderInfoLog(I),F=g.getShaderInfoLog(D),B=!0,z=!0;g.getProgramParameter(P,g.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(P,g.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:T},fragmentShader:{log:F,prefix:S}}),g.deleteShader(I),g.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(g,P,e)),G};var H;return this.getAttributes=function(){return void 0===H&&(H=s(g,P)),H},this.destroy=function(){g.deleteProgram(P),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=p++,this.code=d,this.usedTimes=1,this.program=P,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,i){t*=this.itemSize,i*=e.itemSize;for(var n=0,r=this.itemSize;n1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(n.geometries=o),s.length>0&&(n.materials=s),h.length>0&&(n.textures=h),c.length>0&&(n.images=c)}return n.object=r,n},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var i=0;i0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,i,n,r;for(i=0,n=this.faces.length;i0&&(t+=e[i].distanceTo(e[i-1])),this.lineDistances[i]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new T),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,i){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var n,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,h=t.faces,c=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===i&&(i=0),void 0!==e&&(n=(new S).getNormalMatrix(e));for(var u=0,p=o.length;u=0;i--){var g=d[i];for(this.faces.splice(g,1),o=0,s=this.faceVertexUvs.length;o0,w=v.vertexNormals.length>0,M=1!==v.color.r||1!==v.color.g||1!==v.color.b,E=v.vertexColors.length>0,T=0;if(T=t(T,0,0),T=t(T,1,y),T=t(T,2,x),T=t(T,3,b),T=t(T,4,_),T=t(T,5,w),T=t(T,6,M),T=t(T,7,E),l.push(T),l.push(v.a,v.b,v.c),l.push(v.materialIndex),b){var S=this.faceVertexUvs[0][h];l.push(n(S[0]),n(S[1]),n(S[2]))}if(_&&l.push(e(v.normal)),w){var A=v.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(i(v.color)),E){var L=v.vertexColors;l.push(i(L[0]),i(L[1]),i(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,d.length>0&&(r.data.colors=d),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,i=0,n=e.length;i0,s=a[1]&&a[1].length>0,h=t.morphTargets,c=h.length;if(c>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var i=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(i,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var h in t.morphTargets){for(var c=[],l=t.morphTargets[h],u=0,p=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var g=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",g.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new T);var i=this.attributes.position;if(i){var n=i.array,r=this.boundingSphere.center;t.setFromArray(n),t.center(r);for(var a=0,o=0,s=n.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var h=this.boundingSphere;return null!==h&&(t.data.boundingSphere={center:h.center.toArray(),radius:h.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var i=t.attributes;for(var n in i){var r=i[n];this.addAttribute(n,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=p*f-d,h=p*d-f,l=u*g,s>=0)if(h>=-l)if(h<=l){var v=1/g;s*=v,h*=v,c=s*(s+p*h+2*d)+h*(p*s+h+2*f)+m}else h=u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h=-u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;else h<=-l?(s=Math.max(0,-(-p*u+d)),h=s>0?-u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m):h<=l?(s=0,h=Math.min(Math.max(-u,-f),u),c=h*(h+2*f)+m):(s=Math.max(0,-(p*u+d)),h=s>0?u:Math.min(Math.max(-u,-f),u),c=-s*s+h*(h+2*f)+m);else h=p>0?-u:u,s=Math.max(0,-(p*h+d)),c=-s*s+h*(h+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(h).add(t),c}}(),intersectSphere:function(){var t=new s;return function(e,i){t.subVectors(e.center,this.origin);var n=t.dot(this.direction),r=t.dot(t)-n*n,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=n-o,h=n+o;return s<0&&h<0?null:s<0?this.at(h,i):this.at(s,i)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null},intersectPlane:function(t,e){var i=this.distanceToPlane(t);return null===i?null:this.at(i,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var i=t.normal.dot(this.direction);return i*e<0},intersectBox:function(t,e){var i,n,r,a,o,s,h=1/this.direction.x,c=1/this.direction.y,l=1/this.direction.z,u=this.origin;return h>=0?(i=(t.min.x-u.x)*h,n=(t.max.x-u.x)*h):(i=(t.max.x-u.x)*h,n=(t.min.x-u.x)*h),c>=0?(r=(t.min.y-u.y)*c,a=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,a=(t.min.y-u.y)*c),i>a||r>n?null:((r>i||i!==i)&&(i=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),i>s||o>n?null:((o>i||i!==i)&&(i=o),(s=0?i:n,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,i=new s,n=new s;return function(r,a,o,s,h){e.subVectors(a,r),i.subVectors(o,r),n.crossVectors(e,i);var c,l=this.direction.dot(n);if(l>0){if(s)return null;c=1}else{if(!(l<0))return null;c=-1,l=-l}t.subVectors(this.origin,r);var u=c*this.direction.dot(i.crossVectors(t,i));if(u<0)return null;var p=c*this.direction.dot(e.cross(t));if(p<0)return null;if(u+p>l)return null;var d=-c*t.dot(n);return d<0?null:this.at(d/l,h)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ct.prototype={constructor:ct,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var i=e||new s;return this.delta(i).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,i=new s;return function(n,r){e.subVectors(n,this.start),i.subVectors(this.end,this.start);var a=i.dot(i),o=i.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,i){var n=this.closestPointToPointParameter(t,e),r=i||new s;return this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,i,n,r){var a=r||new s;a.subVectors(n,i),t.subVectors(e,i),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,i=new s;return function(n,r,a,o,h){t.subVectors(o,r),e.subVectors(a,r),i.subVectors(n,r);var c=t.dot(t),l=t.dot(e),u=t.dot(i),p=e.dot(e),d=e.dot(i),f=c*p-l*l,m=h||new s;if(0===f)return m.set(-2,-1,-1);var g=1/f,v=(p*u-l*d)*g,y=(c*d-l*u)*g;return m.set(1-v-y,y,v)}}(),lt.containsPoint=function(){var t=new s;return function(e,i,n,r){var a=lt.barycoordFromPoint(e,i,n,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this},setFromPointsAndIndices:function(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,i,n;return function(r,a){void 0===t&&(t=new A,e=[new ct,new ct,new ct],i=new s,n=new s);var o=a||new s,h=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,i),this.containsPoint(i)===!0)o.copy(i);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var c=0;c0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:c,point:b.clone(),object:t}}function n(i,n,r,a,o,s,h,p){c.fromArray(a,3*s),l.fromArray(a,3*h),u.fromArray(a,3*p);var d=e(i,n,r,c,l,u,x);return d&&(o&&(m.fromArray(o,2*s),g.fromArray(o,2*h),v.fromArray(o,2*p),d.uv=t(x,c,l,u,m,g,v)),d.face=new k(s,h,p,lt.normal(c,l,u)),d.faceIndex=s),d}var r=new a,o=new ht,h=new T,c=new s,l=new s,u=new s,p=new s,d=new s,f=new s,m=new i,g=new i,v=new i,y=new s,x=new s,b=new s;return function(i,a){var s=this.geometry,y=this.material,b=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),h.copy(s.boundingSphere),h.applyMatrix4(b),i.ray.intersectsSphere(h)!==!1&&(r.getInverse(b),o.copy(i.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var _,w;if(s&&s.isBufferGeometry){var M,E,T,S=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(_=A.uv.array),null!==S)for(var R=S.array,P=0,C=R.length;P0&&(_=z);for(var G=0,H=B.length;Gr||i.push({distance:Math.sqrt(n),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,i=0,n=e.length;i1){t.setFromMatrixPosition(i.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);n[0].object.visible=!0;for(var a=1,o=n.length;a=n[a].distance;a++)n[a-1].object.visible=!1,n[a].object.visible=!0;for(;ao)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,b=v.length/3-1;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(h&&h.isGeometry)for(var T=h.vertices,S=T.length,x=0;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Ct.prototype=Object.assign(Object.create(Pt.prototype),{constructor:Ct}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,raycast:function(){var t=new a,e=new ht,i=new T;return function(n,r){function a(t,i){var a=e.distanceSqToPoint(t);if(an.far)return;r.push({distance:h,distanceToRay:Math.sqrt(a),point:s.clone(),index:i,face:null,object:o})}}var o=this,h=this.geometry,c=this.matrixWorld,l=n.params.Points.threshold;if(null===h.boundingSphere&&h.computeBoundingSphere(),i.copy(h.boundingSphere),i.applyMatrix4(c),n.ray.intersectsSphere(i)!==!1){t.getInverse(c),e.copy(n.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),p=u*u,d=new s;if(h&&h.isBufferGeometry){var f=h.index,m=h.attributes,g=m.position.array;if(null!==f)for(var v=f.array,y=0,x=v.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=n?Br:zr,a.image=i,a.needsUpdate=!0,void 0!==e&&e(a)},i,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),e}}),ie.prototype=Object.assign(Object.create(ee.prototype),{constructor:ie,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ne.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)}}),re.prototype=Object.assign(Object.create(ne.prototype),{constructor:re,update:function(e){var i=2*t.Math.RAD2DEG*e.angle,n=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;i===a.fov&&n===a.aspect&&r===a.far||(a.fov=i,a.aspect=n,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ne.prototype),{constructor:se}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce}),t.AnimationUtils={arraySlice:function(e,i,n){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(i,n)):e.slice(i,n)},convertArray:function(t,e,i){return!t||!i&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,i){return t[e]-t[i]}for(var i=t.length,n=new Array(i),r=0;r!==i;++r)n[r]=r;return n.sort(e),n},sortedArray:function(t,e,i){for(var n=t.length,r=new t.constructor(n),a=0,o=0;o!==n;++a)for(var s=i[a]*e,h=0;h!==e;++h)r[o++]=t[s+h];return r},flattenJSON:function(t,e,i,n){for(var r=1,a=t[0];void 0!==a&&void 0===a[n];)a=t[r++];if(void 0!==a){var o=a[n];if(void 0!==o)if(Array.isArray(o)){do o=a[n],void 0!==o&&(e.push(a.time),i.push.apply(i,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[n],void 0!==o&&(e.push(a.time),o.toArray(i,i.length)),a=t[r++];while(void 0!==a)}else do o=a[n],void 0!==o&&(e.push(a.time),i.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,i=this._cachedIndex,n=e[i],r=e[i-1];t:{e:{var a;i:{n:if(!(t=r)break t;var s=e[1];t=r)break e}a=i,i=0}}for(;i>>1;ti;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(n,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,i=this.getValueSize();i-Math.floor(i)!==0&&(console.error("invalid value size in track",this),e=!1);var n=this.times,r=this.values,a=n.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var h=n[s];if("number"==typeof h&&isNaN(h)){console.error("time is not a valid number",this,s,h),e=!1;break}if(null!==o&&o>h){console.error("out of order keys",this,s,h,o),e=!1;break}o=h}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,c=r.length;s!==c;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,i=this.values,n=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,h=e[a],c=e[a+1];if(h!==c&&(1!==a||h!==h[0]))for(var l=a*n,u=l-n,p=l+n,d=0;d!==n;++d){var f=i[l+d];if(f!==i[u+d]||f!==i[p+d]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*n,g=r*n,d=0;d!==n;++d)i[g+d]=i[m+d]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(i,0,r*n)),this}},me.prototype=Object.assign(Object.create(Ss),{constructor:me,ValueTypeName:"vector"}),ge.prototype=Object.assign(Object.create(le.prototype),{constructor:ge,interpolate_:function(t,e,i,n){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,h=t*s,c=(i-e)/(n-e),l=h+s;h!==l;h+=4)o.slerpFlat(r,0,a,h-s,a,h,c);return r}}),ve.prototype=Object.assign(Object.create(Ss),{constructor:ve,ValueTypeName:"quaternion",DefaultInterpolation:na,InterpolantFactoryMethodLinear:function(t){return new ge(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ss),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ss),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:ia,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ss),{constructor:be,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:ia,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ss),{constructor:_e,ValueTypeName:"color"}),we.prototype=Ss,Ss.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var i=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var n=[],r=[];t.AnimationUtils.flattenJSON(e.keys,n,r,"value"),e.times=n,e.values=r}return void 0!==i.parse?i.parse(e):new i(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var i,n=e.constructor;if(void 0!==n.toJSON)i=n.toJSON(e);else{i={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(i.interpolation=r)}return i.type=e.ValueTypeName,i},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return _e;case"quaternion":return ve;case"bool":case"boolean":return be;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,i=0,n=t.length;i!==n;++i){var r=this.tracks[i];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var c=h[1],l=n[c];l||(n[c]=l=[]),l.push(s)}}var u=[];for(var c in n)u.push(Me.CreateFromMorphTargetSequence(c,n[c],e,i));return u},parseAnimation:function(e,i,n){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,i,n,r,a){if(0!==n.length){var o=[],s=[];t.AnimationUtils.flattenJSON(n,o,s,r),0!==o.length&&a.push(new e(i,o,s))}},a=[],o=e.name||"default",s=e.length||-1,h=e.fps||30,c=e.hierarchy||[],l=0;l1?t.skinWeights[i+1]:0,o=e>2?t.skinWeights[i+2]:0,s=e>3?t.skinWeights[i+3]:0;h.skinWeights.push(new d(r,a,o,s))}if(t.skinIndices)for(var i=0,n=t.skinIndices.length;i1?t.skinIndices[i+1]:0,u=e>2?t.skinIndices[i+2]:0,p=e>3?t.skinIndices[i+3]:0;h.skinIndices.push(new d(c,l,u,p))}h.bones=t.bones,h.bones&&h.bones.length>0&&(h.skinWeights.length!==h.skinIndices.length||h.skinIndices.length!==h.vertices.length)&&console.warn("When skinning, number of vertices ("+h.vertices.length+"), skinIndices ("+h.skinIndices.length+"), and skinWeights ("+h.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var i=0,n=t.morphTargets.length;i0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=h.faces,p=t.morphColors[0].colors,i=0,n=u.length;i0&&(h.animations=e)}var h=new q,c=void 0!==t.scale?1/t.scale:1;if(n(c),r(),a(c),o(),h.computeFaceNormals(),h.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:h};var l=Se.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:h,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,i,n){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},i,n)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var i=this.parseGeometries(t.geometries),n=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,n),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,i,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var i=new Ae,n=new Te,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,h=t.length;s0?new Lt(s,h):new pt(s,h);break;case"LOD":o=new Et;break;case"Line":o=new Pt(r(e.geometry),a(e.material),e.mode);break;case"LineSegments":o=new THREE.LineSegments(r(e.geometry),a(e.material));break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var c in e.children)o.add(this.parseObject(e.children[c],i,n));if("LOD"===e.type)for(var l=e.levels,u=0;u(c-s)*(p-h)-(l-h)*(u-s))return!1;var m,g,v,y,x,b,_,w,M,E,T,S,A,L,R;for(m=u-c,g=p-l,v=s-u,y=h-p,x=c-s,b=l-h,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(i,n){var r=i.length;if(r<3)return null;var a,o,s,h=[],c=[],l=[];if(t.ShapeUtils.area(i)>0)for(o=0;o2;){if(p--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),n?l:h;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(i,a,o,s,u,c)){var d,f,m,g,v;for(d=c[a],f=c[o],m=c[s],h.push([i[d],i[f],i[m]]),l.push([c[a],c[o],c[s]]),g=o,v=o+1;v2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,i){return t.x!==e.x?t.xNumber.EPSILON){var f;if(p>0){if(d<0||d>p)return[];if(f=c*l-h*u,f<0||f>p)return[]}else{if(d>0||d0||fT?[]:b===T?a?[]:[y]:_<=T?[y,x]:[y,M]}function o(t,e,i,n){var r=e.x-t.x,a=e.y-t.y,o=i.x-t.x,s=i.y-t.y,h=n.x-t.x,c=n.y-t.y,l=r*s-a*o,u=r*c-a*h;if(Math.abs(l)>Number.EPSILON){var p=h*s-c*o;return l>0?u>=0&&p>=0:u>=0||p>=0}return u>0}function s(t,e){function i(t,e){var i=y.length-1,n=t-1;n<0&&(n=i);var r=t+1;r>i&&(r=0);var a=o(y[t],y[n],y[r],s[e]);if(!a)return!1;var h=s.length-1,c=e-1;c<0&&(c=h);var l=e+1;return l>h&&(l=0),a=o(s[e],s[c],s[l],y[t]),!!a}function n(t,e){var i,n,r;for(i=0;i0)return!0;return!1}function r(t,i){var n,r,o,s,h;for(n=0;n0)return!0;return!1}for(var s,h,c,l,u,p,d,f,m,g,v,y=t.concat(),x=[],b=[],_=0,w=e.length;_0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(c=M;c=0)break;b[d]=!0}if(h>=0)break}}return y}n(e),i.forEach(n);for(var h,c,l,u,p,d,f={},m=e.concat(),g=0,v=i.length;g0)){h=r;break}h=r-1}if(r=h,n[r]===i){var c=r/(a-1);return c}var l=n[r],u=n[r+1],p=u-l,d=(i-l)/p,c=(r+d)/(a-1);return c},getTangent:function(t){var e=1e-4,i=t-e,n=t+e;i<0&&(i=0),n>1&&(n=1);var r=this.getPoint(i),a=this.getPoint(n),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Pe.prototype=Object.create(Re.prototype),Pe.prototype.constructor=Pe,Pe.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Pe.prototype.getPointAt=function(t){return this.getPoint(t)},Pe.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Ce.prototype=Object.assign(Object.create(Re.prototype),{constructor:Ce,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Pe(e,t))},getPoint:function(t){for(var e=t*this.getLength(),i=this.getCurveLengths(),n=0;n=e){var r=i[n]-e,a=this.curves[n],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}n++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,i=0,n=this.curves.length;i1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,i=0,n=t.length;ie;)n-=e;nn.length-2?n.length-1:a+1],l=n[a>n.length-3?n.length-1:a+2],u=t.CurveUtils.interpolate;return new i(u(s.x,h.x,c.x,l.x,o),u(s.y,h.y,c.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var n=t.ShapeUtils.b3;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var n=t.CurveUtils.tangentCubicBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var n=t.ShapeUtils.b2;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var n=t.CurveUtils.tangentQuadraticBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var As;As=Object.assign(Object.create(Ce.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,i=t.length;e0){var c=h.getPoint(0);c.equals(this.currentPoint)||this.lineTo(c.x,c.y)}this.curves.push(h);var l=h.getPoint(1);this.currentPoint.copy(l)}}),Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,i,n){function r(){g[0]=new s,v[0]=new s,h=Number.MAX_VALUE,c=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),c<=h&&(h=c,f.set(1,0,0)),l<=h&&(h=l,f.set(0,1,0)),u<=h&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),g[0].crossVectors(m[0],y),v[0].crossVectors(m[0],g[0])}var o,h,c,l,u,p,d,f=new s,m=[],g=[],v=[],y=new s,x=new a,b=i+1;for(this.tangents=m,this.normals=g,this.binormals=v,p=0;pNumber.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[p-1].dot(m[p]),-1,1)),g[p].applyMatrix4(x.makeRotationAxis(y,o))),v[p].crossVectors(m[p],g[p]);if(n)for(o=Math.acos(t.Math.clamp(g[0].dot(g[b-1]),-1,1)),o/=b-1,m[0].dot(y.crossVectors(g[0],g[b-1]))>0&&(o=-o),p=1;pNumber.EPSILON){var d=Math.sqrt(u),f=Math.sqrt(c*c+l*l),m=e.x-h/d,g=e.y+s/d,v=n.x-l/f,y=n.y+c/f,x=((v-m)*l-(y-g)*c)/(s*l-h*c);r=m+s*x-t.x,a=g+h*x-t.y;var b=r*r+a*a;if(b<=2)return new i(r,a);o=Math.sqrt(b/2)}else{var _=!1;s>Number.EPSILON?c>Number.EPSILON&&(_=!0):s<-Number.EPSILON?c<-Number.EPSILON&&(_=!0):Math.sign(h)===Math.sign(l)&&(_=!0),_?(r=-h,a=s,o=Math.sqrt(u)):(r=s,a=h,o=Math.sqrt(u/2))}return new i(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){i=Z,n=Z-1,n<0&&(n=t.length-1);var r=0,a=E+2*_;for(r=0;r=0;z--){for(H=z/_,V=x*(1-H),G=b*Math.sin(H*Math.PI/2),Z=0,J=B.length;ZNumber.EPSILON){if(c<0&&(o=e[a],h=-h,s=e[r],c=-c),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=c*(t.x-o.x)-h*(t.y-o.y);if(0===l)return!0;if(l<0)continue;n=!n}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return n}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(i===!0)return n(o);var s,h,c,l=[];if(1===o.length)return h=o[0],c=new ze,c.curves=h.curves,l.push(c),l;var u=!a(o[0].getPoints());u=e?!u:u;var p,d=[],f=[],m=[],g=0;f[g]=void 0,m[g]=[];for(var v=0,y=o.length;v1){for(var x=!1,b=[],_=0,w=f.length;_0&&(x||(m=d))}for(var L,v=0,R=f.length;v0){this.source.connect(this.filters[0]); +for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[i+a]},_slerp:function(t,e,i,n,r){o.slerpFlat(t,e,t,e,t,i,n)},_lerp:function(t,e,i,n,r){for(var a=1-n,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[i+o]*n}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,i=e.objectName,n=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(i){var a=e.objectIndex;switch(i){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=i){var u=i++,p=e[u];n[p.uuid]=l,e[l]=p,n[c]=u,e[u]=h;for(var d=0,f=a;d!==f;++d){var m=r[d],g=m[u],v=m[l];m[l]=g,m[u]=v}}}this.nCachedObjects_=i},uncache:function(t){for(var e=this._objects,i=e.length,n=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,h=arguments.length;s!==h;++s){var c=arguments[s],l=c.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var h=this._interpolants,c=this._propertyBindings,l=0,u=h.length;l!==u;++l)h[l].evaluate(o),c[l].accumulate(n,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var i=this._weightInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var i=this._timeScaleInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var i=this._clip.duration,n=this.loop,r=this._loopCount;if(n===$r){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=i)e=i;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=n===ea;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=i||e<0){var o=Math.floor(e/i);e-=i*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?i:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var h=t<0;this._setEndings(h,!h,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,i-e}return this.time=e,e},_setEndings:function(t,e,i){var n=this._interpolantSettings;i?(n.endingStart=oa,n.endingEnd=oa):(t?n.endingStart=this.zeroSlopeAtStart?oa:aa:n.endingStart=sa,e?n.endingEnd=this.zeroSlopeAtEnd?oa:aa:n.endingEnd=sa)},_scheduleFading:function(t,e,i){var n=this._mixer,r=n.time,a=this._weightInterpolant;null===a&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=i,this}},Object.assign(ii.prototype,e.prototype,{clipAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var h=o.actionByRoot[n];if(void 0!==h)return h;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var c=new ii._Action(this,r,e);return this._bindAction(c,s),this._addInactiveAction(c,a,n),c},existingAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[n]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,i=this._bindings,n=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==n;++r)i[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,i=this._nActiveActions,n=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==i;++o){var s=e[o];s.enabled&&s._update(n,t,r,a)}for(var h=this._bindings,c=this._nActiveBindings,o=0;o!==c;++o)h[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,i=t.uuid,n=this._actionsByClip,r=n[i];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var h=a[o];this._deactivateAction(h);var c=h._cacheIndex,l=e[e.length-1];h._cacheIndex=null,h._byClipCacheIndex=null,l._cacheIndex=c,e[c]=l,e.pop(),this._removeInactiveBindingsForAction(h)}delete n[i]}},uncacheRoot:function(t){var e=t.uuid,i=this._actionsByClip;for(var n in i){var r=i[n].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var h in s){var c=s[h];c.restoreOriginalState(),this._removeInactiveBinding(c)}},uncacheAction:function(t,e){var i=this.existingAction(t,e);null!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}}),ii._Action=ei._new,Object.assign(ii.prototype,{_bindAction:function(t,e){var i=t._localRoot||this._root,n=t._clip.tracks,r=n.length,a=t._propertyBindings,o=t._interpolants,s=i.uuid,h=this._bindingsByRootAndName,c=h[s];void 0===c&&(c={},h[s]=c);for(var l=0;l!==r;++l){var u=n[l],p=u.name,d=c[p];if(void 0!==d)a[l]=d;else{if(d=a[l],void 0!==d){null===d._cacheIndex&&(++d.referenceCount,this._addInactiveBinding(d,s,p));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;d=new Ke($e.create(i,p,f),u.ValueTypeName,u.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,s,p),a[l]=d}o[l].resultBuffer=d.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,i=t._clip.uuid,n=this._actionsByClip[i];this._bindAction(t,n&&n.knownActions[0]),this._addInactiveAction(t,i,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,i=0,n=e.length;i!==n;++i){var r=e[i];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var c=h[1];n[c]||(n[c]={start:1/0,end:-(1/0)});var l=n[c];al.end&&(l.end=a),e||(e=c)}}for(var c in n){var l=n[c];this.createAnimation(c,l.start,l.end,t)}this.firstAnimation=e},mi.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},mi.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},mi.prototype.setAnimationFPS=function(t,e){var i=this.animationsMap[t];i&&(i.fps=e,i.duration=(i.end-i.start)/i.fps)},mi.prototype.setAnimationDuration=function(t,e){var i=this.animationsMap[t];i&&(i.duration=e,i.fps=(i.end-i.start)/i.duration)},mi.prototype.setAnimationWeight=function(t,e){var i=this.animationsMap[t];i&&(i.weight=e)},mi.prototype.setAnimationTime=function(t,e){var i=this.animationsMap[t];i&&(i.time=e)},mi.prototype.getAnimationTime=function(t){var e=0,i=this.animationsMap[t];return i&&(e=i.time),e},mi.prototype.getAnimationDuration=function(t){var e=-1,i=this.animationsMap[t];return i&&(e=i.duration),e},mi.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},mi.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},mi.prototype.update=function(e){for(var i=0,n=this.animationsList.length;ir.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var h=r.time%a/a;r.directionBackwards&&(h=1-h),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=h*s,this.morphTargetInfluences[r.lastFrame]=(1-h)*s):this.morphTargetInfluences[r.currentFrame]=s}}},gi.prototype=Object.create(X.prototype),gi.prototype.constructor=gi,vi.prototype=Object.create(Q.prototype),vi.prototype.constructor=vi,yi.prototype=Object.create(Ct.prototype),yi.prototype.constructor=yi,xi.prototype=Object.create(Ct.prototype),xi.prototype.constructor=xi,xi.prototype.update=function(){var t=new s,e=new s,i=new S;return function(){var n=["a","b","c"];this.object.updateMatrixWorld(!0),i.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,h=o.faces,c=0,l=0,u=h.length;l.99999?this.quaternion.set(0,0,0,1):i.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(i.z,0,-i.x).normalize(),t=Math.acos(i.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,i){void 0===e&&(e=.2*t),void 0===i&&(i=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Oi.prototype=Object.create(Ct.prototype),Oi.prototype.constructor=Oi,Fi.prototype=Object.create(q.prototype),Fi.prototype.constructor=Fi,Bi.prototype=Object.create(q.prototype),Bi.prototype.constructor=Bi,zi.prototype=Object.create(Bi.prototype),zi.prototype.constructor=zi,Gi.prototype=Object.create(Bi.prototype),Gi.prototype.constructor=Gi,Hi.prototype=Object.create(Bi.prototype),Hi.prototype.constructor=Hi,Vi.prototype=Object.create(Bi.prototype),Vi.prototype.constructor=Vi,ki.prototype=Object.create(Q.prototype),ki.prototype.constructor=ki,ji.prototype=Object.create(q.prototype),ji.prototype.constructor=ji,Wi.prototype=Object.create(Q.prototype),Wi.prototype.constructor=Wi,Xi.prototype=Object.create(q.prototype),Xi.prototype.constructor=Xi,Yi.prototype=Object.create(Fe.prototype),Yi.prototype.constructor=Yi,qi.prototype=Object.create(Q.prototype),qi.prototype.constructor=qi,Zi.prototype=Object.create(q.prototype),Zi.prototype.constructor=Zi,Ji.prototype=Object.create(q.prototype),Ji.prototype.constructor=Ji,Qi.prototype=Object.create(Q.prototype),Qi.prototype.constructor=Qi,Ki.prototype=Object.create(q.prototype),Ki.prototype.constructor=Ki,$i.prototype=Object.create(q.prototype),$i.prototype.constructor=$i,tn.prototype=Object.create($i.prototype),tn.prototype.constructor=tn,en.prototype=Object.create(Q.prototype),en.prototype.constructor=en,nn.prototype=Object.create(Q.prototype),nn.prototype.constructor=nn,rn.prototype=Object.create(q.prototype),rn.prototype.constructor=rn,t.CatmullRomCurve3=function(){function t(){}var e=new s,i=new t,n=new t,r=new t;return t.prototype.init=function(t,e,i,n){this.c0=t,this.c1=i,this.c2=-3*t+3*e-2*i-n,this.c3=2*t-2*e+i+n},t.prototype.initNonuniformCatmullRom=function(t,e,i,n,r,a,o){var s=(e-t)/r-(i-t)/(r+a)+(i-e)/a,h=(i-e)/a-(n-e)/(a+o)+(n-i)/o;s*=a,h*=a,this.init(e,i,s,h)},t.prototype.initCatmullRom=function(t,e,i,n,r){this.init(e,i,r*(i-t),r*(n-e))},t.prototype.calc=function(t){var e=t*t,i=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*i},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,h,c,l=this.points;c=l.length,c<2&&console.log("duh, you need at least 2 points"),a=(c-(this.closed?0:1))*t,o=Math.floor(a),h=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===h&&o===c-1&&(o=c-2,h=1);var u,p,d,f;if(this.closed||o>0?u=l[(o-1)%c]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),p=l[o%c],d=l[(o+1)%c],this.closed||o+2i.length-2?i.length-1:r+1],l=i[r>i.length-3?i.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,h.x,c.x,l.x,a),u(o.y,h.y,c.y,l.y,a),u(o.z,h.z,c.z,l.z,a))}),t.CubicBezierCurve3=Re.create(function(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n},function(e){var i=t.ShapeUtils.b3;return new s(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),i(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,i){this.v0=t,this.v1=e,this.v2=i},function(e){var i=t.ShapeUtils.b2;return new s(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y),i(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),on.prototype=Object.create(Ue.prototype),on.prototype.constructor=on,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var i=new Dt,n=0,r=e.length;n build/three.min.js", + "dev": "rollup -c -w", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { @@ -45,6 +45,8 @@ "argparse": "^1.0.3", "chokidar-cli": "1.2.0", "jscs": "^1.13.1", + "rollup": "^0.33.1", + "rollup-plugin-string": "^2.0.2", "uglify-js": "^2.6.0" } } diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 00000000000000..79f94e6c931ccd --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,26 @@ +import * as fs from 'fs'; +import string from 'rollup-plugin-string'; + +var outro = ` +Object.defineProperty( exports, 'AudioContext', { + get: function () { + return exports.getAudioContext(); + } +});`; + +var footer = fs.readFileSync( 'src/Three.Legacy.js', 'utf-8' ); + +export default { + entry: 'src/Three.js', + dest: 'build/three.js', + moduleName: 'THREE', + format: 'umd', + plugins: [ + string({ + include: '**/*.glsl' + }) + ], + + outro: outro, + footer: footer +}; diff --git a/src/Three.js b/src/Three.js index 851975f47fbdb0..e76012b86998e9 100644 --- a/src/Three.js +++ b/src/Three.js @@ -1,335 +1,239 @@ -/** - * @author mrdoob / http://mrdoob.com/ - */ - -var THREE = { REVISION: '79' }; - -// - -if ( typeof define === 'function' && define.amd ) { - - define( 'three', THREE ); - -} else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) { - - module.exports = THREE; - -} - -// Polyfills - -if ( Number.EPSILON === undefined ) { - - Number.EPSILON = Math.pow( 2, - 52 ); - -} - -// - -if ( Math.sign === undefined ) { - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - - Math.sign = function ( x ) { - - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - - }; - -} - -if ( Function.prototype.name === undefined ) { - - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - - Object.defineProperty( Function.prototype, 'name', { - - get: function () { - - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - - } - - } ); - -} - -if ( Object.assign === undefined ) { - - // Missing in IE. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - - ( function () { - - Object.assign = function ( target ) { - - 'use strict'; - - if ( target === undefined || target === null ) { - - throw new TypeError( 'Cannot convert undefined or null to object' ); - - } - - var output = Object( target ); - - for ( var index = 1; index < arguments.length; index ++ ) { - - var source = arguments[ index ]; - - if ( source !== undefined && source !== null ) { - - for ( var nextKey in source ) { - - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - - output[ nextKey ] = source[ nextKey ]; - - } - - } - - } - - } - - return output; - - }; - - } )(); - -} - -// - -Object.assign( THREE, { - - // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button - - MOUSE: { LEFT: 0, MIDDLE: 1, RIGHT: 2 }, - - // GL STATE CONSTANTS - - CullFaceNone: 0, - CullFaceBack: 1, - CullFaceFront: 2, - CullFaceFrontBack: 3, - - FrontFaceDirectionCW: 0, - FrontFaceDirectionCCW: 1, - - // SHADOWING TYPES - - BasicShadowMap: 0, - PCFShadowMap: 1, - PCFSoftShadowMap: 2, - - // MATERIAL CONSTANTS - - // side - - FrontSide: 0, - BackSide: 1, - DoubleSide: 2, - - // shading - - FlatShading: 1, - SmoothShading: 2, - - // colors - - NoColors: 0, - FaceColors: 1, - VertexColors: 2, - - // blending modes - - NoBlending: 0, - NormalBlending: 1, - AdditiveBlending: 2, - SubtractiveBlending: 3, - MultiplyBlending: 4, - CustomBlending: 5, - - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) - - AddEquation: 100, - SubtractEquation: 101, - ReverseSubtractEquation: 102, - MinEquation: 103, - MaxEquation: 104, - - // custom blending destination factors - - ZeroFactor: 200, - OneFactor: 201, - SrcColorFactor: 202, - OneMinusSrcColorFactor: 203, - SrcAlphaFactor: 204, - OneMinusSrcAlphaFactor: 205, - DstAlphaFactor: 206, - OneMinusDstAlphaFactor: 207, - - // custom blending source factors - - //ZeroFactor: 200, - //OneFactor: 201, - //SrcAlphaFactor: 204, - //OneMinusSrcAlphaFactor: 205, - //DstAlphaFactor: 206, - //OneMinusDstAlphaFactor: 207, - DstColorFactor: 208, - OneMinusDstColorFactor: 209, - SrcAlphaSaturateFactor: 210, - - // depth modes - - NeverDepth: 0, - AlwaysDepth: 1, - LessDepth: 2, - LessEqualDepth: 3, - EqualDepth: 4, - GreaterEqualDepth: 5, - GreaterDepth: 6, - NotEqualDepth: 7, - - - // TEXTURE CONSTANTS - - MultiplyOperation: 0, - MixOperation: 1, - AddOperation: 2, - - // Tone Mapping modes - - NoToneMapping: 0, // do not do any tone mapping, not even exposure (required for special purpose passes.) - LinearToneMapping: 1, // only apply exposure. - ReinhardToneMapping: 2, - Uncharted2ToneMapping: 3, // John Hable - CineonToneMapping: 4, // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson - - // Mapping modes - - UVMapping: 300, - - CubeReflectionMapping: 301, - CubeRefractionMapping: 302, - - EquirectangularReflectionMapping: 303, - EquirectangularRefractionMapping: 304, - - SphericalReflectionMapping: 305, - CubeUVReflectionMapping: 306, - CubeUVRefractionMapping: 307, - - // Wrapping modes - - RepeatWrapping: 1000, - ClampToEdgeWrapping: 1001, - MirroredRepeatWrapping: 1002, - - // Filters - - NearestFilter: 1003, - NearestMipMapNearestFilter: 1004, - NearestMipMapLinearFilter: 1005, - LinearFilter: 1006, - LinearMipMapNearestFilter: 1007, - LinearMipMapLinearFilter: 1008, - - // Data types - - UnsignedByteType: 1009, - ByteType: 1010, - ShortType: 1011, - UnsignedShortType: 1012, - IntType: 1013, - UnsignedIntType: 1014, - FloatType: 1015, - HalfFloatType: 1025, - - // Pixel types - - //UnsignedByteType: 1009, - UnsignedShort4444Type: 1016, - UnsignedShort5551Type: 1017, - UnsignedShort565Type: 1018, - - // Pixel formats - - AlphaFormat: 1019, - RGBFormat: 1020, - RGBAFormat: 1021, - LuminanceFormat: 1022, - LuminanceAlphaFormat: 1023, - // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders - RGBEFormat: THREE.RGBAFormat, //1024; - DepthFormat: 1026, - - // DDS / ST3C Compressed texture formats - - RGB_S3TC_DXT1_Format: 2001, - RGBA_S3TC_DXT1_Format: 2002, - RGBA_S3TC_DXT3_Format: 2003, - RGBA_S3TC_DXT5_Format: 2004, - - // PVRTC compressed texture formats - - RGB_PVRTC_4BPPV1_Format: 2100, - RGB_PVRTC_2BPPV1_Format: 2101, - RGBA_PVRTC_4BPPV1_Format: 2102, - RGBA_PVRTC_2BPPV1_Format: 2103, - - // ETC compressed texture formats - - RGB_ETC1_Format: 2151, - - // Loop styles for AnimationAction - - LoopOnce: 2200, - LoopRepeat: 2201, - LoopPingPong: 2202, - - // Interpolation - - InterpolateDiscrete: 2300, - InterpolateLinear: 2301, - InterpolateSmooth: 2302, - - // Interpolant ending modes - - ZeroCurvatureEnding: 2400, - ZeroSlopeEnding: 2401, - WrapAroundEnding: 2402, - - // Triangle Draw modes - - TrianglesDrawMode: 0, - TriangleStripDrawMode: 1, - TriangleFanDrawMode: 2, - - // Texture Encodings - - LinearEncoding: 3000, // No encoding at all. - sRGBEncoding: 3001, - GammaEncoding: 3007, // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput - - // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources. - // These encodings should not specified as output encodings except in rare situations. - RGBEEncoding: 3002, // AKA Radiance. - LogLuvEncoding: 3003, - RGBM7Encoding: 3004, - RGBM16Encoding: 3005, - RGBDEncoding: 3006, // MaxRange is 256. - - // Depth packing strategies - - BasicDepthPacking: 3200, // for writing to float textures for high precision or for visualizing results in RGB buffers - RGBADepthPacking: 3201 // for packing into RGBA buffers. - -} ); +import './polyfills.js'; + +export { SpritePlugin } from './renderers/webgl/plugins/SpritePlugin.js'; +export { LensFlarePlugin } from './renderers/webgl/plugins/LensFlarePlugin.js'; +export { WebGLUniforms } from './renderers/webgl/WebGLUniforms.js'; +export { WebGLTextures } from './renderers/webgl/WebGLTextures.js'; +export { + WebGLStencilBuffer, + WebGLDepthBuffer, + WebGLColorBuffer, + WebGLState +} from './renderers/webgl/WebGLState.js'; +export { WebGLShadowMap } from './renderers/webgl/WebGLShadowMap.js'; +export { WebGLShader } from './renderers/webgl/WebGLShader.js'; +export { WebGLProperties } from './renderers/webgl/WebGLProperties.js'; +export { WebGLPrograms } from './renderers/webgl/WebGLPrograms.js'; +export { WebGLProgram } from './renderers/webgl/WebGLProgram.js'; +export { WebGLObjects } from './renderers/webgl/WebGLObjects.js'; +export { WebGLLights } from './renderers/webgl/WebGLLights.js'; +export { WebGLGeometries } from './renderers/webgl/WebGLGeometries.js'; +export { WebGLCapabilities } from './renderers/webgl/WebGLCapabilities.js'; +export { WebGLExtensions } from './renderers/webgl/WebGLExtensions.js'; +export { WebGLIndexedBufferRenderer } from './renderers/webgl/WebGLIndexedBufferRenderer.js'; +export { WebGLClipping } from './renderers/webgl/WebGLClipping.js'; +export { WebGLBufferRenderer } from './renderers/webgl/WebGLBufferRenderer.js'; +export { WebGLRenderTargetCube } from './renderers/WebGLRenderTargetCube.js'; +export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; +export { WebGLRenderer } from './renderers/WebGLRenderer.js'; +export { ShaderLib } from './renderers/shaders/ShaderLib.js'; +export { UniformsLib } from './renderers/shaders/UniformsLib.js'; +export { UniformsUtils } from './renderers/shaders/UniformsUtils.js'; +export { ShaderChunk } from './renderers/shaders/ShaderChunk.js'; +export { FogExp2 } from './scenes/FogExp2.js'; +export { Fog } from './scenes/Fog.js'; +export { Scene } from './scenes/Scene.js'; +export { LensFlare } from './objects/LensFlare.js'; +export { Sprite } from './objects/Sprite.js'; +export { LOD } from './objects/LOD.js'; +export { SkinnedMesh } from './objects/SkinnedMesh.js'; +export { Skeleton } from './objects/Skeleton.js'; +export { Bone } from './objects/Bone.js'; +export { Mesh } from './objects/Mesh.js'; +export { LineSegments } from './objects/LineSegments.js'; +export { Line } from './objects/Line.js'; +export { Points } from './objects/Points.js'; +export { Group } from './objects/Group.js'; +export { VideoTexture } from './textures/VideoTexture.js'; +export { DataTexture } from './textures/DataTexture.js'; +export { CompressedTexture } from './textures/CompressedTexture.js'; +export { CubeTexture } from './textures/CubeTexture.js'; +export { CanvasTexture } from './textures/CanvasTexture.js'; +export { DepthTexture } from './textures/DepthTexture.js'; +export { TextureIdCount, Texture } from './textures/Texture.js'; +export { ShadowMaterial } from './materials/ShadowMaterial.js'; +export { SpriteMaterial } from './materials/SpriteMaterial.js'; +export { RawShaderMaterial } from './materials/RawShaderMaterial.js'; +export { ShaderMaterial } from './materials/ShaderMaterial.js'; +export { PointsMaterial } from './materials/PointsMaterial.js'; +export { MultiMaterial } from './materials/MultiMaterial.js'; +export { MeshPhysicalMaterial } from './materials/MeshPhysicalMaterial.js'; +export { MeshStandardMaterial } from './materials/MeshStandardMaterial.js'; +export { MeshPhongMaterial } from './materials/MeshPhongMaterial.js'; +export { MeshNormalMaterial } from './materials/MeshNormalMaterial.js'; +export { MeshLambertMaterial } from './materials/MeshLambertMaterial.js'; +export { MeshDepthMaterial } from './materials/MeshDepthMaterial.js'; +export { MeshBasicMaterial } from './materials/MeshBasicMaterial.js'; +export { LineDashedMaterial } from './materials/LineDashedMaterial.js'; +export { LineBasicMaterial } from './materials/LineBasicMaterial.js'; +export { MaterialIdCount, Material } from './materials/Material.js'; +export { CompressedTextureLoader } from './loaders/CompressedTextureLoader.js'; +export { BinaryTextureLoader, DataTextureLoader } from './loaders/BinaryTextureLoader.js'; +export { CubeTextureLoader } from './loaders/CubeTextureLoader.js'; +export { TextureLoader } from './loaders/TextureLoader.js'; +export { ObjectLoader } from './loaders/ObjectLoader.js'; +export { MaterialLoader } from './loaders/MaterialLoader.js'; +export { BufferGeometryLoader } from './loaders/BufferGeometryLoader.js'; +export { DefaultLoadingManager, LoadingManager } from './loaders/LoadingManager.js'; +export { JSONLoader } from './loaders/JSONLoader.js'; +export { ImageLoader } from './loaders/ImageLoader.js'; +export { FontLoader } from './loaders/FontLoader.js'; +export { XHRLoader } from './loaders/XHRLoader.js'; +export { Loader } from './loaders/Loader.js'; +export { Cache } from './loaders/Cache.js'; +export { AudioLoader } from './loaders/AudioLoader.js'; +export { SpotLightShadow } from './lights/SpotLightShadow.js'; +export { SpotLight } from './lights/SpotLight.js'; +export { PointLight } from './lights/PointLight.js'; +export { HemisphereLight } from './lights/HemisphereLight.js'; +export { DirectionalLightShadow } from './lights/DirectionalLightShadow.js'; +export { DirectionalLight } from './lights/DirectionalLight.js'; +export { AmbientLight } from './lights/AmbientLight.js'; +export { LightShadow } from './lights/LightShadow.js'; +export { Light } from './lights/Light.js'; +export { StereoCamera } from './cameras/StereoCamera.js'; +export { PerspectiveCamera } from './cameras/PerspectiveCamera.js'; +export { OrthographicCamera } from './cameras/OrthographicCamera.js'; +export { CubeCamera } from './cameras/CubeCamera.js'; +export { Camera } from './cameras/Camera.js'; +export { AudioListener } from './audio/AudioListener.js'; +export { PositionalAudio } from './audio/PositionalAudio.js'; +export { getAudioContext } from './audio/AudioContext.js'; +export { AudioAnalyser } from './audio/AudioAnalyser.js'; +export { Audio } from './audio/Audio.js'; +export { VectorKeyframeTrack } from './animation/tracks/VectorKeyframeTrack.js'; +export { StringKeyframeTrack } from './animation/tracks/StringKeyframeTrack.js'; +export { QuaternionKeyframeTrack } from './animation/tracks/QuaternionKeyframeTrack.js'; +export { NumberKeyframeTrack } from './animation/tracks/NumberKeyframeTrack.js'; +export { ColorKeyframeTrack } from './animation/tracks/ColorKeyframeTrack.js'; +export { BooleanKeyframeTrack } from './animation/tracks/BooleanKeyframeTrack.js'; +export { PropertyMixer } from './animation/PropertyMixer.js'; +export { PropertyBinding } from './animation/PropertyBinding.js'; +export { KeyframeTrack } from './animation/KeyframeTrack.js'; +export { AnimationUtils } from './animation/AnimationUtils.js'; +export { AnimationObjectGroup } from './animation/AnimationObjectGroup.js'; +export { AnimationMixer } from './animation/AnimationMixer.js'; +export { AnimationClip } from './animation/AnimationClip.js'; +export { AnimationAction } from './animation/AnimationAction.js'; +export { Uniform } from './core/Uniform.js'; +export { InstancedBufferGeometry } from './core/InstancedBufferGeometry.js'; +export { BufferGeometry } from './core/BufferGeometry.js'; +export { DirectGeometry } from './core/DirectGeometry.js'; +export { GeometryIdCount, Geometry } from './core/Geometry.js'; +export { InterleavedBufferAttribute } from './core/InterleavedBufferAttribute.js'; +export { InstancedInterleavedBuffer } from './core/InstancedInterleavedBuffer.js'; +export { InterleavedBuffer } from './core/InterleavedBuffer.js'; +export { InstancedBufferAttribute } from './core/InstancedBufferAttribute.js'; +export { + DynamicBufferAttribute, + Float64Attribute, + Float32Attribute, + Uint32Attribute, + Int32Attribute, + Uint16Attribute, + Int16Attribute, + Uint8ClampedAttribute, + Uint8Attribute, + Int8Attribute, + BufferAttribute +} from './core/BufferAttribute.js'; +export { Face3 } from './core/Face3.js'; +export { Object3DIdCount, Object3D } from './core/Object3D.js'; +export { Raycaster } from './core/Raycaster.js'; +export { Layers } from './core/Layers.js'; +export { EventDispatcher } from './core/EventDispatcher.js'; +export { Clock } from './core/Clock.js'; +export { QuaternionLinearInterpolant } from './math/interpolants/QuaternionLinearInterpolant.js'; +export { LinearInterpolant } from './math/interpolants/LinearInterpolant.js'; +export { DiscreteInterpolant } from './math/interpolants/DiscreteInterpolant.js'; +export { CubicInterpolant } from './math/interpolants/CubicInterpolant.js'; +export { Interpolant } from './math/Interpolant.js'; +export { Triangle } from './math/Triangle.js'; +export { Spline } from './math/Spline.js'; +export { _Math as Math } from './math/Math.js'; +export { Spherical } from './math/Spherical.js'; +export { Plane } from './math/Plane.js'; +export { Frustum } from './math/Frustum.js'; +export { Sphere } from './math/Sphere.js'; +export { Ray } from './math/Ray.js'; +export { Matrix4 } from './math/Matrix4.js'; +export { Matrix3 } from './math/Matrix3.js'; +export { Box3 } from './math/Box3.js'; +export { Box2 } from './math/Box2.js'; +export { Line3 } from './math/Line3.js'; +export { Euler } from './math/Euler.js'; +export { Vector4 } from './math/Vector4.js'; +export { Vector3 } from './math/Vector3.js'; +export { Vector2 } from './math/Vector2.js'; +export { Quaternion } from './math/Quaternion.js'; +export { ColorKeywords, Color } from './math/Color.js'; +export { MorphBlendMesh } from './extras/objects/MorphBlendMesh.js'; +export { ImmediateRenderObject } from './extras/objects/ImmediateRenderObject.js'; +export { WireframeHelper } from './extras/helpers/WireframeHelper.js'; +export { VertexNormalsHelper } from './extras/helpers/VertexNormalsHelper.js'; +export { SpotLightHelper } from './extras/helpers/SpotLightHelper.js'; +export { SkeletonHelper } from './extras/helpers/SkeletonHelper.js'; +export { PointLightHelper } from './extras/helpers/PointLightHelper.js'; +export { HemisphereLightHelper } from './extras/helpers/HemisphereLightHelper.js'; +export { GridHelper } from './extras/helpers/GridHelper.js'; +export { FaceNormalsHelper } from './extras/helpers/FaceNormalsHelper.js'; +export { EdgesHelper } from './extras/helpers/EdgesHelper.js'; +export { DirectionalLightHelper } from './extras/helpers/DirectionalLightHelper.js'; +export { CameraHelper } from './extras/helpers/CameraHelper.js'; +export { BoundingBoxHelper } from './extras/helpers/BoundingBoxHelper.js'; +export { BoxHelper } from './extras/helpers/BoxHelper.js'; +export { ArrowHelper } from './extras/helpers/ArrowHelper.js'; +export { AxisHelper } from './extras/helpers/AxisHelper.js'; +export { WireframeGeometry } from './extras/geometries/WireframeGeometry.js'; +export { ParametricGeometry } from './extras/geometries/ParametricGeometry.js'; +export { TetrahedronGeometry } from './extras/geometries/TetrahedronGeometry.js'; +export { OctahedronGeometry } from './extras/geometries/OctahedronGeometry.js'; +export { IcosahedronGeometry } from './extras/geometries/IcosahedronGeometry.js'; +export { DodecahedronGeometry } from './extras/geometries/DodecahedronGeometry.js'; +export { PolyhedronGeometry } from './extras/geometries/PolyhedronGeometry.js'; +export { TubeGeometry } from './extras/geometries/TubeGeometry.js'; +export { TorusKnotGeometry } from './extras/geometries/TorusKnotGeometry.js'; +export { TorusKnotBufferGeometry } from './extras/geometries/TorusKnotBufferGeometry.js'; +export { TorusGeometry } from './extras/geometries/TorusGeometry.js'; +export { TorusBufferGeometry } from './extras/geometries/TorusBufferGeometry.js'; +export { TextGeometry } from './extras/geometries/TextGeometry.js'; +export { SphereBufferGeometry } from './extras/geometries/SphereBufferGeometry.js'; +export { SphereGeometry } from './extras/geometries/SphereGeometry.js'; +export { RingGeometry } from './extras/geometries/RingGeometry.js'; +export { RingBufferGeometry } from './extras/geometries/RingBufferGeometry.js'; +export { PlaneBufferGeometry } from './extras/geometries/PlaneBufferGeometry.js'; +export { PlaneGeometry } from './extras/geometries/PlaneGeometry.js'; +export { LatheGeometry } from './extras/geometries/LatheGeometry.js'; +export { LatheBufferGeometry } from './extras/geometries/LatheBufferGeometry.js'; +export { ShapeGeometry } from './extras/geometries/ShapeGeometry.js'; +export { ExtrudeGeometry } from './extras/geometries/ExtrudeGeometry.js'; +export { EdgesGeometry } from './extras/geometries/EdgesGeometry.js'; +export { ConeGeometry } from './extras/geometries/ConeGeometry.js'; +export { ConeBufferGeometry } from './extras/geometries/ConeBufferGeometry.js'; +export { CylinderGeometry } from './extras/geometries/CylinderGeometry.js'; +export { CylinderBufferGeometry } from './extras/geometries/CylinderBufferGeometry.js'; +export { CircleBufferGeometry } from './extras/geometries/CircleBufferGeometry.js'; +export { CircleGeometry } from './extras/geometries/CircleGeometry.js'; +export { BoxBufferGeometry } from './extras/geometries/BoxBufferGeometry.js'; +export { CubeGeometry, BoxGeometry } from './extras/geometries/BoxGeometry.js'; +export { ClosedSplineCurve3 } from './extras/curves/ClosedSplineCurve3.js'; +export { CatmullRomCurve3 } from './extras/curves/CatmullRomCurve3.js'; +export { SplineCurve3 } from './extras/curves/SplineCurve3.js'; +export { CubicBezierCurve3 } from './extras/curves/CubicBezierCurve3.js'; +export { QuadraticBezierCurve3 } from './extras/curves/QuadraticBezierCurve3.js'; +export { LineCurve3 } from './extras/curves/LineCurve3.js'; +export { ArcCurve } from './extras/curves/ArcCurve.js'; +export { EllipseCurve } from './extras/curves/EllipseCurve.js'; +export { SplineCurve } from './extras/curves/SplineCurve.js'; +export { CubicBezierCurve } from './extras/curves/CubicBezierCurve.js'; +export { QuadraticBezierCurve } from './extras/curves/QuadraticBezierCurve.js'; +export { LineCurve } from './extras/curves/LineCurve.js'; +export { Shape } from './extras/core/Shape.js'; +export { ShapePath, Path } from './extras/core/Path.js'; +export { Font } from './extras/core/Font.js'; +export { CurvePath } from './extras/core/CurvePath.js'; +export { Curve } from './extras/core/Curve.js'; +export { ShapeUtils } from './extras/ShapeUtils.js'; +export { SceneUtils } from './extras/SceneUtils.js'; +export { CurveUtils } from './extras/CurveUtils.js'; +export * from './constants.js'; diff --git a/src/animation/AnimationAction.js b/src/animation/AnimationAction.js index 7763c611de9daf..ad8308c85836e8 100644 --- a/src/animation/AnimationAction.js +++ b/src/animation/AnimationAction.js @@ -1,3 +1,5 @@ +import { WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, LoopPingPong, LoopOnce, LoopRepeat } from '../constants'; + /** * * Action provided by AnimationMixer for scheduling clip playback on specific @@ -9,14 +11,15 @@ * */ -THREE.AnimationAction = function() { +function AnimationAction() { + this.isAnimationAction = true; throw new Error( "THREE.AnimationAction: " + "Use mixer.clipAction for construction." ); }; -THREE.AnimationAction._new = +AnimationAction._new = function AnimationAction( mixer, clip, localRoot ) { this._mixer = mixer; @@ -28,8 +31,8 @@ THREE.AnimationAction._new = interpolants = new Array( nTracks ); var interpolantSettings = { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding }; for ( var i = 0; i !== nTracks; ++ i ) { @@ -53,7 +56,7 @@ THREE.AnimationAction._new = this._timeScaleInterpolant = null; this._weightInterpolant = null; - this.loop = THREE.LoopRepeat; + this.loop = LoopRepeat; this._loopCount = -1; // global mixer time when the action is to be started @@ -82,9 +85,9 @@ THREE.AnimationAction._new = }; -THREE.AnimationAction._new.prototype = { +AnimationAction._new.prototype = { - constructor: THREE.AnimationAction._new, + constructor: AnimationAction._new, // State & Scheduling @@ -478,7 +481,7 @@ THREE.AnimationAction._new.prototype = { loop = this.loop, loopCount = this._loopCount; - if ( loop === THREE.LoopOnce ) { + if ( loop === LoopOnce ) { if ( loopCount === -1 ) { // just started @@ -512,7 +515,7 @@ THREE.AnimationAction._new.prototype = { } else { // repetitive Repeat or PingPong - var pingPong = ( loop === THREE.LoopPingPong ); + var pingPong = ( loop === LoopPingPong ); if ( loopCount === -1 ) { // just started @@ -606,8 +609,8 @@ THREE.AnimationAction._new.prototype = { if ( pingPong ) { - settings.endingStart = THREE.ZeroSlopeEnding; - settings.endingEnd = THREE.ZeroSlopeEnding; + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; } else { @@ -616,22 +619,22 @@ THREE.AnimationAction._new.prototype = { if ( atStart ) { settings.endingStart = this.zeroSlopeAtStart ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + ZeroSlopeEnding : ZeroCurvatureEnding; } else { - settings.endingStart = THREE.WrapAroundEnding; + settings.endingStart = WrapAroundEnding; } if ( atEnd ) { settings.endingEnd = this.zeroSlopeAtEnd ? - THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding; + ZeroSlopeEnding : ZeroCurvatureEnding; } else { - settings.endingEnd = THREE.WrapAroundEnding; + settings.endingEnd = WrapAroundEnding; } @@ -663,3 +666,6 @@ THREE.AnimationAction._new.prototype = { }; + + +export { AnimationAction }; \ No newline at end of file diff --git a/src/animation/AnimationClip.js b/src/animation/AnimationClip.js index a5e64a8fe13b6b..efb6c48c6b62c5 100644 --- a/src/animation/AnimationClip.js +++ b/src/animation/AnimationClip.js @@ -1,3 +1,10 @@ +import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack'; +import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack'; +import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack'; +import { AnimationUtils } from './AnimationUtils'; +import { KeyframeTrack } from './KeyframeTrack'; +import { _Math } from '../math/Math'; + /** * * Reusable set of Tracks that represent an animation. @@ -6,13 +13,14 @@ * @author David Sarno / http://lighthaus.us/ */ -THREE.AnimationClip = function ( name, duration, tracks ) { +function AnimationClip ( name, duration, tracks ) { + this.isAnimationClip = true; this.name = name; this.tracks = tracks; this.duration = ( duration !== undefined ) ? duration : -1; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks if ( this.duration < 0 ) { @@ -28,9 +36,9 @@ THREE.AnimationClip = function ( name, duration, tracks ) { }; -THREE.AnimationClip.prototype = { +AnimationClip.prototype = { - constructor: THREE.AnimationClip, + constructor: AnimationClip, resetDuration: function() { @@ -78,7 +86,7 @@ THREE.AnimationClip.prototype = { // Static methods: -Object.assign( THREE.AnimationClip, { +Object.assign( AnimationClip, { parse: function( json ) { @@ -88,11 +96,11 @@ Object.assign( THREE.AnimationClip, { for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); } - return new THREE.AnimationClip( json.name, json.duration, tracks ); + return new AnimationClip( json.name, json.duration, tracks ); }, @@ -112,7 +120,7 @@ Object.assign( THREE.AnimationClip, { for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) ); + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); } @@ -138,9 +146,9 @@ Object.assign( THREE.AnimationClip, { values.push( 0, 1, 0 ); - var order = THREE.AnimationUtils.getKeyframeOrder( times ); - times = THREE.AnimationUtils.sortedArray( times, 1, order ); - values = THREE.AnimationUtils.sortedArray( values, 1, order ); + var order = AnimationUtils.getKeyframeOrder( times ); + times = AnimationUtils.sortedArray( times, 1, order ); + values = AnimationUtils.sortedArray( values, 1, order ); // if there is a key at the first frame, duplicate it as the // last frame as well for perfect loop. @@ -152,13 +160,13 @@ Object.assign( THREE.AnimationClip, { } tracks.push( - new THREE.NumberKeyframeTrack( + new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', times, values ).scale( 1.0 / fps ) ); } - return new THREE.AnimationClip( name, -1, tracks ); + return new AnimationClip( name, -1, tracks ); }, @@ -222,7 +230,7 @@ Object.assign( THREE.AnimationClip, { for ( var name in animationToMorphTargets ) { - clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); } @@ -249,7 +257,7 @@ Object.assign( THREE.AnimationClip, { var times = []; var values = []; - THREE.AnimationUtils.flattenJSON( + AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); // empty keys are filtered out, so check again @@ -316,7 +324,7 @@ Object.assign( THREE.AnimationClip, { } - tracks.push( new THREE.NumberKeyframeTrack( + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); } @@ -329,15 +337,15 @@ Object.assign( THREE.AnimationClip, { var boneName = '.bones[' + bones[ h ].name + ']'; addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.position', + VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks ); addNonemptyTrack( - THREE.QuaternionKeyframeTrack, boneName + '.quaternion', + QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks ); addNonemptyTrack( - THREE.VectorKeyframeTrack, boneName + '.scale', + VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks ); } @@ -350,10 +358,13 @@ Object.assign( THREE.AnimationClip, { } - var clip = new THREE.AnimationClip( clipName, duration, tracks ); + var clip = new AnimationClip( clipName, duration, tracks ); return clip; } } ); + + +export { AnimationClip }; \ No newline at end of file diff --git a/src/animation/AnimationMixer.js b/src/animation/AnimationMixer.js index 8483c40faf2fec..d0cfd3bada73f8 100644 --- a/src/animation/AnimationMixer.js +++ b/src/animation/AnimationMixer.js @@ -1,3 +1,10 @@ +import { AnimationAction } from './AnimationAction'; +import { EventDispatcher } from '../core/EventDispatcher'; +import { LinearInterpolant } from '../math/interpolants/LinearInterpolant'; +import { PropertyBinding } from './PropertyBinding'; +import { PropertyMixer } from './PropertyMixer'; +import { AnimationClip } from './AnimationClip'; + /** * * Player for AnimationClips. @@ -8,7 +15,8 @@ * @author tschw */ -THREE.AnimationMixer = function( root ) { +function AnimationMixer( root ) { + this.isAnimationMixer = true; this._root = root; this._initMemoryManager(); @@ -20,7 +28,7 @@ THREE.AnimationMixer = function( root ) { }; -Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, { +Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { // return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a @@ -31,7 +39,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject !== null ? clipObject.uuid : clip, @@ -63,8 +71,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, if ( clipObject === null ) return null; // allocate all resources required to run it - var newAction = new THREE. - AnimationMixer._Action( this, clipObject, optionalRoot ); + var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); this._bindAction( newAction, prototypeAction ); @@ -82,7 +89,7 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? - THREE.AnimationClip.findByName( root, clip ) : clip, + AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject ? clipObject.uuid : clip, @@ -269,11 +276,11 @@ Object.assign( THREE.AnimationMixer.prototype, THREE.EventDispatcher.prototype, } ); -THREE.AnimationMixer._Action = THREE.AnimationAction._new; +AnimationMixer._Action = AnimationAction._new; // Implementation details: -Object.assign( THREE.AnimationMixer.prototype, { +Object.assign( AnimationMixer.prototype, { _bindAction: function( action, prototypeAction ) { @@ -325,8 +332,8 @@ Object.assign( THREE.AnimationMixer.prototype, { var path = prototypeAction && prototypeAction. _propertyBindings[ i ].binding.parsedPath; - binding = new THREE.PropertyMixer( - THREE.PropertyBinding.create( root, trackName, path ), + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), track.ValueTypeName, track.getValueSize() ); ++ binding.referenceCount; @@ -703,7 +710,7 @@ Object.assign( THREE.AnimationMixer.prototype, { if ( interpolant === undefined ) { - interpolant = new THREE.LinearInterpolant( + interpolant = new LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, this._controlInterpolantsResultBuffer ); @@ -736,3 +743,6 @@ Object.assign( THREE.AnimationMixer.prototype, { _controlInterpolantsResultBuffer: new Float32Array( 1 ) } ); + + +export { AnimationMixer }; \ No newline at end of file diff --git a/src/animation/AnimationObjectGroup.js b/src/animation/AnimationObjectGroup.js index 815aee2b4e62c6..c5df23305c3aee 100644 --- a/src/animation/AnimationObjectGroup.js +++ b/src/animation/AnimationObjectGroup.js @@ -1,3 +1,6 @@ +import { PropertyBinding } from './PropertyBinding'; +import { _Math } from '../math/Math'; + /** * * A group of objects that receives a shared animation state. @@ -29,9 +32,10 @@ * @author tschw */ -THREE.AnimationObjectGroup = function( var_args ) { +function AnimationObjectGroup( var_args ) { + this.isAnimationObjectGroup = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); // cached objects followed by the active ones this._objects = Array.prototype.slice.call( arguments ); @@ -68,9 +72,9 @@ THREE.AnimationObjectGroup = function( var_args ) { }; -THREE.AnimationObjectGroup.prototype = { +AnimationObjectGroup.prototype = { - constructor: THREE.AnimationObjectGroup, + constructor: AnimationObjectGroup, add: function( var_args ) { @@ -102,7 +106,7 @@ THREE.AnimationObjectGroup.prototype = { for ( var j = 0, m = nBindings; j !== m; ++ j ) { bindings[ j ].push( - new THREE.PropertyBinding( + new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); } @@ -138,7 +142,7 @@ THREE.AnimationObjectGroup.prototype = { // for objects that are cached, the binding may // or may not exist - binding = new THREE.PropertyBinding( + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); } @@ -327,7 +331,7 @@ THREE.AnimationObjectGroup.prototype = { var object = objects[ i ]; bindingsForPath[ i ] = - new THREE.PropertyBinding( object, path, parsedPath ); + new PropertyBinding( object, path, parsedPath ); } @@ -368,3 +372,6 @@ THREE.AnimationObjectGroup.prototype = { }; + + +export { AnimationObjectGroup }; \ No newline at end of file diff --git a/src/animation/AnimationUtils.js b/src/animation/AnimationUtils.js index ff7bce3fa12f67..b85bb836d9c27f 100644 --- a/src/animation/AnimationUtils.js +++ b/src/animation/AnimationUtils.js @@ -1,15 +1,17 @@ +var AnimationUtils; + /** * @author tschw * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */ -THREE.AnimationUtils = { +AnimationUtils = { // same as Array.prototype.slice, but also works on typed arrays arraySlice: function( array, from, to ) { - if ( THREE.AnimationUtils.isTypedArray( array ) ) { + if ( AnimationUtils.isTypedArray( array ) ) { return new array.constructor( array.subarray( from, to ) ); @@ -157,3 +159,6 @@ THREE.AnimationUtils = { } }; + + +export { AnimationUtils }; \ No newline at end of file diff --git a/src/animation/KeyframeTrack.js b/src/animation/KeyframeTrack.js index 30f73e21ff51bd..ce8a03d5e7ee60 100644 --- a/src/animation/KeyframeTrack.js +++ b/src/animation/KeyframeTrack.js @@ -1,3 +1,13 @@ +import { KeyframeTrackPrototype } from './KeyframeTrackPrototype'; +import { StringKeyframeTrack } from './tracks/StringKeyframeTrack'; +import { BooleanKeyframeTrack } from './tracks/BooleanKeyframeTrack'; +import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack'; +import { ColorKeyframeTrack } from './tracks/ColorKeyframeTrack'; +import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack'; +import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack'; +import { AnimationUtils } from './AnimationUtils'; +import { KeyframeTrackConstructor } from './KeyframeTrackConstructor'; + /** * * A timed sequence of keyframes for a specific property. @@ -8,368 +18,16 @@ * @author tschw */ -THREE.KeyframeTrack = function ( name, times, values, interpolation ) { - - if( name === undefined ) throw new Error( "track name is undefined" ); - - if( times === undefined || times.length === 0 ) { - - throw new Error( "no keyframes in track named " + name ); - - } - - this.name = name; - - this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType ); - - this.setInterpolation( interpolation || this.DefaultInterpolation ); - - this.validate(); - this.optimize(); - +function KeyframeTrack ( name, times, values, interpolation ) { + KeyframeTrackConstructor.apply( this, arguments ); }; -THREE.KeyframeTrack.prototype = { - - constructor: THREE.KeyframeTrack, - - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, - - DefaultInterpolation: THREE.InterpolateLinear, - - InterpolantFactoryMethodDiscrete: function( result ) { - - return new THREE.DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - InterpolantFactoryMethodLinear: function( result ) { - - return new THREE.LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - InterpolantFactoryMethodSmooth: function( result ) { - - return new THREE.CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); - - }, - - setInterpolation: function( interpolation ) { - - var factoryMethod; - - switch ( interpolation ) { - - case THREE.InterpolateDiscrete: - - factoryMethod = this.InterpolantFactoryMethodDiscrete; - - break; - - case THREE.InterpolateLinear: - - factoryMethod = this.InterpolantFactoryMethodLinear; - - break; - - case THREE.InterpolateSmooth: - - factoryMethod = this.InterpolantFactoryMethodSmooth; - - break; - - } - - if ( factoryMethod === undefined ) { - - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; - - if ( this.createInterpolant === undefined ) { - - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { - - this.setInterpolation( this.DefaultInterpolation ); - - } else { - - throw new Error( message ); // fatal, in this case - - } - - } - - console.warn( message ); - return; - - } - - this.createInterpolant = factoryMethod; - - }, - - getInterpolation: function() { - - switch ( this.createInterpolant ) { - - case this.InterpolantFactoryMethodDiscrete: - - return THREE.InterpolateDiscrete; - - case this.InterpolantFactoryMethodLinear: - - return THREE.InterpolateLinear; - - case this.InterpolantFactoryMethodSmooth: - - return THREE.InterpolateSmooth; - - } - - }, - - getValueSize: function() { - - return this.values.length / this.times.length; - - }, - - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { - - if( timeOffset !== 0.0 ) { - - var times = this.times; - - for( var i = 0, n = times.length; i !== n; ++ i ) { - - times[ i ] += timeOffset; - - } - - } - - return this; - - }, - - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { - - if( timeScale !== 1.0 ) { - - var times = this.times; - - for( var i = 0, n = times.length; i !== n; ++ i ) { - - times[ i ] *= timeScale; - - } - - } - - return this; - - }, - - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function( startTime, endTime ) { - - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; - - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== -1 && times[ to ] > endTime ) -- to; - - ++ to; // inclusive -> exclusive bound - - if( from !== 0 || to !== nKeys ) { - - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - - var stride = this.getValueSize(); - this.times = THREE.AnimationUtils.arraySlice( times, from, to ); - this.values = THREE.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); - - } - - return this; - - }, - - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { - - var valid = true; - - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { - - console.error( "invalid value size in track", this ); - valid = false; - - } - - var times = this.times, - values = this.values, - - nKeys = times.length; - - if( nKeys === 0 ) { - - console.error( "track is empty", this ); - valid = false; - - } - - var prevTime = null; - - for( var i = 0; i !== nKeys; i ++ ) { - - var currTime = times[ i ]; - - if ( typeof currTime === 'number' && isNaN( currTime ) ) { - - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; - - } - - if( prevTime !== null && prevTime > currTime ) { - - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; - - } - - prevTime = currTime; - - } - - if ( values !== undefined ) { - - if ( THREE.AnimationUtils.isTypedArray( values ) ) { - - for ( var i = 0, n = values.length; i !== n; ++ i ) { - - var value = values[ i ]; - - if ( isNaN( value ) ) { - - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; - - } - - } - - } - - } - - return valid; - - }, - - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function() { - - var times = this.times, - values = this.values, - stride = this.getValueSize(), - - writeIndex = 1; - - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - - var keep = false; - - var time = times[ i ]; - var timeNext = times[ i + 1 ]; - - // remove adjacent keyframes scheduled at the same time - - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; - - for ( var j = 0; j !== stride; ++ j ) { - - var value = values[ offset + j ]; - - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { - - keep = true; - break; - - } - - } - - } - - // in-place compaction - - if ( keep ) { - - if ( i !== writeIndex ) { - - times[ writeIndex ] = times[ i ]; - - var readOffset = i * stride, - writeOffset = writeIndex * stride; - - for ( var j = 0; j !== stride; ++ j ) { - - values[ writeOffset + j ] = values[ readOffset + j ]; - - } - - - } - - ++ writeIndex; - - } - - } - - if ( writeIndex !== times.length ) { - - this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - - } - - return this; - - } - -}; +KeyframeTrack.prototype = KeyframeTrackPrototype; +KeyframeTrackPrototype.constructor = KeyframeTrack; // Static methods: -Object.assign( THREE.KeyframeTrack, { +Object.assign( KeyframeTrack, { // Serialization (in static context, because of constructor invocation // and automatic invocation of .toJSON): @@ -382,13 +40,13 @@ Object.assign( THREE.KeyframeTrack, { } - var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); if ( json.times === undefined ) { var times = [], values = []; - THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); json.times = times; json.values = values; @@ -427,8 +85,8 @@ Object.assign( THREE.KeyframeTrack, { json = { 'name': track.name, - 'times': THREE.AnimationUtils.convertArray( track.times, Array ), - 'values': THREE.AnimationUtils.convertArray( track.values, Array ) + 'times': AnimationUtils.convertArray( track.times, Array ), + 'values': AnimationUtils.convertArray( track.values, Array ) }; @@ -458,31 +116,31 @@ Object.assign( THREE.KeyframeTrack, { case "number": case "integer": - return THREE.NumberKeyframeTrack; + return NumberKeyframeTrack; case "vector": case "vector2": case "vector3": case "vector4": - return THREE.VectorKeyframeTrack; + return VectorKeyframeTrack; case "color": - return THREE.ColorKeyframeTrack; + return ColorKeyframeTrack; case "quaternion": - return THREE.QuaternionKeyframeTrack; + return QuaternionKeyframeTrack; case "bool": case "boolean": - return THREE.BooleanKeyframeTrack; + return BooleanKeyframeTrack; case "string": - return THREE.StringKeyframeTrack; + return StringKeyframeTrack; } @@ -491,3 +149,6 @@ Object.assign( THREE.KeyframeTrack, { } } ); + + +export { KeyframeTrack }; \ No newline at end of file diff --git a/src/animation/KeyframeTrackConstructor.js b/src/animation/KeyframeTrackConstructor.js new file mode 100644 index 00000000000000..015cff61c007a6 --- /dev/null +++ b/src/animation/KeyframeTrackConstructor.js @@ -0,0 +1,26 @@ +import { AnimationUtils } from './AnimationUtils'; + +function KeyframeTrackConstructor ( name, times, values, interpolation ) { + this.isKeyframeTrack = true; + + if( name === undefined ) throw new Error( "track name is undefined" ); + + if( times === undefined || times.length === 0 ) { + + throw new Error( "no keyframes in track named " + name ); + + } + + this.name = name; + + this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + this.validate(); + this.optimize(); + +} + +export { KeyframeTrackConstructor }; \ No newline at end of file diff --git a/src/animation/KeyframeTrackPrototype.js b/src/animation/KeyframeTrackPrototype.js new file mode 100644 index 00000000000000..aebc7da9b17820 --- /dev/null +++ b/src/animation/KeyframeTrackPrototype.js @@ -0,0 +1,345 @@ +import { InterpolateLinear } from '../constants'; +import { AnimationUtils } from './AnimationUtils'; +import { InterpolateSmooth, InterpolateDiscrete } from '../constants'; +import { CubicInterpolant } from '../math/interpolants/CubicInterpolant'; +import { LinearInterpolant } from '../math/interpolants/LinearInterpolant'; +import { DiscreteInterpolant } from '../math/interpolants/DiscreteInterpolant'; + +var KeyframeTrackPrototype; + +KeyframeTrackPrototype = { + + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, + + DefaultInterpolation: InterpolateLinear, + + InterpolantFactoryMethodDiscrete: function( result ) { + + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + InterpolantFactoryMethodLinear: function( result ) { + + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + InterpolantFactoryMethodSmooth: function( result ) { + + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); + + }, + + setInterpolation: function( interpolation ) { + + var factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + } + + if ( factoryMethod === undefined ) { + + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; + + if ( this.createInterpolant === undefined ) { + + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { + + this.setInterpolation( this.DefaultInterpolation ); + + } else { + + throw new Error( message ); // fatal, in this case + + } + + } + + console.warn( message ); + return; + + } + + this.createInterpolant = factoryMethod; + + }, + + getInterpolation: function() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + } + + }, + + getValueSize: function() { + + return this.values.length / this.times.length; + + }, + + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { + + if( timeOffset !== 0.0 ) { + + var times = this.times; + + for( var i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] += timeOffset; + + } + + } + + return this; + + }, + + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { + + if( timeScale !== 1.0 ) { + + var times = this.times; + + for( var i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] *= timeScale; + + } + + } + + return this; + + }, + + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function( startTime, endTime ) { + + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; + + while ( from !== nKeys && times[ from ] < startTime ) ++ from; + while ( to !== -1 && times[ to ] > endTime ) -- to; + + ++ to; // inclusive -> exclusive bound + + if( from !== 0 || to !== nKeys ) { + + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; + + var stride = this.getValueSize(); + this.times = AnimationUtils.arraySlice( times, from, to ); + this.values = AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); + + } + + return this; + + }, + + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { + + var valid = true; + + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + console.error( "invalid value size in track", this ); + valid = false; + + } + + var times = this.times, + values = this.values, + + nKeys = times.length; + + if( nKeys === 0 ) { + + console.error( "track is empty", this ); + valid = false; + + } + + var prevTime = null; + + for( var i = 0; i !== nKeys; i ++ ) { + + var currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; + + } + + if( prevTime !== null && prevTime > currTime ) { + + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( AnimationUtils.isTypedArray( values ) ) { + + for ( var i = 0, n = values.length; i !== n; ++ i ) { + + var value = values[ i ]; + + if ( isNaN( value ) ) { + + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; + + } + + } + + } + + } + + return valid; + + }, + + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function() { + + var times = this.times, + values = this.values, + stride = this.getValueSize(), + + writeIndex = 1; + + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + + var keep = false; + + var time = times[ i ]; + var timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( var j = 0; j !== stride; ++ j ) { + + var value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + var readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( var j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + + } + + ++ writeIndex; + + } + + } + + if ( writeIndex !== times.length ) { + + this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + + } + + return this; + + } + +} + +export { KeyframeTrackPrototype }; \ No newline at end of file diff --git a/src/animation/PropertyBinding.js b/src/animation/PropertyBinding.js index 0d9416de90a456..6e3fef2026fab1 100644 --- a/src/animation/PropertyBinding.js +++ b/src/animation/PropertyBinding.js @@ -8,22 +8,23 @@ * @author tschw */ -THREE.PropertyBinding = function ( rootNode, path, parsedPath ) { +function PropertyBinding ( rootNode, path, parsedPath ) { + this.isPropertyBinding = true; this.path = path; this.parsedPath = parsedPath || - THREE.PropertyBinding.parseTrackName( path ); + PropertyBinding.parseTrackName( path ); - this.node = THREE.PropertyBinding.findNode( + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; this.rootNode = rootNode; }; -THREE.PropertyBinding.prototype = { +PropertyBinding.prototype = { - constructor: THREE.PropertyBinding, + constructor: PropertyBinding, getValue: function getValue_unbound( targetArray, offset ) { @@ -57,7 +58,7 @@ THREE.PropertyBinding.prototype = { if ( ! targetObject ) { - targetObject = THREE.PropertyBinding.findNode( + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; this.node = targetObject; @@ -268,15 +269,15 @@ THREE.PropertyBinding.prototype = { }; -Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued +Object.assign( PropertyBinding.prototype, { // prototype, continued // these are used to "bind" a nonexistent property _getValue_unavailable: function() {}, _setValue_unavailable: function() {}, // initial state of these methods that calls 'bind' - _getValue_unbound: THREE.PropertyBinding.prototype.getValue, - _setValue_unbound: THREE.PropertyBinding.prototype.setValue, + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, BindingType: { Direct: 0, @@ -448,20 +449,20 @@ Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued } ); -THREE.PropertyBinding.Composite = +PropertyBinding.Composite = function( targetGroup, path, optionalParsedPath ) { var parsedPath = optionalParsedPath || - THREE.PropertyBinding.parseTrackName( path ); + PropertyBinding.parseTrackName( path ); this._targetGroup = targetGroup; this._bindings = targetGroup.subscribe_( path, parsedPath ); }; -THREE.PropertyBinding.Composite.prototype = { +PropertyBinding.Composite.prototype = { - constructor: THREE.PropertyBinding.Composite, + constructor: PropertyBinding.Composite, getValue: function( array, offset ) { @@ -516,21 +517,21 @@ THREE.PropertyBinding.Composite.prototype = { }; -THREE.PropertyBinding.create = function( root, path, parsedPath ) { +PropertyBinding.create = function( root, path, parsedPath ) { - if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) { + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - return new THREE.PropertyBinding( root, path, parsedPath ); + return new PropertyBinding( root, path, parsedPath ); } else { - return new THREE.PropertyBinding.Composite( root, path, parsedPath ); + return new PropertyBinding.Composite( root, path, parsedPath ); } }; -THREE.PropertyBinding.parseTrackName = function( trackName ) { +PropertyBinding.parseTrackName = function( trackName ) { // matches strings in the form of: // nodeName.property @@ -577,7 +578,7 @@ THREE.PropertyBinding.parseTrackName = function( trackName ) { }; -THREE.PropertyBinding.findNode = function( root, nodeName ) { +PropertyBinding.findNode = function( root, nodeName ) { if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { @@ -652,3 +653,6 @@ THREE.PropertyBinding.findNode = function( root, nodeName ) { return null; }; + + +export { PropertyBinding }; \ No newline at end of file diff --git a/src/animation/PropertyMixer.js b/src/animation/PropertyMixer.js index ebd3132bbd5863..ee03f7e99143fc 100644 --- a/src/animation/PropertyMixer.js +++ b/src/animation/PropertyMixer.js @@ -1,3 +1,5 @@ +import { Quaternion } from '../math/Quaternion'; + /** * * Buffered scene graph property that allows weighted accumulation. @@ -8,7 +10,8 @@ * @author tschw */ -THREE.PropertyMixer = function ( binding, typeName, valueSize ) { +function PropertyMixer ( binding, typeName, valueSize ) { + this.isPropertyMixer = true; this.binding = binding; this.valueSize = valueSize; @@ -50,9 +53,9 @@ THREE.PropertyMixer = function ( binding, typeName, valueSize ) { }; -THREE.PropertyMixer.prototype = { +PropertyMixer.prototype = { - constructor: THREE.PropertyMixer, + constructor: PropertyMixer, // accumulate data in the 'incoming' region into 'accu' accumulate: function( accuIndex, weight ) { @@ -181,7 +184,7 @@ THREE.PropertyMixer.prototype = { _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - THREE.Quaternion.slerpFlat( buffer, dstOffset, + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); }, @@ -201,3 +204,6 @@ THREE.PropertyMixer.prototype = { } }; + + +export { PropertyMixer }; \ No newline at end of file diff --git a/src/animation/tracks/BooleanKeyframeTrack.js b/src/animation/tracks/BooleanKeyframeTrack.js index 10633c1a456c9d..e314cec6623069 100644 --- a/src/animation/tracks/BooleanKeyframeTrack.js +++ b/src/animation/tracks/BooleanKeyframeTrack.js @@ -1,3 +1,7 @@ +import { InterpolateDiscrete } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of Boolean keyframe values. @@ -8,21 +12,22 @@ * @author tschw */ -THREE.BooleanKeyframeTrack = function ( name, times, values ) { +function BooleanKeyframeTrack ( name, times, values ) { + this.isBooleanKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values ); + KeyframeTrackConstructor.call( this, name, times, values ); }; -THREE.BooleanKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.BooleanKeyframeTrack, + constructor: BooleanKeyframeTrack, ValueTypeName: 'bool', ValueBufferType: Array, - DefaultInterpolation: THREE.InterpolateDiscrete, + DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined @@ -32,3 +37,6 @@ THREE.BooleanKeyframeTrack.prototype = // computes "firstValue ^ isOdd( index )". } ); + + +export { BooleanKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/ColorKeyframeTrack.js b/src/animation/tracks/ColorKeyframeTrack.js index 9b4a156de9a57c..3f508c323f2ca6 100644 --- a/src/animation/tracks/ColorKeyframeTrack.js +++ b/src/animation/tracks/ColorKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of keyframe values that represent color. @@ -8,16 +11,17 @@ * @author tschw */ -THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) { +function ColorKeyframeTrack ( name, times, values, interpolation ) { + this.isColorKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.ColorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.ColorKeyframeTrack, + constructor: ColorKeyframeTrack, ValueTypeName: 'color' @@ -30,3 +34,6 @@ THREE.ColorKeyframeTrack.prototype = // However, this is the place for color space parameterization. } ); + + +export { ColorKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/NumberKeyframeTrack.js b/src/animation/tracks/NumberKeyframeTrack.js index 01585638438cbe..cdf584c03c42aa 100644 --- a/src/animation/tracks/NumberKeyframeTrack.js +++ b/src/animation/tracks/NumberKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of numeric keyframe values. @@ -7,16 +10,17 @@ * @author tschw */ -THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) { +function NumberKeyframeTrack ( name, times, values, interpolation ) { + this.isNumberKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.NumberKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.NumberKeyframeTrack, + constructor: NumberKeyframeTrack, ValueTypeName: 'number', @@ -25,3 +29,6 @@ THREE.NumberKeyframeTrack.prototype = // DefaultInterpolation is inherited } ); + + +export { NumberKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/QuaternionKeyframeTrack.js b/src/animation/tracks/QuaternionKeyframeTrack.js index e0e3002f7dd9f7..63aec7a0e82d9d 100644 --- a/src/animation/tracks/QuaternionKeyframeTrack.js +++ b/src/animation/tracks/QuaternionKeyframeTrack.js @@ -1,3 +1,8 @@ +import { InterpolateLinear } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { QuaternionLinearInterpolant } from '../../math/interpolants/QuaternionLinearInterpolant'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of quaternion keyframe values. @@ -7,26 +12,27 @@ * @author tschw */ -THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) { +function QuaternionKeyframeTrack ( name, times, values, interpolation ) { + this.isQuaternionKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.QuaternionKeyframeTrack, + constructor: QuaternionKeyframeTrack, ValueTypeName: 'quaternion', // ValueBufferType is inherited - DefaultInterpolation: THREE.InterpolateLinear, + DefaultInterpolation: InterpolateLinear, InterpolantFactoryMethodLinear: function( result ) { - return new THREE.QuaternionLinearInterpolant( + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); }, @@ -34,3 +40,6 @@ THREE.QuaternionKeyframeTrack.prototype = InterpolantFactoryMethodSmooth: undefined // not yet implemented } ); + + +export { QuaternionKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/StringKeyframeTrack.js b/src/animation/tracks/StringKeyframeTrack.js index 38afdcb95cd398..df4fe0907cefb6 100644 --- a/src/animation/tracks/StringKeyframeTrack.js +++ b/src/animation/tracks/StringKeyframeTrack.js @@ -1,3 +1,7 @@ +import { InterpolateDiscrete } from '../../constants'; +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track that interpolates Strings @@ -8,24 +12,28 @@ * @author tschw */ -THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) { +function StringKeyframeTrack ( name, times, values, interpolation ) { + this.isStringKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.StringKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.StringKeyframeTrack, + constructor: StringKeyframeTrack, ValueTypeName: 'string', ValueBufferType: Array, - DefaultInterpolation: THREE.InterpolateDiscrete, + DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined } ); + + +export { StringKeyframeTrack }; \ No newline at end of file diff --git a/src/animation/tracks/VectorKeyframeTrack.js b/src/animation/tracks/VectorKeyframeTrack.js index aa1b04ba240b30..923b32d83211fd 100644 --- a/src/animation/tracks/VectorKeyframeTrack.js +++ b/src/animation/tracks/VectorKeyframeTrack.js @@ -1,3 +1,6 @@ +import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype'; +import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor'; + /** * * A Track of vectored keyframe values. @@ -8,16 +11,17 @@ * @author tschw */ -THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) { +function VectorKeyframeTrack ( name, times, values, interpolation ) { + this.isVectorKeyframeTrack = true; - THREE.KeyframeTrack.call( this, name, times, values, interpolation ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); }; -THREE.VectorKeyframeTrack.prototype = - Object.assign( Object.create( THREE.KeyframeTrack.prototype ), { +VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - constructor: THREE.VectorKeyframeTrack, + constructor: VectorKeyframeTrack, ValueTypeName: 'vector' @@ -26,3 +30,6 @@ THREE.VectorKeyframeTrack.prototype = // DefaultInterpolation is inherited } ); + + +export { VectorKeyframeTrack }; \ No newline at end of file diff --git a/src/audio/Audio.js b/src/audio/Audio.js index ba1229dfa64ebc..d0100abdcd1bfa 100644 --- a/src/audio/Audio.js +++ b/src/audio/Audio.js @@ -1,11 +1,14 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ -THREE.Audio = function ( listener ) { +function Audio ( listener ) { + this.isAudio = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Audio'; @@ -28,9 +31,9 @@ THREE.Audio = function ( listener ) { }; -THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Audio, + constructor: Audio, getOutput: function () { @@ -287,3 +290,6 @@ THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) } } ); + + +export { Audio }; \ No newline at end of file diff --git a/src/audio/AudioAnalyser.js b/src/audio/AudioAnalyser.js index 2f6378e2d59163..3f2ebdcc3ac3e0 100644 --- a/src/audio/AudioAnalyser.js +++ b/src/audio/AudioAnalyser.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.AudioAnalyser = function ( audio, fftSize ) { +function AudioAnalyser ( audio, fftSize ) { + this.isAudioAnalyser = true; this.analyser = audio.context.createAnalyser(); this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; @@ -13,7 +14,7 @@ THREE.AudioAnalyser = function ( audio, fftSize ) { }; -Object.assign( THREE.AudioAnalyser.prototype, { +Object.assign( AudioAnalyser.prototype, { getFrequencyData: function () { @@ -38,3 +39,6 @@ Object.assign( THREE.AudioAnalyser.prototype, { } } ); + + +export { AudioAnalyser }; \ No newline at end of file diff --git a/src/audio/AudioContext.js b/src/audio/AudioContext.js index 11c6a2033589e0..b8c897cefe64d7 100644 --- a/src/audio/AudioContext.js +++ b/src/audio/AudioContext.js @@ -1,25 +1,9 @@ -/** - * @author mrdoob / http://mrdoob.com/ - */ +var context; -Object.defineProperty( THREE, 'AudioContext', { +export function getAudioContext () { + if ( context === undefined ) { + context = new ( window.AudioContext || window.webkitAudioContext )(); + } - get: ( function () { - - var context; - - return function get() { - - if ( context === undefined ) { - - context = new ( window.AudioContext || window.webkitAudioContext )(); - - } - - return context; - - }; - - } )() - -} ); + return context; +} \ No newline at end of file diff --git a/src/audio/AudioListener.js b/src/audio/AudioListener.js index adeacda1952b73..4a6149544cd907 100644 --- a/src/audio/AudioListener.js +++ b/src/audio/AudioListener.js @@ -1,14 +1,20 @@ +import { Vector3 } from '../math/Vector3'; +import { Quaternion } from '../math/Quaternion'; +import { Object3D } from '../core/Object3D'; +import { getAudioContext } from './AudioContext'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.AudioListener = function () { +function AudioListener () { + this.isAudioListener = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'AudioListener'; - this.context = THREE.AudioContext; + this.context = getAudioContext(); this.gain = this.context.createGain(); this.gain.connect( this.context.destination ); @@ -17,9 +23,9 @@ THREE.AudioListener = function () { }; -THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.AudioListener, + constructor: AudioListener, getInput: function () { @@ -79,15 +85,15 @@ THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.pro updateMatrixWorld: ( function () { - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3(); + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - var orientation = new THREE.Vector3(); + var orientation = new Vector3(); return function updateMatrixWorld( force ) { - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + Object3D.prototype.updateMatrixWorld.call( this, force ); var listener = this.context.listener; var up = this.up; @@ -104,3 +110,6 @@ THREE.AudioListener.prototype = Object.assign( Object.create( THREE.Object3D.pro } )() } ); + + +export { AudioListener }; \ No newline at end of file diff --git a/src/audio/PositionalAudio.js b/src/audio/PositionalAudio.js index 188e20c49bba35..c813381c96577b 100644 --- a/src/audio/PositionalAudio.js +++ b/src/audio/PositionalAudio.js @@ -1,19 +1,24 @@ +import { Vector3 } from '../math/Vector3'; +import { Audio } from './Audio'; +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.PositionalAudio = function ( listener ) { +function PositionalAudio ( listener ) { + this.isPositionalAudio = true; - THREE.Audio.call( this, listener ); + Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.connect( this.gain ); }; -THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prototype ), { +PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - constructor: THREE.PositionalAudio, + constructor: PositionalAudio, getOutput: function () { @@ -71,11 +76,11 @@ THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prot updateMatrixWorld: ( function () { - var position = new THREE.Vector3(); + var position = new Vector3(); return function updateMatrixWorld( force ) { - THREE.Object3D.prototype.updateMatrixWorld.call( this, force ); + Object3D.prototype.updateMatrixWorld.call( this, force ); position.setFromMatrixPosition( this.matrixWorld ); @@ -87,3 +92,6 @@ THREE.PositionalAudio.prototype = Object.assign( Object.create( THREE.Audio.prot } ); + + +export { PositionalAudio }; \ No newline at end of file diff --git a/src/cameras/Camera.js b/src/cameras/Camera.js index 11634cae684829..e1c104e5047695 100644 --- a/src/cameras/Camera.js +++ b/src/cameras/Camera.js @@ -1,30 +1,36 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Quaternion } from '../math/Quaternion'; +import { Object3D } from '../core/Object3D'; +import { Vector3 } from '../math/Vector3'; + /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ * @author WestLangley / http://github.com/WestLangley */ -THREE.Camera = function () { +function Camera () { + this.isCamera = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Camera'; - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); }; -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; +Camera.prototype = Object.create( Object3D.prototype ); +Camera.prototype.constructor = Camera; -THREE.Camera.prototype.getWorldDirection = function () { +Camera.prototype.getWorldDirection = function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); @@ -34,11 +40,11 @@ THREE.Camera.prototype.getWorldDirection = function () { }(); -THREE.Camera.prototype.lookAt = function () { +Camera.prototype.lookAt = function () { // This routine does not support cameras with rotated and/or translated parent(s) - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function lookAt( vector ) { @@ -50,15 +56,15 @@ THREE.Camera.prototype.lookAt = function () { }(); -THREE.Camera.prototype.clone = function () { +Camera.prototype.clone = function () { return new this.constructor().copy( this ); }; -THREE.Camera.prototype.copy = function ( source ) { +Camera.prototype.copy = function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.matrixWorldInverse.copy( source.matrixWorldInverse ); this.projectionMatrix.copy( source.projectionMatrix ); @@ -66,3 +72,6 @@ THREE.Camera.prototype.copy = function ( source ) { return this; }; + + +export { Camera }; \ No newline at end of file diff --git a/src/cameras/CubeCamera.js b/src/cameras/CubeCamera.js index 006746d5d7ed12..7c157ba4057519 100644 --- a/src/cameras/CubeCamera.js +++ b/src/cameras/CubeCamera.js @@ -1,3 +1,9 @@ +import { Object3D } from '../core/Object3D'; +import { WebGLRenderTargetCube } from '../renderers/WebGLRenderTargetCube'; +import { LinearFilter, RGBFormat } from '../constants'; +import { Vector3 } from '../math/Vector3'; +import { PerspectiveCamera } from './PerspectiveCamera'; + /** * Camera for rendering cube maps * - renders scene into axis-aligned cube @@ -5,47 +11,48 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.CubeCamera = function ( near, far, cubeResolution ) { +function CubeCamera ( near, far, cubeResolution ) { + this.isCubeCamera = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'CubeCamera'; var fov = 90, aspect = 1; - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); this.add( cameraPX ); - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); this.add( cameraNX ); - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); this.add( cameraPY ); - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); this.add( cameraNY ); - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); this.add( cameraPZ ); - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); this.add( cameraNZ ); - var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter }; + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); this.updateCubeMap = function ( renderer, scene ) { @@ -82,5 +89,8 @@ THREE.CubeCamera = function ( near, far, cubeResolution ) { }; -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; +CubeCamera.prototype = Object.create( Object3D.prototype ); +CubeCamera.prototype.constructor = CubeCamera; + + +export { CubeCamera }; \ No newline at end of file diff --git a/src/cameras/OrthographicCamera.js b/src/cameras/OrthographicCamera.js index da96a1cb38b171..a2f9c8a0beceef 100644 --- a/src/cameras/OrthographicCamera.js +++ b/src/cameras/OrthographicCamera.js @@ -1,11 +1,15 @@ +import { Camera } from './Camera'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ * @author arose / http://github.com/arose */ -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { +function OrthographicCamera ( left, right, top, bottom, near, far ) { + this.isOrthographicCamera = true; - THREE.Camera.call( this ); + Camera.call( this ); this.type = 'OrthographicCamera'; @@ -24,13 +28,13 @@ THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { }; -THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { +OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - constructor: THREE.OrthographicCamera, + constructor: OrthographicCamera, copy: function ( source ) { - THREE.Camera.prototype.copy.call( this, source ); + Camera.prototype.copy.call( this, source ); this.left = source.left; this.right = source.right; @@ -100,7 +104,7 @@ THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera. toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.zoom = this.zoom; data.object.left = this.left; @@ -117,3 +121,6 @@ THREE.OrthographicCamera.prototype = Object.assign( Object.create( THREE.Camera. } } ); + + +export { OrthographicCamera }; \ No newline at end of file diff --git a/src/cameras/PerspectiveCamera.js b/src/cameras/PerspectiveCamera.js index 52c612395d7851..d88abf85da6527 100644 --- a/src/cameras/PerspectiveCamera.js +++ b/src/cameras/PerspectiveCamera.js @@ -1,3 +1,7 @@ +import { Camera } from './Camera'; +import { Object3D } from '../core/Object3D'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author greggman / http://games.greggman.com/ @@ -5,9 +9,10 @@ * @author tschw */ -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { +function PerspectiveCamera ( fov, aspect, near, far ) { + this.isPerspectiveCamera = true; - THREE.Camera.call( this ); + Camera.call( this ); this.type = 'PerspectiveCamera'; @@ -28,13 +33,13 @@ THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { }; -THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.prototype ), { +PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - constructor: THREE.PerspectiveCamera, + constructor: PerspectiveCamera, copy: function ( source ) { - THREE.Camera.prototype.copy.call( this, source ); + Camera.prototype.copy.call( this, source ); this.fov = source.fov; this.zoom = source.zoom; @@ -66,7 +71,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p // see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); this.updateProjectionMatrix(); }, @@ -76,7 +81,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p */ getFocalLength: function () { - var vExtentSlope = Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ); + var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov ); return 0.5 * this.getFilmHeight() / vExtentSlope; @@ -84,8 +89,8 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p getEffectiveFOV: function () { - return THREE.Math.RAD2DEG * 2 * Math.atan( - Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return _Math.RAD2DEG * 2 * Math.atan( + Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); }, @@ -166,7 +171,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p var near = this.near, top = near * Math.tan( - THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, height = 2 * top, width = this.aspect * height, left = - 0.5 * width, @@ -194,7 +199,7 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.fov = this.fov; data.object.zoom = this.zoom; @@ -215,3 +220,6 @@ THREE.PerspectiveCamera.prototype = Object.assign( Object.create( THREE.Camera.p } } ); + + +export { PerspectiveCamera }; \ No newline at end of file diff --git a/src/cameras/StereoCamera.js b/src/cameras/StereoCamera.js index 59550b8d549c97..b02b3c3523b165 100644 --- a/src/cameras/StereoCamera.js +++ b/src/cameras/StereoCamera.js @@ -1,31 +1,36 @@ +import { Matrix4 } from '../math/Matrix4'; +import { _Math } from '../math/Math'; +import { PerspectiveCamera } from './PerspectiveCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.StereoCamera = function () { +function StereoCamera () { + this.isStereoCamera = true; this.type = 'StereoCamera'; this.aspect = 1; - this.cameraL = new THREE.PerspectiveCamera(); + this.cameraL = new PerspectiveCamera(); this.cameraL.layers.enable( 1 ); this.cameraL.matrixAutoUpdate = false; - this.cameraR = new THREE.PerspectiveCamera(); + this.cameraR = new PerspectiveCamera(); this.cameraR.layers.enable( 2 ); this.cameraR.matrixAutoUpdate = false; }; -Object.assign( THREE.StereoCamera.prototype, { +Object.assign( StereoCamera.prototype, { update: ( function () { var focus, fov, aspect, near, far; - var eyeRight = new THREE.Matrix4(); - var eyeLeft = new THREE.Matrix4(); + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); return function update( camera ) { @@ -47,7 +52,7 @@ Object.assign( THREE.StereoCamera.prototype, { var projectionMatrix = camera.projectionMatrix.clone(); var eyeSep = 0.064 / 2; var eyeSepOnProjection = eyeSep * near / focus; - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); + var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 ); var xmin, xmax; // translate xOffset @@ -85,3 +90,6 @@ Object.assign( THREE.StereoCamera.prototype, { } )() } ); + + +export { StereoCamera }; \ No newline at end of file diff --git a/src/constants.js b/src/constants.js new file mode 100644 index 00000000000000..5aebb0129cd4be --- /dev/null +++ b/src/constants.js @@ -0,0 +1,122 @@ +export var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; +export var CullFaceNone = 0; +export var CullFaceBack = 1; +export var CullFaceFront = 2; +export var CullFaceFrontBack = 3; +export var FrontFaceDirectionCW = 0; +export var FrontFaceDirectionCCW = 1; +export var BasicShadowMap = 0; +export var PCFShadowMap = 1; +export var PCFSoftShadowMap = 2; +export var FrontSide = 0; +export var BackSide = 1; +export var DoubleSide = 2; +export var FlatShading = 1; +export var SmoothShading = 2; +export var NoColors = 0; +export var FaceColors = 1; +export var VertexColors = 2; +export var NoBlending = 0; +export var NormalBlending = 1; +export var AdditiveBlending = 2; +export var SubtractiveBlending = 3; +export var MultiplyBlending = 4; +export var CustomBlending = 5; +export var AddEquation = 100; +export var SubtractEquation = 101; +export var ReverseSubtractEquation = 102; +export var MinEquation = 103; +export var MaxEquation = 104; +export var ZeroFactor = 200; +export var OneFactor = 201; +export var SrcColorFactor = 202; +export var OneMinusSrcColorFactor = 203; +export var SrcAlphaFactor = 204; +export var OneMinusSrcAlphaFactor = 205; +export var DstAlphaFactor = 206; +export var OneMinusDstAlphaFactor = 207; +export var DstColorFactor = 208; +export var OneMinusDstColorFactor = 209; +export var SrcAlphaSaturateFactor = 210; +export var NeverDepth = 0; +export var AlwaysDepth = 1; +export var LessDepth = 2; +export var LessEqualDepth = 3; +export var EqualDepth = 4; +export var GreaterEqualDepth = 5; +export var GreaterDepth = 6; +export var NotEqualDepth = 7; +export var MultiplyOperation = 0; +export var MixOperation = 1; +export var AddOperation = 2; +export var NoToneMapping = 0; +export var LinearToneMapping = 1; +export var ReinhardToneMapping = 2; +export var Uncharted2ToneMapping = 3; +export var CineonToneMapping = 4; +export var UVMapping = 300; +export var CubeReflectionMapping = 301; +export var CubeRefractionMapping = 302; +export var EquirectangularReflectionMapping = 303; +export var EquirectangularRefractionMapping = 304; +export var SphericalReflectionMapping = 305; +export var CubeUVReflectionMapping = 306; +export var CubeUVRefractionMapping = 307; +export var RepeatWrapping = 1000; +export var ClampToEdgeWrapping = 1001; +export var MirroredRepeatWrapping = 1002; +export var NearestFilter = 1003; +export var NearestMipMapNearestFilter = 1004; +export var NearestMipMapLinearFilter = 1005; +export var LinearFilter = 1006; +export var LinearMipMapNearestFilter = 1007; +export var LinearMipMapLinearFilter = 1008; +export var UnsignedByteType = 1009; +export var ByteType = 1010; +export var ShortType = 1011; +export var UnsignedShortType = 1012; +export var IntType = 1013; +export var UnsignedIntType = 1014; +export var FloatType = 1015; +export var HalfFloatType = 1025; +export var UnsignedShort4444Type = 1016; +export var UnsignedShort5551Type = 1017; +export var UnsignedShort565Type = 1018; +export var AlphaFormat = 1019; +export var RGBFormat = 1020; +export var RGBAFormat = 1021; +export var LuminanceFormat = 1022; +export var LuminanceAlphaFormat = 1023; +export var RGBEFormat = RGBAFormat; +export var DepthFormat = 1026; +export var RGB_S3TC_DXT1_Format = 2001; +export var RGBA_S3TC_DXT1_Format = 2002; +export var RGBA_S3TC_DXT3_Format = 2003; +export var RGBA_S3TC_DXT5_Format = 2004; +export var RGB_PVRTC_4BPPV1_Format = 2100; +export var RGB_PVRTC_2BPPV1_Format = 2101; +export var RGBA_PVRTC_4BPPV1_Format = 2102; +export var RGBA_PVRTC_2BPPV1_Format = 2103; +export var RGB_ETC1_Format = 2151; +export var LoopOnce = 2200; +export var LoopRepeat = 2201; +export var LoopPingPong = 2202; +export var InterpolateDiscrete = 2300; +export var InterpolateLinear = 2301; +export var InterpolateSmooth = 2302; +export var ZeroCurvatureEnding = 2400; +export var ZeroSlopeEnding = 2401; +export var WrapAroundEnding = 2402; +export var TrianglesDrawMode = 0; +export var TriangleStripDrawMode = 1; +export var TriangleFanDrawMode = 2; +export var LinearEncoding = 3000; +export var sRGBEncoding = 3001; +export var GammaEncoding = 3007; +export var RGBEEncoding = 3002; +export var LogLuvEncoding = 3003; +export var RGBM7Encoding = 3004; +export var RGBM16Encoding = 3005; +export var RGBDEncoding = 3006; +export var BasicDepthPacking = 3200; +export var RGBADepthPacking = 3201; \ No newline at end of file diff --git a/src/core/BufferAttribute.js b/src/core/BufferAttribute.js index 79833201986fc1..ca88f59845be8d 100644 --- a/src/core/BufferAttribute.js +++ b/src/core/BufferAttribute.js @@ -1,10 +1,17 @@ +import { Vector4 } from '../math/Vector4'; +import { Vector3 } from '../math/Vector3'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferAttribute = function ( array, itemSize, normalized ) { +function BufferAttribute ( array, itemSize, normalized ) { + this.isBufferAttribute = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.array = array; this.itemSize = itemSize; @@ -17,9 +24,9 @@ THREE.BufferAttribute = function ( array, itemSize, normalized ) { }; -THREE.BufferAttribute.prototype = { +BufferAttribute.prototype = { - constructor: THREE.BufferAttribute, + constructor: BufferAttribute, get count() { @@ -86,7 +93,7 @@ THREE.BufferAttribute.prototype = { if ( color === undefined ) { console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new THREE.Color(); + color = new Color(); } @@ -129,7 +136,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new THREE.Vector2(); + vector = new Vector2(); } @@ -153,7 +160,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new THREE.Vector3(); + vector = new Vector3(); } @@ -178,7 +185,7 @@ THREE.BufferAttribute.prototype = { if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new THREE.Vector4(); + vector = new Vector4(); } @@ -305,66 +312,91 @@ THREE.BufferAttribute.prototype = { // -THREE.Int8Attribute = function ( array, itemSize ) { +function Int8Attribute ( array, itemSize ) { + this.isInt8Attribute = true; - return new THREE.BufferAttribute( new Int8Array( array ), itemSize ); + return new BufferAttribute( new Int8Array( array ), itemSize ); }; -THREE.Uint8Attribute = function ( array, itemSize ) { +function Uint8Attribute ( array, itemSize ) { + this.isUint8Attribute = true; - return new THREE.BufferAttribute( new Uint8Array( array ), itemSize ); + return new BufferAttribute( new Uint8Array( array ), itemSize ); }; -THREE.Uint8ClampedAttribute = function ( array, itemSize ) { +function Uint8ClampedAttribute ( array, itemSize ) { + this.isUint8ClampedAttribute = true; - return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); }; -THREE.Int16Attribute = function ( array, itemSize ) { +function Int16Attribute ( array, itemSize ) { + this.isInt16Attribute = true; - return new THREE.BufferAttribute( new Int16Array( array ), itemSize ); + return new BufferAttribute( new Int16Array( array ), itemSize ); }; -THREE.Uint16Attribute = function ( array, itemSize ) { +function Uint16Attribute ( array, itemSize ) { + this.isUint16Attribute = true; - return new THREE.BufferAttribute( new Uint16Array( array ), itemSize ); + return new BufferAttribute( new Uint16Array( array ), itemSize ); }; -THREE.Int32Attribute = function ( array, itemSize ) { +function Int32Attribute ( array, itemSize ) { + this.isInt32Attribute = true; - return new THREE.BufferAttribute( new Int32Array( array ), itemSize ); + return new BufferAttribute( new Int32Array( array ), itemSize ); }; -THREE.Uint32Attribute = function ( array, itemSize ) { +function Uint32Attribute ( array, itemSize ) { + this.isUint32Attribute = true; - return new THREE.BufferAttribute( new Uint32Array( array ), itemSize ); + return new BufferAttribute( new Uint32Array( array ), itemSize ); }; -THREE.Float32Attribute = function ( array, itemSize ) { +function Float32Attribute ( array, itemSize ) { + this.isFloat32Attribute = true; - return new THREE.BufferAttribute( new Float32Array( array ), itemSize ); + return new BufferAttribute( new Float32Array( array ), itemSize ); }; -THREE.Float64Attribute = function ( array, itemSize ) { +function Float64Attribute ( array, itemSize ) { + this.isFloat64Attribute = true; - return new THREE.BufferAttribute( new Float64Array( array ), itemSize ); + return new BufferAttribute( new Float64Array( array ), itemSize ); }; // Deprecated -THREE.DynamicBufferAttribute = function ( array, itemSize ) { +function DynamicBufferAttribute ( array, itemSize ) { + this.isDynamicBufferAttribute = true; console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new THREE.BufferAttribute( array, itemSize ).setDynamic( true ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); }; + + +export { + DynamicBufferAttribute, + Float64Attribute, + Float32Attribute, + Uint32Attribute, + Int32Attribute, + Uint16Attribute, + Int16Attribute, + Uint8ClampedAttribute, + Uint8Attribute, + Int8Attribute, + BufferAttribute +}; \ No newline at end of file diff --git a/src/core/BufferGeometry.js b/src/core/BufferGeometry.js index 25a4c8273295be..462c823461a0fb 100644 --- a/src/core/BufferGeometry.js +++ b/src/core/BufferGeometry.js @@ -1,13 +1,26 @@ +import { Vector3 } from '../math/Vector3'; +import { Box3 } from '../math/Box3'; +import { EventDispatcher } from './EventDispatcher'; +import { BufferAttribute, Float32Attribute } from './BufferAttribute'; +import { Sphere } from '../math/Sphere'; +import { DirectGeometry } from './DirectGeometry'; +import { Object3D } from './Object3D'; +import { Matrix4 } from '../math/Matrix4'; +import { Matrix3 } from '../math/Matrix3'; +import { _Math } from '../math/Math'; +import { GeometryIdCount } from './Geometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferGeometry = function () { +function BufferGeometry () { + this.isBufferGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'BufferGeometry'; @@ -26,7 +39,7 @@ THREE.BufferGeometry = function () { }; -Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { getIndex: function () { @@ -42,11 +55,11 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, addAttribute: function ( name, attribute ) { - if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) { + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); return; @@ -121,7 +134,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( normal !== undefined ) { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); normalMatrix.applyToVector3Array( normal.array ); normal.needsUpdate = true; @@ -152,7 +165,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateX( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationX( angle ); @@ -172,7 +185,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateY( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationY( angle ); @@ -192,7 +205,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function rotateZ( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationZ( angle ); @@ -212,7 +225,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function translate( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeTranslation( x, y, z ); @@ -232,7 +245,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function scale( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeScale( x, y, z ); @@ -250,7 +263,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return function lookAt( vector ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + if ( obj === undefined ) obj = new Object3D(); obj.lookAt( vector ); @@ -280,17 +293,17 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var geometry = object.geometry; - if ( object instanceof THREE.Points || object instanceof THREE.Line ) { + if ( (object && object.isPoints) || (object && object.isLine) ) { - var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 ); + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 ); + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); @@ -308,9 +321,9 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - } else if ( object instanceof THREE.Mesh ) { + } else if ( (object && object.isMesh) ) { - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { this.fromGeometry( geometry ); @@ -326,7 +339,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var geometry = object.geometry; - if ( object instanceof THREE.Mesh ) { + if ( (object && object.isMesh) ) { var direct = geometry.__directGeometry; @@ -445,7 +458,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, fromGeometry: function ( geometry ) { - geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry ); + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); return this.fromDirectGeometry( geometry.__directGeometry ); @@ -454,33 +467,33 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, fromDirectGeometry: function ( geometry ) { var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); if ( geometry.normals.length > 0 ) { var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); } if ( geometry.colors.length > 0 ) { var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); } if ( geometry.uvs.length > 0 ) { var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); } if ( geometry.uvs2.length > 0 ) { var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); } @@ -488,7 +501,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); } @@ -507,7 +520,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var morphTarget = morphTargets[ i ]; - var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 ); + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); array.push( attribute.copyVector3sArray( morphTarget ) ); @@ -521,14 +534,14 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( geometry.skinIndices.length > 0 ) { - var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 ); + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); } if ( geometry.skinWeights.length > 0 ) { - var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 ); + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); } @@ -555,7 +568,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( this.boundingBox === null ) { - this.boundingBox = new THREE.Box3(); + this.boundingBox = new Box3(); } @@ -581,14 +594,14 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, computeBoundingSphere: function () { - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + var box = new Box3(); + var vector = new Vector3(); return function computeBoundingSphere() { if ( this.boundingSphere === null ) { - this.boundingSphere = new THREE.Sphere(); + this.boundingSphere = new Sphere(); } @@ -646,7 +659,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, if ( attributes.normal === undefined ) { - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); } else { @@ -666,12 +679,12 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, var vA, vB, vC, - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + cb = new Vector3(), + ab = new Vector3(); // indexed elements @@ -762,7 +775,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, merge: function ( geometry, offset ) { - if ( geometry instanceof THREE.BufferGeometry === false ) { + if ( (geometry && geometry.isBufferGeometry) === false ) { console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); return; @@ -828,7 +841,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - var geometry2 = new THREE.BufferGeometry(); + var geometry2 = new BufferGeometry(); var indices = this.index.array; var attributes = this.attributes; @@ -856,7 +869,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } - geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) ); + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); } @@ -975,7 +988,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, return new this.constructor().copy( this ); */ - return new THREE.BufferGeometry().copy( this ); + return new BufferGeometry().copy( this ); }, @@ -1019,4 +1032,7 @@ Object.assign( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype, } ); -THREE.BufferGeometry.MaxIndex = 65535; +BufferGeometry.MaxIndex = 65535; + + +export { BufferGeometry }; \ No newline at end of file diff --git a/src/core/Clock.js b/src/core/Clock.js index e5286030784e37..4a815039a9d992 100644 --- a/src/core/Clock.js +++ b/src/core/Clock.js @@ -2,7 +2,8 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.Clock = function ( autoStart ) { +function Clock ( autoStart ) { + this.isClock = true; this.autoStart = ( autoStart !== undefined ) ? autoStart : true; @@ -14,9 +15,9 @@ THREE.Clock = function ( autoStart ) { }; -THREE.Clock.prototype = { +Clock.prototype = { - constructor: THREE.Clock, + constructor: Clock, start: function () { @@ -67,3 +68,6 @@ THREE.Clock.prototype = { } }; + + +export { Clock }; \ No newline at end of file diff --git a/src/core/DirectGeometry.js b/src/core/DirectGeometry.js index a50f1a9267bd9a..6daf26aeed5932 100644 --- a/src/core/DirectGeometry.js +++ b/src/core/DirectGeometry.js @@ -1,12 +1,19 @@ +import { Geometry } from './Geometry'; +import { EventDispatcher } from './EventDispatcher'; +import { Vector2 } from '../math/Vector2'; +import { _Math } from '../math/Math'; +import { GeometryIdCount } from './Geometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.DirectGeometry = function () { +function DirectGeometry () { + this.isDirectGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'DirectGeometry'; @@ -40,10 +47,10 @@ THREE.DirectGeometry = function () { }; -Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox, - computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere, + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, computeFaceNormals: function () { @@ -207,7 +214,7 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); } @@ -225,7 +232,7 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); } @@ -284,3 +291,6 @@ Object.assign( THREE.DirectGeometry.prototype, THREE.EventDispatcher.prototype, } } ); + + +export { DirectGeometry }; \ No newline at end of file diff --git a/src/core/EventDispatcher.js b/src/core/EventDispatcher.js index b35fd282f0c44e..09a9f3f92ee726 100644 --- a/src/core/EventDispatcher.js +++ b/src/core/EventDispatcher.js @@ -2,9 +2,10 @@ * https://github.com/mrdoob/eventdispatcher.js/ */ -THREE.EventDispatcher = function () {}; +function EventDispatcher () { + this.isEventDispatcher = true;}; -Object.assign( THREE.EventDispatcher.prototype, { +Object.assign( EventDispatcher.prototype, { addEventListener: function ( type, listener ) { @@ -94,3 +95,6 @@ Object.assign( THREE.EventDispatcher.prototype, { } } ); + + +export { EventDispatcher }; \ No newline at end of file diff --git a/src/core/Face3.js b/src/core/Face3.js index dee52fb22d40e7..3defb50bc57265 100644 --- a/src/core/Face3.js +++ b/src/core/Face3.js @@ -1,27 +1,31 @@ +import { Color } from '../math/Color'; +import { Vector3 } from '../math/Vector3'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { +function Face3 ( a, b, c, normal, color, materialIndex ) { + this.isFace3 = true; this.a = a; this.b = b; this.c = c; - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); this.vertexNormals = Array.isArray( normal ) ? normal : []; - this.color = color instanceof THREE.Color ? color : new THREE.Color(); + this.color = (color && color.isColor) ? color : new Color(); this.vertexColors = Array.isArray( color ) ? color : []; this.materialIndex = materialIndex !== undefined ? materialIndex : 0; }; -THREE.Face3.prototype = { +Face3.prototype = { - constructor: THREE.Face3, + constructor: Face3, clone: function () { @@ -57,3 +61,6 @@ THREE.Face3.prototype = { } }; + + +export { Face3 }; \ No newline at end of file diff --git a/src/core/Geometry.js b/src/core/Geometry.js index c3674acb2749ae..1bb5abb15883ca 100644 --- a/src/core/Geometry.js +++ b/src/core/Geometry.js @@ -1,3 +1,15 @@ +import { EventDispatcher } from './EventDispatcher'; +import { Face3 } from './Face3'; +import { Matrix3 } from '../math/Matrix3'; +import { Sphere } from '../math/Sphere'; +import { Box3 } from '../math/Box3'; +import { Vector3 } from '../math/Vector3'; +import { Matrix4 } from '../math/Matrix4'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; +import { Object3D } from './Object3D'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author kile / http://kile.stravaganza.org/ @@ -7,11 +19,12 @@ * @author bhouston / http://clara.io */ -THREE.Geometry = function () { +function Geometry () { + this.isGeometry = true; - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Geometry'; @@ -44,11 +57,11 @@ THREE.Geometry = function () { }; -Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { +Object.assign( Geometry.prototype, EventDispatcher.prototype, { applyMatrix: function ( matrix ) { - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { @@ -97,7 +110,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateX( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationX( angle ); @@ -117,7 +130,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateY( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationY( angle ); @@ -137,7 +150,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function rotateZ( angle ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeRotationZ( angle ); @@ -157,7 +170,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function translate( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeTranslation( x, y, z ); @@ -177,7 +190,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function scale( x, y, z ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if ( m1 === undefined ) m1 = new Matrix4(); m1.makeScale( x, y, z ); @@ -195,7 +208,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return function lookAt( vector ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + if ( obj === undefined ) obj = new Object3D(); obj.lookAt( vector ); @@ -228,29 +241,29 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); if ( normals !== undefined ) { - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); } if ( colors !== undefined ) { - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); } if ( uvs !== undefined ) { - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); } if ( uvs2 !== undefined ) { - tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); } @@ -261,7 +274,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { 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 face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); scope.faces.push( face ); @@ -359,7 +372,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { var s = radius === 0 ? 1 : 1.0 / radius; - var matrix = new THREE.Matrix4(); + var matrix = new Matrix4(); matrix.set( s, 0, 0, - s * center.x, 0, s, 0, - s * center.y, @@ -375,7 +388,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { computeFaceNormals: function () { - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + var cb = new Vector3(), ab = new Vector3(); for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { @@ -407,7 +420,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - vertices[ v ] = new THREE.Vector3(); + vertices[ v ] = new Vector3(); } @@ -417,7 +430,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { // http://www.iquilezles.org/www/articles/normals/normals.htm var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + var cb = new Vector3(), ab = new Vector3(); for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { @@ -529,7 +542,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { // use temp geometry to compute face and vertex normals for each morph - var tmpGeo = new THREE.Geometry(); + var tmpGeo = new Geometry(); tmpGeo.faces = this.faces; for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { @@ -549,8 +562,8 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; dstNormalsFace.push( faceNormal ); dstNormalsVertex.push( vertexNormals ); @@ -633,7 +646,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( this.boundingBox === null ) { - this.boundingBox = new THREE.Box3(); + this.boundingBox = new Box3(); } @@ -645,7 +658,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( this.boundingSphere === null ) { - this.boundingSphere = new THREE.Sphere(); + this.boundingSphere = new Sphere(); } @@ -655,7 +668,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { merge: function ( geometry, matrix, materialIndexOffset ) { - if ( geometry instanceof THREE.Geometry === false ) { + if ( (geometry && geometry.isGeometry) === false ) { console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); return; @@ -675,7 +688,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { if ( matrix !== undefined ) { - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + normalMatrix = new Matrix3().getNormalMatrix( matrix ); } @@ -701,7 +714,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { faceVertexNormals = face.vertexNormals, faceVertexColors = face.vertexColors; - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); faceCopy.normal.copy( face.normal ); if ( normalMatrix !== undefined ) { @@ -765,7 +778,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { mergeMesh: function ( mesh ) { - if ( mesh instanceof THREE.Mesh === false ) { + if ( (mesh && mesh.isMesh) === false ) { console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); return; @@ -1136,7 +1149,7 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { return new this.constructor().copy( this ); */ - return new THREE.Geometry().copy( this ); + return new Geometry().copy( this ); }, @@ -1202,4 +1215,8 @@ Object.assign( THREE.Geometry.prototype, THREE.EventDispatcher.prototype, { } ); -THREE.GeometryIdCount = 0; +var count = 0; +function GeometryIdCount () { return count++; }; + + +export { GeometryIdCount, Geometry }; \ No newline at end of file diff --git a/src/core/InstancedBufferAttribute.js b/src/core/InstancedBufferAttribute.js index a326811d076ff5..b0e5645344187c 100644 --- a/src/core/InstancedBufferAttribute.js +++ b/src/core/InstancedBufferAttribute.js @@ -1,24 +1,30 @@ +import { BufferAttribute } from './BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) { +function InstancedBufferAttribute ( array, itemSize, meshPerAttribute ) { + this.isInstancedBufferAttribute = this.isBufferAttribute = true; - THREE.BufferAttribute.call( this, array, itemSize ); + BufferAttribute.call( this, array, itemSize ); this.meshPerAttribute = meshPerAttribute || 1; }; -THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute; +InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; -THREE.InstancedBufferAttribute.prototype.copy = function ( source ) { +InstancedBufferAttribute.prototype.copy = function ( source ) { - THREE.BufferAttribute.prototype.copy.call( this, source ); + BufferAttribute.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; }; + + +export { InstancedBufferAttribute }; \ No newline at end of file diff --git a/src/core/InstancedBufferGeometry.js b/src/core/InstancedBufferGeometry.js index 4ee05765c77e05..c39f8b52dee0ab 100644 --- a/src/core/InstancedBufferGeometry.js +++ b/src/core/InstancedBufferGeometry.js @@ -1,20 +1,23 @@ +import { BufferGeometry } from './BufferGeometry'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedBufferGeometry = function () { +function InstancedBufferGeometry () { + this.isInstancedBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'InstancedBufferGeometry'; this.maxInstancedCount = undefined; }; -THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry; +InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; -THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { +InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { this.groups.push( { @@ -26,7 +29,7 @@ THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, inst }; -THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { +InstancedBufferGeometry.prototype.copy = function ( source ) { var index = source.index; @@ -57,3 +60,6 @@ THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { return this; }; + + +export { InstancedBufferGeometry }; \ No newline at end of file diff --git a/src/core/InstancedInterleavedBuffer.js b/src/core/InstancedInterleavedBuffer.js index c6ec553518deca..72e5369ca79034 100644 --- a/src/core/InstancedInterleavedBuffer.js +++ b/src/core/InstancedInterleavedBuffer.js @@ -1,24 +1,30 @@ +import { InterleavedBuffer } from './InterleavedBuffer'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) { +function InstancedInterleavedBuffer ( array, stride, meshPerAttribute ) { + this.isInstancedInterleavedBuffer = this.isInterleavedBuffer = true; - THREE.InterleavedBuffer.call( this, array, stride ); + InterleavedBuffer.call( this, array, stride ); this.meshPerAttribute = meshPerAttribute || 1; }; -THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype ); -THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer; +InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); +InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; -THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) { +InstancedInterleavedBuffer.prototype.copy = function ( source ) { - THREE.InterleavedBuffer.prototype.copy.call( this, source ); + InterleavedBuffer.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; }; + + +export { InstancedInterleavedBuffer }; \ No newline at end of file diff --git a/src/core/InterleavedBuffer.js b/src/core/InterleavedBuffer.js index 21a66712f085a8..7aaeea7911e6d8 100644 --- a/src/core/InterleavedBuffer.js +++ b/src/core/InterleavedBuffer.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InterleavedBuffer = function ( array, stride ) { +function InterleavedBuffer ( array, stride ) { + this.isInterleavedBuffer = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.array = array; this.stride = stride; @@ -16,9 +19,9 @@ THREE.InterleavedBuffer = function ( array, stride ) { }; -THREE.InterleavedBuffer.prototype = { +InterleavedBuffer.prototype = { - constructor: THREE.InterleavedBuffer, + constructor: InterleavedBuffer, get length () { @@ -88,3 +91,6 @@ THREE.InterleavedBuffer.prototype = { } }; + + +export { InterleavedBuffer }; \ No newline at end of file diff --git a/src/core/InterleavedBufferAttribute.js b/src/core/InterleavedBufferAttribute.js index 4655b4610e03c0..5a870a951f14a7 100644 --- a/src/core/InterleavedBufferAttribute.js +++ b/src/core/InterleavedBufferAttribute.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset, normalized ) { +function InterleavedBufferAttribute ( interleavedBuffer, itemSize, offset, normalized ) { + this.isInterleavedBufferAttribute = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.data = interleavedBuffer; this.itemSize = itemSize; @@ -15,9 +18,9 @@ THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offse }; -THREE.InterleavedBufferAttribute.prototype = { +InterleavedBufferAttribute.prototype = { - constructor: THREE.InterleavedBufferAttribute, + constructor: InterleavedBufferAttribute, get length() { @@ -131,3 +134,6 @@ THREE.InterleavedBufferAttribute.prototype = { } }; + + +export { InterleavedBufferAttribute }; \ No newline at end of file diff --git a/src/core/Layers.js b/src/core/Layers.js index 389aa20158efa3..d9f2dc2fabb2a5 100644 --- a/src/core/Layers.js +++ b/src/core/Layers.js @@ -2,15 +2,16 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.Layers = function () { +function Layers () { + this.isLayers = true; this.mask = 1; }; -THREE.Layers.prototype = { +Layers.prototype = { - constructor: THREE.Layers, + constructor: Layers, set: function ( channel ) { @@ -43,3 +44,6 @@ THREE.Layers.prototype = { } }; + + +export { Layers }; \ No newline at end of file diff --git a/src/core/Object3D.js b/src/core/Object3D.js index 0a7fbe3aa28810..520e30e93357f9 100644 --- a/src/core/Object3D.js +++ b/src/core/Object3D.js @@ -1,3 +1,12 @@ +import { Quaternion } from '../math/Quaternion'; +import { Vector3 } from '../math/Vector3'; +import { Matrix4 } from '../math/Matrix4'; +import { EventDispatcher } from './EventDispatcher'; +import { Euler } from '../math/Euler'; +import { Layers } from './Layers'; +import { Matrix3 } from '../math/Matrix3'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ @@ -6,11 +15,12 @@ * @author elephantatwork / www.elephantatwork.ch */ -THREE.Object3D = function () { +function Object3D () { + this.isObject3D = true; - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Object3D'; @@ -18,12 +28,12 @@ THREE.Object3D = function () { this.parent = null; this.children = []; - this.up = THREE.Object3D.DefaultUp.clone(); + this.up = Object3D.DefaultUp.clone(); - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); function onRotationChange() { @@ -58,20 +68,20 @@ THREE.Object3D = function () { value: scale }, modelViewMatrix: { - value: new THREE.Matrix4() + value: new Matrix4() }, normalMatrix: { - value: new THREE.Matrix3() + value: new Matrix3() } } ); - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate; + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; - this.layers = new THREE.Layers(); + this.layers = new Layers(); this.visible = true; this.castShadow = false; @@ -84,10 +94,10 @@ THREE.Object3D = function () { }; -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); -THREE.Object3D.DefaultMatrixAutoUpdate = true; +Object3D.DefaultUp = new Vector3( 0, 1, 0 ); +Object3D.DefaultMatrixAutoUpdate = true; -Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { +Object.assign( Object3D.prototype, EventDispatcher.prototype, { applyMatrix: function ( matrix ) { @@ -132,7 +142,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // rotate object on axis in object space // axis is assumed to be normalized - var q1 = new THREE.Quaternion(); + var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { @@ -148,7 +158,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateX: function () { - var v1 = new THREE.Vector3( 1, 0, 0 ); + var v1 = new Vector3( 1, 0, 0 ); return function rotateX( angle ) { @@ -160,7 +170,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateY: function () { - var v1 = new THREE.Vector3( 0, 1, 0 ); + var v1 = new Vector3( 0, 1, 0 ); return function rotateY( angle ) { @@ -172,7 +182,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { rotateZ: function () { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var v1 = new Vector3( 0, 0, 1 ); return function rotateZ( angle ) { @@ -187,7 +197,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // translate object by distance along axis in object space // axis is assumed to be normalized - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function translateOnAxis( axis, distance ) { @@ -203,7 +213,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateX: function () { - var v1 = new THREE.Vector3( 1, 0, 0 ); + var v1 = new Vector3( 1, 0, 0 ); return function translateX( distance ) { @@ -215,7 +225,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateY: function () { - var v1 = new THREE.Vector3( 0, 1, 0 ); + var v1 = new Vector3( 0, 1, 0 ); return function translateY( distance ) { @@ -227,7 +237,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { translateZ: function () { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var v1 = new Vector3( 0, 0, 1 ); return function translateZ( distance ) { @@ -245,7 +255,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { worldToLocal: function () { - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function worldToLocal( vector ) { @@ -259,7 +269,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { // This routine does not support objects with rotated and/or translated parent(s) - var m1 = new THREE.Matrix4(); + var m1 = new Matrix4(); return function lookAt( vector ) { @@ -292,7 +302,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { } - if ( object instanceof THREE.Object3D ) { + if ( (object && object.isObject3D) ) { if ( object.parent !== null ) { @@ -376,7 +386,7 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldPosition: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); @@ -386,12 +396,12 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldQuaternion: function () { - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + var position = new Vector3(); + var scale = new Vector3(); return function getWorldQuaternion( optionalTarget ) { - var result = optionalTarget || new THREE.Quaternion(); + var result = optionalTarget || new Quaternion(); this.updateMatrixWorld( true ); @@ -405,11 +415,11 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldRotation: function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldRotation( optionalTarget ) { - var result = optionalTarget || new THREE.Euler(); + var result = optionalTarget || new Euler(); this.getWorldQuaternion( quaternion ); @@ -421,12 +431,12 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldScale: function () { - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + var position = new Vector3(); + var quaternion = new Quaternion(); return function getWorldScale( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); @@ -440,11 +450,11 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { getWorldDirection: function () { - var quaternion = new THREE.Quaternion(); + var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); @@ -711,4 +721,8 @@ Object.assign( THREE.Object3D.prototype, THREE.EventDispatcher.prototype, { } ); -THREE.Object3DIdCount = 0; +var count = 0; +function Object3DIdCount () { return count++; }; + + +export { Object3DIdCount, Object3D }; \ No newline at end of file diff --git a/src/core/Raycaster.js b/src/core/Raycaster.js index 8eda8ffc19d9cf..440b29c62bee40 100644 --- a/src/core/Raycaster.js +++ b/src/core/Raycaster.js @@ -1,135 +1,137 @@ +import { Ray } from '../math/Ray'; + /** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://clara.io/ * @author stephomi / http://stephaneginier.com/ */ -( function ( THREE ) { - - THREE.Raycaster = function ( origin, direction, near, far ) { +function Raycaster ( origin, direction, near, far ) { + this.isRaycaster = true; - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - this.near = near || 0; - this.far = far || Infinity; - - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; - - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + this.near = near || 0; + this.far = far || Infinity; + this.params = { + Mesh: {}, + Line: {}, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} }; - function ascSort( a, b ) { + Object.defineProperties( this.params, { + PointCloud: { + get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; + } + } + } ); + +}; - return a.distance - b.distance; +function ascSort( a, b ) { - } + return a.distance - b.distance; - function intersectObject( object, raycaster, intersects, recursive ) { +} - if ( object.visible === false ) return; +function intersectObject( object, raycaster, intersects, recursive ) { - object.raycast( raycaster, intersects ); + if ( object.visible === false ) return; - if ( recursive === true ) { + object.raycast( raycaster, intersects ); - var children = object.children; + if ( recursive === true ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + var children = object.children; - intersectObject( children[ i ], raycaster, intersects, true ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + intersectObject( children[ i ], raycaster, intersects, true ); } } - // +} - THREE.Raycaster.prototype = { +// - constructor: THREE.Raycaster, +Raycaster.prototype = { - linePrecision: 1, + constructor: Raycaster, - set: function ( origin, direction ) { + linePrecision: 1, - // direction is assumed to be normalized (for accurate distance calculations) + set: function ( origin, direction ) { - this.ray.set( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - }, + this.ray.set( origin, direction ); - setFromCamera: function ( coords, camera ) { + }, - if ( camera instanceof THREE.PerspectiveCamera ) { + setFromCamera: function ( coords, camera ) { - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + if ( (camera && camera.isPerspectiveCamera) ) { - } else if ( camera instanceof THREE.OrthographicCamera ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + } else if ( (camera && camera.isOrthographicCamera) ) { - } else { + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + } else { - } + console.error( 'THREE.Raycaster: Unsupported camera type.' ); + + } - }, + }, - intersectObject: function ( object, recursive ) { + intersectObject: function ( object, recursive ) { - var intersects = []; + var intersects = []; - intersectObject( object, this, intersects, recursive ); + intersectObject( object, this, intersects, recursive ); - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - }, + }, - intersectObjects: function ( objects, recursive ) { + intersectObjects: function ( objects, recursive ) { - var intersects = []; + var intersects = []; - if ( Array.isArray( objects ) === false ) { + if ( Array.isArray( objects ) === false ) { - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - } + } - for ( var i = 0, l = objects.length; i < l; i ++ ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - } + } + +}; - }; -}( THREE ) ); +export { Raycaster }; \ No newline at end of file diff --git a/src/core/Uniform.js b/src/core/Uniform.js index e13a5a0b27a9c3..1c27c24f4a9023 100644 --- a/src/core/Uniform.js +++ b/src/core/Uniform.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.Uniform = function ( value ) { +function Uniform ( value ) { + this.isUniform = true; if ( typeof value === 'string' ) { @@ -17,9 +18,9 @@ THREE.Uniform = function ( value ) { }; -THREE.Uniform.prototype = { +Uniform.prototype = { - constructor: THREE.Uniform, + constructor: Uniform, onUpdate: function ( callback ) { @@ -31,3 +32,6 @@ THREE.Uniform.prototype = { } }; + + +export { Uniform }; \ No newline at end of file diff --git a/src/extras/CurveUtils.js b/src/extras/CurveUtils.js index 1c0ea80f63d9a0..bc60235fbc2980 100644 --- a/src/extras/CurveUtils.js +++ b/src/extras/CurveUtils.js @@ -1,8 +1,10 @@ +var CurveUtils; + /** * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.CurveUtils = { +CurveUtils = { tangentQuadraticBezier: function ( t, p0, p1, p2 ) { @@ -47,3 +49,6 @@ THREE.CurveUtils = { } }; + + +export { CurveUtils }; \ No newline at end of file diff --git a/src/extras/SceneUtils.js b/src/extras/SceneUtils.js index c86eaa9a6faa8b..d866c90a370b25 100644 --- a/src/extras/SceneUtils.js +++ b/src/extras/SceneUtils.js @@ -1,16 +1,22 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Mesh } from '../objects/Mesh'; +import { Group } from '../objects/Group'; + +var SceneUtils; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.SceneUtils = { +SceneUtils = { createMultiMaterialObject: function ( geometry, materials ) { - var group = new THREE.Group(); + var group = new Group(); for ( var i = 0, l = materials.length; i < l; i ++ ) { - group.add( new THREE.Mesh( geometry, materials[ i ] ) ); + group.add( new Mesh( geometry, materials[ i ] ) ); } @@ -28,7 +34,7 @@ THREE.SceneUtils = { attach: function ( child, scene, parent ) { - var matrixWorldInverse = new THREE.Matrix4(); + var matrixWorldInverse = new Matrix4(); matrixWorldInverse.getInverse( parent.matrixWorld ); child.applyMatrix( matrixWorldInverse ); @@ -38,3 +44,6 @@ THREE.SceneUtils = { } }; + + +export { SceneUtils }; \ No newline at end of file diff --git a/src/extras/ShapeUtils.js b/src/extras/ShapeUtils.js index 795781358b60b9..edf861fa0f8cd0 100644 --- a/src/extras/ShapeUtils.js +++ b/src/extras/ShapeUtils.js @@ -1,8 +1,10 @@ +var ShapeUtils; + /** * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.ShapeUtils = { +ShapeUtils = { // calculate area of the contour polygon @@ -105,7 +107,7 @@ THREE.ShapeUtils = { var u, v, w; - if ( THREE.ShapeUtils.area( contour ) > 0.0 ) { + if ( ShapeUtils.area( contour ) > 0.0 ) { for ( v = 0; v < n; v ++ ) verts[ v ] = v; @@ -654,7 +656,7 @@ THREE.ShapeUtils = { // remove holes by cutting paths to holes and adding them to the shape var shapeWithoutHoles = removeHoles( contour, holes ); - var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape //console.log( "triangles",triangles, triangles.length ); // check all face vertices against all points map @@ -685,7 +687,7 @@ THREE.ShapeUtils = { isClockWise: function ( pts ) { - return THREE.ShapeUtils.area( pts ) < 0; + return ShapeUtils.area( pts ) < 0; }, @@ -763,3 +765,6 @@ THREE.ShapeUtils = { } )() }; + + +export { ShapeUtils }; \ No newline at end of file diff --git a/src/extras/core/Curve.js b/src/extras/core/Curve.js index e869e61f7dc351..6f5843cad37689 100644 --- a/src/extras/core/Curve.js +++ b/src/extras/core/Curve.js @@ -33,13 +33,14 @@ * Abstract Curve base class **************************************************************/ -THREE.Curve = function () { +function Curve () { + this.isCurve = true; }; -THREE.Curve.prototype = { +Curve.prototype = { - constructor: THREE.Curve, + constructor: Curve, // Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] @@ -273,12 +274,15 @@ THREE.Curve.prototype = { // A Factory method for creating new curve subclasses -THREE.Curve.create = function ( constructor, getPointFunc ) { +Curve.create = function ( constructor, getPointFunc ) { - constructor.prototype = Object.create( THREE.Curve.prototype ); + constructor.prototype = Object.create( Curve.prototype ); constructor.prototype.constructor = constructor; constructor.prototype.getPoint = getPointFunc; return constructor; }; + + +export { Curve }; \ No newline at end of file diff --git a/src/extras/core/CurvePath.js b/src/extras/core/CurvePath.js index 6eb94bfad40c2f..c9df8d79eed09e 100644 --- a/src/extras/core/CurvePath.js +++ b/src/extras/core/CurvePath.js @@ -1,3 +1,8 @@ +import { Curve } from './Curve'; +import { Vector3 } from '../../math/Vector3'; +import { Geometry } from '../../core/Geometry'; +import { LineCurve } from '../curves/LineCurve'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @@ -8,7 +13,8 @@ * curves, but retains the api of a curve **************************************************************/ -THREE.CurvePath = function () { +function CurvePath () { + this.isCurvePath = true; this.curves = []; @@ -16,9 +22,9 @@ THREE.CurvePath = function () { }; -THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype ), { +CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - constructor: THREE.CurvePath, + constructor: CurvePath, add: function ( curve ) { @@ -34,7 +40,7 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype if ( ! startPoint.equals( endPoint ) ) { - this.curves.push( new THREE.LineCurve( endPoint, startPoint ) ); + this.curves.push( new LineCurve( endPoint, startPoint ) ); } @@ -163,9 +169,9 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { var curve = curves[ i ]; - var resolution = curve instanceof THREE.EllipseCurve ? divisions * 2 - : curve instanceof THREE.LineCurve ? 1 - : curve instanceof THREE.SplineCurve ? divisions * curve.points.length + var resolution = (curve && curve.isEllipseCurve) ? divisions * 2 + : (curve && curve.isLineCurve) ? 1 + : (curve && curve.isSplineCurve) ? divisions * curve.points.length : divisions; var pts = curve.getPoints( resolution ); @@ -217,12 +223,12 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype createGeometry: function ( points ) { - var geometry = new THREE.Geometry(); + var geometry = new Geometry(); for ( var i = 0, l = points.length; i < l; i ++ ) { var point = points[ i ]; - geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) ); + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); } @@ -231,3 +237,6 @@ THREE.CurvePath.prototype = Object.assign( Object.create( THREE.Curve.prototype } } ); + + +export { CurvePath }; \ No newline at end of file diff --git a/src/extras/core/Font.js b/src/extras/core/Font.js index 4f13af583d7e87..619fe7d24a1723 100644 --- a/src/extras/core/Font.js +++ b/src/extras/core/Font.js @@ -1,15 +1,19 @@ +import { ShapeUtils } from '../ShapeUtils'; +import { ShapePath } from './Path'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author mrdoob / http://mrdoob.com/ */ -THREE.Font = function ( data ) { +function Font ( data ) { + this.isFont = true; this.data = data; }; -Object.assign( THREE.Font.prototype, { +Object.assign( Font.prototype, { generateShapes: function ( text, size, divisions ) { @@ -40,9 +44,9 @@ Object.assign( THREE.Font.prototype, { if ( ! glyph ) return; - var path = new THREE.ShapePath(); + var path = new ShapePath(); - var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3; + var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3; var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; if ( glyph.o ) { @@ -162,3 +166,6 @@ Object.assign( THREE.Font.prototype, { } } ); + + +export { Font }; \ No newline at end of file diff --git a/src/extras/core/Path.js b/src/extras/core/Path.js index c2246e3a7620ba..7dfdef956f6d6a 100644 --- a/src/extras/core/Path.js +++ b/src/extras/core/Path.js @@ -1,13 +1,20 @@ +import { PathPrototype } from './PathPrototype'; +import { Shape } from './Shape'; +import { ShapeUtils } from '../ShapeUtils'; +import { Vector2 } from '../../math/Vector2'; +import { CurvePath } from './CurvePath'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * Creates free form 2d path using series of points, lines or curves. * **/ -THREE.Path = function ( points ) { +function Path ( points ) { + this.isPath = true; - THREE.CurvePath.call( this ); - this.currentPoint = new THREE.Vector2(); + CurvePath.call( this ); + this.currentPoint = new Vector2(); if ( points ) { @@ -17,140 +24,20 @@ THREE.Path = function ( points ) { }; -THREE.Path.prototype = Object.assign( Object.create( THREE.CurvePath.prototype ), { - - constructor: THREE.Path, - - // Create path using straight lines to connect all points - // - vectors: array of Vector2 - fromPoints: function ( vectors ) { - - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - - for ( var i = 1, l = vectors.length; i < l; i ++ ) { - - this.lineTo( vectors[ i ].x, vectors[ i ].y ); - - } - - }, - - moveTo: function ( x, y ) { - - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - - }, - - lineTo: function ( x, y ) { - - var curve = new THREE.LineCurve( this.currentPoint.clone(), new THREE.Vector2( x, y ) ); - this.curves.push( curve ); - - this.currentPoint.set( x, y ); - - }, - - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - - var curve = new THREE.QuadraticBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCPx, aCPy ), - new THREE.Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - - var curve = new THREE.CubicBezierCurve( - this.currentPoint.clone(), - new THREE.Vector2( aCP1x, aCP1y ), - new THREE.Vector2( aCP2x, aCP2y ), - new THREE.Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - splineThru: function ( pts /*Array of Vector*/ ) { - - var npts = [ this.currentPoint.clone() ].concat( pts ); - - var curve = new THREE.SplineCurve( npts ); - this.curves.push( curve ); - - this.currentPoint.copy( pts[ pts.length - 1 ] ); - - }, - - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); - - }, - - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - - }, - - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - }, - - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - if ( this.curves.length > 0 ) { - - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); - - if ( ! firstPoint.equals( this.currentPoint ) ) { - - this.lineTo( firstPoint.x, firstPoint.y ); - - } - - } - - this.curves.push( curve ); - - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); - - } - -} ); +Path.prototype = PathPrototype; +PathPrototype.constructor = Path; // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" -THREE.ShapePath = function() { +function ShapePath() { + this.isShapePath = true; this.subPaths = []; this.currentPath = null; } -THREE.ShapePath.prototype = { +ShapePath.prototype = { moveTo: function ( x, y ) { - this.currentPath = new THREE.Path(); + this.currentPath = new Path(); this.subPaths.push(this.currentPath); this.currentPath.moveTo( x, y ); }, @@ -177,7 +64,7 @@ THREE.ShapePath.prototype = { var tmpPath = inSubpaths[ i ]; - var tmpShape = new THREE.Shape(); + var tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); @@ -247,7 +134,7 @@ THREE.ShapePath.prototype = { } - var isClockWise = THREE.ShapeUtils.isClockWise; + var isClockWise = ShapeUtils.isClockWise; var subPaths = this.subPaths; if ( subPaths.length === 0 ) return []; @@ -260,7 +147,7 @@ THREE.ShapePath.prototype = { if ( subPaths.length === 1 ) { tmpPath = subPaths[ 0 ]; - tmpShape = new THREE.Shape(); + tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); return shapes; @@ -292,7 +179,7 @@ THREE.ShapePath.prototype = { if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints }; + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; newShapes[ mainIdx ].s.curves = tmpPath.curves; if ( holesFirst ) mainIdx ++; @@ -394,3 +281,6 @@ THREE.ShapePath.prototype = { } } + + +export { ShapePath, Path }; \ No newline at end of file diff --git a/src/extras/core/PathPrototype.js b/src/extras/core/PathPrototype.js new file mode 100644 index 00000000000000..d2db1a76208814 --- /dev/null +++ b/src/extras/core/PathPrototype.js @@ -0,0 +1,131 @@ +import { CurvePath } from './CurvePath'; +import { EllipseCurve } from '../curves/EllipseCurve'; +import { SplineCurve } from '../curves/SplineCurve'; +import { Vector2 } from '../../math/Vector2'; +import { CubicBezierCurve } from '../curves/CubicBezierCurve'; +import { QuadraticBezierCurve } from '../curves/QuadraticBezierCurve'; +import { LineCurve } from '../curves/LineCurve'; + +var PathPrototype; + +PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { + + fromPoints: function ( vectors ) { + + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + + for ( var i = 1, l = vectors.length; i < l; i ++ ) { + + this.lineTo( vectors[ i ].x, vectors[ i ].y ); + + } + + }, + + moveTo: function ( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + }, + + lineTo: function ( x, y ) { + + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + }, + + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + }, + + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + }, + + splineThru: function ( pts /*Array of Vector*/ ) { + + var npts = [ this.currentPoint.clone() ].concat( pts ); + + var curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + }, + + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + }, + + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + }, + + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + }, + + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + if ( this.curves.length > 0 ) { + + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + } + +} ) + +export { PathPrototype }; \ No newline at end of file diff --git a/src/extras/core/Shape.js b/src/extras/core/Shape.js index b785e068be7b86..a962e31b94d82b 100644 --- a/src/extras/core/Shape.js +++ b/src/extras/core/Shape.js @@ -1,3 +1,8 @@ +import { PathPrototype } from './PathPrototype'; +import { ShapeGeometry } from '../geometries/ShapeGeometry'; +import { ExtrudeGeometry } from '../geometries/ExtrudeGeometry'; +import { Path } from './Path'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * Defines a 2d shape plane using paths. @@ -9,23 +14,24 @@ // STEP 3a - Extract points from each shape, turn to vertices // STEP 3b - Triangulate each shape, add faces. -THREE.Shape = function () { +function Shape () { + this.isShape = true; - THREE.Path.apply( this, arguments ); + Path.apply( this, arguments ); this.holes = []; }; -THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { +Shape.prototype = Object.assign( Object.create( PathPrototype ), { - constructor: THREE.Shape, + constructor: Shape, // Convenience method to return ExtrudeGeometry extrude: function ( options ) { - return new THREE.ExtrudeGeometry( this, options ); + return new ExtrudeGeometry( this, options ); }, @@ -33,7 +39,7 @@ THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { makeGeometry: function ( options ) { - return new THREE.ShapeGeometry( this, options ); + return new ShapeGeometry( this, options ); }, @@ -71,3 +77,6 @@ THREE.Shape.prototype = Object.assign( Object.create( THREE.Path.prototype ), { } } ); + + +export { Shape }; \ No newline at end of file diff --git a/src/extras/curves/ArcCurve.js b/src/extras/curves/ArcCurve.js index 5f7bc9b0f7425d..23fc96ea8c9346 100644 --- a/src/extras/curves/ArcCurve.js +++ b/src/extras/curves/ArcCurve.js @@ -1,12 +1,18 @@ +import { EllipseCurve } from './EllipseCurve'; + /************************************************************** * Arc curve **************************************************************/ -THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { +function ArcCurve ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.isArcCurve = this.isEllipseCurve = this.isCurve = true; - THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); }; -THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype ); -THREE.ArcCurve.prototype.constructor = THREE.ArcCurve; +ArcCurve.prototype = Object.create( EllipseCurve.prototype ); +ArcCurve.prototype.constructor = ArcCurve; + + +export { ArcCurve }; \ No newline at end of file diff --git a/src/extras/curves/CatmullRomCurve3.js b/src/extras/curves/CatmullRomCurve3.js index 2b57912fd33c0e..bbe22a76ede2fd 100644 --- a/src/extras/curves/CatmullRomCurve3.js +++ b/src/extras/curves/CatmullRomCurve3.js @@ -1,3 +1,8 @@ +import { Vector3 } from '../../math/Vector3'; +import { Curve } from '../core/Curve'; + +var CatmullRomCurve3; + /** * @author zz85 https://github.com/zz85 * @@ -9,10 +14,10 @@ * curve.tension is used for catmullrom which defaults to 0.5 */ -THREE.CatmullRomCurve3 = ( function() { +CatmullRomCurve3 = ( function() { var - tmp = new THREE.Vector3(), + tmp = new Vector3(), px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); @@ -79,7 +84,7 @@ THREE.CatmullRomCurve3 = ( function() { }; // Subclass Three.js curve - return THREE.Curve.create( + return Curve.create( function ( p /* array of Vector3 */ ) { @@ -167,7 +172,7 @@ THREE.CatmullRomCurve3 = ( function() { } - var v = new THREE.Vector3( + var v = new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) @@ -180,3 +185,6 @@ THREE.CatmullRomCurve3 = ( function() { ); } )(); + + +export { CatmullRomCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/ClosedSplineCurve3.js b/src/extras/curves/ClosedSplineCurve3.js index d1d7102192313c..9dea7d1e122bba 100644 --- a/src/extras/curves/ClosedSplineCurve3.js +++ b/src/extras/curves/ClosedSplineCurve3.js @@ -1,16 +1,22 @@ +import { CatmullRomCurve3 } from './CatmullRomCurve3'; + /************************************************************** * Closed Spline 3D curve **************************************************************/ -THREE.ClosedSplineCurve3 = function ( points ) { +function ClosedSplineCurve3 ( points ) { + this.isClosedSplineCurve3 = this.isCatmullRomCurve3 = true; console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); - THREE.CatmullRomCurve3.call( this, points ); + CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; this.closed = true; }; -THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype ); +ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); + + +export { ClosedSplineCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/CubicBezierCurve.js b/src/extras/curves/CubicBezierCurve.js index 3d751bbe23d0cb..557db4d8f065fe 100644 --- a/src/extras/curves/CubicBezierCurve.js +++ b/src/extras/curves/CubicBezierCurve.js @@ -1,8 +1,14 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; +import { ShapeUtils } from '../ShapeUtils'; + /************************************************************** * Cubic Bezier curve **************************************************************/ -THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { +function CubicBezierCurve ( v0, v1, v2, v3 ) { + this.isCubicBezierCurve = this.isCurve = true; this.v0 = v0; this.v1 = v1; @@ -11,27 +17,30 @@ THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) { }; -THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve; +CubicBezierCurve.prototype = Object.create( Curve.prototype ); +CubicBezierCurve.prototype.constructor = CubicBezierCurve; -THREE.CubicBezierCurve.prototype.getPoint = function ( t ) { +CubicBezierCurve.prototype.getPoint = function ( t ) { - var b3 = THREE.ShapeUtils.b3; + var b3 = ShapeUtils.b3; - return new THREE.Vector2( + return new Vector2( b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) ); }; -THREE.CubicBezierCurve.prototype.getTangent = function( t ) { +CubicBezierCurve.prototype.getTangent = function( t ) { - var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier; + var tangentCubicBezier = CurveUtils.tangentCubicBezier; - return new THREE.Vector2( + return new Vector2( tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) ).normalize(); }; + + +export { CubicBezierCurve }; \ No newline at end of file diff --git a/src/extras/curves/CubicBezierCurve3.js b/src/extras/curves/CubicBezierCurve3.js index 1a49b6ae9c314c..05903b6dd6f3b7 100644 --- a/src/extras/curves/CubicBezierCurve3.js +++ b/src/extras/curves/CubicBezierCurve3.js @@ -1,8 +1,14 @@ +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { Curve } from '../core/Curve'; + +var CubicBezierCurve3; + /************************************************************** * Cubic Bezier 3D curve **************************************************************/ -THREE.CubicBezierCurve3 = THREE.Curve.create( +CubicBezierCurve3 = Curve.create( function ( v0, v1, v2, v3 ) { @@ -15,9 +21,9 @@ THREE.CubicBezierCurve3 = THREE.Curve.create( function ( t ) { - var b3 = THREE.ShapeUtils.b3; + var b3 = ShapeUtils.b3; - return new THREE.Vector3( + return new Vector3( b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) @@ -26,3 +32,6 @@ THREE.CubicBezierCurve3 = THREE.Curve.create( } ); + + +export { CubicBezierCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/EllipseCurve.js b/src/extras/curves/EllipseCurve.js index 64e74616de67b4..f9b5a5f7bb29c1 100644 --- a/src/extras/curves/EllipseCurve.js +++ b/src/extras/curves/EllipseCurve.js @@ -1,8 +1,12 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; + /************************************************************** * Ellipse curve **************************************************************/ -THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { +function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.isEllipseCurve = this.isCurve = true; this.aX = aX; this.aY = aY; @@ -19,10 +23,10 @@ THREE.EllipseCurve = function( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, }; -THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve; +EllipseCurve.prototype = Object.create( Curve.prototype ); +EllipseCurve.prototype.constructor = EllipseCurve; -THREE.EllipseCurve.prototype.getPoint = function( t ) { +EllipseCurve.prototype.getPoint = function( t ) { var twoPi = Math.PI * 2; var deltaAngle = this.aEndAngle - this.aStartAngle; @@ -78,6 +82,9 @@ THREE.EllipseCurve.prototype.getPoint = function( t ) { } - return new THREE.Vector2( x, y ); + return new Vector2( x, y ); }; + + +export { EllipseCurve }; \ No newline at end of file diff --git a/src/extras/curves/LineCurve.js b/src/extras/curves/LineCurve.js index e4326886d3606c..bc44749a71028b 100644 --- a/src/extras/curves/LineCurve.js +++ b/src/extras/curves/LineCurve.js @@ -1,18 +1,21 @@ +import { Curve } from '../core/Curve'; + /************************************************************** * Line **************************************************************/ -THREE.LineCurve = function ( v1, v2 ) { +function LineCurve ( v1, v2 ) { + this.isLineCurve = this.isCurve = true; this.v1 = v1; this.v2 = v2; }; -THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.LineCurve.prototype.constructor = THREE.LineCurve; +LineCurve.prototype = Object.create( Curve.prototype ); +LineCurve.prototype.constructor = LineCurve; -THREE.LineCurve.prototype.getPoint = function ( t ) { +LineCurve.prototype.getPoint = function ( t ) { if ( t === 1 ) { @@ -29,16 +32,19 @@ THREE.LineCurve.prototype.getPoint = function ( t ) { // Line curve is linear, so we can overwrite default getPointAt -THREE.LineCurve.prototype.getPointAt = function ( u ) { +LineCurve.prototype.getPointAt = function ( u ) { return this.getPoint( u ); }; -THREE.LineCurve.prototype.getTangent = function( t ) { +LineCurve.prototype.getTangent = function( t ) { var tangent = this.v2.clone().sub( this.v1 ); return tangent.normalize(); }; + + +export { LineCurve }; \ No newline at end of file diff --git a/src/extras/curves/LineCurve3.js b/src/extras/curves/LineCurve3.js index 0f6fcd3b88f577..de57a71029f79a 100644 --- a/src/extras/curves/LineCurve3.js +++ b/src/extras/curves/LineCurve3.js @@ -1,8 +1,13 @@ +import { Vector3 } from '../../math/Vector3'; +import { Curve } from '../core/Curve'; + +var LineCurve3; + /************************************************************** * Line3D **************************************************************/ -THREE.LineCurve3 = THREE.Curve.create( +LineCurve3 = Curve.create( function ( v1, v2 ) { @@ -19,7 +24,7 @@ THREE.LineCurve3 = THREE.Curve.create( } - var vector = new THREE.Vector3(); + var vector = new Vector3(); vector.subVectors( this.v2, this.v1 ); // diff vector.multiplyScalar( t ); @@ -30,3 +35,6 @@ THREE.LineCurve3 = THREE.Curve.create( } ); + + +export { LineCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/QuadraticBezierCurve.js b/src/extras/curves/QuadraticBezierCurve.js index b8fc978027c2d9..428ed01cf299d8 100644 --- a/src/extras/curves/QuadraticBezierCurve.js +++ b/src/extras/curves/QuadraticBezierCurve.js @@ -1,9 +1,15 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; +import { ShapeUtils } from '../ShapeUtils'; + /************************************************************** * Quadratic Bezier curve **************************************************************/ -THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { +function QuadraticBezierCurve ( v0, v1, v2 ) { + this.isQuadraticBezierCurve = this.isCurve = true; this.v0 = v0; this.v1 = v1; @@ -11,15 +17,15 @@ THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) { }; -THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve; +QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); +QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; -THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { +QuadraticBezierCurve.prototype.getPoint = function ( t ) { - var b2 = THREE.ShapeUtils.b2; + var b2 = ShapeUtils.b2; - return new THREE.Vector2( + return new Vector2( b2( t, this.v0.x, this.v1.x, this.v2.x ), b2( t, this.v0.y, this.v1.y, this.v2.y ) ); @@ -27,13 +33,16 @@ THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) { }; -THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) { +QuadraticBezierCurve.prototype.getTangent = function( t ) { - var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier; + var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier; - return new THREE.Vector2( + return new Vector2( tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) ).normalize(); }; + + +export { QuadraticBezierCurve }; \ No newline at end of file diff --git a/src/extras/curves/QuadraticBezierCurve3.js b/src/extras/curves/QuadraticBezierCurve3.js index 1bdddd131ea59d..c2a6c72c257a6e 100644 --- a/src/extras/curves/QuadraticBezierCurve3.js +++ b/src/extras/curves/QuadraticBezierCurve3.js @@ -1,8 +1,14 @@ +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { Curve } from '../core/Curve'; + +var QuadraticBezierCurve3; + /************************************************************** * Quadratic Bezier 3D curve **************************************************************/ -THREE.QuadraticBezierCurve3 = THREE.Curve.create( +QuadraticBezierCurve3 = Curve.create( function ( v0, v1, v2 ) { @@ -14,9 +20,9 @@ THREE.QuadraticBezierCurve3 = THREE.Curve.create( function ( t ) { - var b2 = THREE.ShapeUtils.b2; + var b2 = ShapeUtils.b2; - return new THREE.Vector3( + return new Vector3( b2( t, this.v0.x, this.v1.x, this.v2.x ), b2( t, this.v0.y, this.v1.y, this.v2.y ), b2( t, this.v0.z, this.v1.z, this.v2.z ) @@ -25,3 +31,6 @@ THREE.QuadraticBezierCurve3 = THREE.Curve.create( } ); + + +export { QuadraticBezierCurve3 }; \ No newline at end of file diff --git a/src/extras/curves/SplineCurve.js b/src/extras/curves/SplineCurve.js index 0a84eaacc1c220..e669be3d153d7b 100644 --- a/src/extras/curves/SplineCurve.js +++ b/src/extras/curves/SplineCurve.js @@ -1,17 +1,22 @@ +import { Curve } from '../core/Curve'; +import { Vector2 } from '../../math/Vector2'; +import { CurveUtils } from '../CurveUtils'; + /************************************************************** * Spline curve **************************************************************/ -THREE.SplineCurve = function ( points /* array of Vector2 */ ) { +function SplineCurve ( points /* array of Vector2 */ ) { + this.isSplineCurve = this.isCurve = true; this.points = ( points == undefined ) ? [] : points; }; -THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype ); -THREE.SplineCurve.prototype.constructor = THREE.SplineCurve; +SplineCurve.prototype = Object.create( Curve.prototype ); +SplineCurve.prototype.constructor = SplineCurve; -THREE.SplineCurve.prototype.getPoint = function ( t ) { +SplineCurve.prototype.getPoint = function ( t ) { var points = this.points; var point = ( points.length - 1 ) * t; @@ -24,11 +29,14 @@ THREE.SplineCurve.prototype.getPoint = function ( t ) { 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 interpolate = THREE.CurveUtils.interpolate; + var interpolate = CurveUtils.interpolate; - return new THREE.Vector2( + return new Vector2( interpolate( point0.x, point1.x, point2.x, point3.x, weight ), interpolate( point0.y, point1.y, point2.y, point3.y, weight ) ); }; + + +export { SplineCurve }; \ No newline at end of file diff --git a/src/extras/curves/SplineCurve3.js b/src/extras/curves/SplineCurve3.js index 1782fcfba40e6b..957780f6777a32 100644 --- a/src/extras/curves/SplineCurve3.js +++ b/src/extras/curves/SplineCurve3.js @@ -1,9 +1,15 @@ +import { Vector3 } from '../../math/Vector3'; +import { CurveUtils } from '../CurveUtils'; +import { Curve } from '../core/Curve'; + +var SplineCurve3; + /************************************************************** * Spline 3D curve **************************************************************/ -THREE.SplineCurve3 = THREE.Curve.create( +SplineCurve3 = Curve.create( function ( points /* array of Vector3 */ ) { @@ -25,9 +31,9 @@ THREE.SplineCurve3 = THREE.Curve.create( 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 interpolate = THREE.CurveUtils.interpolate; + var interpolate = CurveUtils.interpolate; - return new THREE.Vector3( + return new Vector3( interpolate( point0.x, point1.x, point2.x, point3.x, weight ), interpolate( point0.y, point1.y, point2.y, point3.y, weight ), interpolate( point0.z, point1.z, point2.z, point3.z, weight ) @@ -36,3 +42,6 @@ THREE.SplineCurve3 = THREE.Curve.create( } ); + + +export { SplineCurve3 }; \ No newline at end of file diff --git a/src/extras/geometries/BoxBufferGeometry.js b/src/extras/geometries/BoxBufferGeometry.js index 46459ba73a9244..f3203a4e165ba9 100644 --- a/src/extras/geometries/BoxBufferGeometry.js +++ b/src/extras/geometries/BoxBufferGeometry.js @@ -1,10 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { +function BoxBufferGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'BoxBufferGeometry'; @@ -52,10 +57,10 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz // build geometry - this.setIndex( 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 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); // helper functions @@ -100,7 +105,7 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height var vertexCounter = 0; var groupCount = 0; - var vector = new THREE.Vector3(); + var vector = new Vector3(); // generate vertices, normals and uvs @@ -190,5 +195,8 @@ THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, height }; -THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry; +BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + + +export { BoxBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/BoxGeometry.js b/src/extras/geometries/BoxGeometry.js index 12a69b86305856..b91f355f6ebe3a 100644 --- a/src/extras/geometries/BoxGeometry.js +++ b/src/extras/geometries/BoxGeometry.js @@ -1,11 +1,17 @@ +import { Geometry } from '../../core/Geometry'; +import { BoxBufferGeometry } from './BoxBufferGeometry'; + +var CubeGeometry; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as */ -THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) { +function BoxGeometry ( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.isBoxGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'BoxGeometry'; @@ -18,12 +24,15 @@ THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegmen depthSegments: depthSegments }; - this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); this.mergeVertices(); }; -THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry; +BoxGeometry.prototype = Object.create( Geometry.prototype ); +BoxGeometry.prototype.constructor = BoxGeometry; + +CubeGeometry = BoxGeometry; + -THREE.CubeGeometry = THREE.BoxGeometry; +export { CubeGeometry, BoxGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CircleBufferGeometry.js b/src/extras/geometries/CircleBufferGeometry.js index f5b2f8b6701215..49835afdadea4c 100644 --- a/src/extras/geometries/CircleBufferGeometry.js +++ b/src/extras/geometries/CircleBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams */ -THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) { +function CircleBufferGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'CircleBufferGeometry'; @@ -54,14 +60,17 @@ THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLengt } - this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); }; -THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry; +CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; + + +export { CircleBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CircleGeometry.js b/src/extras/geometries/CircleGeometry.js index 10e64731a763f4..620df514c8f005 100644 --- a/src/extras/geometries/CircleGeometry.js +++ b/src/extras/geometries/CircleGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { CircleBufferGeometry } from './CircleBufferGeometry'; + /** * @author hughes */ -THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { +function CircleGeometry ( radius, segments, thetaStart, thetaLength ) { + this.isCircleGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'CircleGeometry'; @@ -15,9 +19,12 @@ THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) { thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); }; -THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry; +CircleGeometry.prototype = Object.create( Geometry.prototype ); +CircleGeometry.prototype.constructor = CircleGeometry; + + +export { CircleGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ConeBufferGeometry.js b/src/extras/geometries/ConeBufferGeometry.js index 8a1334e0df1c44..51680a499e9be4 100644 --- a/src/extras/geometries/ConeBufferGeometry.js +++ b/src/extras/geometries/ConeBufferGeometry.js @@ -1,13 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { CylinderBufferGeometry } from './CylinderBufferGeometry'; + /* * @author: abelnation / http://github.com/abelnation */ -THREE.ConeBufferGeometry = function ( +function ConeBufferGeometry ( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isConeBufferGeometry = this.isBufferGeometry = true; - THREE.CylinderBufferGeometry.call( this, + CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); @@ -25,5 +29,8 @@ THREE.ConeBufferGeometry = function ( }; -THREE.ConeBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.ConeBufferGeometry.prototype.constructor = THREE.ConeBufferGeometry; +ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; + + +export { ConeBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ConeGeometry.js b/src/extras/geometries/ConeGeometry.js index 12b52bb8ae6435..8c3f7f7ce3ea06 100644 --- a/src/extras/geometries/ConeGeometry.js +++ b/src/extras/geometries/ConeGeometry.js @@ -1,13 +1,16 @@ +import { CylinderGeometry } from './CylinderGeometry'; + /** * @author abelnation / http://github.com/abelnation */ -THREE.ConeGeometry = function ( +function ConeGeometry ( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isConeGeometry = this.isCylinderGeometry = this.isGeometry = true; - THREE.CylinderGeometry.call( this, + CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); @@ -26,5 +29,8 @@ THREE.ConeGeometry = function ( }; -THREE.ConeGeometry.prototype = Object.create( THREE.CylinderGeometry.prototype ); -THREE.ConeGeometry.prototype.constructor = THREE.ConeGeometry; +ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); +ConeGeometry.prototype.constructor = ConeGeometry; + + +export { ConeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CylinderBufferGeometry.js b/src/extras/geometries/CylinderBufferGeometry.js index 4664ee615d7c3d..fed02359a25422 100644 --- a/src/extras/geometries/CylinderBufferGeometry.js +++ b/src/extras/geometries/CylinderBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'CylinderBufferGeometry'; @@ -48,10 +54,10 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables @@ -114,8 +120,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial function generateTorso() { var x, y; - var normal = new THREE.Vector3(); - var vertex = new THREE.Vector3(); + var normal = new Vector3(); + var vertex = new Vector3(); var groupCount = 0; @@ -215,8 +221,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial var x, centerIndexStart, centerIndexEnd; - var uv = new THREE.Vector2(); - var vertex = new THREE.Vector3(); + var uv = new Vector2(); + var vertex = new Vector3(); var groupCount = 0; @@ -319,5 +325,8 @@ THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radial }; -THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry; +CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + + +export { CylinderBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/CylinderGeometry.js b/src/extras/geometries/CylinderGeometry.js index 83bfbd42d3b6c1..a0c2de767d2739 100644 --- a/src/extras/geometries/CylinderGeometry.js +++ b/src/extras/geometries/CylinderGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { CylinderBufferGeometry } from './CylinderBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +function CylinderGeometry ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.isCylinderGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'CylinderGeometry'; @@ -19,10 +23,13 @@ THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegme thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); this.mergeVertices(); }; -THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry; +CylinderGeometry.prototype = Object.create( Geometry.prototype ); +CylinderGeometry.prototype.constructor = CylinderGeometry; + + +export { CylinderGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/DodecahedronGeometry.js b/src/extras/geometries/DodecahedronGeometry.js index 0c540cd465ca5e..ac270d5902aead 100644 --- a/src/extras/geometries/DodecahedronGeometry.js +++ b/src/extras/geometries/DodecahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author Abe Pazos / https://hamoid.com */ -THREE.DodecahedronGeometry = function ( radius, detail ) { +function DodecahedronGeometry ( radius, detail ) { + this.isDodecahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var t = ( 1 + Math.sqrt( 5 ) ) / 2; var r = 1 / t; @@ -43,7 +46,7 @@ THREE.DodecahedronGeometry = function ( radius, detail ) { 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'DodecahedronGeometry'; @@ -54,5 +57,8 @@ THREE.DodecahedronGeometry = function ( radius, detail ) { }; -THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry; +DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; + + +export { DodecahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/EdgesGeometry.js b/src/extras/geometries/EdgesGeometry.js index 7515bce8413ed1..937854fdd049ea 100644 --- a/src/extras/geometries/EdgesGeometry.js +++ b/src/extras/geometries/EdgesGeometry.js @@ -1,14 +1,20 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { Geometry } from '../../core/Geometry'; +import { _Math } from '../../math/Math'; + /** * @author WestLangley / http://github.com/WestLangley */ -THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { +function EdgesGeometry ( geometry, thresholdAngle ) { + this.isEdgesGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle ); + var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle ); var edge = [ 0, 0 ], hash = {}; @@ -22,9 +28,9 @@ THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { var geometry2; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { - geometry2 = new THREE.Geometry(); + geometry2 = new Geometry(); geometry2.fromBufferGeometry( geometry ); } else { @@ -87,9 +93,12 @@ THREE.EdgesGeometry = function ( geometry, thresholdAngle ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) ); + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); }; -THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry; +EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); +EdgesGeometry.prototype.constructor = EdgesGeometry; + + +export { EdgesGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ExtrudeGeometry.js b/src/extras/geometries/ExtrudeGeometry.js index ce4a6a3cd192ba..c7be71da812bd0 100644 --- a/src/extras/geometries/ExtrudeGeometry.js +++ b/src/extras/geometries/ExtrudeGeometry.js @@ -1,3 +1,10 @@ +import { Geometry } from '../../core/Geometry'; +import { Vector2 } from '../../math/Vector2'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { TubeGeometry } from './TubeGeometry'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @@ -22,7 +29,8 @@ * } **/ -THREE.ExtrudeGeometry = function ( shapes, options ) { +function ExtrudeGeometry ( shapes, options ) { + this.isExtrudeGeometry = this.isGeometry = true; if ( typeof( shapes ) === "undefined" ) { @@ -31,7 +39,7 @@ THREE.ExtrudeGeometry = function ( shapes, options ) { } - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ExtrudeGeometry'; @@ -51,10 +59,10 @@ THREE.ExtrudeGeometry = function ( shapes, options ) { }; -THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry; +ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); +ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; -THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { +ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { var sl = shapes.length; @@ -67,7 +75,7 @@ THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { }; -THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { +ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var amount = options.amount !== undefined ? options.amount : 100; @@ -85,7 +93,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var extrudePts, extrudeByPath = false; // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator; + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; var splineTube, binormal, normal, position2; if ( extrudePath ) { @@ -100,13 +108,13 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { // Reuse TNB from TubeGeomtry for now. // TODO1 - have a .isClosed in spline? - splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false ); + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - binormal = new THREE.Vector3(); - normal = new THREE.Vector3(); - position2 = new THREE.Vector3(); + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); } @@ -132,7 +140,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + var reverse = ! ShapeUtils.isClockWise( vertices ); if ( reverse ) { @@ -144,7 +152,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { ahole = holes[ h ]; - if ( THREE.ShapeUtils.isClockWise( ahole ) ) { + if ( ShapeUtils.isClockWise( ahole ) ) { holes[ h ] = ahole.reverse(); @@ -157,7 +165,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { } - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + var faces = ShapeUtils.triangulateShape( vertices, holes ); /* Vertices */ @@ -243,7 +251,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { 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 ); + return new Vector2( v_trans_x, v_trans_y ); } else { @@ -304,7 +312,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { } - return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); } @@ -616,7 +624,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { function v( x, y, z ) { - scope.vertices.push( new THREE.Vector3( x, y, z ) ); + scope.vertices.push( new Vector3( x, y, z ) ); } @@ -626,7 +634,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { b += shapesOffset; c += shapesOffset; - scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) ); + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); var uvs = uvgen.generateTopUV( scope, a, b, c ); @@ -641,8 +649,8 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { c += shapesOffset; d += shapesOffset; - scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) ); - scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) ); + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); @@ -653,7 +661,7 @@ THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) { }; -THREE.ExtrudeGeometry.WorldUVGenerator = { +ExtrudeGeometry.WorldUVGenerator = { generateTopUV: function ( geometry, indexA, indexB, indexC ) { @@ -664,9 +672,9 @@ THREE.ExtrudeGeometry.WorldUVGenerator = { var c = vertices[ indexC ]; return [ - new THREE.Vector2( a.x, a.y ), - new THREE.Vector2( b.x, b.y ), - new THREE.Vector2( c.x, c.y ) + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) ]; }, @@ -683,22 +691,25 @@ THREE.ExtrudeGeometry.WorldUVGenerator = { 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 ) + new Vector2( a.x, 1 - a.z ), + new Vector2( b.x, 1 - b.z ), + new Vector2( c.x, 1 - c.z ), + new 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 ) + new Vector2( a.y, 1 - a.z ), + new Vector2( b.y, 1 - b.z ), + new Vector2( c.y, 1 - c.z ), + new Vector2( d.y, 1 - d.z ) ]; } } }; + + +export { ExtrudeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/IcosahedronGeometry.js b/src/extras/geometries/IcosahedronGeometry.js index c562c626bdaf8e..587e743dd2e79f 100644 --- a/src/extras/geometries/IcosahedronGeometry.js +++ b/src/extras/geometries/IcosahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.IcosahedronGeometry = function ( radius, detail ) { +function IcosahedronGeometry ( radius, detail ) { + this.isIcosahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var t = ( 1 + Math.sqrt( 5 ) ) / 2; @@ -19,7 +22,7 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'IcosahedronGeometry'; @@ -30,5 +33,8 @@ THREE.IcosahedronGeometry = function ( radius, detail ) { }; -THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry; +IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; + + +export { IcosahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/LatheBufferGeometry.js b/src/extras/geometries/LatheBufferGeometry.js index a7353ced5544a4..fb936b01fca0cb 100644 --- a/src/extras/geometries/LatheBufferGeometry.js +++ b/src/extras/geometries/LatheBufferGeometry.js @@ -1,3 +1,9 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { _Math } from '../../math/Math'; + /** * @author Mugen87 / https://github.com/Mugen87 */ @@ -9,9 +15,10 @@ // phiLength - the radian (0 to 2PI) range of the lathed section // 2PI is a closed lathe, less than 2PI is a portion. -THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { +function LatheBufferGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'LatheBufferGeometry'; @@ -27,23 +34,23 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ] - phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 ); + phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 ); // these are used to calculate buffer length var vertexCount = ( segments + 1 ) * points.length; var indexCount = segments * points.length * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables var index = 0, indexOffset = 0, base; var inversePointLength = 1.0 / ( points.length - 1 ); var inverseSegments = 1.0 / segments; - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var uv = new Vector2(); var i, j; // generate vertices and uvs @@ -119,9 +126,9 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { if( phiLength === Math.PI * 2 ) { var normals = this.attributes.normal.array; - var n1 = new THREE.Vector3(); - var n2 = new THREE.Vector3(); - var n = new THREE.Vector3(); + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); // this is the buffer offset for the last line of vertices base = segments * points.length * 3; @@ -152,5 +159,8 @@ THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) { }; -THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry; +LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; + + +export { LatheBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/LatheGeometry.js b/src/extras/geometries/LatheGeometry.js index 5e46d75b35e204..3146acb8418728 100644 --- a/src/extras/geometries/LatheGeometry.js +++ b/src/extras/geometries/LatheGeometry.js @@ -1,3 +1,6 @@ +import { Geometry } from '../../core/Geometry'; +import { LatheBufferGeometry } from './LatheBufferGeometry'; + /** * @author astrodud / http://astrodud.isgreat.org/ * @author zz85 / https://github.com/zz85 @@ -11,9 +14,10 @@ // phiLength - the radian (0 to 2PI) range of the lathed section // 2PI is a closed lathe, less than 2PI is a portion. -THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { +function LatheGeometry ( points, segments, phiStart, phiLength ) { + this.isLatheGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'LatheGeometry'; @@ -24,10 +28,13 @@ THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) { phiLength: phiLength }; - this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); this.mergeVertices(); }; -THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry; +LatheGeometry.prototype = Object.create( Geometry.prototype ); +LatheGeometry.prototype.constructor = LatheGeometry; + + +export { LatheGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/OctahedronGeometry.js b/src/extras/geometries/OctahedronGeometry.js index 491aa8b8a286c1..b38c0c8e8d7110 100644 --- a/src/extras/geometries/OctahedronGeometry.js +++ b/src/extras/geometries/OctahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.OctahedronGeometry = function ( radius, detail ) { +function OctahedronGeometry ( radius, detail ) { + this.isOctahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var vertices = [ 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 @@ -12,7 +15,7 @@ THREE.OctahedronGeometry = function ( radius, detail ) { 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 ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'OctahedronGeometry'; @@ -23,5 +26,8 @@ THREE.OctahedronGeometry = function ( radius, detail ) { }; -THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry; +OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +OctahedronGeometry.prototype.constructor = OctahedronGeometry; + + +export { OctahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ParametricGeometry.js b/src/extras/geometries/ParametricGeometry.js index 23b886b0ee148e..0eacf32b94c498 100644 --- a/src/extras/geometries/ParametricGeometry.js +++ b/src/extras/geometries/ParametricGeometry.js @@ -1,3 +1,7 @@ +import { Geometry } from '../../core/Geometry'; +import { Face3 } from '../../core/Face3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author zz85 / https://github.com/zz85 * Parametric Surfaces Geometry @@ -7,9 +11,10 @@ * */ -THREE.ParametricGeometry = function ( func, slices, stacks ) { +function ParametricGeometry ( func, slices, stacks ) { + this.isParametricGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ParametricGeometry'; @@ -55,15 +60,15 @@ THREE.ParametricGeometry = function ( func, slices, stacks ) { c = ( i + 1 ) * sliceCount + j + 1; d = ( i + 1 ) * sliceCount + j; - 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 ); + uva = new Vector2( j / slices, i / stacks ); + uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); - faces.push( new THREE.Face3( a, b, d ) ); + faces.push( new Face3( a, b, d ) ); uvs.push( [ uva, uvb, uvd ] ); - faces.push( new THREE.Face3( b, c, d ) ); + faces.push( new Face3( b, c, d ) ); uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); } @@ -81,5 +86,8 @@ THREE.ParametricGeometry = function ( func, slices, stacks ) { }; -THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry; +ParametricGeometry.prototype = Object.create( Geometry.prototype ); +ParametricGeometry.prototype.constructor = ParametricGeometry; + + +export { ParametricGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PlaneBufferGeometry.js b/src/extras/geometries/PlaneBufferGeometry.js index 132d021983aaca..f2b185c7bc03af 100644 --- a/src/extras/geometries/PlaneBufferGeometry.js +++ b/src/extras/geometries/PlaneBufferGeometry.js @@ -1,11 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ -THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) { +function PlaneBufferGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'PlaneBufferGeometry'; @@ -85,12 +89,15 @@ THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegme } - this.setIndex( 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 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); }; -THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry; +PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; + + +export { PlaneBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PlaneGeometry.js b/src/extras/geometries/PlaneGeometry.js index c8698ba095d7df..af5f75a1fe1666 100644 --- a/src/extras/geometries/PlaneGeometry.js +++ b/src/extras/geometries/PlaneGeometry.js @@ -1,11 +1,15 @@ +import { Geometry } from '../../core/Geometry'; +import { PlaneBufferGeometry } from './PlaneBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ -THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) { +function PlaneGeometry ( width, height, widthSegments, heightSegments ) { + this.isPlaneGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'PlaneGeometry'; @@ -16,9 +20,12 @@ THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) heightSegments: heightSegments }; - this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); }; -THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry; +PlaneGeometry.prototype = Object.create( Geometry.prototype ); +PlaneGeometry.prototype.constructor = PlaneGeometry; + + +export { PlaneGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/PolyhedronGeometry.js b/src/extras/geometries/PolyhedronGeometry.js index 47c1a1e7b7d437..c6c2f1f706d02f 100644 --- a/src/extras/geometries/PolyhedronGeometry.js +++ b/src/extras/geometries/PolyhedronGeometry.js @@ -1,12 +1,19 @@ +import { Geometry } from '../../core/Geometry'; +import { Vector2 } from '../../math/Vector2'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; + /** * @author clockworkgeek / https://github.com/clockworkgeek * @author timothypratley / https://github.com/timothypratley * @author WestLangley / http://github.com/WestLangley */ -THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { +function PolyhedronGeometry ( vertices, indices, radius, detail ) { + this.isPolyhedronGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'PolyhedronGeometry'; @@ -24,7 +31,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); } @@ -38,11 +45,11 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { 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() ] ); + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); } - var centroid = new THREE.Vector3(); + var centroid = new Vector3(); for ( var i = 0, l = faces.length; i < l; i ++ ) { @@ -92,7 +99,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { this.computeFaceNormals(); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); // Project vector onto sphere's surface @@ -106,7 +113,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { 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 ); + vertex.uv = new Vector2( u, 1 - v ); return vertex; @@ -117,7 +124,7 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function make( v1, v2, v3 ) { - var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); that.faces.push( face ); centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); @@ -224,8 +231,8 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { function correctUV( uv, vector, azimuth ) { - 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 ); + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); return uv.clone(); } @@ -233,5 +240,8 @@ THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) { }; -THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry; +PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); +PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; + + +export { PolyhedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/RingBufferGeometry.js b/src/extras/geometries/RingBufferGeometry.js index 33a5115dbb7ed9..d9d448457503f5 100644 --- a/src/extras/geometries/RingBufferGeometry.js +++ b/src/extras/geometries/RingBufferGeometry.js @@ -1,10 +1,16 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector2 } from '../../math/Vector2'; +import { Vector3 } from '../../math/Vector3'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { +function RingBufferGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'RingBufferGeometry'; @@ -31,17 +37,17 @@ THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, p var indexCount = thetaSegments * phiSegments * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // some helper variables var index = 0, indexOffset = 0, segment; var radius = innerRadius; var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var uv = new Vector2(); var j, i; // generate vertices, normals and uvs @@ -116,5 +122,8 @@ THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, p }; -THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry; +RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +RingBufferGeometry.prototype.constructor = RingBufferGeometry; + + +export { RingBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/RingGeometry.js b/src/extras/geometries/RingGeometry.js index f3304f7740c3c7..9705e08e278c57 100644 --- a/src/extras/geometries/RingGeometry.js +++ b/src/extras/geometries/RingGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { RingBufferGeometry } from './RingBufferGeometry'; + /** * @author Kaleb Murphy */ -THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { +function RingGeometry ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + this.isRingGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'RingGeometry'; @@ -17,9 +21,12 @@ THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegm thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); }; -THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.RingGeometry.prototype.constructor = THREE.RingGeometry; +RingGeometry.prototype = Object.create( Geometry.prototype ); +RingGeometry.prototype.constructor = RingGeometry; + + +export { RingGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/ShapeGeometry.js b/src/extras/geometries/ShapeGeometry.js index f9989695f4ebcd..f7fcb54de321ac 100644 --- a/src/extras/geometries/ShapeGeometry.js +++ b/src/extras/geometries/ShapeGeometry.js @@ -1,3 +1,9 @@ +import { Geometry } from '../../core/Geometry'; +import { Face3 } from '../../core/Face3'; +import { Vector3 } from '../../math/Vector3'; +import { ShapeUtils } from '../ShapeUtils'; +import { ExtrudeGeometry } from './ExtrudeGeometry'; + /** * @author jonobr1 / http://jonobr1.com * @@ -14,9 +20,10 @@ * } **/ -THREE.ShapeGeometry = function ( shapes, options ) { +function ShapeGeometry ( shapes, options ) { + this.isShapeGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'ShapeGeometry'; @@ -28,13 +35,13 @@ THREE.ShapeGeometry = function ( shapes, options ) { }; -THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry; +ShapeGeometry.prototype = Object.create( Geometry.prototype ); +ShapeGeometry.prototype.constructor = ShapeGeometry; /** * Add an array of shapes to THREE.ShapeGeometry. */ -THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { +ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { @@ -49,13 +56,13 @@ THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { /** * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. */ -THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { +ShapeGeometry.prototype.addShape = function ( shape, options ) { if ( options === undefined ) options = {}; var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; var material = options.material; - var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; // @@ -67,7 +74,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var vertices = shapePoints.shape; var holes = shapePoints.holes; - var reverse = ! THREE.ShapeUtils.isClockWise( vertices ); + var reverse = ! ShapeUtils.isClockWise( vertices ); if ( reverse ) { @@ -79,7 +86,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { hole = holes[ i ]; - if ( THREE.ShapeUtils.isClockWise( hole ) ) { + if ( ShapeUtils.isClockWise( hole ) ) { holes[ i ] = hole.reverse(); @@ -91,7 +98,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { } - var faces = THREE.ShapeUtils.triangulateShape( vertices, holes ); + var faces = ShapeUtils.triangulateShape( vertices, holes ); // Vertices @@ -111,7 +118,7 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { vert = vertices[ i ]; - this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) ); + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); } @@ -123,9 +130,12 @@ THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) { var b = face[ 1 ] + shapesOffset; var c = face[ 2 ] + shapesOffset; - this.faces.push( new THREE.Face3( a, b, c, null, null, material ) ); + this.faces.push( new Face3( a, b, c, null, null, material ) ); this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); } }; + + +export { ShapeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/SphereBufferGeometry.js b/src/extras/geometries/SphereBufferGeometry.js index e95a0e30ada1fa..d4cb6914f659bc 100644 --- a/src/extras/geometries/SphereBufferGeometry.js +++ b/src/extras/geometries/SphereBufferGeometry.js @@ -1,11 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Sphere } from '../../math/Sphere'; +import { Uint16Attribute, Uint32Attribute, BufferAttribute } from '../../core/BufferAttribute'; + /** * @author benaadams / https://twitter.com/ben_a_adams * based on THREE.SphereGeometry */ -THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { +function SphereBufferGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'SphereBufferGeometry'; @@ -34,11 +40,11 @@ THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, p var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); - var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - var index = 0, vertices = [], normal = new THREE.Vector3(); + var index = 0, vertices = [], normal = new Vector3(); for ( var y = 0; y <= heightSegments; y ++ ) { @@ -88,14 +94,17 @@ THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, p } - this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) ); + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); this.addAttribute( 'position', positions ); this.addAttribute( 'normal', normals ); this.addAttribute( 'uv', uvs ); - this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); }; -THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry; +SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + + +export { SphereBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/SphereGeometry.js b/src/extras/geometries/SphereGeometry.js index c48de23561cacf..96d58123da6007 100644 --- a/src/extras/geometries/SphereGeometry.js +++ b/src/extras/geometries/SphereGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { SphereBufferGeometry } from './SphereBufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { +function SphereGeometry ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + this.isSphereGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'SphereGeometry'; @@ -18,9 +22,12 @@ THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStar thetaLength: thetaLength }; - this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); }; -THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry; +SphereGeometry.prototype = Object.create( Geometry.prototype ); +SphereGeometry.prototype.constructor = SphereGeometry; + + +export { SphereGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TetrahedronGeometry.js b/src/extras/geometries/TetrahedronGeometry.js index cf3fad8a723a54..efa5093c666ab7 100644 --- a/src/extras/geometries/TetrahedronGeometry.js +++ b/src/extras/geometries/TetrahedronGeometry.js @@ -1,8 +1,11 @@ +import { PolyhedronGeometry } from './PolyhedronGeometry'; + /** * @author timothypratley / https://github.com/timothypratley */ -THREE.TetrahedronGeometry = function ( radius, detail ) { +function TetrahedronGeometry ( radius, detail ) { + this.isTetrahedronGeometry = this.isPolyhedronGeometry = this.isGeometry = true; var vertices = [ 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 @@ -12,7 +15,7 @@ THREE.TetrahedronGeometry = function ( radius, detail ) { 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 ]; - THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); this.type = 'TetrahedronGeometry'; @@ -23,5 +26,8 @@ THREE.TetrahedronGeometry = function ( radius, detail ) { }; -THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype ); -THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry; +TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); +TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; + + +export { TetrahedronGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TextGeometry.js b/src/extras/geometries/TextGeometry.js index 049166f3e844a6..50664fb9fa0777 100644 --- a/src/extras/geometries/TextGeometry.js +++ b/src/extras/geometries/TextGeometry.js @@ -1,3 +1,6 @@ +import { ExtrudeGeometry } from './ExtrudeGeometry'; +import { Geometry } from '../../core/Geometry'; + /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author alteredq / http://alteredqualia.com/ @@ -17,16 +20,17 @@ * } */ -THREE.TextGeometry = function ( text, parameters ) { +function TextGeometry ( text, parameters ) { + this.isTextGeometry = this.isExtrudeGeometry = this.isGeometry = true; parameters = parameters || {}; var font = parameters.font; - if ( font instanceof THREE.Font === false ) { + if ( (font && font.isFont) === false ) { console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new THREE.Geometry(); + return new Geometry(); } @@ -42,11 +46,14 @@ THREE.TextGeometry = function ( text, parameters ) { if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - THREE.ExtrudeGeometry.call( this, shapes, parameters ); + ExtrudeGeometry.call( this, shapes, parameters ); this.type = 'TextGeometry'; }; -THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype ); -THREE.TextGeometry.prototype.constructor = THREE.TextGeometry; +TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); +TextGeometry.prototype.constructor = TextGeometry; + + +export { TextGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusBufferGeometry.js b/src/extras/geometries/TorusBufferGeometry.js index 5c55aebc52636a..833bec1d884b40 100644 --- a/src/extras/geometries/TorusBufferGeometry.js +++ b/src/extras/geometries/TorusBufferGeometry.js @@ -1,10 +1,15 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { Vector3 } from '../../math/Vector3'; + /** * @author Mugen87 / https://github.com/Mugen87 */ -THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) { +function TorusBufferGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'TorusBufferGeometry'; @@ -38,9 +43,9 @@ THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegm var indexBufferOffset = 0; // helper variables - var center = new THREE.Vector3(); - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); var j, i; @@ -115,12 +120,15 @@ THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegm } // build geometry - this.setIndex( 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 ) ); + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); }; -THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry; +TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; + + +export { TorusBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusGeometry.js b/src/extras/geometries/TorusGeometry.js index adf567027c9b11..1d126a20396ef4 100644 --- a/src/extras/geometries/TorusGeometry.js +++ b/src/extras/geometries/TorusGeometry.js @@ -1,12 +1,16 @@ +import { Geometry } from '../../core/Geometry'; +import { TorusBufferGeometry } from './TorusBufferGeometry'; + /** * @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 ) { +function TorusGeometry ( radius, tube, radialSegments, tubularSegments, arc ) { + this.isTorusGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TorusGeometry'; @@ -18,9 +22,12 @@ THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc: arc }; - this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); }; -THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry; +TorusGeometry.prototype = Object.create( Geometry.prototype ); +TorusGeometry.prototype.constructor = TorusGeometry; + + +export { TorusGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusKnotBufferGeometry.js b/src/extras/geometries/TorusKnotBufferGeometry.js index 49245daec75c2e..e3e0cdb15ae05f 100644 --- a/src/extras/geometries/TorusKnotBufferGeometry.js +++ b/src/extras/geometries/TorusKnotBufferGeometry.js @@ -1,11 +1,17 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author Mugen87 / https://github.com/Mugen87 * * see: http://www.blackpawn.com/texts/pqtorus/ */ -THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) { +function TorusKnotBufferGeometry ( radius, tube, tubularSegments, radialSegments, p, q ) { + this.isTorusKnotBufferGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); this.type = 'TorusKnotBufferGeometry'; @@ -30,24 +36,24 @@ THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radial var indexCount = radialSegments * tubularSegments * 2 * 3; // buffers - var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); // helper variables var i, j, index = 0, indexOffset = 0; - var vertex = new THREE.Vector3(); - var normal = new THREE.Vector3(); - var uv = new THREE.Vector2(); + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); - var P1 = new THREE.Vector3(); - var P2 = new THREE.Vector3(); + var P1 = new Vector3(); + var P2 = new Vector3(); - var B = new THREE.Vector3(); - var T = new THREE.Vector3(); - var N = new THREE.Vector3(); + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); // generate vertices, normals and uvs @@ -160,5 +166,8 @@ THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radial }; -THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry; +TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; + + +export { TorusKnotBufferGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TorusKnotGeometry.js b/src/extras/geometries/TorusKnotGeometry.js index cd8209b27b4737..f62713ce4a3885 100644 --- a/src/extras/geometries/TorusKnotGeometry.js +++ b/src/extras/geometries/TorusKnotGeometry.js @@ -1,10 +1,14 @@ +import { Geometry } from '../../core/Geometry'; +import { TorusKnotBufferGeometry } from './TorusKnotBufferGeometry'; + /** * @author oosmoxiecode */ -THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { +function TorusKnotGeometry ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + this.isTorusKnotGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TorusKnotGeometry'; @@ -19,10 +23,13 @@ THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegmen if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); this.mergeVertices(); }; -THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry; +TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); +TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; + + +export { TorusKnotGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/TubeGeometry.js b/src/extras/geometries/TubeGeometry.js index 502b9d1bb06214..963b4b1b1c311a 100644 --- a/src/extras/geometries/TubeGeometry.js +++ b/src/extras/geometries/TubeGeometry.js @@ -1,3 +1,10 @@ +import { Geometry } from '../../core/Geometry'; +import { _Math } from '../../math/Math'; +import { Vector3 } from '../../math/Vector3'; +import { Matrix4 } from '../../math/Matrix4'; +import { Face3 } from '../../core/Face3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author WestLangley / https://github.com/WestLangley * @author zz85 / https://github.com/zz85 @@ -12,9 +19,10 @@ * http://www.cs.indiana.edu/pub/techreports/TR425.pdf */ -THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) { +function TubeGeometry ( path, segments, radius, radialSegments, closed, taper ) { + this.isTubeGeometry = this.isGeometry = true; - THREE.Geometry.call( this ); + Geometry.call( this ); this.type = 'TubeGeometry'; @@ -31,7 +39,7 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, radius = radius || 1; radialSegments = radialSegments || 8; closed = closed || false; - taper = taper || THREE.TubeGeometry.NoTaper; + taper = taper || TubeGeometry.NoTaper; var grid = []; @@ -46,13 +54,13 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, u, v, r, cx, cy, - pos, pos2 = new THREE.Vector3(), + pos, pos2 = new Vector3(), i, j, ip, jp, a, b, c, d, uva, uvb, uvc, uvd; - var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ), + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), tangents = frames.tangents, normals = frames.normals, binormals = frames.binormals; @@ -64,7 +72,7 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, function vert( x, y, z ) { - return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1; + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; } @@ -117,15 +125,15 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, 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 ); + uva = new Vector2( i / segments, j / radialSegments ); + uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); - this.faces.push( new THREE.Face3( a, b, d ) ); + this.faces.push( new Face3( a, b, d ) ); this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - this.faces.push( new THREE.Face3( b, c, d ) ); + this.faces.push( new Face3( b, c, d ) ); this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); } @@ -137,32 +145,32 @@ THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, }; -THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype ); -THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry; +TubeGeometry.prototype = Object.create( Geometry.prototype ); +TubeGeometry.prototype.constructor = TubeGeometry; -THREE.TubeGeometry.NoTaper = function ( u ) { +TubeGeometry.NoTaper = function ( u ) { return 1; }; -THREE.TubeGeometry.SinusoidalTaper = function ( u ) { +TubeGeometry.SinusoidalTaper = function ( u ) { return Math.sin( Math.PI * u ); }; // For computing of Frenet frames, exposing the tangents, normals and binormals the spline -THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { +TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - var normal = new THREE.Vector3(), + var normal = new Vector3(), tangents = [], normals = [], binormals = [], - vec = new THREE.Vector3(), - mat = new THREE.Matrix4(), + vec = new Vector3(), + mat = new Matrix4(), numpoints = segments + 1, theta, @@ -219,8 +227,8 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { // select an initial normal vector perpendicular to the first tangent vector, // and in the direction of the smallest tangent xyz component - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); smallest = Number.MAX_VALUE; tx = Math.abs( tangents[ 0 ].x ); ty = Math.abs( tangents[ 0 ].y ); @@ -268,7 +276,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { vec.normalize(); - theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); @@ -283,7 +291,7 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { if ( closed ) { - theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); theta /= ( numpoints - 1 ); if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { @@ -303,3 +311,6 @@ THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) { } }; + + +export { TubeGeometry }; \ No newline at end of file diff --git a/src/extras/geometries/WireframeGeometry.js b/src/extras/geometries/WireframeGeometry.js index 4d417be10afb83..52363f2a27e5cf 100644 --- a/src/extras/geometries/WireframeGeometry.js +++ b/src/extras/geometries/WireframeGeometry.js @@ -1,10 +1,14 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; +import { BufferAttribute } from '../../core/BufferAttribute'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WireframeGeometry = function ( geometry ) { +function WireframeGeometry ( geometry ) { + this.isWireframeGeometry = this.isBufferGeometry = true; - THREE.BufferGeometry.call( this ); + BufferGeometry.call( this ); var edge = [ 0, 0 ], hash = {}; @@ -16,7 +20,7 @@ THREE.WireframeGeometry = function ( geometry ) { var keys = [ 'a', 'b', 'c' ]; - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; var faces = geometry.faces; @@ -67,9 +71,9 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - } else if ( geometry instanceof THREE.BufferGeometry ) { + } else if ( (geometry && geometry.isBufferGeometry) ) { if ( geometry.index !== null ) { @@ -138,7 +142,7 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); } else { @@ -170,7 +174,7 @@ THREE.WireframeGeometry = function ( geometry ) { } - this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); } @@ -178,5 +182,8 @@ THREE.WireframeGeometry = function ( geometry ) { }; -THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry; +WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); +WireframeGeometry.prototype.constructor = WireframeGeometry; + + +export { WireframeGeometry }; \ No newline at end of file diff --git a/src/extras/helpers/ArrowHelper.js b/src/extras/helpers/ArrowHelper.js index 802fd1f11713d2..8e777e07b10c67 100644 --- a/src/extras/helpers/ArrowHelper.js +++ b/src/extras/helpers/ArrowHelper.js @@ -1,3 +1,15 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { CylinderBufferGeometry } from '../geometries/CylinderBufferGeometry'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { Mesh } from '../../objects/Mesh'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Line } from '../../objects/Line'; + +var ArrowHelper; + /** * @author WestLangley / http://github.com/WestLangley * @author zz85 / http://github.com/zz85 @@ -14,19 +26,19 @@ * headWidth - Number */ -THREE.ArrowHelper = ( function () { +ArrowHelper = ( function () { - var lineGeometry = new THREE.BufferGeometry(); - lineGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - var coneGeometry = new THREE.CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); coneGeometry.translate( 0, - 0.5, 0 ); return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { // dir is assumed to be normalized - THREE.Object3D.call( this ); + Object3D.call( this ); if ( color === undefined ) color = 0xffff00; if ( length === undefined ) length = 1; @@ -35,11 +47,11 @@ THREE.ArrowHelper = ( function () { this.position.copy( origin ); - this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) ); + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); this.line.matrixAutoUpdate = false; this.add( this.line ); - this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) ); + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); this.cone.matrixAutoUpdate = false; this.add( this.cone ); @@ -50,12 +62,12 @@ THREE.ArrowHelper = ( function () { }() ); -THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper; +ArrowHelper.prototype = Object.create( Object3D.prototype ); +ArrowHelper.prototype.constructor = ArrowHelper; -THREE.ArrowHelper.prototype.setDirection = ( function () { +ArrowHelper.prototype.setDirection = ( function () { - var axis = new THREE.Vector3(); + var axis = new Vector3(); var radians; return function setDirection( dir ) { @@ -84,7 +96,7 @@ THREE.ArrowHelper.prototype.setDirection = ( function () { }() ); -THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { +ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { if ( headLength === undefined ) headLength = 0.2 * length; if ( headWidth === undefined ) headWidth = 0.2 * headLength; @@ -98,9 +110,12 @@ THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth }; -THREE.ArrowHelper.prototype.setColor = function ( color ) { +ArrowHelper.prototype.setColor = function ( color ) { this.line.material.color.copy( color ); this.cone.material.color.copy( color ); }; + + +export { ArrowHelper }; \ No newline at end of file diff --git a/src/extras/helpers/AxisHelper.js b/src/extras/helpers/AxisHelper.js index 4e16b37e00ce99..a3bf3a188c51ae 100644 --- a/src/extras/helpers/AxisHelper.js +++ b/src/extras/helpers/AxisHelper.js @@ -1,9 +1,16 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author sroucheray / http://sroucheray.org/ * @author mrdoob / http://mrdoob.com/ */ -THREE.AxisHelper = function ( size ) { +function AxisHelper ( size ) { + this.isAxisHelper = this.isLineSegments = true; size = size || 1; @@ -19,15 +26,18 @@ THREE.AxisHelper = function ( size ) { 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 ) ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); }; -THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.AxisHelper.prototype.constructor = THREE.AxisHelper; +AxisHelper.prototype = Object.create( LineSegments.prototype ); +AxisHelper.prototype.constructor = AxisHelper; + + +export { AxisHelper }; \ No newline at end of file diff --git a/src/extras/helpers/BoundingBoxHelper.js b/src/extras/helpers/BoundingBoxHelper.js index b299e8187620fc..23e64a2eff0aae 100644 --- a/src/extras/helpers/BoundingBoxHelper.js +++ b/src/extras/helpers/BoundingBoxHelper.js @@ -1,25 +1,31 @@ +import { Mesh } from '../../objects/Mesh'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { BoxGeometry } from '../geometries/BoxGeometry'; +import { Box3 } from '../../math/Box3'; + /** * @author WestLangley / http://github.com/WestLangley */ // a helper to show the world-axis-aligned bounding box for an object -THREE.BoundingBoxHelper = function ( object, hex ) { +function BoundingBoxHelper ( object, hex ) { + this.isBoundingBoxHelper = this.isMesh = true; var color = ( hex !== undefined ) ? hex : 0x888888; this.object = object; - this.box = new THREE.Box3(); + this.box = new Box3(); - THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) ); + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); }; -THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper; +BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); +BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; -THREE.BoundingBoxHelper.prototype.update = function () { +BoundingBoxHelper.prototype.update = function () { this.box.setFromObject( this.object ); @@ -28,3 +34,6 @@ THREE.BoundingBoxHelper.prototype.update = function () { this.box.center( this.position ); }; + + +export { BoundingBoxHelper }; \ No newline at end of file diff --git a/src/extras/helpers/BoxHelper.js b/src/extras/helpers/BoxHelper.js index ee03890f7f9540..1106d62bff1363 100644 --- a/src/extras/helpers/BoxHelper.js +++ b/src/extras/helpers/BoxHelper.js @@ -1,19 +1,26 @@ +import { Box3 } from '../../math/Box3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { BufferAttribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BoxHelper = function ( object, color ) { +function BoxHelper ( object, color ) { + this.isBoxHelper = this.isLineSegments = true; if ( color === undefined ) color = 0xffff00; var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); var positions = new Float32Array( 8 * 3 ); - var geometry = new THREE.BufferGeometry(); - geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); if ( object !== undefined ) { @@ -23,16 +30,16 @@ THREE.BoxHelper = function ( object, color ) { }; -THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.BoxHelper.prototype.constructor = THREE.BoxHelper; +BoxHelper.prototype = Object.create( LineSegments.prototype ); +BoxHelper.prototype.constructor = BoxHelper; -THREE.BoxHelper.prototype.update = ( function () { +BoxHelper.prototype.update = ( function () { - var box = new THREE.Box3(); + var box = new Box3(); return function update( object ) { - if ( object instanceof THREE.Box3 ) { + if ( (object && object.isBox3) ) { box.copy( object ); @@ -82,3 +89,6 @@ THREE.BoxHelper.prototype.update = ( function () { }; } )(); + + +export { BoxHelper }; \ No newline at end of file diff --git a/src/extras/helpers/CameraHelper.js b/src/extras/helpers/CameraHelper.js index 07fda0f1dd389d..8675556f2eadc8 100644 --- a/src/extras/helpers/CameraHelper.js +++ b/src/extras/helpers/CameraHelper.js @@ -1,3 +1,11 @@ +import { Camera } from '../../cameras/Camera'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { Color } from '../../math/Color'; +import { FaceColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Geometry } from '../../core/Geometry'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -7,10 +15,11 @@ * http://evanw.github.com/lightgl.js/tests/shadowmap.html */ -THREE.CameraHelper = function ( camera ) { +function CameraHelper ( camera ) { + this.isCameraHelper = this.isLineSegments = true; - var geometry = new THREE.Geometry(); - var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ); + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); var pointMap = {}; @@ -78,8 +87,8 @@ THREE.CameraHelper = function ( camera ) { function addPoint( id, hex ) { - geometry.vertices.push( new THREE.Vector3() ); - geometry.colors.push( new THREE.Color( hex ) ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); if ( pointMap[ id ] === undefined ) { @@ -91,7 +100,7 @@ THREE.CameraHelper = function ( camera ) { } - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); this.camera = camera; if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); @@ -105,15 +114,15 @@ THREE.CameraHelper = function ( camera ) { }; -THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.CameraHelper.prototype.constructor = THREE.CameraHelper; +CameraHelper.prototype = Object.create( LineSegments.prototype ); +CameraHelper.prototype.constructor = CameraHelper; -THREE.CameraHelper.prototype.update = function () { +CameraHelper.prototype.update = function () { var geometry, pointMap; - var vector = new THREE.Vector3(); - var camera = new THREE.Camera(); + var vector = new Vector3(); + var camera = new Camera(); function setPoint( point, x, y, z ) { @@ -187,3 +196,6 @@ THREE.CameraHelper.prototype.update = function () { }; }(); + + +export { CameraHelper }; \ No newline at end of file diff --git a/src/extras/helpers/DirectionalLightHelper.js b/src/extras/helpers/DirectionalLightHelper.js index 0443bd942196ad..52b9b487e0ef53 100644 --- a/src/extras/helpers/DirectionalLightHelper.js +++ b/src/extras/helpers/DirectionalLightHelper.js @@ -1,12 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { Line } from '../../objects/Line'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.DirectionalLightHelper = function ( light, size ) { +function DirectionalLightHelper ( light, size ) { + this.isDirectionalLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -16,8 +24,8 @@ THREE.DirectionalLightHelper = function ( light, size ) { if ( size === undefined ) size = 1; - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ - size, size, 0, size, size, 0, size, - size, 0, @@ -25,23 +33,23 @@ THREE.DirectionalLightHelper = function ( light, size ) { - size, size, 0 ], 3 ) ); - var material = new THREE.LineBasicMaterial( { fog: false } ); + var material = new LineBasicMaterial( { fog: false } ); - this.add( new THREE.Line( geometry, material ) ); + this.add( new Line( geometry, material ) ); - geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - this.add( new THREE.Line( geometry, material )); + this.add( new Line( geometry, material )); this.update(); }; -THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper; +DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); +DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; -THREE.DirectionalLightHelper.prototype.dispose = function () { +DirectionalLightHelper.prototype.dispose = function () { var lightPlane = this.children[ 0 ]; var targetLine = this.children[ 1 ]; @@ -53,11 +61,11 @@ THREE.DirectionalLightHelper.prototype.dispose = function () { }; -THREE.DirectionalLightHelper.prototype.update = function () { +DirectionalLightHelper.prototype.update = function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var v3 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); return function update() { @@ -77,3 +85,6 @@ THREE.DirectionalLightHelper.prototype.update = function () { }; }(); + + +export { DirectionalLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/EdgesHelper.js b/src/extras/helpers/EdgesHelper.js index 051e314efd5762..8211da3db52bae 100644 --- a/src/extras/helpers/EdgesHelper.js +++ b/src/extras/helpers/EdgesHelper.js @@ -1,3 +1,7 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { EdgesGeometry } from '../geometries/EdgesGeometry'; + /** * @author WestLangley / http://github.com/WestLangley * @param object THREE.Mesh whose geometry will be used @@ -8,16 +12,20 @@ * an edge is only rendered if the angle is at least 10 degrees. */ -THREE.EdgesHelper = function ( object, hex, thresholdAngle ) { +function EdgesHelper ( object, hex, thresholdAngle ) { + this.isEdgesHelper = this.isLineSegments = true; var color = ( hex !== undefined ) ? hex : 0xffffff; - THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; }; -THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper; +EdgesHelper.prototype = Object.create( LineSegments.prototype ); +EdgesHelper.prototype.constructor = EdgesHelper; + + +export { EdgesHelper }; \ No newline at end of file diff --git a/src/extras/helpers/FaceNormalsHelper.js b/src/extras/helpers/FaceNormalsHelper.js index 1868ab0bec1d9c..a6ef79b1d5e7a3 100644 --- a/src/extras/helpers/FaceNormalsHelper.js +++ b/src/extras/helpers/FaceNormalsHelper.js @@ -1,9 +1,17 @@ +import { Matrix3 } from '../../math/Matrix3'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { +function FaceNormalsHelper ( object, size, hex, linewidth ) { + this.isFaceNormalsHelper = this.isLineSegments = true; // FaceNormalsHelper only supports THREE.Geometry @@ -21,7 +29,7 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { nNormals = objGeometry.faces.length; @@ -33,13 +41,13 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { // - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); geometry.addAttribute( 'position', positions ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); // @@ -48,14 +56,14 @@ THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) { }; -THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper; +FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); +FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; -THREE.FaceNormalsHelper.prototype.update = ( function () { +FaceNormalsHelper.prototype.update = ( function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); return function update() { @@ -108,3 +116,6 @@ THREE.FaceNormalsHelper.prototype.update = ( function () { }; }() ); + + +export { FaceNormalsHelper }; \ No newline at end of file diff --git a/src/extras/helpers/GridHelper.js b/src/extras/helpers/GridHelper.js index eb794f5dad3b1f..45fb6af3e9f94e 100644 --- a/src/extras/helpers/GridHelper.js +++ b/src/extras/helpers/GridHelper.js @@ -1,12 +1,20 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; +import { Color } from '../../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.GridHelper = function ( size, divisions, color1, color2 ) { +function GridHelper ( size, divisions, color1, color2 ) { + this.isGridHelper = this.isLineSegments = true; divisions = divisions || 1; - color1 = new THREE.Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new THREE.Color( color2 !== undefined ? color2 : 0x888888 ); + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); var center = divisions / 2; var step = ( size * 2 ) / divisions; @@ -26,21 +34,24 @@ THREE.GridHelper = function ( size, divisions, color1, color2 ) { } - var geometry = new THREE.BufferGeometry(); - geometry.addAttribute( 'position', new THREE.Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new THREE.Float32Attribute( colors, 3 ) ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); }; -THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.GridHelper.prototype.constructor = THREE.GridHelper; +GridHelper.prototype = Object.create( LineSegments.prototype ); +GridHelper.prototype.constructor = GridHelper; -THREE.GridHelper.prototype.setColors = function () { +GridHelper.prototype.setColors = function () { console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); }; + + +export { GridHelper }; \ No newline at end of file diff --git a/src/extras/helpers/HemisphereLightHelper.js b/src/extras/helpers/HemisphereLightHelper.js index 034d81f04dbc77..45c73cb2fc1c44 100644 --- a/src/extras/helpers/HemisphereLightHelper.js +++ b/src/extras/helpers/HemisphereLightHelper.js @@ -1,11 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { Mesh } from '../../objects/Mesh'; +import { FaceColors } from '../../constants'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { SphereGeometry } from '../geometries/SphereGeometry'; +import { Color } from '../../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.HemisphereLightHelper = function ( light, sphereSize ) { +function HemisphereLightHelper ( light, sphereSize ) { + this.isHemisphereLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -13,9 +22,9 @@ THREE.HemisphereLightHelper = function ( light, sphereSize ) { this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; - this.colors = [ new THREE.Color(), new THREE.Color() ]; + this.colors = [ new Color(), new Color() ]; - var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 ); + var geometry = new SphereGeometry( sphereSize, 4, 2 ); geometry.rotateX( - Math.PI / 2 ); for ( var i = 0, il = 8; i < il; i ++ ) { @@ -24,28 +33,28 @@ THREE.HemisphereLightHelper = function ( light, sphereSize ) { } - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } ); + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - this.lightSphere = new THREE.Mesh( geometry, material ); + this.lightSphere = new Mesh( geometry, material ); this.add( this.lightSphere ); this.update(); }; -THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper; +HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); +HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; -THREE.HemisphereLightHelper.prototype.dispose = function () { +HemisphereLightHelper.prototype.dispose = function () { this.lightSphere.geometry.dispose(); this.lightSphere.material.dispose(); }; -THREE.HemisphereLightHelper.prototype.update = function () { +HemisphereLightHelper.prototype.update = function () { - var vector = new THREE.Vector3(); + var vector = new Vector3(); return function update() { @@ -58,3 +67,6 @@ THREE.HemisphereLightHelper.prototype.update = function () { }; }(); + + +export { HemisphereLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/PointLightHelper.js b/src/extras/helpers/PointLightHelper.js index 40742519746b25..edcf1d3035d0de 100644 --- a/src/extras/helpers/PointLightHelper.js +++ b/src/extras/helpers/PointLightHelper.js @@ -1,18 +1,23 @@ +import { Mesh } from '../../objects/Mesh'; +import { MeshBasicMaterial } from '../../materials/MeshBasicMaterial'; +import { SphereBufferGeometry } from '../geometries/SphereBufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.PointLightHelper = function ( light, sphereSize ) { +function PointLightHelper ( light, sphereSize ) { + this.isPointLightHelper = this.isMesh = true; this.light = light; this.light.updateMatrixWorld(); - var geometry = new THREE.SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } ); + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.matrix = this.light.matrixWorld; this.matrixAutoUpdate = false; @@ -41,17 +46,17 @@ THREE.PointLightHelper = function ( light, sphereSize ) { }; -THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype ); -THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper; +PointLightHelper.prototype = Object.create( Mesh.prototype ); +PointLightHelper.prototype.constructor = PointLightHelper; -THREE.PointLightHelper.prototype.dispose = function () { +PointLightHelper.prototype.dispose = function () { this.geometry.dispose(); this.material.dispose(); }; -THREE.PointLightHelper.prototype.update = function () { +PointLightHelper.prototype.update = function () { this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); @@ -71,3 +76,6 @@ THREE.PointLightHelper.prototype.update = function () { */ }; + + +export { PointLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/SkeletonHelper.js b/src/extras/helpers/SkeletonHelper.js index 169dd1e24118c1..f20d5c5aa8e3f2 100644 --- a/src/extras/helpers/SkeletonHelper.js +++ b/src/extras/helpers/SkeletonHelper.js @@ -1,3 +1,11 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { Matrix4 } from '../../math/Matrix4'; +import { VertexColors } from '../../constants'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Color } from '../../math/Color'; +import { Vector3 } from '../../math/Vector3'; +import { Geometry } from '../../core/Geometry'; + /** * @author Sean Griffin / http://twitter.com/sgrif * @author Michael Guerrero / http://realitymeltdown.com @@ -5,22 +13,23 @@ * @author ikerr / http://verold.com */ -THREE.SkeletonHelper = function ( object ) { +function SkeletonHelper ( object ) { + this.isSkeletonHelper = this.isLineSegments = true; this.bones = this.getBoneList( object ); - var geometry = new THREE.Geometry(); + var geometry = new Geometry(); for ( var i = 0; i < this.bones.length; i ++ ) { var bone = this.bones[ i ]; - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { - 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 ) ); + geometry.vertices.push( new Vector3() ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( 0, 0, 1 ) ); + geometry.colors.push( new Color( 0, 1, 0 ) ); } @@ -28,9 +37,9 @@ THREE.SkeletonHelper = function ( object ) { geometry.dynamic = true; - var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - THREE.LineSegments.call( this, geometry, material ); + LineSegments.call( this, geometry, material ); this.root = object; @@ -42,14 +51,14 @@ THREE.SkeletonHelper = function ( object ) { }; -THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper; +SkeletonHelper.prototype = Object.create( LineSegments.prototype ); +SkeletonHelper.prototype.constructor = SkeletonHelper; -THREE.SkeletonHelper.prototype.getBoneList = function( object ) { +SkeletonHelper.prototype.getBoneList = function( object ) { var boneList = []; - if ( object instanceof THREE.Bone ) { + if ( (object && object.isBone) ) { boneList.push( object ); @@ -65,13 +74,13 @@ THREE.SkeletonHelper.prototype.getBoneList = function( object ) { }; -THREE.SkeletonHelper.prototype.update = function () { +SkeletonHelper.prototype.update = function () { var geometry = this.geometry; - var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld ); + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - var boneMatrix = new THREE.Matrix4(); + var boneMatrix = new Matrix4(); var j = 0; @@ -79,7 +88,7 @@ THREE.SkeletonHelper.prototype.update = function () { var bone = this.bones[ i ]; - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); @@ -98,3 +107,6 @@ THREE.SkeletonHelper.prototype.update = function () { geometry.computeBoundingSphere(); }; + + +export { SkeletonHelper }; \ No newline at end of file diff --git a/src/extras/helpers/SpotLightHelper.js b/src/extras/helpers/SpotLightHelper.js index 8caea9848d52e9..7b2a0f9bdca6da 100644 --- a/src/extras/helpers/SpotLightHelper.js +++ b/src/extras/helpers/SpotLightHelper.js @@ -1,12 +1,20 @@ +import { Vector3 } from '../../math/Vector3'; +import { Object3D } from '../../core/Object3D'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.SpotLightHelper = function ( light ) { +function SpotLightHelper ( light ) { + this.isSpotLightHelper = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); @@ -14,7 +22,7 @@ THREE.SpotLightHelper = function ( light ) { this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); var positions = [ 0, 0, 0, 0, 0, 1, @@ -36,31 +44,31 @@ THREE.SpotLightHelper = function ( light ) { } - geometry.addAttribute( 'position', new THREE.Float32Attribute( positions, 3 ) ); + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - var material = new THREE.LineBasicMaterial( { fog: false } ); + var material = new LineBasicMaterial( { fog: false } ); - this.cone = new THREE.LineSegments( geometry, material ); + this.cone = new LineSegments( geometry, material ); this.add( this.cone ); this.update(); }; -THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype ); -THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper; +SpotLightHelper.prototype = Object.create( Object3D.prototype ); +SpotLightHelper.prototype.constructor = SpotLightHelper; -THREE.SpotLightHelper.prototype.dispose = function () { +SpotLightHelper.prototype.dispose = function () { this.cone.geometry.dispose(); this.cone.material.dispose(); }; -THREE.SpotLightHelper.prototype.update = function () { +SpotLightHelper.prototype.update = function () { - var vector = new THREE.Vector3(); - var vector2 = new THREE.Vector3(); + var vector = new Vector3(); + var vector2 = new Vector3(); return function update() { @@ -79,3 +87,6 @@ THREE.SpotLightHelper.prototype.update = function () { }; }(); + + +export { SpotLightHelper }; \ No newline at end of file diff --git a/src/extras/helpers/VertexNormalsHelper.js b/src/extras/helpers/VertexNormalsHelper.js index 3121b52a16e42e..a7f2e668e57117 100644 --- a/src/extras/helpers/VertexNormalsHelper.js +++ b/src/extras/helpers/VertexNormalsHelper.js @@ -1,9 +1,17 @@ +import { Matrix3 } from '../../math/Matrix3'; +import { Vector3 } from '../../math/Vector3'; +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { Float32Attribute } from '../../core/BufferAttribute'; +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ -THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { +function VertexNormalsHelper ( object, size, hex, linewidth ) { + this.isVertexNormalsHelper = this.isLineSegments = true; this.object = object; @@ -19,11 +27,11 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { nNormals = objGeometry.faces.length * 3; - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { nNormals = objGeometry.attributes.normal.count; @@ -31,13 +39,13 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { // - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); - var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 ); + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); geometry.addAttribute( 'position', positions ); - THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); // @@ -47,14 +55,14 @@ THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) { }; -THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper; +VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); +VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; -THREE.VertexNormalsHelper.prototype.update = ( function () { +VertexNormalsHelper.prototype.update = ( function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var normalMatrix = new THREE.Matrix3(); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); return function update() { @@ -72,7 +80,7 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { var objGeometry = this.object.geometry; - if ( objGeometry instanceof THREE.Geometry ) { + if ( (objGeometry && objGeometry.isGeometry) ) { var vertices = objGeometry.vertices; @@ -106,7 +114,7 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { } - } else if ( objGeometry instanceof THREE.BufferGeometry ) { + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { var objPos = objGeometry.attributes.position; @@ -143,3 +151,6 @@ THREE.VertexNormalsHelper.prototype.update = ( function () { }; }() ); + + +export { VertexNormalsHelper }; \ No newline at end of file diff --git a/src/extras/helpers/WireframeHelper.js b/src/extras/helpers/WireframeHelper.js index 5fcdf90f76753b..42d7d8eca911b0 100644 --- a/src/extras/helpers/WireframeHelper.js +++ b/src/extras/helpers/WireframeHelper.js @@ -1,17 +1,25 @@ +import { LineSegments } from '../../objects/LineSegments'; +import { LineBasicMaterial } from '../../materials/LineBasicMaterial'; +import { WireframeGeometry } from '../geometries/WireframeGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WireframeHelper = function ( object, hex ) { +function WireframeHelper ( object, hex ) { + this.isWireframeHelper = this.isLineSegments = true; var color = ( hex !== undefined ) ? hex : 0xffffff; - THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) ); + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; }; -THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype ); -THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper; +WireframeHelper.prototype = Object.create( LineSegments.prototype ); +WireframeHelper.prototype.constructor = WireframeHelper; + + +export { WireframeHelper }; \ No newline at end of file diff --git a/src/extras/objects/ImmediateRenderObject.js b/src/extras/objects/ImmediateRenderObject.js index e5d447b5499f65..aeef3325f7d71f 100644 --- a/src/extras/objects/ImmediateRenderObject.js +++ b/src/extras/objects/ImmediateRenderObject.js @@ -1,15 +1,21 @@ +import { Object3D } from '../../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.ImmediateRenderObject = function ( material ) { +function ImmediateRenderObject ( material ) { + this.isImmediateRenderObject = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.material = material; this.render = function ( renderCallback ) {}; }; -THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); -THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject; +ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); +ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + + +export { ImmediateRenderObject }; \ No newline at end of file diff --git a/src/extras/objects/MorphBlendMesh.js b/src/extras/objects/MorphBlendMesh.js index fa3cfce9fc28d7..5d47f9b86fb666 100644 --- a/src/extras/objects/MorphBlendMesh.js +++ b/src/extras/objects/MorphBlendMesh.js @@ -1,10 +1,14 @@ +import { Mesh } from '../../objects/Mesh'; +import { _Math } from '../../math/Math'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.MorphBlendMesh = function( geometry, material ) { +function MorphBlendMesh( geometry, material ) { + this.isMorphBlendMesh = this.isMesh = true; - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.animationsMap = {}; this.animationsList = []; @@ -26,10 +30,10 @@ THREE.MorphBlendMesh = function( geometry, material ) { }; -THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh; +MorphBlendMesh.prototype = Object.create( Mesh.prototype ); +MorphBlendMesh.prototype.constructor = MorphBlendMesh; -THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { +MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { var animation = { @@ -60,7 +64,7 @@ THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fp }; -THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { +MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { var pattern = /([a-z]+)_?(\d+)/i; @@ -101,7 +105,7 @@ THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { }; -THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { +MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { var animation = this.animationsMap[ name ]; @@ -114,7 +118,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) }; -THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { +MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { var animation = this.animationsMap[ name ]; @@ -127,7 +131,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) }; -THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { +MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { var animation = this.animationsMap[ name ]; @@ -140,7 +144,7 @@ THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { }; -THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { +MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { var animation = this.animationsMap[ name ]; @@ -153,7 +157,7 @@ THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration }; -THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { +MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { var animation = this.animationsMap[ name ]; @@ -165,7 +169,7 @@ THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { }; -THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { +MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { var animation = this.animationsMap[ name ]; @@ -177,7 +181,7 @@ THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { }; -THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { +MorphBlendMesh.prototype.getAnimationTime = function ( name ) { var time = 0; @@ -193,7 +197,7 @@ THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) { }; -THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { +MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { var duration = - 1; @@ -209,7 +213,7 @@ THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { }; -THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { +MorphBlendMesh.prototype.playAnimation = function ( name ) { var animation = this.animationsMap[ name ]; @@ -226,7 +230,7 @@ THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) { }; -THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { +MorphBlendMesh.prototype.stopAnimation = function ( name ) { var animation = this.animationsMap[ name ]; @@ -238,7 +242,7 @@ THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) { }; -THREE.MorphBlendMesh.prototype.update = function ( delta ) { +MorphBlendMesh.prototype.update = function ( delta ) { for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { @@ -280,7 +284,7 @@ THREE.MorphBlendMesh.prototype.update = function ( delta ) { } - var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); var weight = animation.weight; if ( keyframe !== animation.currentFrame ) { @@ -313,3 +317,6 @@ THREE.MorphBlendMesh.prototype.update = function ( delta ) { } }; + + +export { MorphBlendMesh }; \ No newline at end of file diff --git a/src/lights/AmbientLight.js b/src/lights/AmbientLight.js index 3135fdf9fa2d8e..485c585892399f 100644 --- a/src/lights/AmbientLight.js +++ b/src/lights/AmbientLight.js @@ -1,10 +1,13 @@ +import { Light } from './Light'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.AmbientLight = function ( color, intensity ) { +function AmbientLight ( color, intensity ) { + this.isAmbientLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'AmbientLight'; @@ -12,8 +15,11 @@ THREE.AmbientLight = function ( color, intensity ) { }; -THREE.AmbientLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.AmbientLight + constructor: AmbientLight } ); + + +export { AmbientLight }; \ No newline at end of file diff --git a/src/lights/DirectionalLight.js b/src/lights/DirectionalLight.js index 406aba28218633..fc807ba767f6e1 100644 --- a/src/lights/DirectionalLight.js +++ b/src/lights/DirectionalLight.js @@ -1,30 +1,35 @@ +import { Light } from './Light'; +import { DirectionalLightShadow } from './DirectionalLightShadow'; +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.DirectionalLight = function ( color, intensity ) { +function DirectionalLight ( color, intensity ) { + this.isDirectionalLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'DirectionalLight'; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.target = new THREE.Object3D(); + this.target = new Object3D(); - this.shadow = new THREE.DirectionalLightShadow(); + this.shadow = new DirectionalLightShadow(); }; -THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.DirectionalLight, + constructor: DirectionalLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.target = source.target.clone(); @@ -35,3 +40,6 @@ THREE.DirectionalLight.prototype = Object.assign( Object.create( THREE.Light.pro } } ); + + +export { DirectionalLight }; \ No newline at end of file diff --git a/src/lights/DirectionalLightShadow.js b/src/lights/DirectionalLightShadow.js index f446f4d6a6ab59..de772fb07a1fc4 100644 --- a/src/lights/DirectionalLightShadow.js +++ b/src/lights/DirectionalLightShadow.js @@ -1,15 +1,22 @@ +import { LightShadow } from './LightShadow'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.DirectionalLightShadow = function ( light ) { +function DirectionalLightShadow ( light ) { + this.isDirectionalLightShadow = true; - THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); }; -THREE.DirectionalLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { +DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - constructor: THREE.DirectionalLightShadow + constructor: DirectionalLightShadow } ); + + +export { DirectionalLightShadow }; \ No newline at end of file diff --git a/src/lights/HemisphereLight.js b/src/lights/HemisphereLight.js index 4f6269cf4bcbb6..9d08bb24f7166a 100644 --- a/src/lights/HemisphereLight.js +++ b/src/lights/HemisphereLight.js @@ -1,29 +1,34 @@ +import { Light } from './Light'; +import { Color } from '../math/Color'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { +function HemisphereLight ( skyColor, groundColor, intensity ) { + this.isHemisphereLight = true; - THREE.Light.call( this, skyColor, intensity ); + Light.call( this, skyColor, intensity ); this.type = 'HemisphereLight'; this.castShadow = undefined; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.groundColor = new THREE.Color( groundColor ); + this.groundColor = new Color( groundColor ); }; -THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.HemisphereLight, + constructor: HemisphereLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.groundColor.copy( source.groundColor ); @@ -32,3 +37,6 @@ THREE.HemisphereLight.prototype = Object.assign( Object.create( THREE.Light.prot } } ); + + +export { HemisphereLight }; \ No newline at end of file diff --git a/src/lights/Light.js b/src/lights/Light.js index 5e215acc01ef10..fe5cb367a41596 100644 --- a/src/lights/Light.js +++ b/src/lights/Light.js @@ -1,28 +1,32 @@ +import { Object3D } from '../core/Object3D'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Light = function ( color, intensity ) { +function Light ( color, intensity ) { + this.isLight = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Light'; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.intensity = intensity !== undefined ? intensity : 1; this.receiveShadow = undefined; }; -THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Light, + constructor: Light, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.color.copy( source.color ); this.intensity = source.intensity; @@ -33,7 +37,7 @@ THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.color = this.color.getHex(); data.object.intensity = this.intensity; @@ -50,3 +54,6 @@ THREE.Light.prototype = Object.assign( Object.create( THREE.Object3D.prototype ) } } ); + + +export { Light }; \ No newline at end of file diff --git a/src/lights/LightShadow.js b/src/lights/LightShadow.js index 7e2409c991bbd5..1033a41844aba5 100644 --- a/src/lights/LightShadow.js +++ b/src/lights/LightShadow.js @@ -1,22 +1,26 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Vector2 } from '../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LightShadow = function ( camera ) { +function LightShadow ( camera ) { + this.isLightShadow = true; this.camera = camera; this.bias = 0; this.radius = 1; - this.mapSize = new THREE.Vector2( 512, 512 ); + this.mapSize = new Vector2( 512, 512 ); this.map = null; - this.matrix = new THREE.Matrix4(); + this.matrix = new Matrix4(); }; -Object.assign( THREE.LightShadow.prototype, { +Object.assign( LightShadow.prototype, { copy: function ( source ) { @@ -38,3 +42,6 @@ Object.assign( THREE.LightShadow.prototype, { } } ); + + +export { LightShadow }; \ No newline at end of file diff --git a/src/lights/PointLight.js b/src/lights/PointLight.js index 64df91bb17726f..d1a87c9d238dd1 100644 --- a/src/lights/PointLight.js +++ b/src/lights/PointLight.js @@ -1,11 +1,16 @@ +import { Light } from './Light'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { LightShadow } from './LightShadow'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.PointLight = function ( color, intensity, distance, decay ) { +function PointLight ( color, intensity, distance, decay ) { + this.isPointLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'PointLight'; @@ -26,17 +31,17 @@ THREE.PointLight = function ( color, intensity, distance, decay ) { this.distance = ( distance !== undefined ) ? distance : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); }; -THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.PointLight, + constructor: PointLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.distance = source.distance; this.decay = source.decay; @@ -48,3 +53,6 @@ THREE.PointLight.prototype = Object.assign( Object.create( THREE.Light.prototype } } ); + + +export { PointLight }; \ No newline at end of file diff --git a/src/lights/SpotLight.js b/src/lights/SpotLight.js index 3becdcd725aca1..d6597709d5ad8f 100644 --- a/src/lights/SpotLight.js +++ b/src/lights/SpotLight.js @@ -1,17 +1,22 @@ +import { Light } from './Light'; +import { SpotLightShadow } from './SpotLightShadow'; +import { Object3D } from '../core/Object3D'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) { +function SpotLight ( color, intensity, distance, angle, penumbra, decay ) { + this.isSpotLight = true; - THREE.Light.call( this, color, intensity ); + Light.call( this, color, intensity ); this.type = 'SpotLight'; - this.position.copy( THREE.Object3D.DefaultUp ); + this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); - this.target = new THREE.Object3D(); + this.target = new Object3D(); Object.defineProperty( this, 'power', { get: function () { @@ -31,17 +36,17 @@ THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.shadow = new THREE.SpotLightShadow(); + this.shadow = new SpotLightShadow(); }; -THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype ), { +SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: THREE.SpotLight, + constructor: SpotLight, copy: function ( source ) { - THREE.Light.prototype.copy.call( this, source ); + Light.prototype.copy.call( this, source ); this.distance = source.distance; this.angle = source.angle; @@ -57,3 +62,6 @@ THREE.SpotLight.prototype = Object.assign( Object.create( THREE.Light.prototype } } ); + + +export { SpotLight }; \ No newline at end of file diff --git a/src/lights/SpotLightShadow.js b/src/lights/SpotLightShadow.js index 42416844473bdf..15bc3a5d12d9a8 100644 --- a/src/lights/SpotLightShadow.js +++ b/src/lights/SpotLightShadow.js @@ -1,20 +1,25 @@ +import { LightShadow } from './LightShadow'; +import { _Math } from '../math/Math'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.SpotLightShadow = function () { +function SpotLightShadow () { + this.isSpotLightShadow = true; - THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) ); + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); }; -THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShadow.prototype ), { +SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - constructor: THREE.SpotLightShadow, + constructor: SpotLightShadow, update: function ( light ) { - var fov = THREE.Math.RAD2DEG * 2 * light.angle; + var fov = _Math.RAD2DEG * 2 * light.angle; var aspect = this.mapSize.width / this.mapSize.height; var far = light.distance || 500; @@ -32,3 +37,6 @@ THREE.SpotLightShadow.prototype = Object.assign( Object.create( THREE.LightShado } } ); + + +export { SpotLightShadow }; \ No newline at end of file diff --git a/src/loaders/AnimationLoader.js b/src/loaders/AnimationLoader.js index aada51b26ab694..cbd807397780da 100644 --- a/src/loaders/AnimationLoader.js +++ b/src/loaders/AnimationLoader.js @@ -1,20 +1,25 @@ +import { AnimationClip } from '../animation/AnimationClip'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author bhouston / http://clara.io/ */ -THREE.AnimationLoader = function ( manager ) { +function AnimationLoader ( manager ) { + this.isAnimationLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.AnimationLoader.prototype, { +Object.assign( AnimationLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -29,7 +34,7 @@ Object.assign( THREE.AnimationLoader.prototype, { for ( var i = 0; i < json.length; i ++ ) { - var clip = THREE.AnimationClip.parse( json[ i ] ); + var clip = AnimationClip.parse( json[ i ] ); animations.push( clip ); @@ -40,3 +45,6 @@ Object.assign( THREE.AnimationLoader.prototype, { } } ); + + +export { AnimationLoader }; \ No newline at end of file diff --git a/src/loaders/AudioLoader.js b/src/loaders/AudioLoader.js index ebaff2ee6fac72..8f0573b079c782 100644 --- a/src/loaders/AudioLoader.js +++ b/src/loaders/AudioLoader.js @@ -1,22 +1,27 @@ +import { getAudioContext } from '../audio/AudioContext'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ -THREE.AudioLoader = function ( manager ) { +function AudioLoader ( manager ) { + this.isAudioLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.AudioLoader.prototype, { +Object.assign( AudioLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( buffer ) { - var context = THREE.AudioContext; + var context = getAudioContext(); context.decodeAudioData( buffer, function ( audioBuffer ) { @@ -29,3 +34,6 @@ Object.assign( THREE.AudioLoader.prototype, { } } ); + + +export { AudioLoader }; \ No newline at end of file diff --git a/src/loaders/BinaryTextureLoader.js b/src/loaders/BinaryTextureLoader.js index d0062d96f73e77..be22309b98186e 100644 --- a/src/loaders/BinaryTextureLoader.js +++ b/src/loaders/BinaryTextureLoader.js @@ -1,27 +1,33 @@ +import { LinearFilter, LinearMipMapLinearFilter, ClampToEdgeWrapping } from '../constants'; +import { XHRLoader } from './XHRLoader'; +import { DataTexture } from '../textures/DataTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author Nikos M. / https://github.com/foo123/ * * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) */ -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) { +var DataTextureLoader = BinaryTextureLoader; +function BinaryTextureLoader ( manager ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; // override in sub classes this._parser = null; }; -Object.assign( THREE.BinaryTextureLoader.prototype, { +Object.assign( BinaryTextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var texture = new THREE.DataTexture(); + var texture = new DataTexture(); - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( buffer ) { @@ -42,11 +48,11 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { } - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; @@ -69,7 +75,7 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { if ( 1 === texData.mipmapCount ) { - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; } @@ -85,3 +91,6 @@ Object.assign( THREE.BinaryTextureLoader.prototype, { } } ); + + +export { BinaryTextureLoader, DataTextureLoader }; \ No newline at end of file diff --git a/src/loaders/BufferGeometryLoader.js b/src/loaders/BufferGeometryLoader.js index 120d2b2bdaa17e..06edbc7699a51a 100644 --- a/src/loaders/BufferGeometryLoader.js +++ b/src/loaders/BufferGeometryLoader.js @@ -1,20 +1,28 @@ +import { Sphere } from '../math/Sphere'; +import { Vector3 } from '../math/Vector3'; +import { BufferAttribute } from '../core/BufferAttribute'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.BufferGeometryLoader = function ( manager ) { +function BufferGeometryLoader ( manager ) { + this.isBufferGeometryLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.BufferGeometryLoader.prototype, { +Object.assign( BufferGeometryLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -25,7 +33,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { parse: function ( json ) { - var geometry = new THREE.BufferGeometry(); + var geometry = new BufferGeometry(); var index = json.data.index; @@ -44,7 +52,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { if ( index !== undefined ) { var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); } @@ -55,7 +63,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { var attribute = attributes[ key ]; var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); } @@ -77,7 +85,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { if ( boundingSphere !== undefined ) { - var center = new THREE.Vector3(); + var center = new Vector3(); if ( boundingSphere.center !== undefined ) { @@ -85,7 +93,7 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { } - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); } @@ -94,3 +102,6 @@ Object.assign( THREE.BufferGeometryLoader.prototype, { } } ); + + +export { BufferGeometryLoader }; \ No newline at end of file diff --git a/src/loaders/Cache.js b/src/loaders/Cache.js index 081efd99d263e8..d8172f547126d7 100644 --- a/src/loaders/Cache.js +++ b/src/loaders/Cache.js @@ -1,8 +1,10 @@ +var Cache; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Cache = { +Cache = { enabled: false, @@ -41,3 +43,6 @@ THREE.Cache = { } }; + + +export { Cache }; \ No newline at end of file diff --git a/src/loaders/CompressedTextureLoader.js b/src/loaders/CompressedTextureLoader.js index 9bd1d082e760c0..de47f67431aef6 100644 --- a/src/loaders/CompressedTextureLoader.js +++ b/src/loaders/CompressedTextureLoader.js @@ -1,19 +1,25 @@ +import { LinearFilter } from '../constants'; +import { XHRLoader } from './XHRLoader'; +import { CompressedTexture } from '../textures/CompressedTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ * * Abstract Base class to block based textures loader (dds, pvr, ...) */ -THREE.CompressedTextureLoader = function ( manager ) { +function CompressedTextureLoader ( manager ) { + this.isCompressedTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; // override in sub classes this._parser = null; }; -Object.assign( THREE.CompressedTextureLoader.prototype, { +Object.assign( CompressedTextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -21,10 +27,10 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { var images = []; - var texture = new THREE.CompressedTexture(); + var texture = new CompressedTexture(); texture.image = images; - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); @@ -46,7 +52,7 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { if ( loaded === 6 ) { if ( texDatas.mipmapCount === 1 ) - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; texture.format = texDatas.format; texture.needsUpdate = true; @@ -106,7 +112,7 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { if ( texDatas.mipmapCount === 1 ) { - texture.minFilter = THREE.LinearFilter; + texture.minFilter = LinearFilter; } @@ -131,3 +137,6 @@ Object.assign( THREE.CompressedTextureLoader.prototype, { } } ); + + +export { CompressedTextureLoader }; \ No newline at end of file diff --git a/src/loaders/CubeTextureLoader.js b/src/loaders/CubeTextureLoader.js index 22c57532a2f64c..3adf142ec98a7f 100644 --- a/src/loaders/CubeTextureLoader.js +++ b/src/loaders/CubeTextureLoader.js @@ -1,20 +1,25 @@ +import { ImageLoader } from './ImageLoader'; +import { CubeTexture } from '../textures/CubeTexture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CubeTextureLoader = function ( manager ) { +function CubeTextureLoader ( manager ) { + this.isCubeTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.CubeTextureLoader.prototype, { +Object.assign( CubeTextureLoader.prototype, { load: function ( urls, onLoad, onProgress, onError ) { - var texture = new THREE.CubeTexture(); + var texture = new CubeTexture(); - var loader = new THREE.ImageLoader( this.manager ); + var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); @@ -65,3 +70,6 @@ Object.assign( THREE.CubeTextureLoader.prototype, { } } ); + + +export { CubeTextureLoader }; \ No newline at end of file diff --git a/src/loaders/FontLoader.js b/src/loaders/FontLoader.js index 8115ee357c224f..d4f0a5b310c94a 100644 --- a/src/loaders/FontLoader.js +++ b/src/loaders/FontLoader.js @@ -1,20 +1,25 @@ +import { Font } from '../extras/core/Font'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.FontLoader = function ( manager ) { +function FontLoader ( manager ) { + this.isFontLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.FontLoader.prototype, { +Object.assign( FontLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.load( url, function ( text ) { var json; @@ -40,8 +45,11 @@ Object.assign( THREE.FontLoader.prototype, { parse: function ( json ) { - return new THREE.Font( json ); + return new Font( json ); } } ); + + +export { FontLoader }; \ No newline at end of file diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index d4e7989ffce6af..2b870a00c205a1 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -1,14 +1,18 @@ +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ImageLoader = function ( manager ) { +function ImageLoader ( manager ) { + this.isImageLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.ImageLoader.prototype, { +Object.assign( ImageLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -31,7 +35,7 @@ Object.assign( THREE.ImageLoader.prototype, { } else { - var loader = new THREE.XHRLoader(); + var loader = new XHRLoader(); loader.setPath( this.path ); loader.setResponseType( 'blob' ); loader.load( url, function ( blob ) { @@ -63,3 +67,6 @@ Object.assign( THREE.ImageLoader.prototype, { } } ); + + +export { ImageLoader }; \ No newline at end of file diff --git a/src/loaders/JSONLoader.js b/src/loaders/JSONLoader.js index 06c656ed129c7a..a7d932e3012523 100644 --- a/src/loaders/JSONLoader.js +++ b/src/loaders/JSONLoader.js @@ -1,9 +1,21 @@ +import { Loader } from './Loader'; +import { AnimationClip } from '../animation/AnimationClip'; +import { Vector3 } from '../math/Vector3'; +import { Vector4 } from '../math/Vector4'; +import { Color } from '../math/Color'; +import { Vector2 } from '../math/Vector2'; +import { Face3 } from '../core/Face3'; +import { Geometry } from '../core/Geometry'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.JSONLoader = function ( manager ) { +function JSONLoader ( manager ) { + this.isJSONLoader = true; if ( typeof manager === 'boolean' ) { @@ -12,21 +24,21 @@ THREE.JSONLoader = function ( manager ) { } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.withCredentials = false; }; -Object.assign( THREE.JSONLoader.prototype, { +Object.assign( JSONLoader.prototype, { load: function( url, onLoad, onProgress, onError ) { var scope = this; - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url ); + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - var loader = new THREE.XHRLoader( this.manager ); + var loader = new XHRLoader( this.manager ); loader.setWithCredentials( this.withCredentials ); loader.load( url, function ( text ) { @@ -72,7 +84,7 @@ Object.assign( THREE.JSONLoader.prototype, { parse: function ( json, texturePath ) { - var geometry = new THREE.Geometry(), + var geometry = new Geometry(), scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; parseModel( scale ); @@ -139,7 +151,7 @@ Object.assign( THREE.JSONLoader.prototype, { while ( offset < zLength ) { - vertex = new THREE.Vector3(); + vertex = new Vector3(); vertex.x = vertices[ offset ++ ] * scale; vertex.y = vertices[ offset ++ ] * scale; @@ -169,12 +181,12 @@ Object.assign( THREE.JSONLoader.prototype, { if ( isQuad ) { - faceA = new THREE.Face3(); + faceA = new Face3(); faceA.a = faces[ offset ]; faceA.b = faces[ offset + 1 ]; faceA.c = faces[ offset + 3 ]; - faceB = new THREE.Face3(); + faceB = new Face3(); faceB.a = faces[ offset + 1 ]; faceB.b = faces[ offset + 2 ]; faceB.c = faces[ offset + 3 ]; @@ -209,7 +221,7 @@ Object.assign( THREE.JSONLoader.prototype, { u = uvLayer[ uvIndex * 2 ]; v = uvLayer[ uvIndex * 2 + 1 ]; - uv = new THREE.Vector2( u, v ); + uv = new Vector2( u, v ); if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); @@ -240,7 +252,7 @@ Object.assign( THREE.JSONLoader.prototype, { normalIndex = faces[ offset ++ ] * 3; - normal = new THREE.Vector3( + normal = new Vector3( normals[ normalIndex ++ ], normals[ normalIndex ++ ], normals[ normalIndex ] @@ -273,8 +285,8 @@ Object.assign( THREE.JSONLoader.prototype, { colorIndex = faces[ offset ++ ]; hex = colors[ colorIndex ]; - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); } @@ -285,7 +297,7 @@ Object.assign( THREE.JSONLoader.prototype, { } else { - face = new THREE.Face3(); + face = new Face3(); face.a = faces[ offset ++ ]; face.b = faces[ offset ++ ]; face.c = faces[ offset ++ ]; @@ -316,7 +328,7 @@ Object.assign( THREE.JSONLoader.prototype, { u = uvLayer[ uvIndex * 2 ]; v = uvLayer[ uvIndex * 2 + 1 ]; - uv = new THREE.Vector2( u, v ); + uv = new Vector2( u, v ); geometry.faceVertexUvs[ i ][ fi ].push( uv ); @@ -344,7 +356,7 @@ Object.assign( THREE.JSONLoader.prototype, { normalIndex = faces[ offset ++ ] * 3; - normal = new THREE.Vector3( + normal = new Vector3( normals[ normalIndex ++ ], normals[ normalIndex ++ ], normals[ normalIndex ] @@ -370,7 +382,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( i = 0; i < 3; i ++ ) { colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); } @@ -397,7 +409,7 @@ Object.assign( THREE.JSONLoader.prototype, { var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) ); + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); } @@ -412,7 +424,7 @@ Object.assign( THREE.JSONLoader.prototype, { 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 ) ); + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); } @@ -444,7 +456,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - var vertex = new THREE.Vector3(); + var vertex = new Vector3(); vertex.x = srcVertices[ v ] * scale; vertex.y = srcVertices[ v + 1 ] * scale; vertex.z = srcVertices[ v + 2 ] * scale; @@ -503,7 +515,7 @@ Object.assign( THREE.JSONLoader.prototype, { for ( var i = 0; i < animations.length; i ++ ) { - var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); if ( clip ) outputAnimations.push( clip ); } @@ -512,7 +524,7 @@ Object.assign( THREE.JSONLoader.prototype, { if ( geometry.morphTargets ) { // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); outputAnimations = outputAnimations.concat( morphAnimationClips ); } @@ -527,7 +539,7 @@ Object.assign( THREE.JSONLoader.prototype, { } else { - var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); return { geometry: geometry, materials: materials }; @@ -536,3 +548,6 @@ Object.assign( THREE.JSONLoader.prototype, { } } ); + + +export { JSONLoader }; \ No newline at end of file diff --git a/src/loaders/Loader.js b/src/loaders/Loader.js index 04162b65410e64..a08db2eaa05c4b 100644 --- a/src/loaders/Loader.js +++ b/src/loaders/Loader.js @@ -1,8 +1,15 @@ +import { FaceColors, VertexColors, DoubleSide, BackSide, MirroredRepeatWrapping, RepeatWrapping } from '../constants'; +import { _Math } from '../math/Math'; +import { MaterialLoader } from './MaterialLoader'; +import { TextureLoader } from './TextureLoader'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.Loader = function () { +function Loader () { + this.isLoader = true; this.onLoadStart = function () {}; this.onLoadProgress = function () {}; @@ -10,9 +17,9 @@ THREE.Loader = function () { }; -THREE.Loader.prototype = { +Loader.prototype = { - constructor: THREE.Loader, + constructor: Loader, crossOrigin: undefined, @@ -48,9 +55,9 @@ THREE.Loader.prototype = { return function createMaterial( m, texturePath, crossOrigin ) { - if ( color === undefined ) color = new THREE.Color(); - if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader(); + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); // convert from old material format @@ -59,7 +66,7 @@ THREE.Loader.prototype = { function loadTexture( path, repeat, offset, wrap, anisotropy ) { var fullPath = texturePath + path; - var loader = THREE.Loader.Handlers.get( fullPath ); + var loader = Loader.Handlers.get( fullPath ); var texture; @@ -78,8 +85,8 @@ THREE.Loader.prototype = { texture.repeat.fromArray( repeat ); - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; } @@ -91,11 +98,11 @@ THREE.Loader.prototype = { if ( wrap !== undefined ) { - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping; + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping; + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; } @@ -105,7 +112,7 @@ THREE.Loader.prototype = { } - var uuid = THREE.Math.generateUUID(); + var uuid = _Math.generateUUID(); textures[ uuid ] = texture; @@ -116,7 +123,7 @@ THREE.Loader.prototype = { // var json = { - uuid: THREE.Math.generateUUID(), + uuid: _Math.generateUUID(), type: 'MeshLambertMaterial' }; @@ -244,10 +251,10 @@ THREE.Loader.prototype = { case 'mapAlphaAnisotropy': break; case 'flipSided': - json.side = THREE.BackSide; + json.side = BackSide; break; case 'doubleSided': - json.side = THREE.DoubleSide; + json.side = DoubleSide; break; case 'transparency': console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); @@ -264,8 +271,8 @@ THREE.Loader.prototype = { json[ name ] = value; break; case 'vertexColors': - if ( value === true ) json.vertexColors = THREE.VertexColors; - if ( value === 'face' ) json.vertexColors = THREE.FaceColors; + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; break; default: console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); @@ -289,7 +296,7 @@ THREE.Loader.prototype = { }; -THREE.Loader.Handlers = { +Loader.Handlers = { handlers: [], @@ -321,3 +328,6 @@ THREE.Loader.Handlers = { } }; + + +export { Loader }; \ No newline at end of file diff --git a/src/loaders/LoadingManager.js b/src/loaders/LoadingManager.js index 72a14cc40d44e5..42a85e83898467 100644 --- a/src/loaders/LoadingManager.js +++ b/src/loaders/LoadingManager.js @@ -1,8 +1,11 @@ +var DefaultLoadingManager; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { +function LoadingManager ( onLoad, onProgress, onError ) { + this.isLoadingManager = true; var scope = this; @@ -67,4 +70,7 @@ THREE.LoadingManager = function ( onLoad, onProgress, onError ) { }; -THREE.DefaultLoadingManager = new THREE.LoadingManager(); +DefaultLoadingManager = new LoadingManager(); + + +export { DefaultLoadingManager, LoadingManager }; \ No newline at end of file diff --git a/src/loaders/MaterialLoader.js b/src/loaders/MaterialLoader.js index 171fcb59ea9126..1d63fabf7e9102 100644 --- a/src/loaders/MaterialLoader.js +++ b/src/loaders/MaterialLoader.js @@ -1,21 +1,27 @@ +import { MultiplyOperation } from '../constants'; +import { Vector2 } from '../math/Vector2'; +import { XHRLoader } from './XHRLoader'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.MaterialLoader = function ( manager ) { +function MaterialLoader ( manager ) { + this.isMaterialLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.textures = {}; }; -Object.assign( THREE.MaterialLoader.prototype, { +Object.assign( MaterialLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); @@ -103,7 +109,7 @@ Object.assign( THREE.MaterialLoader.prototype, { } - material.normalScale = new THREE.Vector2().fromArray( normalScale ); + material.normalScale = new Vector2().fromArray( normalScale ); } @@ -122,7 +128,7 @@ Object.assign( THREE.MaterialLoader.prototype, { if ( json.envMap !== undefined ) { material.envMap = this.getTexture( json.envMap ); - material.combine = THREE.MultiplyOperation; + material.combine = MultiplyOperation; } @@ -151,3 +157,6 @@ Object.assign( THREE.MaterialLoader.prototype, { } } ); + + +export { MaterialLoader }; \ No newline at end of file diff --git a/src/loaders/ObjectLoader.js b/src/loaders/ObjectLoader.js old mode 100755 new mode 100644 index e22bf4c493a044..cb754bceabe404 --- a/src/loaders/ObjectLoader.js +++ b/src/loaders/ObjectLoader.js @@ -1,15 +1,42 @@ +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Group } from '../objects/Group'; +import { Sprite } from '../objects/Sprite'; +import { Points } from '../objects/Points'; +import { Line } from '../objects/Line'; +import { LOD } from '../objects/LOD'; +import { Mesh } from '../objects/Mesh'; +import { SkinnedMesh } from '../objects/SkinnedMesh'; +import { HemisphereLight } from '../lights/HemisphereLight'; +import { SpotLight } from '../lights/SpotLight'; +import { PointLight } from '../lights/PointLight'; +import { DirectionalLight } from '../lights/DirectionalLight'; +import { AmbientLight } from '../lights/AmbientLight'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { Scene } from '../scenes/Scene'; +import { Texture } from '../textures/Texture'; +import { ImageLoader } from './ImageLoader'; +import { LoadingManager, DefaultLoadingManager } from './LoadingManager'; +import { AnimationClip } from '../animation/AnimationClip'; +import { MaterialLoader } from './MaterialLoader'; +import { BufferGeometryLoader } from './BufferGeometryLoader'; +import { JSONLoader } from './JSONLoader'; +import { XHRLoader } from './XHRLoader'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ObjectLoader = function ( manager ) { +function ObjectLoader ( manager ) { + this.isObjectLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.texturePath = ''; }; -Object.assign( THREE.ObjectLoader.prototype, { +Object.assign( ObjectLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -21,7 +48,7 @@ Object.assign( THREE.ObjectLoader.prototype, { var scope = this; - var loader = new THREE.XHRLoader( scope.manager ); + var loader = new XHRLoader( scope.manager ); loader.load( url, function ( text ) { scope.parse( JSON.parse( text ), onLoad ); @@ -79,8 +106,8 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined ) { - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -279,7 +306,7 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined ) { - var loader = new THREE.MaterialLoader(); + var loader = new MaterialLoader(); loader.setTextures( textures ); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -301,7 +328,7 @@ Object.assign( THREE.ObjectLoader.prototype, { for ( var i = 0; i < json.length; i ++ ) { - var clip = THREE.AnimationClip.parse( json[ i ] ); + var clip = AnimationClip.parse( json[ i ] ); animations.push( clip ); @@ -330,9 +357,9 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( json !== undefined && json.length > 0 ) { - var manager = new THREE.LoadingManager( onLoad ); + var manager = new LoadingManager( onLoad ); - var loader = new THREE.ImageLoader( manager ); + var loader = new ImageLoader( manager ); loader.setCrossOrigin( this.crossOrigin ); for ( var i = 0, l = json.length; i < l; i ++ ) { @@ -382,7 +409,7 @@ Object.assign( THREE.ObjectLoader.prototype, { } - var texture = new THREE.Texture( images[ data.image ] ); + var texture = new Texture( images[ data.image ] ); texture.needsUpdate = true; texture.uuid = data.uuid; @@ -418,7 +445,7 @@ Object.assign( THREE.ObjectLoader.prototype, { parseObject: function () { - var matrix = new THREE.Matrix4(); + var matrix = new Matrix4(); return function parseObject( data, geometries, materials ) { @@ -454,13 +481,13 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'Scene': - object = new THREE.Scene(); + object = new Scene(); break; case 'PerspectiveCamera': - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); if ( data.focus !== undefined ) object.focus = data.focus; if ( data.zoom !== undefined ) object.zoom = data.zoom; @@ -472,37 +499,37 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'OrthographicCamera': - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); break; case 'AmbientLight': - object = new THREE.AmbientLight( data.color, data.intensity ); + object = new AmbientLight( data.color, data.intensity ); break; case 'DirectionalLight': - object = new THREE.DirectionalLight( data.color, data.intensity ); + object = new DirectionalLight( data.color, data.intensity ); break; case 'PointLight': - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); break; case 'SpotLight': - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); break; case 'HemisphereLight': - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); break; @@ -513,11 +540,11 @@ Object.assign( THREE.ObjectLoader.prototype, { if ( geometry.bones && geometry.bones.length > 0 ) { - object = new THREE.SkinnedMesh( geometry, material ); + object = new SkinnedMesh( geometry, material ); } else { - object = new THREE.Mesh( geometry, material ); + object = new Mesh( geometry, material ); } @@ -525,13 +552,13 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'LOD': - object = new THREE.LOD(); + object = new LOD(); break; case 'Line': - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); break; @@ -544,25 +571,25 @@ Object.assign( THREE.ObjectLoader.prototype, { case 'PointCloud': case 'Points': - object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'Sprite': - object = new THREE.Sprite( getMaterial( data.material ) ); + object = new Sprite( getMaterial( data.material ) ); break; case 'Group': - object = new THREE.Group(); + object = new Group(); break; default: - object = new THREE.Object3D(); + object = new Object3D(); } @@ -625,3 +652,6 @@ Object.assign( THREE.ObjectLoader.prototype, { }() } ); + + +export { ObjectLoader }; \ No newline at end of file diff --git a/src/loaders/TextureLoader.js b/src/loaders/TextureLoader.js index c81645c64ab64f..4721d255fd4608 100644 --- a/src/loaders/TextureLoader.js +++ b/src/loaders/TextureLoader.js @@ -1,20 +1,26 @@ +import { RGBAFormat, RGBFormat } from '../constants'; +import { ImageLoader } from './ImageLoader'; +import { Texture } from '../textures/Texture'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.TextureLoader = function ( manager ) { +function TextureLoader ( manager ) { + this.isTextureLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.TextureLoader.prototype, { +Object.assign( TextureLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { - var texture = new THREE.Texture(); + var texture = new Texture(); - var loader = new THREE.ImageLoader( this.manager ); + var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); loader.load( url, function ( image ) { @@ -22,7 +28,7 @@ Object.assign( THREE.TextureLoader.prototype, { // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat; + texture.format = isJPEG ? RGBFormat : RGBAFormat; texture.image = image; texture.needsUpdate = true; @@ -53,3 +59,6 @@ Object.assign( THREE.TextureLoader.prototype, { } } ); + + +export { TextureLoader }; \ No newline at end of file diff --git a/src/loaders/XHRLoader.js b/src/loaders/XHRLoader.js index cddb0290cc49ae..85f48769d03278 100644 --- a/src/loaders/XHRLoader.js +++ b/src/loaders/XHRLoader.js @@ -1,14 +1,18 @@ +import { Cache } from './Cache'; +import { DefaultLoadingManager } from './LoadingManager'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.XHRLoader = function ( manager ) { +function XHRLoader ( manager ) { + this.isXHRLoader = true; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; }; -Object.assign( THREE.XHRLoader.prototype, { +Object.assign( XHRLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { @@ -16,7 +20,7 @@ Object.assign( THREE.XHRLoader.prototype, { var scope = this; - var cached = THREE.Cache.get( url ); + var cached = Cache.get( url ); if ( cached !== undefined ) { @@ -42,7 +46,7 @@ Object.assign( THREE.XHRLoader.prototype, { var response = event.target.response; - THREE.Cache.add( url, response ); + Cache.add( url, response ); if ( this.status === 200 ) { @@ -122,3 +126,6 @@ Object.assign( THREE.XHRLoader.prototype, { } } ); + + +export { XHRLoader }; \ No newline at end of file diff --git a/src/materials/LineBasicMaterial.js b/src/materials/LineBasicMaterial.js index 06fd3bbd6b381b..3bbd876b9da2af 100644 --- a/src/materials/LineBasicMaterial.js +++ b/src/materials/LineBasicMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -12,13 +15,14 @@ * } */ -THREE.LineBasicMaterial = function ( parameters ) { +function LineBasicMaterial ( parameters ) { + this.isLineBasicMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'LineBasicMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.linewidth = 1; this.linecap = 'round'; @@ -30,12 +34,12 @@ THREE.LineBasicMaterial = function ( parameters ) { }; -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; +LineBasicMaterial.prototype = Object.create( Material.prototype ); +LineBasicMaterial.prototype.constructor = LineBasicMaterial; -THREE.LineBasicMaterial.prototype.copy = function ( source ) { +LineBasicMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -46,3 +50,6 @@ THREE.LineBasicMaterial.prototype.copy = function ( source ) { return this; }; + + +export { LineBasicMaterial }; \ No newline at end of file diff --git a/src/materials/LineDashedMaterial.js b/src/materials/LineDashedMaterial.js index 26b2e304cbfd30..331b35b5aaa7e7 100644 --- a/src/materials/LineDashedMaterial.js +++ b/src/materials/LineDashedMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -13,13 +16,14 @@ * } */ -THREE.LineDashedMaterial = function ( parameters ) { +function LineDashedMaterial ( parameters ) { + this.isLineDashedMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'LineDashedMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.linewidth = 1; @@ -33,12 +37,12 @@ THREE.LineDashedMaterial = function ( parameters ) { }; -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; +LineDashedMaterial.prototype = Object.create( Material.prototype ); +LineDashedMaterial.prototype.constructor = LineDashedMaterial; -THREE.LineDashedMaterial.prototype.copy = function ( source ) { +LineDashedMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -51,3 +55,6 @@ THREE.LineDashedMaterial.prototype.copy = function ( source ) { return this; }; + + +export { LineDashedMaterial }; \ No newline at end of file diff --git a/src/materials/Material.js b/src/materials/Material.js index 028b87a2fcaa9e..0648f315a10ce7 100644 --- a/src/materials/Material.js +++ b/src/materials/Material.js @@ -1,13 +1,18 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { NoColors, FrontSide, SmoothShading, NormalBlending, LessEqualDepth, AddEquation, OneMinusSrcAlphaFactor, SrcAlphaFactor } from '../constants'; +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Material = function () { +function Material () { + this.isMaterial = true; - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Material'; @@ -15,22 +20,22 @@ THREE.Material = function () { this.fog = true; this.lights = true; - this.blending = THREE.NormalBlending; - this.side = THREE.FrontSide; - this.shading = THREE.SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = THREE.NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors this.opacity = 1; this.transparent = false; - this.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; this.blendSrcAlpha = null; this.blendDstAlpha = null; this.blendEquationAlpha = null; - this.depthFunc = THREE.LessEqualDepth; + this.depthFunc = LessEqualDepth; this.depthTest = true; this.depthWrite = true; @@ -56,9 +61,9 @@ THREE.Material = function () { }; -THREE.Material.prototype = { +Material.prototype = { - constructor: THREE.Material, + constructor: Material, get needsUpdate() { @@ -97,11 +102,11 @@ THREE.Material.prototype = { } - if ( currentValue instanceof THREE.Color ) { + if ( (currentValue && currentValue.isColor) ) { currentValue.set( newValue ); - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { currentValue.copy( newValue ); @@ -147,44 +152,44 @@ THREE.Material.prototype = { if ( this.name !== '' ) data.name = this.name; - if ( this.color instanceof THREE.Color ) data.color = this.color.getHex(); + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); if ( this.roughness !== undefined ) data.roughness = this.roughness; if ( this.metalness !== undefined ) data.metalness = this.metalness; - if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex(); - if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex(); + if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); + if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); if ( this.shininess !== undefined ) data.shininess = this.shininess; - if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap instanceof THREE.Texture ) { + if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; + if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( (this.bumpMap && this.bumpMap.isTexture) ) { data.bumpMap = this.bumpMap.toJSON( meta ).uuid; data.bumpScale = this.bumpScale; } - if ( this.normalMap instanceof THREE.Texture ) { + if ( (this.normalMap && this.normalMap.isTexture) ) { data.normalMap = this.normalMap.toJSON( meta ).uuid; data.normalScale = this.normalScale.toArray(); } - if ( this.displacementMap instanceof THREE.Texture ) { + if ( (this.displacementMap && this.displacementMap.isTexture) ) { data.displacementMap = this.displacementMap.toJSON( meta ).uuid; data.displacementScale = this.displacementScale; data.displacementBias = this.displacementBias; } - if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - if ( this.envMap instanceof THREE.Texture ) { + if ( (this.envMap && this.envMap.isTexture) ) { data.envMap = this.envMap.toJSON( meta ).uuid; data.reflectivity = this.reflectivity; // Scale behind envMap @@ -194,10 +199,10 @@ THREE.Material.prototype = { if ( this.size !== undefined ) data.size = this.size; if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending; - if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading; - if ( this.side !== THREE.FrontSide ) data.side = this.side; - if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors; + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.shading !== SmoothShading ) data.shading = this.shading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; if ( this.opacity < 1 ) data.opacity = this.opacity; if ( this.transparent === true ) data.transparent = this.transparent; @@ -320,6 +325,10 @@ THREE.Material.prototype = { }; -Object.assign( THREE.Material.prototype, THREE.EventDispatcher.prototype ); +Object.assign( Material.prototype, EventDispatcher.prototype ); + +var count = 0; +function MaterialIdCount () { return count++; }; + -THREE.MaterialIdCount = 0; +export { MaterialIdCount, Material }; \ No newline at end of file diff --git a/src/materials/MeshBasicMaterial.js b/src/materials/MeshBasicMaterial.js index ef1dd3ab9358c5..b220b26e79e968 100644 --- a/src/materials/MeshBasicMaterial.js +++ b/src/materials/MeshBasicMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -31,13 +35,14 @@ * } */ -THREE.MeshBasicMaterial = function ( parameters ) { +function MeshBasicMaterial ( parameters ) { + this.isMeshBasicMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshBasicMaterial'; - this.color = new THREE.Color( 0xffffff ); // emissive + this.color = new Color( 0xffffff ); // emissive this.map = null; @@ -49,7 +54,7 @@ THREE.MeshBasicMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -67,12 +72,12 @@ THREE.MeshBasicMaterial = function ( parameters ) { }; -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; +MeshBasicMaterial.prototype = Object.create( Material.prototype ); +MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; -THREE.MeshBasicMaterial.prototype.copy = function ( source ) { +MeshBasicMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -101,3 +106,6 @@ THREE.MeshBasicMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshBasicMaterial }; \ No newline at end of file diff --git a/src/materials/MeshDepthMaterial.js b/src/materials/MeshDepthMaterial.js index 0813dc2a563fa7..915969064ca712 100644 --- a/src/materials/MeshDepthMaterial.js +++ b/src/materials/MeshDepthMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { BasicDepthPacking } from '../constants'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -21,13 +24,14 @@ * } */ -THREE.MeshDepthMaterial = function ( parameters ) { +function MeshDepthMaterial ( parameters ) { + this.isMeshDepthMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshDepthMaterial'; - this.depthPacking = THREE.BasicDepthPacking; + this.depthPacking = BasicDepthPacking; this.skinning = false; this.morphTargets = false; @@ -50,12 +54,12 @@ THREE.MeshDepthMaterial = function ( parameters ) { }; -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; +MeshDepthMaterial.prototype = Object.create( Material.prototype ); +MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; -THREE.MeshDepthMaterial.prototype.copy = function ( source ) { +MeshDepthMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.depthPacking = source.depthPacking; @@ -76,3 +80,6 @@ THREE.MeshDepthMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshDepthMaterial }; \ No newline at end of file diff --git a/src/materials/MeshLambertMaterial.js b/src/materials/MeshLambertMaterial.js index 6ea4094f69c3c6..915ed026059952 100644 --- a/src/materials/MeshLambertMaterial.js +++ b/src/materials/MeshLambertMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -36,13 +40,14 @@ * } */ -THREE.MeshLambertMaterial = function ( parameters ) { +function MeshLambertMaterial ( parameters ) { + this.isMeshLambertMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshLambertMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse + this.color = new Color( 0xffffff ); // diffuse this.map = null; @@ -52,7 +57,7 @@ THREE.MeshLambertMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -61,7 +66,7 @@ THREE.MeshLambertMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -78,12 +83,12 @@ THREE.MeshLambertMaterial = function ( parameters ) { }; -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; +MeshLambertMaterial.prototype = Object.create( Material.prototype ); +MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; -THREE.MeshLambertMaterial.prototype.copy = function ( source ) { +MeshLambertMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -120,3 +125,6 @@ THREE.MeshLambertMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshLambertMaterial }; \ No newline at end of file diff --git a/src/materials/MeshNormalMaterial.js b/src/materials/MeshNormalMaterial.js index d85582ef8ef3d8..dc0fc88db66fb9 100644 --- a/src/materials/MeshNormalMaterial.js +++ b/src/materials/MeshNormalMaterial.js @@ -1,3 +1,5 @@ +import { Material } from './Material'; + /** * @author mrdoob / http://mrdoob.com/ * @@ -9,9 +11,10 @@ * } */ -THREE.MeshNormalMaterial = function ( parameters ) { +function MeshNormalMaterial ( parameters ) { + this.isMeshNormalMaterial = this.isMaterial = true; - THREE.Material.call( this, parameters ); + Material.call( this, parameters ); this.type = 'MeshNormalMaterial'; @@ -26,12 +29,12 @@ THREE.MeshNormalMaterial = function ( parameters ) { }; -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; +MeshNormalMaterial.prototype = Object.create( Material.prototype ); +MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; -THREE.MeshNormalMaterial.prototype.copy = function ( source ) { +MeshNormalMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; @@ -39,3 +42,6 @@ THREE.MeshNormalMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshNormalMaterial }; \ No newline at end of file diff --git a/src/materials/MeshPhongMaterial.js b/src/materials/MeshPhongMaterial.js index 0ab6b8bfa77735..fc8fff1d5856cc 100644 --- a/src/materials/MeshPhongMaterial.js +++ b/src/materials/MeshPhongMaterial.js @@ -1,3 +1,8 @@ +import { Material } from './Material'; +import { MultiplyOperation } from '../constants'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -48,14 +53,15 @@ * } */ -THREE.MeshPhongMaterial = function ( parameters ) { +function MeshPhongMaterial ( parameters ) { + this.isMeshPhongMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'MeshPhongMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse - this.specular = new THREE.Color( 0x111111 ); + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); this.shininess = 30; this.map = null; @@ -66,7 +72,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -74,7 +80,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.bumpScale = 1; this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; @@ -85,7 +91,7 @@ THREE.MeshPhongMaterial = function ( parameters ) { this.alphaMap = null; this.envMap = null; - this.combine = THREE.MultiplyOperation; + this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; @@ -102,12 +108,12 @@ THREE.MeshPhongMaterial = function ( parameters ) { }; -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; +MeshPhongMaterial.prototype = Object.create( Material.prototype ); +MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; -THREE.MeshPhongMaterial.prototype.copy = function ( source ) { +MeshPhongMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.specular.copy( source.specular ); @@ -156,3 +162,6 @@ THREE.MeshPhongMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshPhongMaterial }; \ No newline at end of file diff --git a/src/materials/MeshPhysicalMaterial.js b/src/materials/MeshPhysicalMaterial.js index 021b0bd8d83fce..a539c53a90654f 100644 --- a/src/materials/MeshPhysicalMaterial.js +++ b/src/materials/MeshPhysicalMaterial.js @@ -1,3 +1,5 @@ +import { MeshStandardMaterial } from './MeshStandardMaterial'; + /** * @author WestLangley / http://github.com/WestLangley * @@ -6,9 +8,10 @@ * } */ -THREE.MeshPhysicalMaterial = function ( parameters ) { +function MeshPhysicalMaterial ( parameters ) { + this.isMeshPhysicalMaterial = this.isMeshStandardMaterial = this.isMaterial = true; - THREE.MeshStandardMaterial.call( this ); + MeshStandardMaterial.call( this ); this.defines = { 'PHYSICAL': '' }; @@ -23,12 +26,12 @@ THREE.MeshPhysicalMaterial = function ( parameters ) { }; -THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype ); -THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial; +MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); +MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; -THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { +MeshPhysicalMaterial.prototype.copy = function ( source ) { - THREE.MeshStandardMaterial.prototype.copy.call( this, source ); + MeshStandardMaterial.prototype.copy.call( this, source ); this.defines = { 'PHYSICAL': '' }; @@ -40,3 +43,6 @@ THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshPhysicalMaterial }; \ No newline at end of file diff --git a/src/materials/MeshStandardMaterial.js b/src/materials/MeshStandardMaterial.js index 82950c86657c9f..ec1ea9b2b8d10c 100644 --- a/src/materials/MeshStandardMaterial.js +++ b/src/materials/MeshStandardMaterial.js @@ -1,3 +1,7 @@ +import { Material } from './Material'; +import { Vector2 } from '../math/Vector2'; +import { Color } from '../math/Color'; + /** * @author WestLangley / http://github.com/WestLangley * @@ -49,15 +53,16 @@ * } */ -THREE.MeshStandardMaterial = function ( parameters ) { +function MeshStandardMaterial ( parameters ) { + this.isMeshStandardMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.defines = { 'STANDARD': '' }; this.type = 'MeshStandardMaterial'; - this.color = new THREE.Color( 0xffffff ); // diffuse + this.color = new Color( 0xffffff ); // diffuse this.roughness = 0.5; this.metalness = 0.5; @@ -69,7 +74,7 @@ THREE.MeshStandardMaterial = function ( parameters ) { this.aoMap = null; this.aoMapIntensity = 1.0; - this.emissive = new THREE.Color( 0x000000 ); + this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; @@ -77,7 +82,7 @@ THREE.MeshStandardMaterial = function ( parameters ) { this.bumpScale = 1; this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; @@ -107,12 +112,12 @@ THREE.MeshStandardMaterial = function ( parameters ) { }; -THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial; +MeshStandardMaterial.prototype = Object.create( Material.prototype ); +MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; -THREE.MeshStandardMaterial.prototype.copy = function ( source ) { +MeshStandardMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.defines = { 'STANDARD': '' }; @@ -165,3 +170,6 @@ THREE.MeshStandardMaterial.prototype.copy = function ( source ) { return this; }; + + +export { MeshStandardMaterial }; \ No newline at end of file diff --git a/src/materials/MultiMaterial.js b/src/materials/MultiMaterial.js index 3aff3fbdd502aa..add0775060b578 100644 --- a/src/materials/MultiMaterial.js +++ b/src/materials/MultiMaterial.js @@ -1,10 +1,13 @@ +import { _Math } from '../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.MultiMaterial = function ( materials ) { +function MultiMaterial ( materials ) { + this.isMultiMaterial = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.type = 'MultiMaterial'; @@ -14,9 +17,9 @@ THREE.MultiMaterial = function ( materials ) { }; -THREE.MultiMaterial.prototype = { +MultiMaterial.prototype = { - constructor: THREE.MultiMaterial, + constructor: MultiMaterial, toJSON: function ( meta ) { @@ -65,3 +68,6 @@ THREE.MultiMaterial.prototype = { } }; + + +export { MultiMaterial }; \ No newline at end of file diff --git a/src/materials/PointsMaterial.js b/src/materials/PointsMaterial.js index c036dbe7465b8d..b3c2ad1b999ba0 100644 --- a/src/materials/PointsMaterial.js +++ b/src/materials/PointsMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -12,13 +15,14 @@ * } */ -THREE.PointsMaterial = function ( parameters ) { +function PointsMaterial ( parameters ) { + this.isPointsMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'PointsMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.map = null; @@ -31,12 +35,12 @@ THREE.PointsMaterial = function ( parameters ) { }; -THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial; +PointsMaterial.prototype = Object.create( Material.prototype ); +PointsMaterial.prototype.constructor = PointsMaterial; -THREE.PointsMaterial.prototype.copy = function ( source ) { +PointsMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); @@ -48,3 +52,6 @@ THREE.PointsMaterial.prototype.copy = function ( source ) { return this; }; + + +export { PointsMaterial }; \ No newline at end of file diff --git a/src/materials/RawShaderMaterial.js b/src/materials/RawShaderMaterial.js index 130edcaa3b3fa4..801799d01e2114 100644 --- a/src/materials/RawShaderMaterial.js +++ b/src/materials/RawShaderMaterial.js @@ -1,14 +1,20 @@ +import { ShaderMaterial } from './ShaderMaterial'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.RawShaderMaterial = function ( parameters ) { +function RawShaderMaterial ( parameters ) { + this.isRawShaderMaterial = this.isShaderMaterial = this.isMaterial = true; - THREE.ShaderMaterial.call( this, parameters ); + ShaderMaterial.call( this, parameters ); this.type = 'RawShaderMaterial'; }; -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; +RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); +RawShaderMaterial.prototype.constructor = RawShaderMaterial; + + +export { RawShaderMaterial }; \ No newline at end of file diff --git a/src/materials/ShaderMaterial.js b/src/materials/ShaderMaterial.js index b4592cd3898462..9922c549dbc422 100644 --- a/src/materials/ShaderMaterial.js +++ b/src/materials/ShaderMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { UniformsUtils } from '../renderers/shaders/UniformsUtils'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -19,9 +22,10 @@ * } */ -THREE.ShaderMaterial = function ( parameters ) { +function ShaderMaterial ( parameters ) { + this.isShaderMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'ShaderMaterial'; @@ -75,17 +79,17 @@ THREE.ShaderMaterial = function ( parameters ) { }; -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; +ShaderMaterial.prototype = Object.create( Material.prototype ); +ShaderMaterial.prototype.constructor = ShaderMaterial; -THREE.ShaderMaterial.prototype.copy = function ( source ) { +ShaderMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.fragmentShader = source.fragmentShader; this.vertexShader = source.vertexShader; - this.uniforms = THREE.UniformsUtils.clone( source.uniforms ); + this.uniforms = UniformsUtils.clone( source.uniforms ); this.defines = source.defines; @@ -106,9 +110,9 @@ THREE.ShaderMaterial.prototype.copy = function ( source ) { }; -THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { +ShaderMaterial.prototype.toJSON = function ( meta ) { - var data = THREE.Material.prototype.toJSON.call( this, meta ); + var data = Material.prototype.toJSON.call( this, meta ); data.uniforms = this.uniforms; data.vertexShader = this.vertexShader; @@ -117,3 +121,6 @@ THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { return data; }; + + +export { ShaderMaterial }; \ No newline at end of file diff --git a/src/materials/ShadowMaterial.js b/src/materials/ShadowMaterial.js index 86d800676cbab4..f4118e1b808dd5 100644 --- a/src/materials/ShadowMaterial.js +++ b/src/materials/ShadowMaterial.js @@ -1,18 +1,24 @@ +import { ShaderMaterial } from './ShaderMaterial'; +import { ShaderChunk } from '../renderers/shaders/ShaderChunk'; +import { UniformsLib } from '../renderers/shaders/UniformsLib'; +import { UniformsUtils } from '../renderers/shaders/UniformsUtils'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.ShadowMaterial = function () { +function ShadowMaterial () { + this.isShadowMaterial = this.isShaderMaterial = this.isMaterial = true; - THREE.ShaderMaterial.call( this, { - uniforms: THREE.UniformsUtils.merge( [ - THREE.UniformsLib[ "lights" ], + ShaderMaterial.call( this, { + uniforms: UniformsUtils.merge( [ + UniformsLib[ "lights" ], { opacity: { value: 1.0 } } ] ), - vertexShader: THREE.ShaderChunk[ 'shadow_vert' ], - fragmentShader: THREE.ShaderChunk[ 'shadow_frag' ] + vertexShader: ShaderChunk[ 'shadow_vert' ], + fragmentShader: ShaderChunk[ 'shadow_frag' ] } ); this.lights = true; @@ -32,5 +38,8 @@ THREE.ShadowMaterial = function () { }; -THREE.ShadowMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.ShadowMaterial.prototype.constructor = THREE.ShadowMaterial; +ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); +ShadowMaterial.prototype.constructor = ShadowMaterial; + + +export { ShadowMaterial }; diff --git a/src/materials/SpriteMaterial.js b/src/materials/SpriteMaterial.js index e56c1947ca53e9..637c82bb5aa469 100644 --- a/src/materials/SpriteMaterial.js +++ b/src/materials/SpriteMaterial.js @@ -1,3 +1,6 @@ +import { Material } from './Material'; +import { Color } from '../math/Color'; + /** * @author alteredq / http://alteredqualia.com/ * @@ -11,13 +14,14 @@ * } */ -THREE.SpriteMaterial = function ( parameters ) { +function SpriteMaterial ( parameters ) { + this.isSpriteMaterial = this.isMaterial = true; - THREE.Material.call( this ); + Material.call( this ); this.type = 'SpriteMaterial'; - this.color = new THREE.Color( 0xffffff ); + this.color = new Color( 0xffffff ); this.map = null; this.rotation = 0; @@ -29,12 +33,12 @@ THREE.SpriteMaterial = function ( parameters ) { }; -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; +SpriteMaterial.prototype = Object.create( Material.prototype ); +SpriteMaterial.prototype.constructor = SpriteMaterial; -THREE.SpriteMaterial.prototype.copy = function ( source ) { +SpriteMaterial.prototype.copy = function ( source ) { - THREE.Material.prototype.copy.call( this, source ); + Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; @@ -44,3 +48,6 @@ THREE.SpriteMaterial.prototype.copy = function ( source ) { return this; }; + + +export { SpriteMaterial }; \ No newline at end of file diff --git a/src/math/Box2.js b/src/math/Box2.js index 7dfa62ab547d52..2f676e86bb5f4c 100644 --- a/src/math/Box2.js +++ b/src/math/Box2.js @@ -1,17 +1,20 @@ +import { Vector2 } from './Vector2'; + /** * @author bhouston / http://clara.io */ -THREE.Box2 = function ( min, max ) { +function Box2 ( min, max ) { + this.isBox2 = true; - this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); }; -THREE.Box2.prototype = { +Box2.prototype = { - constructor: THREE.Box2, + constructor: Box2, set: function ( min, max ) { @@ -38,7 +41,7 @@ THREE.Box2.prototype = { setFromCenterAndSize: function () { - var v1 = new THREE.Vector2(); + var v1 = new Vector2(); return function setFromCenterAndSize( center, size ) { @@ -86,14 +89,14 @@ THREE.Box2.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, size: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.subVectors( this.max, this.min ); }, @@ -156,7 +159,7 @@ THREE.Box2.prototype = { // This can potentially have a divide by zero if the box // has a size dimension of 0. - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), @@ -182,14 +185,14 @@ THREE.Box2.prototype = { clampPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector2(); + var result = optionalTarget || new Vector2(); return result.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function () { - var v1 = new THREE.Vector2(); + var v1 = new Vector2(); return function distanceToPoint( point ) { @@ -234,3 +237,6 @@ THREE.Box2.prototype = { } }; + + +export { Box2 }; \ No newline at end of file diff --git a/src/math/Box3.js b/src/math/Box3.js index cf93582b2afce4..07cef70754f4db 100644 --- a/src/math/Box3.js +++ b/src/math/Box3.js @@ -1,18 +1,22 @@ +import { Vector3 } from './Vector3'; +import { Sphere } from './Sphere'; + /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley */ -THREE.Box3 = function ( min, max ) { +function Box3 ( min, max ) { + this.isBox3 = true; - this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); }; -THREE.Box3.prototype = { +Box3.prototype = { - constructor: THREE.Box3, + constructor: Box3, set: function ( min, max ) { @@ -70,7 +74,7 @@ THREE.Box3.prototype = { setFromCenterAndSize: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function setFromCenterAndSize( center, size ) { @@ -90,7 +94,7 @@ THREE.Box3.prototype = { // Computes the world-axis-aligned bounding box of an object (including its children), // accounting for both the object's, and children's, world transforms - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function setFromObject( object ) { @@ -106,7 +110,7 @@ THREE.Box3.prototype = { if ( geometry !== undefined ) { - if ( geometry instanceof THREE.Geometry ) { + if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; @@ -119,7 +123,7 @@ THREE.Box3.prototype = { } - } else if ( geometry instanceof THREE.BufferGeometry ) { + } else if ( (geometry && geometry.isBufferGeometry) ) { var attribute = geometry.attributes.position; @@ -127,7 +131,7 @@ THREE.Box3.prototype = { var array, offset, stride; - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { array = attribute.data.array; offset = attribute.offset; @@ -198,14 +202,14 @@ THREE.Box3.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, size: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.subVectors( this.max, this.min ); }, @@ -270,7 +274,7 @@ THREE.Box3.prototype = { // This can potentially have a divide by zero if the box // has a size dimension of 0. - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), @@ -302,7 +306,7 @@ THREE.Box3.prototype = { return function intersectsSphere( sphere ) { - if ( closestPoint === undefined ) closestPoint = new THREE.Vector3(); + if ( closestPoint === undefined ) closestPoint = new Vector3(); // Find the point on the AABB closest to the sphere center. this.clampPoint( sphere.center, closestPoint ); @@ -363,14 +367,14 @@ THREE.Box3.prototype = { clampPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function distanceToPoint( point ) { @@ -383,11 +387,11 @@ THREE.Box3.prototype = { getBoundingSphere: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function getBoundingSphere( optionalTarget ) { - var result = optionalTarget || new THREE.Sphere(); + var result = optionalTarget || new Sphere(); result.center = this.center(); result.radius = this.size( v1 ).length() * 0.5; @@ -422,14 +426,14 @@ THREE.Box3.prototype = { 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() + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() ]; return function applyMatrix4( matrix ) { @@ -471,3 +475,6 @@ THREE.Box3.prototype = { } }; + + +export { Box3 }; \ No newline at end of file diff --git a/src/math/Color.js b/src/math/Color.js index 1e566cde6a7ad7..d303b8444ce13a 100644 --- a/src/math/Color.js +++ b/src/math/Color.js @@ -1,8 +1,13 @@ +import { _Math } from './Math'; + +var ColorKeywords; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Color = function ( r, g, b ) { +function Color ( r, g, b ) { + this.isColor = true; if ( g === undefined && b === undefined ) { @@ -15,15 +20,15 @@ THREE.Color = function ( r, g, b ) { }; -THREE.Color.prototype = { +Color.prototype = { - constructor: THREE.Color, + constructor: Color, r: 1, g: 1, b: 1, set: function ( value ) { - if ( value instanceof THREE.Color ) { + if ( (value && value.isColor) ) { this.copy( value ); @@ -87,9 +92,9 @@ THREE.Color.prototype = { return function setHSL( h, s, l ) { // h,s,l ranges are in 0.0 - 1.0 - h = THREE.Math.euclideanModulo( h, 1 ); - s = THREE.Math.clamp( s, 0, 1 ); - l = THREE.Math.clamp( l, 0, 1 ); + h = _Math.euclideanModulo( h, 1 ); + s = _Math.clamp( s, 0, 1 ); + l = _Math.clamp( l, 0, 1 ); if ( s === 0 ) { @@ -222,7 +227,7 @@ THREE.Color.prototype = { if ( style && style.length > 0 ) { // color keywords - var hex = THREE.ColorKeywords[ style ]; + var hex = ColorKeywords[ style ]; if ( hex !== undefined ) { @@ -484,7 +489,7 @@ THREE.Color.prototype = { }; -THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, +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, @@ -508,3 +513,6 @@ THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': '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 }; + + +export { ColorKeywords, Color }; \ No newline at end of file diff --git a/src/math/Euler.js b/src/math/Euler.js index 2cf60f844416d0..73bfd63be081d8 100644 --- a/src/math/Euler.js +++ b/src/math/Euler.js @@ -1,25 +1,31 @@ +import { Quaternion } from './Quaternion'; +import { Vector3 } from './Vector3'; +import { Matrix4 } from './Matrix4'; +import { _Math } from './Math'; + /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley * @author bhouston / http://clara.io */ -THREE.Euler = function ( x, y, z, order ) { +function Euler ( x, y, z, order ) { + this.isEuler = true; this._x = x || 0; this._y = y || 0; this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; + this._order = order || Euler.DefaultOrder; }; -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; +Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; -THREE.Euler.DefaultOrder = 'XYZ'; +Euler.DefaultOrder = 'XYZ'; -THREE.Euler.prototype = { +Euler.prototype = { - constructor: THREE.Euler, + constructor: Euler, get x () { @@ -107,7 +113,7 @@ THREE.Euler.prototype = { setFromRotationMatrix: function ( m, order, update ) { - var clamp = THREE.Math.clamp; + var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) @@ -234,7 +240,7 @@ THREE.Euler.prototype = { return function setFromQuaternion( q, order, update ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.makeRotationFromQuaternion( q ); @@ -254,7 +260,7 @@ THREE.Euler.prototype = { // WARNING: this discards revolution information -bhouston - var q = new THREE.Quaternion(); + var q = new Quaternion(); return function reorder( newOrder ) { @@ -307,7 +313,7 @@ THREE.Euler.prototype = { } else { - return new THREE.Vector3( this._x, this._y, this._z ); + return new Vector3( this._x, this._y, this._z ); } @@ -324,3 +330,6 @@ THREE.Euler.prototype = { onChangeCallback: function () {} }; + + +export { Euler }; \ No newline at end of file diff --git a/src/math/Frustum.js b/src/math/Frustum.js index 227cdb3823cc83..3b1911054be063 100644 --- a/src/math/Frustum.js +++ b/src/math/Frustum.js @@ -1,27 +1,32 @@ +import { Vector3 } from './Vector3'; +import { Sphere } from './Sphere'; +import { Plane } from './Plane'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author bhouston / http://clara.io */ -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { +function Frustum ( p0, p1, p2, p3, p4, p5 ) { + this.isFrustum = true; 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() + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() ]; }; -THREE.Frustum.prototype = { +Frustum.prototype = { - constructor: THREE.Frustum, + constructor: Frustum, set: function ( p0, p1, p2, p3, p4, p5 ) { @@ -80,7 +85,7 @@ THREE.Frustum.prototype = { intersectsObject: function () { - var sphere = new THREE.Sphere(); + var sphere = new Sphere(); return function intersectsObject( object ) { @@ -100,7 +105,7 @@ THREE.Frustum.prototype = { intersectsSprite: function () { - var sphere = new THREE.Sphere(); + var sphere = new Sphere(); return function intersectsSprite( sprite ) { @@ -138,8 +143,8 @@ THREE.Frustum.prototype = { intersectsBox: function () { - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + var p1 = new Vector3(), + p2 = new Vector3(); return function intersectsBox( box ) { @@ -195,3 +200,6 @@ THREE.Frustum.prototype = { } }; + + +export { Frustum }; \ No newline at end of file diff --git a/src/math/Interpolant.js b/src/math/Interpolant.js index c86df556e83952..09afb8fa138c82 100644 --- a/src/math/Interpolant.js +++ b/src/math/Interpolant.js @@ -20,8 +20,9 @@ * @author tschw */ -THREE.Interpolant = function( +function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isInterpolant = true; this.parameterPositions = parameterPositions; this._cachedIndex = 0; @@ -33,9 +34,9 @@ THREE.Interpolant = function( }; -THREE.Interpolant.prototype = { +Interpolant.prototype = { - constructor: THREE.Interpolant, + constructor: Interpolant, evaluate: function( t ) { @@ -246,12 +247,15 @@ THREE.Interpolant.prototype = { }; -Object.assign( THREE.Interpolant.prototype, { +Object.assign( Interpolant.prototype, { beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_, + Interpolant.prototype.copySampleValue_, afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - THREE.Interpolant.prototype.copySampleValue_ + Interpolant.prototype.copySampleValue_ } ); + + +export { Interpolant }; \ No newline at end of file diff --git a/src/math/Line3.js b/src/math/Line3.js index 2ae1f482cb3614..ef1983ef11e40d 100644 --- a/src/math/Line3.js +++ b/src/math/Line3.js @@ -1,17 +1,21 @@ +import { Vector3 } from './Vector3'; +import { _Math } from './Math'; + /** * @author bhouston / http://clara.io */ -THREE.Line3 = function ( start, end ) { +function Line3 ( start, end ) { + this.isLine3 = true; - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); }; -THREE.Line3.prototype = { +Line3.prototype = { - constructor: THREE.Line3, + constructor: Line3, set: function ( start, end ) { @@ -39,14 +43,14 @@ THREE.Line3.prototype = { center: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); }, delta: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.subVectors( this.end, this.start ); }, @@ -65,7 +69,7 @@ THREE.Line3.prototype = { at: function ( t, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return this.delta( result ).multiplyScalar( t ).add( this.start ); @@ -73,8 +77,8 @@ THREE.Line3.prototype = { closestPointToPointParameter: function () { - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + var startP = new Vector3(); + var startEnd = new Vector3(); return function closestPointToPointParameter( point, clampToLine ) { @@ -88,7 +92,7 @@ THREE.Line3.prototype = { if ( clampToLine ) { - t = THREE.Math.clamp( t, 0, 1 ); + t = _Math.clamp( t, 0, 1 ); } @@ -102,7 +106,7 @@ THREE.Line3.prototype = { var t = this.closestPointToPointParameter( point, clampToLine ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return this.delta( result ).multiplyScalar( t ).add( this.start ); @@ -124,3 +128,6 @@ THREE.Line3.prototype = { } }; + + +export { Line3 }; \ No newline at end of file diff --git a/src/math/Math.js b/src/math/Math.js index 59a4ca344734db..f27114c1532dcf 100644 --- a/src/math/Math.js +++ b/src/math/Math.js @@ -1,9 +1,11 @@ +var _Math; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.Math = { +_Math = { DEG2RAD: Math.PI / 180, RAD2DEG: 180 / Math.PI, @@ -125,13 +127,13 @@ THREE.Math = { degToRad: function ( degrees ) { - return degrees * THREE.Math.DEG2RAD; + return degrees * _Math.DEG2RAD; }, radToDeg: function ( radians ) { - return radians * THREE.Math.RAD2DEG; + return radians * _Math.RAD2DEG; }, @@ -162,3 +164,6 @@ THREE.Math = { } }; + + +export { _Math }; \ No newline at end of file diff --git a/src/math/Matrix3.js b/src/math/Matrix3.js index 81067ad3bab313..59ccb36c0b3309 100644 --- a/src/math/Matrix3.js +++ b/src/math/Matrix3.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley @@ -5,7 +7,8 @@ * @author tschw */ -THREE.Matrix3 = function () { +function Matrix3 () { + this.isMatrix3 = true; this.elements = new Float32Array( [ @@ -23,9 +26,9 @@ THREE.Matrix3 = function () { }; -THREE.Matrix3.prototype = { +Matrix3.prototype = { - constructor: THREE.Matrix3, + constructor: Matrix3, set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { @@ -97,7 +100,7 @@ THREE.Matrix3.prototype = { return function applyToVector3Array( array, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = array.length; @@ -121,7 +124,7 @@ THREE.Matrix3.prototype = { return function applyToBuffer( buffer, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = buffer.length / buffer.itemSize; @@ -169,7 +172,7 @@ THREE.Matrix3.prototype = { getInverse: function ( matrix, throwOnDegenerate ) { - if ( matrix instanceof THREE.Matrix4 ) { + if ( (matrix && matrix.isMatrix4) ) { console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); @@ -300,3 +303,6 @@ THREE.Matrix3.prototype = { } }; + + +export { Matrix3 }; \ No newline at end of file diff --git a/src/math/Matrix4.js b/src/math/Matrix4.js index ae705d97ea5c45..43c38c624fbb60 100644 --- a/src/math/Matrix4.js +++ b/src/math/Matrix4.js @@ -1,3 +1,6 @@ +import { _Math } from './Math'; +import { Vector3 } from './Vector3'; + /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ @@ -11,7 +14,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Matrix4 = function () { +function Matrix4 () { + this.isMatrix4 = true; this.elements = new Float32Array( [ @@ -30,9 +34,9 @@ THREE.Matrix4 = function () { }; -THREE.Matrix4.prototype = { +Matrix4.prototype = { - constructor: THREE.Matrix4, + constructor: Matrix4, set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { @@ -64,7 +68,7 @@ THREE.Matrix4.prototype = { clone: function () { - return new THREE.Matrix4().fromArray( this.elements ); + return new Matrix4().fromArray( this.elements ); }, @@ -118,7 +122,7 @@ THREE.Matrix4.prototype = { return function extractRotation( m ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); var te = this.elements; var me = m.elements; @@ -147,7 +151,7 @@ THREE.Matrix4.prototype = { makeRotationFromEuler: function ( euler ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); @@ -318,9 +322,9 @@ THREE.Matrix4.prototype = { if ( x === undefined ) { - x = new THREE.Vector3(); - y = new THREE.Vector3(); - z = new THREE.Vector3(); + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); } @@ -449,7 +453,7 @@ THREE.Matrix4.prototype = { return function applyToVector3Array( array, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = array.length; @@ -473,7 +477,7 @@ THREE.Matrix4.prototype = { return function applyToBuffer( buffer, offset, length ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); if ( offset === undefined ) offset = 0; if ( length === undefined ) length = buffer.length / buffer.itemSize; @@ -577,7 +581,7 @@ THREE.Matrix4.prototype = { return function getPosition() { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); return v1.setFromMatrixColumn( this, 3 ); @@ -808,8 +812,8 @@ THREE.Matrix4.prototype = { if ( vector === undefined ) { - vector = new THREE.Vector3(); - matrix = new THREE.Matrix4(); + vector = new Vector3(); + matrix = new Matrix4(); } @@ -885,7 +889,7 @@ THREE.Matrix4.prototype = { makePerspective: function ( fov, aspect, near, far ) { - var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 ); + var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 ); var ymin = - ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; @@ -969,3 +973,6 @@ THREE.Matrix4.prototype = { } }; + + +export { Matrix4 }; \ No newline at end of file diff --git a/src/math/Plane.js b/src/math/Plane.js index a77ea851b70285..4b37edb78b707a 100644 --- a/src/math/Plane.js +++ b/src/math/Plane.js @@ -1,17 +1,21 @@ +import { Matrix3 } from './Matrix3'; +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io */ -THREE.Plane = function ( normal, constant ) { +function Plane ( normal, constant ) { + this.isPlane = true; - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); this.constant = ( constant !== undefined ) ? constant : 0; }; -THREE.Plane.prototype = { +Plane.prototype = { - constructor: THREE.Plane, + constructor: Plane, set: function ( normal, constant ) { @@ -42,8 +46,8 @@ THREE.Plane.prototype = { setFromCoplanarPoints: function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function setFromCoplanarPoints( a, b, c ) { @@ -117,18 +121,18 @@ THREE.Plane.prototype = { var perpendicularMagnitude = this.distanceToPoint( point ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); }, intersectLine: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function intersectLine( line, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); var direction = line.delta( v1 ); @@ -187,15 +191,15 @@ THREE.Plane.prototype = { coplanarPoint: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.normal ).multiplyScalar( - this.constant ); }, applyMatrix4: function () { - var v1 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + var v1 = new Vector3(); + var m1 = new Matrix3(); return function applyMatrix4( matrix, optionalNormalMatrix ) { @@ -230,3 +234,6 @@ THREE.Plane.prototype = { } }; + + +export { Plane }; \ No newline at end of file diff --git a/src/math/Quaternion.js b/src/math/Quaternion.js index 3743c7dc00e457..98a481d590bcfc 100644 --- a/src/math/Quaternion.js +++ b/src/math/Quaternion.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -5,7 +7,8 @@ * @author bhouston / http://clara.io */ -THREE.Quaternion = function ( x, y, z, w ) { +function Quaternion ( x, y, z, w ) { + this.isQuaternion = true; this._x = x || 0; this._y = y || 0; @@ -14,9 +17,9 @@ THREE.Quaternion = function ( x, y, z, w ) { }; -THREE.Quaternion.prototype = { +Quaternion.prototype = { - constructor: THREE.Quaternion, + constructor: Quaternion, get x () { @@ -104,7 +107,7 @@ THREE.Quaternion.prototype = { setFromEuler: function ( euler, update ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); @@ -263,7 +266,7 @@ THREE.Quaternion.prototype = { return function setFromUnitVectors( vFrom, vTo ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); r = vFrom.dot( vTo ) + 1; @@ -511,7 +514,7 @@ THREE.Quaternion.prototype = { }; -Object.assign( THREE.Quaternion, { +Object.assign( Quaternion, { slerp: function( qa, qb, qm, t ) { @@ -583,3 +586,6 @@ Object.assign( THREE.Quaternion, { } } ); + + +export { Quaternion }; \ No newline at end of file diff --git a/src/math/Ray.js b/src/math/Ray.js index 540a6cb292d7e0..25b6287f5db968 100644 --- a/src/math/Ray.js +++ b/src/math/Ray.js @@ -1,17 +1,20 @@ +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io */ -THREE.Ray = function ( origin, direction ) { +function Ray ( origin, direction ) { + this.isRay = true; - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); }; -THREE.Ray.prototype = { +Ray.prototype = { - constructor: THREE.Ray, + constructor: Ray, set: function ( origin, direction ) { @@ -39,7 +42,7 @@ THREE.Ray.prototype = { at: function ( t, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); @@ -55,7 +58,7 @@ THREE.Ray.prototype = { recast: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function recast( t ) { @@ -69,7 +72,7 @@ THREE.Ray.prototype = { closestPointToPoint: function ( point, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.subVectors( point, this.origin ); var directionDistance = result.dot( this.direction ); @@ -91,7 +94,7 @@ THREE.Ray.prototype = { distanceSqToPoint: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function distanceSqToPoint( point ) { @@ -115,9 +118,9 @@ THREE.Ray.prototype = { distanceSqToSegment: function () { - var segCenter = new THREE.Vector3(); - var segDir = new THREE.Vector3(); - var diff = new THREE.Vector3(); + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { @@ -242,7 +245,7 @@ THREE.Ray.prototype = { intersectSphere: function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function intersectSphere( sphere, optionalTarget ) { @@ -422,7 +425,7 @@ THREE.Ray.prototype = { intersectsBox: ( function () { - var v = new THREE.Vector3(); + var v = new Vector3(); return function intersectsBox( box ) { @@ -435,10 +438,10 @@ THREE.Ray.prototype = { intersectTriangle: function () { // 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(); + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { @@ -533,3 +536,6 @@ THREE.Ray.prototype = { } }; + + +export { Ray }; \ No newline at end of file diff --git a/src/math/Sphere.js b/src/math/Sphere.js index 99ccd79af00799..d910b3e3b6aceb 100644 --- a/src/math/Sphere.js +++ b/src/math/Sphere.js @@ -1,18 +1,22 @@ +import { Box3 } from './Box3'; +import { Vector3 } from './Vector3'; + /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ -THREE.Sphere = function ( center, radius ) { +function Sphere ( center, radius ) { + this.isSphere = true; - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); + this.center = ( center !== undefined ) ? center : new Vector3(); this.radius = ( radius !== undefined ) ? radius : 0; }; -THREE.Sphere.prototype = { +Sphere.prototype = { - constructor: THREE.Sphere, + constructor: Sphere, set: function ( center, radius ) { @@ -25,7 +29,7 @@ THREE.Sphere.prototype = { setFromPoints: function () { - var box = new THREE.Box3(); + var box = new Box3(); return function setFromPoints( points, optionalCenter ) { @@ -122,7 +126,7 @@ THREE.Sphere.prototype = { var deltaLengthSq = this.center.distanceToSquared( point ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.copy( point ); @@ -139,7 +143,7 @@ THREE.Sphere.prototype = { getBoundingBox: function ( optionalTarget ) { - var box = optionalTarget || new THREE.Box3(); + var box = optionalTarget || new Box3(); box.set( this.center, this.center ); box.expandByScalar( this.radius ); @@ -172,3 +176,6 @@ THREE.Sphere.prototype = { } }; + + +export { Sphere }; \ No newline at end of file diff --git a/src/math/Spherical.js b/src/math/Spherical.js index f3870be9a57cac..1d7d96491a00d3 100644 --- a/src/math/Spherical.js +++ b/src/math/Spherical.js @@ -1,3 +1,5 @@ +import { _Math } from './Math'; + /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley @@ -8,7 +10,8 @@ * The equator starts at positive z. */ -THREE.Spherical = function ( radius, phi, theta ) { +function Spherical ( radius, phi, theta ) { + this.isSpherical = true; this.radius = ( radius !== undefined ) ? radius : 1.0; this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole @@ -18,9 +21,9 @@ THREE.Spherical = function ( radius, phi, theta ) { }; -THREE.Spherical.prototype = { +Spherical.prototype = { - constructor: THREE.Spherical, + constructor: Spherical, set: function ( radius, phi, theta ) { @@ -70,7 +73,7 @@ THREE.Spherical.prototype = { } else { this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis - this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle } @@ -79,3 +82,6 @@ THREE.Spherical.prototype = { }, }; + + +export { Spherical }; \ No newline at end of file diff --git a/src/math/Spline.js b/src/math/Spline.js index 8d04fdb6711fb5..4bad0df3dc1d51 100644 --- a/src/math/Spline.js +++ b/src/math/Spline.js @@ -1,3 +1,5 @@ +import { Vector3 } from './Vector3'; + /** * Spline from Tween.js, slightly optimized (and trashed) * http://sole.github.com/tween.js/examples/05_spline.html @@ -6,7 +8,8 @@ * @author alteredq / http://alteredqualia.com/ */ -THREE.Spline = function ( points ) { +function Spline ( points ) { + this.isSpline = true; this.points = points; @@ -75,8 +78,8 @@ THREE.Spline = function ( points ) { var i, index, nSamples, position, point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), + oldPosition = new Vector3(), + tmpVec = new Vector3(), chunkLengths = [], totalLength = 0; @@ -128,7 +131,7 @@ THREE.Spline = function ( points ) { realDistance, sampling, position, newpoints = [], - tmpVec = new THREE.Vector3(), + tmpVec = new Vector3(), sl = this.getLength(); newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); @@ -174,3 +177,6 @@ THREE.Spline = function ( points ) { } }; + + +export { Spline }; \ No newline at end of file diff --git a/src/math/Triangle.js b/src/math/Triangle.js index 3912687e5c576b..d9193d4ddae1cb 100644 --- a/src/math/Triangle.js +++ b/src/math/Triangle.js @@ -1,23 +1,28 @@ +import { Vector3 } from './Vector3'; +import { Line3 } from './Line3'; +import { Plane } from './Plane'; + /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ -THREE.Triangle = function ( a, b, c ) { +function Triangle ( a, b, c ) { + this.isTriangle = true; - 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.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); }; -THREE.Triangle.normal = function () { +Triangle.normal = function () { - var v0 = new THREE.Vector3(); + var v0 = new Vector3(); return function normal( a, b, c, optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); result.subVectors( c, b ); v0.subVectors( a, b ); @@ -38,11 +43,11 @@ THREE.Triangle.normal = function () { // static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { +Triangle.barycoordFromPoint = function () { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function barycoordFromPoint( point, a, b, c, optionalTarget ) { @@ -58,7 +63,7 @@ THREE.Triangle.barycoordFromPoint = function () { var denom = ( dot00 * dot11 - dot01 * dot01 ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); // collinear or singular triangle if ( denom === 0 ) { @@ -80,13 +85,13 @@ THREE.Triangle.barycoordFromPoint = function () { }(); -THREE.Triangle.containsPoint = function () { +Triangle.containsPoint = function () { - var v1 = new THREE.Vector3(); + var v1 = new Vector3(); return function containsPoint( point, a, b, c ) { - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); @@ -94,9 +99,9 @@ THREE.Triangle.containsPoint = function () { }(); -THREE.Triangle.prototype = { +Triangle.prototype = { - constructor: THREE.Triangle, + constructor: Triangle, set: function ( a, b, c ) { @@ -136,8 +141,8 @@ THREE.Triangle.prototype = { area: function () { - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + var v0 = new Vector3(); + var v1 = new Vector3(); return function area() { @@ -152,20 +157,20 @@ THREE.Triangle.prototype = { midpoint: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); }, normal: function ( optionalTarget ) { - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); }, plane: function ( optionalTarget ) { - var result = optionalTarget || new THREE.Plane(); + var result = optionalTarget || new Plane(); return result.setFromCoplanarPoints( this.a, this.b, this.c ); @@ -173,13 +178,13 @@ THREE.Triangle.prototype = { barycoordFromPoint: function ( point, optionalTarget ) { - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); }, containsPoint: function ( point ) { - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + return Triangle.containsPoint( point, this.a, this.b, this.c ); }, @@ -191,14 +196,14 @@ THREE.Triangle.prototype = { if ( plane === undefined ) { - plane = new THREE.Plane(); - edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ]; - projectedPoint = new THREE.Vector3(); - closestPoint = new THREE.Vector3(); + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); } - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); var minDistance = Infinity; // project the point onto the plane of the triangle @@ -253,3 +258,6 @@ THREE.Triangle.prototype = { } }; + + +export { Triangle }; \ No newline at end of file diff --git a/src/math/Vector2.js b/src/math/Vector2.js index fb5b27c2bc3473..2338eed42c2571 100644 --- a/src/math/Vector2.js +++ b/src/math/Vector2.js @@ -5,16 +5,17 @@ * @author zz85 / http://www.lab4games.net/zz85/blog */ -THREE.Vector2 = function ( x, y ) { +function Vector2 ( x, y ) { + this.isVector2 = true; this.x = x || 0; this.y = y || 0; }; -THREE.Vector2.prototype = { +Vector2.prototype = { - constructor: THREE.Vector2, + constructor: Vector2, get width() { @@ -271,8 +272,8 @@ THREE.Vector2.prototype = { if ( min === undefined ) { - min = new THREE.Vector2(); - max = new THREE.Vector2(); + min = new Vector2(); + max = new Vector2(); } @@ -477,3 +478,6 @@ THREE.Vector2.prototype = { } }; + + +export { Vector2 }; \ No newline at end of file diff --git a/src/math/Vector3.js b/src/math/Vector3.js index 25acd8421f4412..a5871c2f374fef 100644 --- a/src/math/Vector3.js +++ b/src/math/Vector3.js @@ -1,3 +1,7 @@ +import { _Math } from './Math'; +import { Matrix4 } from './Matrix4'; +import { Quaternion } from './Quaternion'; + /** * @author mrdoob / http://mrdoob.com/ * @author *kile / http://kile.stravaganza.org/ @@ -7,7 +11,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Vector3 = function ( x, y, z ) { +function Vector3 ( x, y, z ) { + this.isVector3 = true; this.x = x || 0; this.y = y || 0; @@ -15,9 +20,9 @@ THREE.Vector3 = function ( x, y, z ) { }; -THREE.Vector3.prototype = { +Vector3.prototype = { - constructor: THREE.Vector3, + constructor: Vector3, set: function ( x, y, z ) { @@ -242,13 +247,13 @@ THREE.Vector3.prototype = { return function applyEuler( euler ) { - if ( euler instanceof THREE.Euler === false ) { + if ( (euler && euler.isEuler) === false ) { console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); } - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + if ( quaternion === undefined ) quaternion = new Quaternion(); return this.applyQuaternion( quaternion.setFromEuler( euler ) ); @@ -262,7 +267,7 @@ THREE.Vector3.prototype = { return function applyAxisAngle( axis, angle ) { - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + if ( quaternion === undefined ) quaternion = new Quaternion(); return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); @@ -342,7 +347,7 @@ THREE.Vector3.prototype = { return function project( camera ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); return this.applyProjection( matrix ); @@ -357,7 +362,7 @@ THREE.Vector3.prototype = { return function unproject( camera ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + if ( matrix === undefined ) matrix = new Matrix4(); matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); return this.applyProjection( matrix ); @@ -438,8 +443,8 @@ THREE.Vector3.prototype = { if ( min === undefined ) { - min = new THREE.Vector3(); - max = new THREE.Vector3(); + min = new Vector3(); + max = new Vector3(); } @@ -608,7 +613,7 @@ THREE.Vector3.prototype = { return function projectOnPlane( planeNormal ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); v1.copy( this ).projectOnVector( planeNormal ); @@ -627,7 +632,7 @@ THREE.Vector3.prototype = { return function reflect( normal ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( v1 === undefined ) v1 = new Vector3(); return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); @@ -641,7 +646,7 @@ THREE.Vector3.prototype = { // clamp, to handle numerical problems - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + return Math.acos( _Math.clamp( theta, - 1, 1 ) ); }, @@ -758,3 +763,6 @@ THREE.Vector3.prototype = { } }; + + +export { Vector3 }; \ No newline at end of file diff --git a/src/math/Vector4.js b/src/math/Vector4.js index ad4dcd143423fc..1bc3c14f9b6a4d 100644 --- a/src/math/Vector4.js +++ b/src/math/Vector4.js @@ -6,7 +6,8 @@ * @author WestLangley / http://github.com/WestLangley */ -THREE.Vector4 = function ( x, y, z, w ) { +function Vector4 ( x, y, z, w ) { + this.isVector4 = true; this.x = x || 0; this.y = y || 0; @@ -15,9 +16,9 @@ THREE.Vector4 = function ( x, y, z, w ) { }; -THREE.Vector4.prototype = { +Vector4.prototype = { - constructor: THREE.Vector4, + constructor: Vector4, set: function ( x, y, z, w ) { @@ -452,8 +453,8 @@ THREE.Vector4.prototype = { if ( min === undefined ) { - min = new THREE.Vector4(); - max = new THREE.Vector4(); + min = new Vector4(); + max = new Vector4(); } @@ -623,3 +624,6 @@ THREE.Vector4.prototype = { } }; + + +export { Vector4 }; \ No newline at end of file diff --git a/src/math/interpolants/CubicInterpolant.js b/src/math/interpolants/CubicInterpolant.js index 9498ba39f2bb4d..bce70c8e421737 100644 --- a/src/math/interpolants/CubicInterpolant.js +++ b/src/math/interpolants/CubicInterpolant.js @@ -1,3 +1,7 @@ +import { ZeroCurvatureEnding } from '../../constants'; +import { Interpolant } from '../Interpolant'; +import { WrapAroundEnding, ZeroSlopeEnding } from '../../constants'; + /** * Fast and simple cubic spline interpolant. * @@ -8,10 +12,11 @@ * @author tschw */ -THREE.CubicInterpolant = function( +function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isCubicInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); this._weightPrev = -0; @@ -21,15 +26,15 @@ THREE.CubicInterpolant = function( }; -THREE.CubicInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.CubicInterpolant, + constructor: CubicInterpolant, DefaultSettings_: { - endingStart: THREE.ZeroCurvatureEnding, - endingEnd: THREE.ZeroCurvatureEnding + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding }, @@ -46,7 +51,7 @@ THREE.CubicInterpolant.prototype = switch ( this.getSettings_().endingStart ) { - case THREE.ZeroSlopeEnding: + case ZeroSlopeEnding: // f'(t0) = 0 iPrev = i1; @@ -54,7 +59,7 @@ THREE.CubicInterpolant.prototype = break; - case THREE.WrapAroundEnding: + case WrapAroundEnding: // use the other end of the curve iPrev = pp.length - 2; @@ -76,7 +81,7 @@ THREE.CubicInterpolant.prototype = switch ( this.getSettings_().endingEnd ) { - case THREE.ZeroSlopeEnding: + case ZeroSlopeEnding: // f'(tN) = 0 iNext = i1; @@ -84,7 +89,7 @@ THREE.CubicInterpolant.prototype = break; - case THREE.WrapAroundEnding: + case WrapAroundEnding: // use the other end of the curve iNext = 1; @@ -150,3 +155,6 @@ THREE.CubicInterpolant.prototype = } } ); + + +export { CubicInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/DiscreteInterpolant.js b/src/math/interpolants/DiscreteInterpolant.js index e8792aa5cdf60e..cd8eb03259814c 100644 --- a/src/math/interpolants/DiscreteInterpolant.js +++ b/src/math/interpolants/DiscreteInterpolant.js @@ -1,3 +1,5 @@ +import { Interpolant } from '../Interpolant'; + /** * * Interpolant that evaluates to the sample value at the position preceeding @@ -6,18 +8,19 @@ * @author tschw */ -THREE.DiscreteInterpolant = function( +function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isDiscreteInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.DiscreteInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.DiscreteInterpolant, + constructor: DiscreteInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -26,3 +29,6 @@ THREE.DiscreteInterpolant.prototype = } } ); + + +export { DiscreteInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/LinearInterpolant.js b/src/math/interpolants/LinearInterpolant.js index 785d715c01db11..0b8c1b8b805067 100644 --- a/src/math/interpolants/LinearInterpolant.js +++ b/src/math/interpolants/LinearInterpolant.js @@ -1,19 +1,22 @@ +import { Interpolant } from '../Interpolant'; + /** * @author tschw */ -THREE.LinearInterpolant = function( +function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isLinearInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.LinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.LinearInterpolant, + constructor: LinearInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -40,3 +43,6 @@ THREE.LinearInterpolant.prototype = } } ); + + +export { LinearInterpolant }; \ No newline at end of file diff --git a/src/math/interpolants/QuaternionLinearInterpolant.js b/src/math/interpolants/QuaternionLinearInterpolant.js index 0cdbb7f3586d83..4998924afc59b6 100644 --- a/src/math/interpolants/QuaternionLinearInterpolant.js +++ b/src/math/interpolants/QuaternionLinearInterpolant.js @@ -1,21 +1,25 @@ +import { Interpolant } from '../Interpolant'; +import { Quaternion } from '../Quaternion'; + /** * Spherical linear unit quaternion interpolant. * * @author tschw */ -THREE.QuaternionLinearInterpolant = function( +function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this.isQuaternionLinearInterpolant = true; - THREE.Interpolant.call( + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }; -THREE.QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( THREE.Interpolant.prototype ), { +QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - constructor: THREE.QuaternionLinearInterpolant, + constructor: QuaternionLinearInterpolant, interpolate_: function( i1, t0, t, t1 ) { @@ -29,7 +33,7 @@ THREE.QuaternionLinearInterpolant.prototype = for ( var end = offset + stride; offset !== end; offset += 4 ) { - THREE.Quaternion.slerpFlat( result, 0, + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); } @@ -39,3 +43,6 @@ THREE.QuaternionLinearInterpolant.prototype = } } ); + + +export { QuaternionLinearInterpolant }; \ No newline at end of file diff --git a/src/objects/Bone.js b/src/objects/Bone.js index ff12a01e89347f..cacbe25de44c1d 100644 --- a/src/objects/Bone.js +++ b/src/objects/Bone.js @@ -1,12 +1,15 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ -THREE.Bone = function ( skin ) { +function Bone ( skin ) { + this.isBone = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Bone'; @@ -14,13 +17,13 @@ THREE.Bone = function ( skin ) { }; -THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Bone, + constructor: Bone, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.skin = source.skin; @@ -29,3 +32,6 @@ THREE.Bone.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Bone }; \ No newline at end of file diff --git a/src/objects/Group.js b/src/objects/Group.js index 509731d36d6582..5e5094e171e768 100644 --- a/src/objects/Group.js +++ b/src/objects/Group.js @@ -1,17 +1,23 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Group = function () { +function Group () { + this.isGroup = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Group'; }; -THREE.Group.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Group + constructor: Group } ); + + +export { Group }; \ No newline at end of file diff --git a/src/objects/LOD.js b/src/objects/LOD.js index bb47fedeab55d6..9f0276298e70ca 100644 --- a/src/objects/LOD.js +++ b/src/objects/LOD.js @@ -1,12 +1,16 @@ +import { Vector3 } from '../math/Vector3'; +import { Object3D } from '../core/Object3D'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.LOD = function () { +function LOD () { + this.isLOD = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'LOD'; @@ -20,13 +24,13 @@ THREE.LOD = function () { }; -THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.LOD, + constructor: LOD, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source, false ); + Object3D.prototype.copy.call( this, source, false ); var levels = source.levels; @@ -86,7 +90,7 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), raycast: ( function () { - var matrixPosition = new THREE.Vector3(); + var matrixPosition = new Vector3(); return function raycast( raycaster, intersects ) { @@ -102,8 +106,8 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), update: function () { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); return function update( camera ) { @@ -147,7 +151,7 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), toJSON: function ( meta ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var data = Object3D.prototype.toJSON.call( this, meta ); data.object.levels = []; @@ -169,3 +173,6 @@ THREE.LOD.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { LOD }; \ No newline at end of file diff --git a/src/objects/LensFlare.js b/src/objects/LensFlare.js index 81c6dac73974a1..f4b732ac91e8ba 100644 --- a/src/objects/LensFlare.js +++ b/src/objects/LensFlare.js @@ -1,15 +1,21 @@ +import { Object3D } from '../core/Object3D'; +import { NormalBlending } from '../constants'; +import { Color } from '../math/Color'; +import { Vector3 } from '../math/Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.LensFlare = function ( texture, size, distance, blending, color ) { +function LensFlare ( texture, size, distance, blending, color ) { + this.isLensFlare = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.lensFlares = []; - this.positionScreen = new THREE.Vector3(); + this.positionScreen = new Vector3(); this.customUpdateCallback = undefined; if ( texture !== undefined ) { @@ -20,13 +26,13 @@ THREE.LensFlare = function ( texture, size, distance, blending, color ) { }; -THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.LensFlare, + constructor: LensFlare, copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.positionScreen.copy( source.positionScreen ); this.customUpdateCallback = source.customUpdateCallback; @@ -46,8 +52,8 @@ THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototy 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; + if ( color === undefined ) color = new Color( 0xffffff ); + if ( blending === undefined ) blending = NormalBlending; distance = Math.min( distance, Math.max( 0, distance ) ); @@ -92,3 +98,6 @@ THREE.LensFlare.prototype = Object.assign( Object.create( THREE.Object3D.prototy } } ); + + +export { LensFlare }; \ No newline at end of file diff --git a/src/objects/Line.js b/src/objects/Line.js index 3ac2a013de65dd..1d8d922afa2806 100644 --- a/src/objects/Line.js +++ b/src/objects/Line.js @@ -1,34 +1,44 @@ +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Vector3 } from '../math/Vector3'; +import { LineBasicMaterial } from '../materials/LineBasicMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { LineSegments } from './LineSegments'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Line = function ( geometry, material, mode ) { +function Line ( geometry, material, mode ) { + this.isLine = true; if ( mode === 1 ) { console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new THREE.LineSegments( geometry, material ); + return new LineSegments( geometry, material ); } - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Line'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); }; -THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Line, + constructor: Line, raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); return function raycast( raycaster, intersects ) { @@ -52,13 +62,13 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), inverseMatrix.getInverse( matrixWorld ); ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this instanceof THREE.LineSegments ? 2 : 1; + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var index = geometry.index; var attributes = geometry.attributes; @@ -135,7 +145,7 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { var vertices = geometry.vertices; var nbVertices = vertices.length; @@ -180,3 +190,6 @@ THREE.Line.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Line }; \ No newline at end of file diff --git a/src/objects/LineSegments.js b/src/objects/LineSegments.js index 60dde8671cf491..3ef59aa1596b1e 100644 --- a/src/objects/LineSegments.js +++ b/src/objects/LineSegments.js @@ -1,17 +1,23 @@ +import { Line } from './Line'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.LineSegments = function ( geometry, material ) { +function LineSegments ( geometry, material ) { + this.isLineSegments = true; - THREE.Line.call( this, geometry, material ); + Line.call( this, geometry, material ); this.type = 'LineSegments'; }; -THREE.LineSegments.prototype = Object.assign( Object.create( THREE.Line.prototype ), { +LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - constructor: THREE.LineSegments + constructor: LineSegments } ); + + +export { LineSegments }; \ No newline at end of file diff --git a/src/objects/Mesh.js b/src/objects/Mesh.js index 7fb17a69a998a4..7a1ca46ee424cb 100644 --- a/src/objects/Mesh.js +++ b/src/objects/Mesh.js @@ -1,3 +1,15 @@ +import { Vector3 } from '../math/Vector3'; +import { Vector2 } from '../math/Vector2'; +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Triangle } from '../math/Triangle'; +import { Face3 } from '../core/Face3'; +import { DoubleSide, BackSide, TrianglesDrawMode } from '../constants'; +import { MeshBasicMaterial } from '../materials/MeshBasicMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ @@ -5,24 +17,25 @@ * @author jonobr1 / http://jonobr1.com/ */ -THREE.Mesh = function ( geometry, material ) { +function Mesh ( geometry, material ) { + this.isMesh = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Mesh'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - this.drawMode = THREE.TrianglesDrawMode; + this.drawMode = TrianglesDrawMode; this.updateMorphTargets(); }; -THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Mesh, + constructor: Mesh, setDrawMode: function ( value ) { @@ -32,7 +45,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), copy: function ( source ) { - THREE.Object3D.prototype.copy.call( this, source ); + Object3D.prototype.copy.call( this, source ); this.drawMode = source.drawMode; @@ -75,30 +88,30 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - var tempA = new THREE.Vector3(); - var tempB = new THREE.Vector3(); - var tempC = new THREE.Vector3(); + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - var barycoord = new THREE.Vector3(); + var barycoord = new Vector3(); - var intersectionPoint = new THREE.Vector3(); - var intersectionPointWorld = new THREE.Vector3(); + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); uv1.multiplyScalar( barycoord.x ); uv2.multiplyScalar( barycoord.y ); @@ -115,13 +128,13 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), var intersect; var material = object.material; - if ( material.side === THREE.BackSide ) { + if ( material.side === BackSide ) { intersect = ray.intersectTriangle( pC, pB, pA, true, point ); } else { - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point ); + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); } @@ -162,7 +175,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ); + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); intersection.faceIndex = a; } @@ -203,7 +216,7 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), var uvs, intersection; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var a, b, c; var index = geometry.index; @@ -259,10 +272,10 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { var fvA, fvB, fvC; - var isFaceMaterial = material instanceof THREE.MultiMaterial; + var isFaceMaterial = (material && material.isMultiMaterial); var materials = isFaceMaterial === true ? material.materials : null; var vertices = geometry.vertices; @@ -350,3 +363,6 @@ THREE.Mesh.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), } } ); + + +export { Mesh }; \ No newline at end of file diff --git a/src/objects/Points.js b/src/objects/Points.js index 35af105e4dbf6e..411dab45587b20 100644 --- a/src/objects/Points.js +++ b/src/objects/Points.js @@ -1,27 +1,36 @@ +import { Sphere } from '../math/Sphere'; +import { Ray } from '../math/Ray'; +import { Matrix4 } from '../math/Matrix4'; +import { Object3D } from '../core/Object3D'; +import { Vector3 } from '../math/Vector3'; +import { PointsMaterial } from '../materials/PointsMaterial'; +import { BufferGeometry } from '../core/BufferGeometry'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.Points = function ( geometry, material ) { +function Points ( geometry, material ) { + this.isPoints = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Points'; - this.geometry = geometry !== undefined ? geometry : new THREE.BufferGeometry(); - this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); }; -THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Points, + constructor: Points, raycast: ( function () { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); return function raycast( raycaster, intersects ) { @@ -46,7 +55,7 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); var localThresholdSq = localThreshold * localThreshold; - var position = new THREE.Vector3(); + var position = new Vector3(); function testPoint( point, index ) { @@ -76,7 +85,7 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype } - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { var index = geometry.index; var attributes = geometry.attributes; @@ -131,3 +140,6 @@ THREE.Points.prototype = Object.assign( Object.create( THREE.Object3D.prototype } } ); + + +export { Points }; \ No newline at end of file diff --git a/src/objects/Skeleton.js b/src/objects/Skeleton.js index c5f2c97eee34e7..ba25f13712d71c 100644 --- a/src/objects/Skeleton.js +++ b/src/objects/Skeleton.js @@ -1,3 +1,8 @@ +import { Matrix4 } from '../math/Matrix4'; +import { FloatType, RGBAFormat } from '../constants'; +import { DataTexture } from '../textures/DataTexture'; +import { _Math } from '../math/Math'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -5,11 +10,12 @@ * @author ikerr / http://verold.com */ -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { +function Skeleton ( bones, boneInverses, useVertexTexture ) { + this.isSkeleton = true; this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - this.identityMatrix = new THREE.Matrix4(); + this.identityMatrix = new Matrix4(); // copy the bone array @@ -30,14 +36,14 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) ); + size = _Math.nextPowerOfTwo( Math.ceil( size ) ); size = Math.max( size, 4 ); 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 = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); } else { @@ -65,7 +71,7 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.boneInverses.push( new THREE.Matrix4() ); + this.boneInverses.push( new Matrix4() ); } @@ -75,7 +81,7 @@ THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { }; -Object.assign( THREE.Skeleton.prototype, { +Object.assign( Skeleton.prototype, { calculateInverses: function () { @@ -83,7 +89,7 @@ Object.assign( THREE.Skeleton.prototype, { for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - var inverse = new THREE.Matrix4(); + var inverse = new Matrix4(); if ( this.bones[ b ] ) { @@ -123,7 +129,7 @@ Object.assign( THREE.Skeleton.prototype, { if ( bone ) { - if ( bone.parent instanceof THREE.Bone ) { + if ( (bone.parent && bone.parent.isBone) ) { bone.matrix.getInverse( bone.parent.matrixWorld ); bone.matrix.multiply( bone.matrixWorld ); @@ -144,7 +150,7 @@ Object.assign( THREE.Skeleton.prototype, { update: ( function () { - var offsetMatrix = new THREE.Matrix4(); + var offsetMatrix = new Matrix4(); return function update() { @@ -173,8 +179,11 @@ Object.assign( THREE.Skeleton.prototype, { clone: function () { - return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); } } ); + + +export { Skeleton }; \ No newline at end of file diff --git a/src/objects/SkinnedMesh.js b/src/objects/SkinnedMesh.js index 8767cf16fa931b..c7d66de6772c33 100644 --- a/src/objects/SkinnedMesh.js +++ b/src/objects/SkinnedMesh.js @@ -1,18 +1,25 @@ +import { Mesh } from './Mesh'; +import { Vector4 } from '../math/Vector4'; +import { Skeleton } from './Skeleton'; +import { Bone } from './Bone'; +import { Matrix4 } from '../math/Matrix4'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { +function SkinnedMesh ( geometry, material, useVertexTexture ) { + this.isSkinnedMesh = true; - THREE.Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); this.type = 'SkinnedMesh'; this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); // init bones @@ -29,7 +36,7 @@ THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { gbone = this.geometry.bones[ b ]; - bone = new THREE.Bone( this ); + bone = new Bone( this ); bones.push( bone ); bone.name = gbone.name; @@ -61,14 +68,14 @@ THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { this.normalizeSkinWeights(); this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); }; -THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype ), { +SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - constructor: THREE.SkinnedMesh, + constructor: SkinnedMesh, bind: function( skeleton, bindMatrix ) { @@ -97,7 +104,7 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype normalizeSkinWeights: function () { - if ( this.geometry instanceof THREE.Geometry ) { + if ( (this.geometry && this.geometry.isGeometry) ) { for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { @@ -117,9 +124,9 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype } - } else if ( this.geometry instanceof THREE.BufferGeometry ) { + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - var vec = new THREE.Vector4(); + var vec = new Vector4(); var skinWeight = this.geometry.attributes.skinWeight; @@ -152,7 +159,7 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype updateMatrixWorld: function( force ) { - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + Mesh.prototype.updateMatrixWorld.call( this, true ); if ( this.bindMode === "attached" ) { @@ -177,3 +184,6 @@ THREE.SkinnedMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype } } ); + + +export { SkinnedMesh }; \ No newline at end of file diff --git a/src/objects/Sprite.js b/src/objects/Sprite.js index 082cf9be3e3106..b056655ed0485b 100644 --- a/src/objects/Sprite.js +++ b/src/objects/Sprite.js @@ -1,25 +1,30 @@ +import { Vector3 } from '../math/Vector3'; +import { Object3D } from '../core/Object3D'; +import { SpriteMaterial } from '../materials/SpriteMaterial'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Sprite = function ( material ) { +function Sprite ( material ) { + this.isSprite = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Sprite'; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); }; -THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), { +Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: THREE.Sprite, + constructor: Sprite, raycast: ( function () { - var matrixPosition = new THREE.Vector3(); + var matrixPosition = new Vector3(); return function raycast( raycaster, intersects ) { @@ -54,3 +59,6 @@ THREE.Sprite.prototype = Object.assign( Object.create( THREE.Object3D.prototype } } ); + + +export { Sprite }; \ No newline at end of file diff --git a/src/polyfills.js b/src/polyfills.js new file mode 100644 index 00000000000000..5afd4cd1c98444 --- /dev/null +++ b/src/polyfills.js @@ -0,0 +1,85 @@ +// Polyfills + +if ( Number.EPSILON === undefined ) { + + Number.EPSILON = Math.pow( 2, - 52 ); + +} + +// + +if ( Math.sign === undefined ) { + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + + Math.sign = function ( x ) { + + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + + }; + +} + +if ( Function.prototype.name === undefined ) { + + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + + Object.defineProperty( Function.prototype, 'name', { + + get: function () { + + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + + } + + } ); + +} + +if ( Object.assign === undefined ) { + + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + + ( function () { + + Object.assign = function ( target ) { + + 'use strict'; + + if ( target === undefined || target === null ) { + + throw new TypeError( 'Cannot convert undefined or null to object' ); + + } + + var output = Object( target ); + + for ( var index = 1; index < arguments.length; index ++ ) { + + var source = arguments[ index ]; + + if ( source !== undefined && source !== null ) { + + for ( var nextKey in source ) { + + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + + output[ nextKey ] = source[ nextKey ]; + + } + + } + + } + + } + + return output; + + }; + + } )(); + +} diff --git a/src/renderers/WebGLRenderTarget.js b/src/renderers/WebGLRenderTarget.js index 295ed6818c9e48..28528189fb6da7 100644 --- a/src/renderers/WebGLRenderTarget.js +++ b/src/renderers/WebGLRenderTarget.js @@ -1,3 +1,9 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { Texture } from '../textures/Texture'; +import { LinearFilter } from '../constants'; +import { Vector4 } from '../math/Vector4'; +import { _Math } from '../math/Math'; + /** * @author szimek / https://github.com/szimek/ * @author alteredq / http://alteredqualia.com/ @@ -9,23 +15,24 @@ * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */ -THREE.WebGLRenderTarget = function ( width, height, options ) { +function WebGLRenderTarget ( width, height, options ) { + this.isWebGLRenderTarget = true; - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.width = width; this.height = height; - this.scissor = new THREE.Vector4( 0, 0, width, height ); + this.scissor = new Vector4( 0, 0, width, height ); this.scissorTest = false; - this.viewport = new THREE.Vector4( 0, 0, width, height ); + this.viewport = new Vector4( 0, 0, width, height ); options = options || {}; - if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter; + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; @@ -33,7 +40,7 @@ THREE.WebGLRenderTarget = function ( width, height, options ) { }; -Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototype, { +Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { setSize: function ( width, height ) { @@ -81,3 +88,6 @@ Object.assign( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototyp } } ); + + +export { WebGLRenderTarget }; \ No newline at end of file diff --git a/src/renderers/WebGLRenderTargetCube.js b/src/renderers/WebGLRenderTargetCube.js index b64bb135b70c3e..b84faa384242ee 100644 --- a/src/renderers/WebGLRenderTargetCube.js +++ b/src/renderers/WebGLRenderTargetCube.js @@ -1,15 +1,21 @@ +import { WebGLRenderTarget } from './WebGLRenderTarget'; + /** * @author alteredq / http://alteredqualia.com */ -THREE.WebGLRenderTargetCube = function ( width, height, options ) { +function WebGLRenderTargetCube ( width, height, options ) { + this.isWebGLRenderTargetCube = this.isWebGLRenderTarget = true; - THREE.WebGLRenderTarget.call( this, width, height, options ); + WebGLRenderTarget.call( this, width, height, options ); this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 this.activeMipMapLevel = 0; }; -THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype ); -THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube; +WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); +WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; + + +export { WebGLRenderTargetCube }; \ No newline at end of file diff --git a/src/renderers/WebGLRenderer.js b/src/renderers/WebGLRenderer.js index 92f2c4454ceb74..662d5baa83d661 100644 --- a/src/renderers/WebGLRenderer.js +++ b/src/renderers/WebGLRenderer.js @@ -1,3 +1,36 @@ +import { MaxEquation, MinEquation, RGB_ETC1_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, SrcAlphaSaturateFactor, OneMinusDstColorFactor, DstColorFactor, OneMinusDstAlphaFactor, DstAlphaFactor, OneMinusSrcAlphaFactor, SrcAlphaFactor, OneMinusSrcColorFactor, SrcColorFactor, OneFactor, ZeroFactor, ReverseSubtractEquation, SubtractEquation, AddEquation, DepthFormat, LuminanceAlphaFormat, LuminanceFormat, RGBAFormat, RGBFormat, AlphaFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedShort565Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestFilter, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, FrontFaceDirectionCW, NoBlending, BackSide, DoubleSide, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, NoColors, FlatShading, LinearToneMapping } from '../constants'; +import { Matrix4 } from '../math/Matrix4'; +import { WebGLUniforms } from './webgl/WebGLUniforms'; +import { UniformsUtils } from './shaders/UniformsUtils'; +import { ShaderLib } from './shaders/ShaderLib'; +import { LensFlarePlugin } from './webgl/plugins/LensFlarePlugin'; +import { SpritePlugin } from './webgl/plugins/SpritePlugin'; +import { WebGLShadowMap } from './webgl/WebGLShadowMap'; +import { ShaderMaterial } from '../materials/ShaderMaterial'; +import { BoxBufferGeometry } from '../extras/geometries/BoxBufferGeometry'; +import { Mesh } from '../objects/Mesh'; +import { MeshBasicMaterial } from '../materials/MeshBasicMaterial'; +import { PlaneBufferGeometry } from '../extras/geometries/PlaneBufferGeometry'; +import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; +import { OrthographicCamera } from '../cameras/OrthographicCamera'; +import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer'; +import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer'; +import { WebGLLights } from './webgl/WebGLLights'; +import { WebGLPrograms } from './webgl/WebGLPrograms'; +import { WebGLObjects } from './webgl/WebGLObjects'; +import { WebGLTextures } from './webgl/WebGLTextures'; +import { WebGLProperties } from './webgl/WebGLProperties'; +import { WebGLState } from './webgl/WebGLState'; +import { WebGLCapabilities } from './webgl/WebGLCapabilities'; +import { BufferGeometry } from '../core/BufferGeometry'; +import { WebGLExtensions } from './webgl/WebGLExtensions'; +import { Vector3 } from '../math/Vector3'; +import { Sphere } from '../math/Sphere'; +import { WebGLClipping } from './webgl/WebGLClipping'; +import { Frustum } from '../math/Frustum'; +import { Vector4 } from '../math/Vector4'; +import { Color } from '../math/Color'; + /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ @@ -6,9 +39,10 @@ * @author tschw */ -THREE.WebGLRenderer = function ( parameters ) { +function WebGLRenderer ( parameters ) { + this.isWebGLRenderer = true; - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + console.log( 'THREE.WebGLRenderer', "80dev" ); parameters = parameters || {}; @@ -67,7 +101,7 @@ THREE.WebGLRenderer = function ( parameters ) { // tone mapping - this.toneMapping = THREE.LinearToneMapping; + this.toneMapping = LinearToneMapping; this.toneMappingExposure = 1.0; this.toneMappingWhitePoint = 1.0; @@ -89,10 +123,10 @@ THREE.WebGLRenderer = function ( parameters ) { _currentGeometryProgram = '', _currentCamera = null, - _currentScissor = new THREE.Vector4(), + _currentScissor = new Vector4(), _currentScissorTest = null, - _currentViewport = new THREE.Vector4(), + _currentViewport = new Vector4(), // @@ -100,7 +134,7 @@ THREE.WebGLRenderer = function ( parameters ) { // - _clearColor = new THREE.Color( 0x000000 ), + _clearColor = new Color( 0x000000 ), _clearAlpha = 0, _width = _canvas.width, @@ -108,28 +142,28 @@ THREE.WebGLRenderer = function ( parameters ) { _pixelRatio = 1, - _scissor = new THREE.Vector4( 0, 0, _width, _height ), + _scissor = new Vector4( 0, 0, _width, _height ), _scissorTest = false, - _viewport = new THREE.Vector4( 0, 0, _width, _height ), + _viewport = new Vector4( 0, 0, _width, _height ), // frustum - _frustum = new THREE.Frustum(), + _frustum = new Frustum(), // clipping - _clipping = new THREE.WebGLClipping(), + _clipping = new WebGLClipping(), _clippingEnabled = false, _localClippingEnabled = false, - _sphere = new THREE.Sphere(), + _sphere = new Sphere(), // camera matrices cache - _projScreenMatrix = new THREE.Matrix4(), + _projScreenMatrix = new Matrix4(), - _vector3 = new THREE.Vector3(), + _vector3 = new Vector3(), // light arrays cache @@ -229,7 +263,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - var extensions = new THREE.WebGLExtensions( _gl ); + var extensions = new WebGLExtensions( _gl ); extensions.get( 'WEBGL_depth_texture' ); extensions.get( 'OES_texture_float' ); @@ -241,40 +275,40 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extensions.get( 'OES_element_index_uint' ) ) { - THREE.BufferGeometry.MaxIndex = 4294967296; + BufferGeometry.MaxIndex = 4294967296; } - var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new THREE.WebGLProperties(); - var textures = new THREE.WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); - var objects = new THREE.WebGLObjects( _gl, properties, this.info ); - var programCache = new THREE.WebGLPrograms( this, capabilities ); - var lightCache = new THREE.WebGLLights(); + var state = new WebGLState( _gl, extensions, paramThreeToGL ); + var properties = new WebGLProperties(); + var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); + var objects = new WebGLObjects( _gl, properties, this.info ); + var programCache = new WebGLPrograms( this, capabilities ); + var lightCache = new WebGLLights(); this.info.programs = programCache.programs; - var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); // - var backgroundCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - var backgroundCamera2 = new THREE.PerspectiveCamera(); - var backgroundPlaneMesh = new THREE.Mesh( - new THREE.PlaneBufferGeometry( 2, 2 ), - new THREE.MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var backgroundCamera2 = new PerspectiveCamera(); + var backgroundPlaneMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) ); - var backgroundBoxShader = THREE.ShaderLib[ 'cube' ]; - var backgroundBoxMesh = new THREE.Mesh( - new THREE.BoxBufferGeometry( 5, 5, 5 ), - new THREE.ShaderMaterial( { + var backgroundBoxShader = ShaderLib[ 'cube' ]; + var backgroundBoxMesh = new Mesh( + new BoxBufferGeometry( 5, 5, 5 ), + new ShaderMaterial( { uniforms: backgroundBoxShader.uniforms, vertexShader: backgroundBoxShader.vertexShader, fragmentShader: backgroundBoxShader.fragmentShader, - side: THREE.BackSide, + side: BackSide, depthTest: false, depthWrite: false, fog: false @@ -334,15 +368,15 @@ THREE.WebGLRenderer = function ( parameters ) { // shadow map - var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects, capabilities ); + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); this.shadowMap = shadowMap; // Plugins - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); // API @@ -599,7 +633,7 @@ THREE.WebGLRenderer = function ( parameters ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) { + if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { @@ -644,7 +678,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + if ( object.hasColors && material.vertexColors !== NoColors ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); @@ -796,7 +830,7 @@ THREE.WebGLRenderer = function ( parameters ) { // - if ( object instanceof THREE.Mesh ) { + if ( (object && object.isMesh) ) { if ( material.wireframe === true ) { @@ -807,15 +841,15 @@ THREE.WebGLRenderer = function ( parameters ) { switch ( object.drawMode ) { - case THREE.TrianglesDrawMode: + case TrianglesDrawMode: renderer.setMode( _gl.TRIANGLES ); break; - case THREE.TriangleStripDrawMode: + case TriangleStripDrawMode: renderer.setMode( _gl.TRIANGLE_STRIP ); break; - case THREE.TriangleFanDrawMode: + case TriangleFanDrawMode: renderer.setMode( _gl.TRIANGLE_FAN ); break; @@ -824,7 +858,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.Line ) { + } else if ( (object && object.isLine) ) { var lineWidth = material.linewidth; @@ -832,7 +866,7 @@ THREE.WebGLRenderer = function ( parameters ) { state.setLineWidth( lineWidth * getTargetPixelRatio() ); - if ( object instanceof THREE.LineSegments ) { + if ( (object && object.isLineSegments) ) { renderer.setMode( _gl.LINES ); @@ -842,13 +876,13 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.Points ) { + } else if ( (object && object.isPoints) ) { renderer.setMode( _gl.POINTS ); } - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + if ( (geometry && geometry.isInstancedBufferGeometry) ) { if ( geometry.maxInstancedCount > 0 ) { @@ -868,7 +902,7 @@ THREE.WebGLRenderer = function ( parameters ) { var extension; - if ( geometry instanceof THREE.InstancedBufferGeometry ) { + if ( (geometry && geometry.isInstancedBufferGeometry) ) { extension = extensions.get( 'ANGLE_instanced_arrays' ); @@ -942,13 +976,13 @@ THREE.WebGLRenderer = function ( parameters ) { var size = geometryAttribute.itemSize; var buffer = objects.getAttributeBuffer( geometryAttribute ); - if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (geometryAttribute && geometryAttribute.isInterleavedBufferAttribute) ) { var data = geometryAttribute.data; var stride = data.stride; var offset = geometryAttribute.offset; - if ( data instanceof THREE.InstancedInterleavedBuffer ) { + if ( (data && data.isInstancedInterleavedBuffer) ) { state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); @@ -969,7 +1003,7 @@ THREE.WebGLRenderer = function ( parameters ) { } else { - if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) { + if ( (geometryAttribute && geometryAttribute.isInstancedBufferAttribute) ) { state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); @@ -1083,7 +1117,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.render = function ( scene, camera, renderTarget, forceClear ) { - if ( camera instanceof THREE.Camera === false ) { + if ( (camera && camera.isCamera) === false ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; @@ -1169,7 +1203,7 @@ THREE.WebGLRenderer = function ( parameters ) { glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } else if ( background instanceof THREE.Color ) { + } else if ( (background && background.isColor) ) { glClearColor( background.r, background.g, background.b, 1 ); @@ -1181,7 +1215,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( background instanceof THREE.CubeTexture ) { + if ( (background && background.isCubeTexture) ) { backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); @@ -1195,7 +1229,7 @@ THREE.WebGLRenderer = function ( parameters ) { _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - } else if ( background instanceof THREE.Texture ) { + } else if ( (background && background.isTexture) ) { backgroundPlaneMesh.material.map = background; @@ -1218,7 +1252,7 @@ THREE.WebGLRenderer = function ( parameters ) { // opaque pass (front-to-back order) - state.setBlending( THREE.NoBlending ); + state.setBlending( NoBlending ); renderObjects( opaqueObjects, camera, fog ); // transparent pass (back-to-front order) @@ -1356,11 +1390,11 @@ THREE.WebGLRenderer = function ( parameters ) { if ( object.layers.test( camera.layers ) ) { - if ( object instanceof THREE.Light ) { + if ( (object && object.isLight) ) { lights.push( object ); - } else if ( object instanceof THREE.Sprite ) { + } else if ( (object && object.isSprite) ) { if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { @@ -1368,11 +1402,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( object instanceof THREE.LensFlare ) { + } else if ( (object && object.isLensFlare) ) { lensFlares.push( object ); - } else if ( object instanceof THREE.ImmediateRenderObject ) { + } else if ( (object && object.isImmediateRenderObject) ) { if ( _this.sortObjects === true ) { @@ -1383,9 +1417,9 @@ THREE.WebGLRenderer = function ( parameters ) { pushRenderItem( object, null, object.material, _vector3.z, null ); - } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) { + } else if ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) { - if ( object instanceof THREE.SkinnedMesh ) { + if ( (object && object.isSkinnedMesh) ) { object.skeleton.update(); @@ -1406,7 +1440,7 @@ THREE.WebGLRenderer = function ( parameters ) { var geometry = objects.update( object ); - if ( material instanceof THREE.MultiMaterial ) { + if ( (material && material.isMultiMaterial) ) { var groups = geometry.groups; var materials = material.materials; @@ -1462,7 +1496,7 @@ THREE.WebGLRenderer = function ( parameters ) { object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - if ( object instanceof THREE.ImmediateRenderObject ) { + if ( (object && object.isImmediateRenderObject) ) { setMaterial( material ); @@ -1524,11 +1558,11 @@ THREE.WebGLRenderer = function ( parameters ) { if ( parameters.shaderID ) { - var shader = THREE.ShaderLib[ parameters.shaderID ]; + var shader = ShaderLib[ parameters.shaderID ]; materialProperties.__webglShader = { name: material.type, - uniforms: THREE.UniformsUtils.clone( shader.uniforms ), + uniforms: UniformsUtils.clone( shader.uniforms ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }; @@ -1589,8 +1623,8 @@ THREE.WebGLRenderer = function ( parameters ) { var uniforms = materialProperties.__webglShader.uniforms; - if ( ! ( material instanceof THREE.ShaderMaterial ) && - ! ( material instanceof THREE.RawShaderMaterial ) || + if ( ! ( (material && material.isShaderMaterial) ) && + ! ( (material && material.isRawShaderMaterial) ) || material.clipping === true ) { materialProperties.numClippingPlanes = _clipping.numPlanes; @@ -1623,22 +1657,22 @@ THREE.WebGLRenderer = function ( parameters ) { var progUniforms = materialProperties.program.getUniforms(), uniformsList = - THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); materialProperties.uniformsList = uniformsList; materialProperties.dynamicUniforms = - THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + WebGLUniforms.splitDynamic( uniformsList, uniforms ); } function setMaterial( material ) { - if ( material.side !== THREE.DoubleSide ) + if ( material.side !== DoubleSide ) state.enable( _gl.CULL_FACE ); else state.disable( _gl.CULL_FACE ); - state.setFlipSided( material.side === THREE.BackSide ); + state.setFlipSided( material.side === BackSide ); if ( material.transparent === true ) { @@ -1646,7 +1680,7 @@ THREE.WebGLRenderer = function ( parameters ) { } else { - state.setBlending( THREE.NoBlending ); + state.setBlending( NoBlending ); } @@ -1765,9 +1799,9 @@ THREE.WebGLRenderer = function ( parameters ) { // load material specific uniforms // (shader material also gets them for the sake of genericity) - if ( material instanceof THREE.ShaderMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || + if ( (material && material.isShaderMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || material.envMap ) { var uCamPos = p_uniforms.map.cameraPosition; @@ -1781,11 +1815,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.ShaderMaterial || + if ( (material && material.isMeshPhongMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshBasicMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isShaderMaterial) || material.skinning ) { p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); @@ -1851,11 +1885,11 @@ THREE.WebGLRenderer = function ( parameters ) { } - if ( material instanceof THREE.MeshBasicMaterial || - material instanceof THREE.MeshLambertMaterial || - material instanceof THREE.MeshPhongMaterial || - material instanceof THREE.MeshStandardMaterial || - material instanceof THREE.MeshDepthMaterial ) { + if ( (material && material.isMeshBasicMaterial) || + (material && material.isMeshLambertMaterial) || + (material && material.isMeshPhongMaterial) || + (material && material.isMeshStandardMaterial) || + (material && material.isMeshDepthMaterial) ) { refreshUniformsCommon( m_uniforms, material ); @@ -1863,36 +1897,36 @@ THREE.WebGLRenderer = function ( parameters ) { // refresh single material specific uniforms - if ( material instanceof THREE.LineBasicMaterial ) { + if ( (material && material.isLineBasicMaterial) ) { refreshUniformsLine( m_uniforms, material ); - } else if ( material instanceof THREE.LineDashedMaterial ) { + } else if ( (material && material.isLineDashedMaterial) ) { refreshUniformsLine( m_uniforms, material ); refreshUniformsDash( m_uniforms, material ); - } else if ( material instanceof THREE.PointsMaterial ) { + } else if ( (material && material.isPointsMaterial) ) { refreshUniformsPoints( m_uniforms, material ); - } else if ( material instanceof THREE.MeshLambertMaterial ) { + } else if ( (material && material.isMeshLambertMaterial) ) { refreshUniformsLambert( m_uniforms, material ); - } else if ( material instanceof THREE.MeshPhongMaterial ) { + } else if ( (material && material.isMeshPhongMaterial) ) { refreshUniformsPhong( m_uniforms, material ); - } else if ( material instanceof THREE.MeshPhysicalMaterial ) { + } else if ( (material && material.isMeshPhysicalMaterial) ) { refreshUniformsPhysical( m_uniforms, material ); - } else if ( material instanceof THREE.MeshStandardMaterial ) { + } else if ( (material && material.isMeshStandardMaterial) ) { refreshUniformsStandard( m_uniforms, material ); - } else if ( material instanceof THREE.MeshDepthMaterial ) { + } else if ( (material && material.isMeshDepthMaterial) ) { if ( material.displacementMap ) { @@ -1902,13 +1936,13 @@ THREE.WebGLRenderer = function ( parameters ) { } - } else if ( material instanceof THREE.MeshNormalMaterial ) { + } else if ( (material && material.isMeshNormalMaterial) ) { m_uniforms.opacity.value = material.opacity; } - THREE.WebGLUniforms.upload( + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); } @@ -1927,10 +1961,10 @@ THREE.WebGLRenderer = function ( parameters ) { if ( dynUniforms !== null ) { - THREE.WebGLUniforms.evalDynamic( + WebGLUniforms.evalDynamic( dynUniforms, m_uniforms, object, camera ); - THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); } @@ -2014,7 +2048,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( uvScaleMap !== undefined ) { // backwards compatibility - if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) { + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { uvScaleMap = uvScaleMap.texture; @@ -2033,7 +2067,7 @@ THREE.WebGLRenderer = function ( parameters ) { // WebGLRenderTargetCube will be flipped for backwards compatibility // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1; + uniforms.flipEnvMap.value = ( ! ( (material.envMap && material.envMap.isCubeTexture) ) ) ? 1 : - 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; @@ -2079,12 +2113,12 @@ THREE.WebGLRenderer = function ( parameters ) { uniforms.fogColor.value = fog.color; - if ( fog instanceof THREE.Fog ) { + if ( (fog && fog.isFog) ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; - } else if ( fog instanceof THREE.FogExp2 ) { + } else if ( (fog && fog.isFogExp2) ) { uniforms.fogDensity.value = fog.density; @@ -2282,13 +2316,13 @@ THREE.WebGLRenderer = function ( parameters ) { shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - if ( light instanceof THREE.AmbientLight ) { + if ( (light && light.isAmbientLight) ) { r += color.r * intensity; g += color.g * intensity; b += color.b * intensity; - } else if ( light instanceof THREE.DirectionalLight ) { + } else if ( (light && light.isDirectionalLight) ) { var uniforms = lightCache.get( light ); @@ -2312,7 +2346,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; _lights.directional[ directionalLength ++ ] = uniforms; - } else if ( light instanceof THREE.SpotLight ) { + } else if ( (light && light.isSpotLight) ) { var uniforms = lightCache.get( light ); @@ -2345,7 +2379,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; _lights.spot[ spotLength ++ ] = uniforms; - } else if ( light instanceof THREE.PointLight ) { + } else if ( (light && light.isPointLight) ) { var uniforms = lightCache.get( light ); @@ -2370,7 +2404,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4(); + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); } @@ -2381,7 +2415,7 @@ THREE.WebGLRenderer = function ( parameters ) { _lights.point[ pointLength ++ ] = uniforms; - } else if ( light instanceof THREE.HemisphereLight ) { + } else if ( (light && light.isHemisphereLight) ) { var uniforms = lightCache.get( light ); @@ -2416,7 +2450,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.setFaceCulling = function ( cullFace, frontFaceDirection ) { state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); }; @@ -2448,7 +2482,7 @@ THREE.WebGLRenderer = function ( parameters ) { // backwards compatibility: peel texture.texture return function setTexture2D( texture, slot ) { - if ( texture instanceof THREE.WebGLRenderTarget ) { + if ( (texture && texture.isWebGLRenderTarget) ) { if ( ! warned ) { @@ -2493,7 +2527,7 @@ THREE.WebGLRenderer = function ( parameters ) { return function setTextureCube( texture, slot ) { // backwards compatibility: peel texture.texture - if ( texture instanceof THREE.WebGLRenderTargetCube ) { + if ( (texture && texture.isWebGLRenderTargetCube) ) { if ( ! warned ) { @@ -2508,7 +2542,7 @@ THREE.WebGLRenderer = function ( parameters ) { // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture // TODO: unify these code paths - if ( texture instanceof THREE.CubeTexture || + if ( (texture && texture.isCubeTexture) || ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ @@ -2544,7 +2578,7 @@ THREE.WebGLRenderer = function ( parameters ) { } - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); var framebuffer; if ( renderTarget ) { @@ -2600,7 +2634,7 @@ THREE.WebGLRenderer = function ( parameters ) { this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) { + if ( (renderTarget && renderTarget.isWebGLRenderTarget) === false ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); return; @@ -2625,17 +2659,17 @@ THREE.WebGLRenderer = function ( parameters ) { var texture = renderTarget.texture; - if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); return; } - if ( texture.type !== THREE.UnsignedByteType && + if ( texture.type !== UnsignedByteType && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && - ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && - ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && + ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); return; @@ -2678,70 +2712,70 @@ THREE.WebGLRenderer = function ( parameters ) { var extension; - 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 === RepeatWrapping ) return _gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === 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 === NearestFilter ) return _gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - if ( p === THREE.LinearFilter ) return _gl.LINEAR; - if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + if ( p === LinearFilter ) return _gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - if ( p === THREE.ByteType ) return _gl.BYTE; - if ( p === THREE.ShortType ) return _gl.SHORT; - if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === THREE.IntType ) return _gl.INT; - if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === THREE.FloatType ) return _gl.FLOAT; + if ( p === ByteType ) return _gl.BYTE; + if ( p === ShortType ) return _gl.SHORT; + if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === IntType ) return _gl.INT; + if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === FloatType ) return _gl.FLOAT; extension = extensions.get( 'OES_texture_half_float' ); if ( extension !== null ) { - if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES; + if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; } - if ( p === THREE.AlphaFormat ) return _gl.ALPHA; - if ( p === THREE.RGBFormat ) return _gl.RGB; - if ( p === THREE.RGBAFormat ) return _gl.RGBA; - if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; - if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT; + if ( p === AlphaFormat ) return _gl.ALPHA; + if ( p === RGBFormat ) return _gl.RGB; + if ( p === RGBAFormat ) return _gl.RGBA; + if ( p === LuminanceFormat ) return _gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; - if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - if ( p === THREE.ZeroFactor ) return _gl.ZERO; - if ( p === THREE.OneFactor ) return _gl.ONE; - if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + if ( p === ZeroFactor ) return _gl.ZERO; + if ( p === OneFactor ) return _gl.ONE; + if ( p === SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; - if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); 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; + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; } @@ -2749,10 +2783,10 @@ THREE.WebGLRenderer = function ( parameters ) { 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; + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } @@ -2760,7 +2794,7 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extension !== null ) { - if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; } @@ -2768,8 +2802,8 @@ THREE.WebGLRenderer = function ( parameters ) { if ( extension !== null ) { - if ( p === THREE.MinEquation ) return extension.MIN_EXT; - if ( p === THREE.MaxEquation ) return extension.MAX_EXT; + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; } @@ -2778,3 +2812,6 @@ THREE.WebGLRenderer = function ( parameters ) { } }; + + +export { WebGLRenderer }; diff --git a/src/renderers/shaders/ShaderChunk.js b/src/renderers/shaders/ShaderChunk.js index 6ffa98166bfa21..121315103be17d 100644 --- a/src/renderers/shaders/ShaderChunk.js +++ b/src/renderers/shaders/ShaderChunk.js @@ -1 +1,217 @@ -THREE.ShaderChunk = {}; +import alphamap_fragment from './ShaderChunk/alphamap_fragment.glsl'; +import alphamap_pars_fragment from './ShaderChunk/alphamap_pars_fragment.glsl'; +import alphatest_fragment from './ShaderChunk/alphatest_fragment.glsl'; +import ambient_pars from './ShaderChunk/ambient_pars.glsl'; +import aomap_fragment from './ShaderChunk/aomap_fragment.glsl'; +import aomap_pars_fragment from './ShaderChunk/aomap_pars_fragment.glsl'; +import begin_vertex from './ShaderChunk/begin_vertex.glsl'; +import beginnormal_vertex from './ShaderChunk/beginnormal_vertex.glsl'; +import bsdfs from './ShaderChunk/bsdfs.glsl'; +import bumpmap_pars_fragment from './ShaderChunk/bumpmap_pars_fragment.glsl'; +import clipping_planes_fragment from './ShaderChunk/clipping_planes_fragment.glsl'; +import clipping_planes_pars_fragment from './ShaderChunk/clipping_planes_pars_fragment.glsl'; +import clipping_planes_pars_vertex from './ShaderChunk/clipping_planes_pars_vertex.glsl'; +import clipping_planes_vertex from './ShaderChunk/clipping_planes_vertex.glsl'; +import color_fragment from './ShaderChunk/color_fragment.glsl'; +import color_pars_fragment from './ShaderChunk/color_pars_fragment.glsl'; +import color_pars_vertex from './ShaderChunk/color_pars_vertex.glsl'; +import color_vertex from './ShaderChunk/color_vertex.glsl'; +import common from './ShaderChunk/common.glsl'; +import cube_uv_reflection_fragment from './ShaderChunk/cube_uv_reflection_fragment.glsl'; +import defaultnormal_vertex from './ShaderChunk/defaultnormal_vertex.glsl'; +import displacementmap_pars_vertex from './ShaderChunk/displacementmap_pars_vertex.glsl'; +import displacementmap_vertex from './ShaderChunk/displacementmap_vertex.glsl'; +import emissivemap_fragment from './ShaderChunk/emissivemap_fragment.glsl'; +import emissivemap_pars_fragment from './ShaderChunk/emissivemap_pars_fragment.glsl'; +import encodings_fragment from './ShaderChunk/encodings_fragment.glsl'; +import encodings_pars_fragment from './ShaderChunk/encodings_pars_fragment.glsl'; +import envmap_fragment from './ShaderChunk/envmap_fragment.glsl'; +import envmap_pars_fragment from './ShaderChunk/envmap_pars_fragment.glsl'; +import envmap_pars_vertex from './ShaderChunk/envmap_pars_vertex.glsl'; +import envmap_vertex from './ShaderChunk/envmap_vertex.glsl'; +import fog_fragment from './ShaderChunk/fog_fragment.glsl'; +import fog_pars_fragment from './ShaderChunk/fog_pars_fragment.glsl'; +import lightmap_fragment from './ShaderChunk/lightmap_fragment.glsl'; +import lightmap_pars_fragment from './ShaderChunk/lightmap_pars_fragment.glsl'; +import lights_lambert_vertex from './ShaderChunk/lights_lambert_vertex.glsl'; +import lights_pars from './ShaderChunk/lights_pars.glsl'; +import lights_phong_fragment from './ShaderChunk/lights_phong_fragment.glsl'; +import lights_phong_pars_fragment from './ShaderChunk/lights_phong_pars_fragment.glsl'; +import lights_physical_fragment from './ShaderChunk/lights_physical_fragment.glsl'; +import lights_physical_pars_fragment from './ShaderChunk/lights_physical_pars_fragment.glsl'; +import lights_template from './ShaderChunk/lights_template.glsl'; +import logdepthbuf_fragment from './ShaderChunk/logdepthbuf_fragment.glsl'; +import logdepthbuf_pars_fragment from './ShaderChunk/logdepthbuf_pars_fragment.glsl'; +import logdepthbuf_pars_vertex from './ShaderChunk/logdepthbuf_pars_vertex.glsl'; +import logdepthbuf_vertex from './ShaderChunk/logdepthbuf_vertex.glsl'; +import map_fragment from './ShaderChunk/map_fragment.glsl'; +import map_pars_fragment from './ShaderChunk/map_pars_fragment.glsl'; +import map_particle_fragment from './ShaderChunk/map_particle_fragment.glsl'; +import map_particle_pars_fragment from './ShaderChunk/map_particle_pars_fragment.glsl'; +import metalnessmap_fragment from './ShaderChunk/metalnessmap_fragment.glsl'; +import metalnessmap_pars_fragment from './ShaderChunk/metalnessmap_pars_fragment.glsl'; +import morphnormal_vertex from './ShaderChunk/morphnormal_vertex.glsl'; +import morphtarget_pars_vertex from './ShaderChunk/morphtarget_pars_vertex.glsl'; +import morphtarget_vertex from './ShaderChunk/morphtarget_vertex.glsl'; +import normal_flip from './ShaderChunk/normal_flip.glsl'; +import normal_fragment from './ShaderChunk/normal_fragment.glsl'; +import normalmap_pars_fragment from './ShaderChunk/normalmap_pars_fragment.glsl'; +import packing from './ShaderChunk/packing.glsl'; +import premultiplied_alpha_fragment from './ShaderChunk/premultiplied_alpha_fragment.glsl'; +import project_vertex from './ShaderChunk/project_vertex.glsl'; +import roughnessmap_fragment from './ShaderChunk/roughnessmap_fragment.glsl'; +import roughnessmap_pars_fragment from './ShaderChunk/roughnessmap_pars_fragment.glsl'; +import shadowmap_pars_fragment from './ShaderChunk/shadowmap_pars_fragment.glsl'; +import shadowmap_pars_vertex from './ShaderChunk/shadowmap_pars_vertex.glsl'; +import shadowmap_vertex from './ShaderChunk/shadowmap_vertex.glsl'; +import shadowmask_pars_fragment from './ShaderChunk/shadowmask_pars_fragment.glsl'; +import skinbase_vertex from './ShaderChunk/skinbase_vertex.glsl'; +import skinning_pars_vertex from './ShaderChunk/skinning_pars_vertex.glsl'; +import skinning_vertex from './ShaderChunk/skinning_vertex.glsl'; +import skinnormal_vertex from './ShaderChunk/skinnormal_vertex.glsl'; +import specularmap_fragment from './ShaderChunk/specularmap_fragment.glsl'; +import specularmap_pars_fragment from './ShaderChunk/specularmap_pars_fragment.glsl'; +import tonemapping_fragment from './ShaderChunk/tonemapping_fragment.glsl'; +import tonemapping_pars_fragment from './ShaderChunk/tonemapping_pars_fragment.glsl'; +import uv_pars_fragment from './ShaderChunk/uv_pars_fragment.glsl'; +import uv_pars_vertex from './ShaderChunk/uv_pars_vertex.glsl'; +import uv_vertex from './ShaderChunk/uv_vertex.glsl'; +import uv2_pars_fragment from './ShaderChunk/uv2_pars_fragment.glsl'; +import uv2_pars_vertex from './ShaderChunk/uv2_pars_vertex.glsl'; +import uv2_vertex from './ShaderChunk/uv2_vertex.glsl'; +import worldpos_vertex from './ShaderChunk/worldpos_vertex.glsl'; + +import cube_frag from './ShaderLib/cube_frag.glsl'; +import cube_vert from './ShaderLib/cube_vert.glsl'; +import depth_frag from './ShaderLib/depth_frag.glsl'; +import depth_vert from './ShaderLib/depth_vert.glsl'; +import distanceRGBA_frag from './ShaderLib/distanceRGBA_frag.glsl'; +import distanceRGBA_vert from './ShaderLib/distanceRGBA_vert.glsl'; +import equirect_frag from './ShaderLib/equirect_frag.glsl'; +import equirect_vert from './ShaderLib/equirect_vert.glsl'; +import linedashed_frag from './ShaderLib/linedashed_frag.glsl'; +import linedashed_vert from './ShaderLib/linedashed_vert.glsl'; +import meshbasic_frag from './ShaderLib/meshbasic_frag.glsl'; +import meshbasic_vert from './ShaderLib/meshbasic_vert.glsl'; +import meshlambert_frag from './ShaderLib/meshlambert_frag.glsl'; +import meshlambert_vert from './ShaderLib/meshlambert_vert.glsl'; +import meshphong_frag from './ShaderLib/meshphong_frag.glsl'; +import meshphong_vert from './ShaderLib/meshphong_vert.glsl'; +import meshphysical_frag from './ShaderLib/meshphysical_frag.glsl'; +import meshphysical_vert from './ShaderLib/meshphysical_vert.glsl'; +import normal_frag from './ShaderLib/normal_frag.glsl'; +import normal_vert from './ShaderLib/normal_vert.glsl'; +import points_frag from './ShaderLib/points_frag.glsl'; +import points_vert from './ShaderLib/points_vert.glsl'; +import shadow_frag from './ShaderLib/shadow_frag.glsl'; +import shadow_vert from './ShaderLib/shadow_vert.glsl'; + +export var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + ambient_pars: ambient_pars, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_vertex: envmap_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars: lights_pars, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_template: lights_template, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_flip: normal_flip, + normal_fragment: normal_fragment, + normalmap_pars_fragment: normalmap_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, + + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert +}; diff --git a/src/renderers/shaders/ShaderLib.js b/src/renderers/shaders/ShaderLib.js index 73370ec75b94c0..030cccdef44534 100644 --- a/src/renderers/shaders/ShaderLib.js +++ b/src/renderers/shaders/ShaderLib.js @@ -1,3 +1,11 @@ +import { ShaderChunk } from './ShaderChunk'; +import { UniformsUtils } from './UniformsUtils'; +import { Vector3 } from '../../math/Vector3'; +import { UniformsLib } from './UniformsLib'; +import { Color } from '../../math/Color'; + +var ShaderLib; + /** * Webgl Shader Library for three.js * @@ -7,90 +15,90 @@ */ -THREE.ShaderLib = { +ShaderLib = { 'basic': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'fog' ] + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'fog' ] ] ), - vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ] + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] }, 'lambert': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) } + "emissive" : { value: new Color( 0x000000 ) } } ] ), - vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ] + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] }, 'phong': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'bumpmap' ], + UniformsLib[ 'normalmap' ], + UniformsLib[ 'displacementmap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) }, - "specular" : { value: new THREE.Color( 0x111111 ) }, + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, "shininess": { value: 30 } } ] ), - vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ] + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] }, 'standard': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'aomap' ], - THREE.UniformsLib[ 'lightmap' ], - THREE.UniformsLib[ 'emissivemap' ], - THREE.UniformsLib[ 'bumpmap' ], - THREE.UniformsLib[ 'normalmap' ], - THREE.UniformsLib[ 'displacementmap' ], - THREE.UniformsLib[ 'roughnessmap' ], - THREE.UniformsLib[ 'metalnessmap' ], - THREE.UniformsLib[ 'fog' ], - THREE.UniformsLib[ 'lights' ], + UniformsLib[ 'common' ], + UniformsLib[ 'aomap' ], + UniformsLib[ 'lightmap' ], + UniformsLib[ 'emissivemap' ], + UniformsLib[ 'bumpmap' ], + UniformsLib[ 'normalmap' ], + UniformsLib[ 'displacementmap' ], + UniformsLib[ 'roughnessmap' ], + UniformsLib[ 'metalnessmap' ], + UniformsLib[ 'fog' ], + UniformsLib[ 'lights' ], { - "emissive" : { value: new THREE.Color( 0x000000 ) }, + "emissive" : { value: new Color( 0x000000 ) }, "roughness": { value: 0.5 }, "metalness": { value: 0 }, "envMapIntensity" : { value: 1 }, // temporary @@ -98,31 +106,31 @@ THREE.ShaderLib = { ] ), - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }, 'points': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'points' ], - THREE.UniformsLib[ 'fog' ] + UniformsLib[ 'points' ], + UniformsLib[ 'fog' ] ] ), - vertexShader: THREE.ShaderChunk[ 'points_vert' ], - fragmentShader: THREE.ShaderChunk[ 'points_frag' ] + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] }, 'dashed': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'fog' ], + UniformsLib[ 'common' ], + UniformsLib[ 'fog' ], { "scale" : { value: 1 }, @@ -132,22 +140,22 @@ THREE.ShaderLib = { ] ), - vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ], - fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ] + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] }, 'depth': { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.UniformsLib[ 'common' ], - THREE.UniformsLib[ 'displacementmap' ] + UniformsLib[ 'common' ], + UniformsLib[ 'displacementmap' ] ] ), - vertexShader: THREE.ShaderChunk[ 'depth_vert' ], - fragmentShader: THREE.ShaderChunk[ 'depth_frag' ] + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] }, @@ -159,8 +167,8 @@ THREE.ShaderLib = { }, - vertexShader: THREE.ShaderChunk[ 'normal_vert' ], - fragmentShader: THREE.ShaderChunk[ 'normal_frag' ] + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] }, @@ -176,8 +184,8 @@ THREE.ShaderLib = { "opacity": { value: 1.0 } }, - vertexShader: THREE.ShaderChunk[ 'cube_vert' ], - fragmentShader: THREE.ShaderChunk[ 'cube_frag' ] + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] }, @@ -192,8 +200,8 @@ THREE.ShaderLib = { "tFlip": { value: - 1 } }, - vertexShader: THREE.ShaderChunk[ 'equirect_vert' ], - fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ] + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] }, @@ -201,22 +209,22 @@ THREE.ShaderLib = { uniforms: { - "lightPos": { value: new THREE.Vector3() } + "lightPos": { value: new Vector3() } }, - vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ] + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] } }; -THREE.ShaderLib[ 'physical' ] = { +ShaderLib[ 'physical' ] = { - uniforms: THREE.UniformsUtils.merge( [ + uniforms: UniformsUtils.merge( [ - THREE.ShaderLib[ 'standard' ].uniforms, + ShaderLib[ 'standard' ].uniforms, { "clearCoat": { value: 0 }, @@ -225,7 +233,10 @@ THREE.ShaderLib[ 'physical' ] = { ] ), - vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ] + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] }; + + +export { ShaderLib }; \ No newline at end of file diff --git a/src/renderers/shaders/UniformsLib.js b/src/renderers/shaders/UniformsLib.js index 72c9098acefb4e..0a3dab0d6cb8b6 100644 --- a/src/renderers/shaders/UniformsLib.js +++ b/src/renderers/shaders/UniformsLib.js @@ -1,16 +1,22 @@ +import { Vector4 } from '../../math/Vector4'; +import { Color } from '../../math/Color'; +import { Vector2 } from '../../math/Vector2'; + +var UniformsLib; + /** * Uniforms library for shared webgl shaders */ -THREE.UniformsLib = { +UniformsLib = { common: { - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, + "diffuse": { value: new Color( 0xeeeeee ) }, "opacity": { value: 1.0 }, "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, "specularMap": { value: null }, "alphaMap": { value: null }, @@ -52,7 +58,7 @@ THREE.UniformsLib = { normalmap: { "normalMap": { value: null }, - "normalScale": { value: new THREE.Vector2( 1, 1 ) } + "normalScale": { value: new Vector2( 1, 1 ) } }, @@ -81,7 +87,7 @@ THREE.UniformsLib = { "fogDensity": { value: 0.00025 }, "fogNear": { value: 1 }, "fogFar": { value: 2000 }, - "fogColor": { value: new THREE.Color( 0xffffff ) } + "fogColor": { value: new Color( 0xffffff ) } }, @@ -145,13 +151,16 @@ THREE.UniformsLib = { points: { - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, + "diffuse": { value: new Color( 0xeeeeee ) }, "opacity": { value: 1.0 }, "size": { value: 1.0 }, "scale": { value: 1.0 }, "map": { value: null }, - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) } + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } } }; + + +export { UniformsLib }; \ No newline at end of file diff --git a/src/renderers/shaders/UniformsUtils.js b/src/renderers/shaders/UniformsUtils.js index b8b33ff0889926..15b65dd89688d8 100644 --- a/src/renderers/shaders/UniformsUtils.js +++ b/src/renderers/shaders/UniformsUtils.js @@ -1,8 +1,10 @@ +var UniformsUtils; + /** * Uniform Utilities */ -THREE.UniformsUtils = { +UniformsUtils = { merge: function ( uniforms ) { @@ -36,13 +38,13 @@ THREE.UniformsUtils = { 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.Matrix3 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + if ( (parameter_src && parameter_src.isColor) || + (parameter_src && parameter_src.isVector2) || + (parameter_src && parameter_src.isVector3) || + (parameter_src && parameter_src.isVector4) || + (parameter_src && parameter_src.isMatrix3) || + (parameter_src && parameter_src.isMatrix4) || + (parameter_src && parameter_src.isTexture) ) { uniforms_dst[ u ][ p ] = parameter_src.clone(); @@ -65,3 +67,6 @@ THREE.UniformsUtils = { } }; + + +export { UniformsUtils }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLBufferRenderer.js b/src/renderers/webgl/WebGLBufferRenderer.js index 700344dddbc405..c0d6ee42c810cd 100644 --- a/src/renderers/webgl/WebGLBufferRenderer.js +++ b/src/renderers/webgl/WebGLBufferRenderer.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { +function WebGLBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLBufferRenderer = true; var mode; @@ -37,7 +38,7 @@ THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { var count = 0; - if ( position instanceof THREE.InterleavedBufferAttribute ) { + if ( (position && position.isInterleavedBufferAttribute) ) { count = position.data.count; @@ -62,3 +63,6 @@ THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) { this.renderInstances = renderInstances; }; + + +export { WebGLBufferRenderer }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLCapabilities.js b/src/renderers/webgl/WebGLCapabilities.js index ea08751785e3d3..854bd93c05b4d8 100644 --- a/src/renderers/webgl/WebGLCapabilities.js +++ b/src/renderers/webgl/WebGLCapabilities.js @@ -1,4 +1,5 @@ -THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { +function WebGLCapabilities ( gl, extensions, parameters ) { + this.isWebGLCapabilities = true; var maxAnisotropy; @@ -88,3 +89,6 @@ THREE.WebGLCapabilities = function ( gl, extensions, parameters ) { } }; + + +export { WebGLCapabilities }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLClipping.js b/src/renderers/webgl/WebGLClipping.js index 095ecee094957a..ff8c044f2bcbc2 100644 --- a/src/renderers/webgl/WebGLClipping.js +++ b/src/renderers/webgl/WebGLClipping.js @@ -1,4 +1,8 @@ -THREE.WebGLClipping = function() { +import { Matrix3 } from '../../math/Matrix3'; +import { Plane } from '../../math/Plane'; + +function WebGLClipping() { + this.isWebGLClipping = true; var scope = this, @@ -7,8 +11,8 @@ THREE.WebGLClipping = function() { localClippingEnabled = false, renderingShadows = false, - plane = new THREE.Plane(), - viewNormalMatrix = new THREE.Matrix3(), + plane = new Plane(), + viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; @@ -150,3 +154,6 @@ THREE.WebGLClipping = function() { }; + + +export { WebGLClipping }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLExtensions.js b/src/renderers/webgl/WebGLExtensions.js index d7f972d9b76f55..05d7e516da291e 100644 --- a/src/renderers/webgl/WebGLExtensions.js +++ b/src/renderers/webgl/WebGLExtensions.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLExtensions = function ( gl ) { +function WebGLExtensions ( gl ) { + this.isWebGLExtensions = true; var extensions = {}; @@ -56,3 +57,6 @@ THREE.WebGLExtensions = function ( gl ) { }; }; + + +export { WebGLExtensions }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLGeometries.js b/src/renderers/webgl/WebGLGeometries.js index 9b63e24a92726d..377b6115eca5aa 100644 --- a/src/renderers/webgl/WebGLGeometries.js +++ b/src/renderers/webgl/WebGLGeometries.js @@ -1,8 +1,11 @@ +import { BufferGeometry } from '../../core/BufferGeometry'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLGeometries = function ( gl, properties, info ) { +function WebGLGeometries ( gl, properties, info ) { + this.isWebGLGeometries = true; var geometries = {}; @@ -20,15 +23,15 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { var buffergeometry; - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { buffergeometry = geometry; - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { if ( geometry._bufferGeometry === undefined ) { - geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object ); + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); } @@ -91,7 +94,7 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { function getAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { return properties.get( attribute.data ).__webglBuffer; @@ -126,7 +129,7 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { function removeAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { properties.delete( attribute.data ); @@ -141,3 +144,6 @@ THREE.WebGLGeometries = function ( gl, properties, info ) { this.get = get; }; + + +export { WebGLGeometries }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLIndexedBufferRenderer.js b/src/renderers/webgl/WebGLIndexedBufferRenderer.js index f528f4cb23c01e..7db13c9e029244 100644 --- a/src/renderers/webgl/WebGLIndexedBufferRenderer.js +++ b/src/renderers/webgl/WebGLIndexedBufferRenderer.js @@ -2,7 +2,8 @@ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { +function WebGLIndexedBufferRenderer ( _gl, extensions, _infoRender ) { + this.isWebGLIndexedBufferRenderer = true; var mode; @@ -64,3 +65,6 @@ THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) { this.renderInstances = renderInstances; }; + + +export { WebGLIndexedBufferRenderer }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLLights.js b/src/renderers/webgl/WebGLLights.js index 924ab55a1b67e8..79919392703225 100644 --- a/src/renderers/webgl/WebGLLights.js +++ b/src/renderers/webgl/WebGLLights.js @@ -1,8 +1,13 @@ +import { Color } from '../../math/Color'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLLights = function () { +function WebGLLights () { + this.isWebGLLights = true; var lights = {}; @@ -20,21 +25,21 @@ THREE.WebGLLights = function () { case 'DirectionalLight': uniforms = { - direction: new THREE.Vector3(), - color: new THREE.Color(), + direction: new Vector3(), + color: new Color(), shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'SpotLight': uniforms = { - position: new THREE.Vector3(), - direction: new THREE.Vector3(), - color: new THREE.Color(), + position: new Vector3(), + direction: new Vector3(), + color: new Color(), distance: 0, coneCos: 0, penumbraCos: 0, @@ -43,29 +48,29 @@ THREE.WebGLLights = function () { shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'PointLight': uniforms = { - position: new THREE.Vector3(), - color: new THREE.Color(), + position: new Vector3(), + color: new Color(), distance: 0, decay: 0, shadow: false, shadowBias: 0, shadowRadius: 1, - shadowMapSize: new THREE.Vector2() + shadowMapSize: new Vector2() }; break; case 'HemisphereLight': uniforms = { - direction: new THREE.Vector3(), - skyColor: new THREE.Color(), - groundColor: new THREE.Color() + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() }; break; @@ -78,3 +83,6 @@ THREE.WebGLLights = function () { }; }; + + +export { WebGLLights }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLObjects.js b/src/renderers/webgl/WebGLObjects.js index 1bda38fde34efc..295709f56fc31f 100644 --- a/src/renderers/webgl/WebGLObjects.js +++ b/src/renderers/webgl/WebGLObjects.js @@ -1,10 +1,14 @@ +import { BufferAttribute } from '../../core/BufferAttribute'; +import { WebGLGeometries } from './WebGLGeometries'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLObjects = function ( gl, properties, info ) { +function WebGLObjects ( gl, properties, info ) { + this.isWebGLObjects = true; - var geometries = new THREE.WebGLGeometries( gl, properties, info ); + var geometries = new WebGLGeometries( gl, properties, info ); // @@ -14,7 +18,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { var geometry = geometries.get( object ); - if ( object.geometry instanceof THREE.Geometry ) { + if ( (object.geometry && object.geometry.isGeometry) ) { geometry.updateFromObject( object ); @@ -57,7 +61,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { function updateAttribute( attribute, bufferType ) { - var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute; + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; var attributeProperties = properties.get( data ); @@ -115,7 +119,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { function getAttributeBuffer( attribute ) { - if ( attribute instanceof THREE.InterleavedBufferAttribute ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { return properties.get( attribute.data ).__webglBuffer; @@ -179,7 +183,7 @@ THREE.WebGLObjects = function ( gl, properties, info ) { // console.timeEnd( 'wireframe' ); var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 ); + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); @@ -223,3 +227,6 @@ THREE.WebGLObjects = function ( gl, properties, info ) { this.update = update; }; + + +export { WebGLObjects }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLProgram.js b/src/renderers/webgl/WebGLProgram.js index 1e0353b56b9633..881ce70f71185f 100644 --- a/src/renderers/webgl/WebGLProgram.js +++ b/src/renderers/webgl/WebGLProgram.js @@ -1,4 +1,11 @@ -THREE.WebGLProgram = ( function () { +import { WebGLUniforms } from './WebGLUniforms'; +import { WebGLShader } from './WebGLShader'; +import { ShaderChunk } from '../shaders/ShaderChunk'; +import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, EquirectangularRefractionMapping, CubeRefractionMapping, SphericalReflectionMapping, EquirectangularReflectionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, CineonToneMapping, Uncharted2ToneMapping, ReinhardToneMapping, LinearToneMapping, GammaEncoding, RGBDEncoding, RGBM16Encoding, RGBM7Encoding, RGBEEncoding, sRGBEncoding, LinearEncoding } from '../../constants'; + +var WebGLProgram; + +WebGLProgram = ( function () { var programIdCount = 0; @@ -6,19 +13,19 @@ THREE.WebGLProgram = ( function () { switch ( encoding ) { - case THREE.LinearEncoding: + case LinearEncoding: return [ 'Linear','( value )' ]; - case THREE.sRGBEncoding: + case sRGBEncoding: return [ 'sRGB','( value )' ]; - case THREE.RGBEEncoding: + case RGBEEncoding: return [ 'RGBE','( value )' ]; - case THREE.RGBM7Encoding: + case RGBM7Encoding: return [ 'RGBM','( value, 7.0 )' ]; - case THREE.RGBM16Encoding: + case RGBM16Encoding: return [ 'RGBM','( value, 16.0 )' ]; - case THREE.RGBDEncoding: + case RGBDEncoding: return [ 'RGBD','( value, 256.0 )' ]; - case THREE.GammaEncoding: + case GammaEncoding: return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; default: throw new Error( 'unsupported encoding: ' + encoding ); @@ -47,19 +54,19 @@ THREE.WebGLProgram = ( function () { switch ( toneMapping ) { - case THREE.LinearToneMapping: + case LinearToneMapping: toneMappingName = "Linear"; break; - case THREE.ReinhardToneMapping: + case ReinhardToneMapping: toneMappingName = "Reinhard"; break; - case THREE.Uncharted2ToneMapping: + case Uncharted2ToneMapping: toneMappingName = "Uncharted2"; break; - case THREE.CineonToneMapping: + case CineonToneMapping: toneMappingName = "OptimizedCineon"; break; @@ -148,7 +155,7 @@ THREE.WebGLProgram = ( function () { function replace( match, include ) { - var replace = THREE.ShaderChunk[ include ]; + var replace = ShaderChunk[ include ]; if ( replace === undefined ) { @@ -198,11 +205,11 @@ THREE.WebGLProgram = ( function () { var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - if ( parameters.shadowMapType === THREE.PCFShadowMap ) { + if ( parameters.shadowMapType === PCFShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; @@ -216,22 +223,22 @@ THREE.WebGLProgram = ( function () { switch ( material.envMap.mapping ) { - case THREE.CubeReflectionMapping: - case THREE.CubeRefractionMapping: + case CubeReflectionMapping: + case CubeRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; break; - case THREE.CubeUVReflectionMapping: - case THREE.CubeUVRefractionMapping: + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; break; - case THREE.EquirectangularReflectionMapping: - case THREE.EquirectangularRefractionMapping: + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; break; - case THREE.SphericalReflectionMapping: + case SphericalReflectionMapping: envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; break; @@ -239,8 +246,8 @@ THREE.WebGLProgram = ( function () { switch ( material.envMap.mapping ) { - case THREE.CubeRefractionMapping: - case THREE.EquirectangularRefractionMapping: + case CubeRefractionMapping: + case EquirectangularRefractionMapping: envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; break; @@ -248,15 +255,15 @@ THREE.WebGLProgram = ( function () { switch ( material.combine ) { - case THREE.MultiplyOperation: + case MultiplyOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; break; - case THREE.MixOperation: + case MixOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; break; - case THREE.AddOperation: + case AddOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; break; @@ -280,7 +287,7 @@ THREE.WebGLProgram = ( function () { var prefixVertex, prefixFragment; - if ( material instanceof THREE.RawShaderMaterial ) { + if ( (material && material.isRawShaderMaterial) ) { prefixVertex = [ @@ -455,11 +462,11 @@ THREE.WebGLProgram = ( function () { 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', - ( parameters.toneMapping !== THREE.NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== THREE.NoToneMapping ) ? THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== THREE.NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', + ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? THREE.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', @@ -479,7 +486,7 @@ THREE.WebGLProgram = ( function () { fragmentShader = parseIncludes( fragmentShader, parameters ); fragmentShader = replaceLightNums( fragmentShader, parameters ); - if ( material instanceof THREE.ShaderMaterial === false ) { + if ( (material && material.isShaderMaterial) === false ) { vertexShader = unrollLoops( vertexShader ); fragmentShader = unrollLoops( fragmentShader ); @@ -492,8 +499,8 @@ THREE.WebGLProgram = ( function () { // console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); - var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); - var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); gl.attachShader( program, glVertexShader ); gl.attachShader( program, glFragmentShader ); @@ -580,7 +587,7 @@ THREE.WebGLProgram = ( function () { if ( cachedUniforms === undefined ) { cachedUniforms = - new THREE.WebGLUniforms( gl, program, renderer ); + new WebGLUniforms( gl, program, renderer ); } @@ -652,3 +659,6 @@ THREE.WebGLProgram = ( function () { }; } )(); + + +export { WebGLProgram }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLPrograms.js b/src/renderers/webgl/WebGLPrograms.js index 45398df0e0c4c4..504bb9cbcd1e17 100644 --- a/src/renderers/webgl/WebGLPrograms.js +++ b/src/renderers/webgl/WebGLPrograms.js @@ -1,4 +1,8 @@ -THREE.WebGLPrograms = function ( renderer, capabilities ) { +import { WebGLProgram } from './WebGLProgram'; +import { BackSide, DoubleSide, FlatShading, CubeUVRefractionMapping, CubeUVReflectionMapping, GammaEncoding, LinearEncoding } from '../../constants'; + +function WebGLPrograms ( renderer, capabilities ) { + this.isWebGLPrograms = true; var programs = []; @@ -49,7 +53,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { var maxBones = nVertexMatrices; - if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { + if ( object !== undefined && (object && object.isSkinnedMesh) ) { maxBones = Math.min( object.skeleton.bones.length, maxBones ); @@ -73,13 +77,13 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { if ( ! map ) { - encoding = THREE.LinearEncoding; + encoding = LinearEncoding; - } else if ( map instanceof THREE.Texture ) { + } else if ( (map && map.isTexture) ) { encoding = map.encoding; - } else if ( map instanceof THREE.WebGLRenderTarget ) { + } else if ( (map && map.isWebGLRenderTarget) ) { console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); encoding = map.texture.encoding; @@ -87,9 +91,9 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) { + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - encoding = THREE.GammaEncoding; + encoding = GammaEncoding; } @@ -133,7 +137,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { envMap: !! material.envMap, envMapMode: material.envMap && material.envMap.mapping, envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ), + envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), lightMap: !! material.lightMap, aoMap: !! material.aoMap, emissiveMap: !! material.emissiveMap, @@ -152,9 +156,9 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { fog: !! fog, useFog: material.fog, - fogExp: fog instanceof THREE.FogExp2, + fogExp: (fog && fog.isFogExp2), - flatShading: material.shading === THREE.FlatShading, + flatShading: material.shading === FlatShading, sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, @@ -184,8 +188,8 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { premultipliedAlpha: material.premultipliedAlpha, alphaTest: material.alphaTest, - doubleSided: material.side === THREE.DoubleSide, - flipSided: material.side === THREE.BackSide, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false @@ -253,7 +257,7 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { if ( program === undefined ) { - program = new THREE.WebGLProgram( renderer, code, material, parameters ); + program = new WebGLProgram( renderer, code, material, parameters ); programs.push( program ); } @@ -282,3 +286,6 @@ THREE.WebGLPrograms = function ( renderer, capabilities ) { this.programs = programs; }; + + +export { WebGLPrograms }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLProperties.js b/src/renderers/webgl/WebGLProperties.js index 7637b85b79d8b4..b213545c0afeec 100644 --- a/src/renderers/webgl/WebGLProperties.js +++ b/src/renderers/webgl/WebGLProperties.js @@ -2,7 +2,8 @@ * @author fordacious / fordacious.github.io */ -THREE.WebGLProperties = function () { +function WebGLProperties () { + this.isWebGLProperties = true; var properties = {}; @@ -35,3 +36,6 @@ THREE.WebGLProperties = function () { }; }; + + +export { WebGLProperties }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLShader.js b/src/renderers/webgl/WebGLShader.js index 6fcbc37e60aebb..93ed5445681f58 100644 --- a/src/renderers/webgl/WebGLShader.js +++ b/src/renderers/webgl/WebGLShader.js @@ -1,4 +1,6 @@ -THREE.WebGLShader = ( function () { +var WebGLShader; + +WebGLShader = ( function () { function addLineNumbers( string ) { @@ -41,3 +43,6 @@ THREE.WebGLShader = ( function () { }; } )(); + + +export { WebGLShader }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLShadowMap.js b/src/renderers/webgl/WebGLShadowMap.js index 45016804159132..452dfe379f0fa1 100644 --- a/src/renderers/webgl/WebGLShadowMap.js +++ b/src/renderers/webgl/WebGLShadowMap.js @@ -1,22 +1,35 @@ +import { FrontSide, BackSide, DoubleSide, RGBAFormat, NearestFilter, PCFShadowMap, RGBADepthPacking } from '../../constants'; +import { WebGLRenderTarget } from '../WebGLRenderTarget'; +import { ShaderMaterial } from '../../materials/ShaderMaterial'; +import { UniformsUtils } from '../shaders/UniformsUtils'; +import { ShaderLib } from '../shaders/ShaderLib'; +import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial'; +import { Vector4 } from '../../math/Vector4'; +import { Vector3 } from '../../math/Vector3'; +import { Vector2 } from '../../math/Vector2'; +import { Matrix4 } from '../../math/Matrix4'; +import { Frustum } from '../../math/Frustum'; + /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { +function WebGLShadowMap ( _renderer, _lights, _objects, capabilities ) { + this.isWebGLShadowMap = true; var _gl = _renderer.context, _state = _renderer.state, - _frustum = new THREE.Frustum(), - _projScreenMatrix = new THREE.Matrix4(), + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), _lightShadows = _lights.shadows, - _shadowMapSize = new THREE.Vector2(), - _maxShadowMapSize = new THREE.Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - _lookTarget = new THREE.Vector3(), - _lightPositionWorld = new THREE.Vector3(), + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), _renderList = [], @@ -31,28 +44,28 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _materialCache = {}; var cubeDirections = [ - new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ), - new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 ) + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) ]; var cubeUps = [ - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), - new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 ) + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) ]; var cube2DViewPorts = [ - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(), - new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4() + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() ]; // init - var depthMaterialTemplate = new THREE.MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = THREE.RGBADepthPacking; + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; depthMaterialTemplate.clipping = true; - var distanceShader = THREE.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms ); + var distanceShader = ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms ); for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { @@ -65,7 +78,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _depthMaterials[ i ] = depthMaterial; - var distanceMaterial = new THREE.ShaderMaterial( { + var distanceMaterial = new ShaderMaterial( { defines: { 'USE_SHADOWMAP': '' }, @@ -90,7 +103,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { this.autoUpdate = true; this.needsUpdate = false; - this.type = THREE.PCFShadowMap; + this.type = PCFShadowMap; this.renderReverseSided = true; this.renderSingleSided = true; @@ -129,7 +142,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { _shadowMapSize.copy( shadow.mapSize ); _shadowMapSize.min( _maxShadowMapSize ); - if ( light instanceof THREE.PointLight ) { + if ( (light && light.isPointLight) ) { faceCount = 6; isPointLight = true; @@ -175,15 +188,15 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( shadow.map === null ) { - var pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat }; + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadowCamera.updateProjectionMatrix(); } - if ( shadow instanceof THREE.SpotLightShadow ) { + if ( (shadow && shadow.isSpotLightShadow) ) { shadow.update( light ); @@ -255,7 +268,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { var geometry = _objects.update( object ); var material = object.material; - if ( material instanceof THREE.MultiMaterial ) { + if ( (material && material.isMultiMaterial) ) { var groups = geometry.groups; var materials = material.materials; @@ -318,11 +331,11 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( material.morphTargets ) { - if ( geometry instanceof THREE.BufferGeometry ) { + if ( (geometry && geometry.isBufferGeometry) ) { useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - } else if ( geometry instanceof THREE.Geometry ) { + } else if ( (geometry && geometry.isGeometry) ) { useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; @@ -330,7 +343,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { } - var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning; + var useSkinning = (object && object.isSkinnedMesh) && material.skinning; var variantIndex = 0; @@ -381,16 +394,16 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { var side = material.side; - if ( scope.renderSingleSided && side == THREE.DoubleSide ) { + if ( scope.renderSingleSided && side == DoubleSide ) { - side = THREE.FrontSide; + side = FrontSide; } if ( scope.renderReverseSided ) { - if ( side === THREE.FrontSide ) side = THREE.BackSide; - else if ( side === THREE.BackSide ) side = THREE.FrontSide; + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; } @@ -416,7 +429,7 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { if ( object.visible === false ) return; - if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) { + if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { @@ -444,3 +457,6 @@ THREE.WebGLShadowMap = function ( _renderer, _lights, _objects, capabilities ) { } }; + + +export { WebGLShadowMap }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLState.js b/src/renderers/webgl/WebGLState.js index b03b5b09b31cce..f389dbe92d207a 100644 --- a/src/renderers/webgl/WebGLState.js +++ b/src/renderers/webgl/WebGLState.js @@ -1,15 +1,19 @@ +import { NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceFront, CullFaceBack, CullFaceNone, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NoBlending, NormalBlending } from '../../constants'; +import { Vector4 } from '../../math/Vector4'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { +function WebGLState ( gl, extensions, paramThreeToGL ) { + this.isWebGLState = true; var _this = this; this.buffers = { - color: new THREE.WebGLColorBuffer( gl, this ), - depth: new THREE.WebGLDepthBuffer( gl, this ), - stencil: new THREE.WebGLStencilBuffer( gl, this ) + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) }; var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); @@ -45,8 +49,8 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { var currentTextureSlot = null; var currentBoundTextures = {}; - var currentScissor = new THREE.Vector4(); - var currentViewport = new THREE.Vector4(); + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); function createTexture( type, target, count ) { @@ -80,14 +84,14 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.clearStencil( 0 ); this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( THREE.LessEqualDepth ); + this.setDepthFunc( LessEqualDepth ); this.setFlipSided( false ); - this.setCullFace( THREE.CullFaceBack ); + this.setCullFace( CullFaceBack ); this.enable( gl.CULL_FACE ); this.enable( gl.BLEND ); - this.setBlending( THREE.NormalBlending ); + this.setBlending( NormalBlending ); }; @@ -208,7 +212,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - if ( blending !== THREE.NoBlending ) { + if ( blending !== NoBlending ) { this.enable( gl.BLEND ); @@ -222,7 +226,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - if ( blending === THREE.AdditiveBlending ) { + if ( blending === AdditiveBlending ) { if ( premultipliedAlpha ) { @@ -236,7 +240,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - } else if ( blending === THREE.SubtractiveBlending ) { + } else if ( blending === SubtractiveBlending ) { if ( premultipliedAlpha ) { @@ -250,7 +254,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - } else if ( blending === THREE.MultiplyBlending ) { + } else if ( blending === MultiplyBlending ) { if ( premultipliedAlpha ) { @@ -285,7 +289,7 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { } - if ( blending === THREE.CustomBlending ) { + if ( blending === CustomBlending ) { blendEquationAlpha = blendEquationAlpha || blendEquation; blendSrcAlpha = blendSrcAlpha || blendSrc; @@ -398,17 +402,17 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { this.setCullFace = function ( cullFace ) { - if ( cullFace !== THREE.CullFaceNone ) { + if ( cullFace !== CullFaceNone ) { this.enable( gl.CULL_FACE ); if ( cullFace !== currentCullFace ) { - if ( cullFace === THREE.CullFaceBack ) { + if ( cullFace === CullFaceBack ) { gl.cullFace( gl.BACK ); - } else if ( cullFace === THREE.CullFaceFront ) { + } else if ( cullFace === CullFaceFront ) { gl.cullFace( gl.FRONT ); @@ -637,13 +641,14 @@ THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { }; -THREE.WebGLColorBuffer = function ( gl, state ) { +function WebGLColorBuffer ( gl, state ) { + this.isWebGLColorBuffer = true; var locked = false; - var color = new THREE.Vector4(); + var color = new Vector4(); var currentColorMask = null; - var currentColorClear = new THREE.Vector4(); + var currentColorClear = new Vector4(); this.setMask = function ( colorMask ) { @@ -680,13 +685,14 @@ THREE.WebGLColorBuffer = function ( gl, state ) { locked = false; currentColorMask = null; - currentColorClear = new THREE.Vector4(); + currentColorClear = new Vector4(); }; }; -THREE.WebGLDepthBuffer = function( gl, state ) { +function WebGLDepthBuffer( gl, state ) { + this.isWebGLDepthBuffer = true; var locked = false; @@ -727,42 +733,42 @@ THREE.WebGLDepthBuffer = function( gl, state ) { switch ( depthFunc ) { - case THREE.NeverDepth: + case NeverDepth: gl.depthFunc( gl.NEVER ); break; - case THREE.AlwaysDepth: + case AlwaysDepth: gl.depthFunc( gl.ALWAYS ); break; - case THREE.LessDepth: + case LessDepth: gl.depthFunc( gl.LESS ); break; - case THREE.LessEqualDepth: + case LessEqualDepth: gl.depthFunc( gl.LEQUAL ); break; - case THREE.EqualDepth: + case EqualDepth: gl.depthFunc( gl.EQUAL ); break; - case THREE.GreaterEqualDepth: + case GreaterEqualDepth: gl.depthFunc( gl.GEQUAL ); break; - case THREE.GreaterDepth: + case GreaterDepth: gl.depthFunc( gl.GREATER ); break; - case THREE.NotEqualDepth: + case NotEqualDepth: gl.depthFunc( gl.NOTEQUAL ); break; @@ -814,7 +820,8 @@ THREE.WebGLDepthBuffer = function( gl, state ) { }; -THREE.WebGLStencilBuffer = function ( gl, state ) { +function WebGLStencilBuffer ( gl, state ) { + this.isWebGLStencilBuffer = true; var locked = false; @@ -917,3 +924,6 @@ THREE.WebGLStencilBuffer = function ( gl, state ) { }; }; + + +export { WebGLStencilBuffer, WebGLDepthBuffer, WebGLColorBuffer, WebGLState }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLTextures.js b/src/renderers/webgl/WebGLTextures.js index e22a485e0826ab..cc12748d233753 100644 --- a/src/renderers/webgl/WebGLTextures.js +++ b/src/renderers/webgl/WebGLTextures.js @@ -1,8 +1,12 @@ +import { LinearFilter, NearestFilter, RGBFormat, RGBAFormat, FloatType, HalfFloatType, ClampToEdgeWrapping, NearestMipMapLinearFilter, NearestMipMapNearestFilter } from '../../constants'; +import { _Math } from '../../math/Math'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { +function WebGLTextures ( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + this.isWebGLTextures = true; var _infoMemory = info.memory; var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); @@ -37,7 +41,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function isPowerOfTwo( image ) { - return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ); + return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height ); } @@ -46,8 +50,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = THREE.Math.nearestPowerOfTwo( image.width ); - canvas.height = THREE.Math.nearestPowerOfTwo( image.height ); + canvas.width = _Math.nearestPowerOfTwo( image.width ); + canvas.height = _Math.nearestPowerOfTwo( image.height ); var context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, canvas.width, canvas.height ); @@ -64,8 +68,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function textureNeedsPowerOfTwo( texture ) { - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; return false; @@ -75,7 +79,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie function filterFallback ( f ) { - if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { return _gl.NEAREST; @@ -158,7 +162,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie } - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { for ( var i = 0; i < 6; i ++ ) { @@ -236,8 +240,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - var isCompressed = texture instanceof THREE.CompressedTexture; - var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture; + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); var cubeImage = []; @@ -284,7 +288,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie mipmap = mipmaps[ j ]; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { @@ -353,7 +357,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) { + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); @@ -362,7 +366,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _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 ) { + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); @@ -374,8 +378,8 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie if ( extension ) { - if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { @@ -425,13 +429,13 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var mipmap, mipmaps = texture.mipmaps; - if ( texture instanceof THREE.DepthTexture ) { + if ( (texture && texture.isDepthTexture) ) { // populate depth texture with dummy data var internalFormat = _gl.DEPTH_COMPONENT; - if ( texture.type === THREE.FloatType ) { + if ( texture.type === FloatType ) { if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); internalFormat = _gl.DEPTH_COMPONENT32F; @@ -445,7 +449,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - } else if ( texture instanceof THREE.DataTexture ) { + } else if ( (texture && texture.isDataTexture) ) { // use manually created mipmaps if available // if there are no manual mipmaps @@ -468,13 +472,13 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie } - } else if ( texture instanceof THREE.CompressedTexture ) { + } else if ( (texture && texture.isCompressedTexture) ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; - if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) { + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { @@ -572,12 +576,12 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie // Setup resources for a Depth Texture for a FBO (needs an extension) function setupDepthTexture ( framebuffer, renderTarget ) { - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) { + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); @@ -604,7 +608,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var renderTargetProperties = properties.get( renderTarget ); - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); if ( renderTarget.depthTexture ) { @@ -652,7 +656,7 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie _infoMemory.textures ++; - var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); // Setup framebuffer @@ -715,10 +719,10 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie var texture = renderTarget.texture; if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== THREE.NearestFilter && - texture.minFilter !== THREE.LinearFilter ) { + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; var webglTexture = properties.get( texture ).__webglTexture; state.bindTexture( target, webglTexture ); @@ -736,3 +740,6 @@ THREE.WebGLTextures = function ( _gl, extensions, state, properties, capabilitie this.updateRenderTargetMipmap = updateRenderTargetMipmap; }; + + +export { WebGLTextures }; \ No newline at end of file diff --git a/src/renderers/webgl/WebGLUniforms.js b/src/renderers/webgl/WebGLUniforms.js index 9a954170dcaf74..ca68371f0a0562 100644 --- a/src/renderers/webgl/WebGLUniforms.js +++ b/src/renderers/webgl/WebGLUniforms.js @@ -1,3 +1,8 @@ +import { CubeTexture } from '../../textures/CubeTexture'; +import { Texture } from '../../textures/Texture'; + +var WebGLUniforms; + /** * * Uniforms of a program. @@ -53,10 +58,10 @@ * */ -THREE.WebGLUniforms = ( function() { // scope +WebGLUniforms = ( function() { // scope - var emptyTexture = new THREE.Texture(); - var emptyCubeTexture = new THREE.CubeTexture(); + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); // --- Base for inner nodes (including the root) --- @@ -600,3 +605,6 @@ THREE.WebGLUniforms = ( function() { // scope return WebGLUniforms; } )(); + + +export { WebGLUniforms }; \ No newline at end of file diff --git a/src/renderers/webgl/plugins/LensFlarePlugin.js b/src/renderers/webgl/plugins/LensFlarePlugin.js index 788aa8a0003b85..fd836c2802ad87 100644 --- a/src/renderers/webgl/plugins/LensFlarePlugin.js +++ b/src/renderers/webgl/plugins/LensFlarePlugin.js @@ -1,9 +1,14 @@ +import { Box2 } from '../../../math/Box2'; +import { Vector2 } from '../../../math/Vector2'; +import { Vector3 } from '../../../math/Vector3'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.LensFlarePlugin = function ( renderer, flares ) { +function LensFlarePlugin ( renderer, flares ) { + this.isLensFlarePlugin = true; var gl = renderer.context; var state = renderer.state; @@ -181,19 +186,19 @@ THREE.LensFlarePlugin = function ( renderer, flares ) { if ( flares.length === 0 ) return; - var tempPosition = new THREE.Vector3(); + var tempPosition = new Vector3(); var invAspect = viewport.w / viewport.z, halfViewportWidth = viewport.z * 0.5, halfViewportHeight = viewport.w * 0.5; var size = 16 / viewport.w, - scale = new THREE.Vector2( size * invAspect, size ); + scale = new Vector2( size * invAspect, size ); - var screenPosition = new THREE.Vector3( 1, 1, 0 ), - screenPositionPixels = new THREE.Vector2( 1, 1 ); + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - var validArea = new THREE.Box2(); + var validArea = new Box2(); validArea.min.set( 0, 0 ); validArea.max.set( viewport.z - 16, viewport.w - 16 ); @@ -380,3 +385,6 @@ THREE.LensFlarePlugin = function ( renderer, flares ) { } }; + + +export { LensFlarePlugin }; \ No newline at end of file diff --git a/src/renderers/webgl/plugins/SpritePlugin.js b/src/renderers/webgl/plugins/SpritePlugin.js index 8b65cf0662534e..f1abbbbfeb98e9 100644 --- a/src/renderers/webgl/plugins/SpritePlugin.js +++ b/src/renderers/webgl/plugins/SpritePlugin.js @@ -1,9 +1,14 @@ +import { Texture } from '../../../textures/Texture'; +import { Vector3 } from '../../../math/Vector3'; +import { Quaternion } from '../../../math/Quaternion'; + /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ -THREE.SpritePlugin = function ( renderer, sprites ) { +function SpritePlugin ( renderer, sprites ) { + this.isSpritePlugin = true; var gl = renderer.context; var state = renderer.state; @@ -15,9 +20,9 @@ THREE.SpritePlugin = function ( renderer, sprites ) { // decompose matrixWorld - var spritePosition = new THREE.Vector3(); - var spriteRotation = new THREE.Quaternion(); - var spriteScale = new THREE.Vector3(); + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); function init() { @@ -80,7 +85,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { context.fillStyle = 'white'; context.fillRect( 0, 0, 8, 8 ); - texture = new THREE.Texture( canvas ); + texture = new Texture( canvas ); texture.needsUpdate = true; } @@ -126,7 +131,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - if ( fog instanceof THREE.Fog ) { + if ( (fog && fog.isFog) ) { gl.uniform1f( uniforms.fogNear, fog.near ); gl.uniform1f( uniforms.fogFar, fog.far ); @@ -135,7 +140,7 @@ THREE.SpritePlugin = function ( renderer, sprites ) { oldFogType = 1; sceneFogType = 1; - } else if ( fog instanceof THREE.FogExp2 ) { + } else if ( (fog && fog.isFogExp2) ) { gl.uniform1f( uniforms.fogDensity, fog.density ); @@ -371,3 +376,6 @@ THREE.SpritePlugin = function ( renderer, sprites ) { } }; + + +export { SpritePlugin }; \ No newline at end of file diff --git a/src/scenes/Fog.js b/src/scenes/Fog.js index cb9b5e08ba9418..d35d8f2fc9066f 100644 --- a/src/scenes/Fog.js +++ b/src/scenes/Fog.js @@ -1,21 +1,27 @@ +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.Fog = function ( color, near, far ) { +function Fog ( color, near, far ) { + this.isFog = true; this.name = ''; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.near = ( near !== undefined ) ? near : 1; this.far = ( far !== undefined ) ? far : 1000; }; -THREE.Fog.prototype.clone = function () { +Fog.prototype.clone = function () { - return new THREE.Fog( this.color.getHex(), this.near, this.far ); + return new Fog( this.color.getHex(), this.near, this.far ); }; + + +export { Fog }; \ No newline at end of file diff --git a/src/scenes/FogExp2.js b/src/scenes/FogExp2.js index 20247e95107f34..177640d1a18eb1 100644 --- a/src/scenes/FogExp2.js +++ b/src/scenes/FogExp2.js @@ -1,19 +1,25 @@ +import { Color } from '../math/Color'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ -THREE.FogExp2 = function ( color, density ) { +function FogExp2 ( color, density ) { + this.isFogExp2 = true; this.name = ''; - this.color = new THREE.Color( color ); + this.color = new Color( color ); this.density = ( density !== undefined ) ? density : 0.00025; }; -THREE.FogExp2.prototype.clone = function () { +FogExp2.prototype.clone = function () { - return new THREE.FogExp2( this.color.getHex(), this.density ); + return new FogExp2( this.color.getHex(), this.density ); }; + + +export { FogExp2 }; \ No newline at end of file diff --git a/src/scenes/Scene.js b/src/scenes/Scene.js index 91436e2136aa06..9a49df52262812 100644 --- a/src/scenes/Scene.js +++ b/src/scenes/Scene.js @@ -1,10 +1,13 @@ +import { Object3D } from '../core/Object3D'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.Scene = function () { +function Scene () { + this.isScene = this.isObject3D = true; - THREE.Object3D.call( this ); + Object3D.call( this ); this.type = 'Scene'; @@ -16,12 +19,12 @@ THREE.Scene = function () { }; -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; +Scene.prototype = Object.create( Object3D.prototype ); +Scene.prototype.constructor = Scene; -THREE.Scene.prototype.copy = function ( source, recursive ) { +Scene.prototype.copy = function ( source, recursive ) { - THREE.Object3D.prototype.copy.call( this, source, recursive ); + Object3D.prototype.copy.call( this, source, recursive ); if ( source.background !== null ) this.background = source.background.clone(); if ( source.fog !== null ) this.fog = source.fog.clone(); @@ -33,3 +36,6 @@ THREE.Scene.prototype.copy = function ( source, recursive ) { return this; }; + + +export { Scene }; \ No newline at end of file diff --git a/src/textures/CanvasTexture.js b/src/textures/CanvasTexture.js index baf661ca1802e7..e73815a9248414 100644 --- a/src/textures/CanvasTexture.js +++ b/src/textures/CanvasTexture.js @@ -1,14 +1,20 @@ +import { Texture } from './Texture'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { +function CanvasTexture ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isCanvasTexture = this.isTexture = true; - THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.needsUpdate = true; }; -THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture; +CanvasTexture.prototype = Object.create( Texture.prototype ); +CanvasTexture.prototype.constructor = CanvasTexture; + + +export { CanvasTexture }; \ No newline at end of file diff --git a/src/textures/CompressedTexture.js b/src/textures/CompressedTexture.js index 3e8937e5561ef0..c9821f9f08f354 100644 --- a/src/textures/CompressedTexture.js +++ b/src/textures/CompressedTexture.js @@ -1,10 +1,13 @@ +import { Texture } from './Texture'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { +function CompressedTexture ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isCompressedTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { width: width, height: height }; this.mipmaps = mipmaps; @@ -21,5 +24,8 @@ THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mappi }; -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; +CompressedTexture.prototype = Object.create( Texture.prototype ); +CompressedTexture.prototype.constructor = CompressedTexture; + + +export { CompressedTexture }; \ No newline at end of file diff --git a/src/textures/CubeTexture.js b/src/textures/CubeTexture.js index 77023b6f7cd554..f9355cb73f4f54 100644 --- a/src/textures/CubeTexture.js +++ b/src/textures/CubeTexture.js @@ -1,22 +1,26 @@ +import { Texture } from './Texture'; +import { CubeReflectionMapping } from '../constants'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { +function CubeTexture ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isCubeTexture = this.isTexture = true; images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.flipY = false; }; -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; +CubeTexture.prototype = Object.create( Texture.prototype ); +CubeTexture.prototype.constructor = CubeTexture; -Object.defineProperty( THREE.CubeTexture.prototype, 'images', { +Object.defineProperty( CubeTexture.prototype, 'images', { get: function () { @@ -31,3 +35,6 @@ Object.defineProperty( THREE.CubeTexture.prototype, 'images', { } } ); + + +export { CubeTexture }; \ No newline at end of file diff --git a/src/textures/DataTexture.js b/src/textures/DataTexture.js index 02b065aed273cf..eed343e2fc07ef 100644 --- a/src/textures/DataTexture.js +++ b/src/textures/DataTexture.js @@ -1,20 +1,27 @@ +import { Texture } from './Texture'; +import { NearestFilter } from '../constants'; + /** * @author alteredq / http://alteredqualia.com/ */ -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { +function DataTexture ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isDataTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { data: data, width: width, height: height }; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; }; -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; +DataTexture.prototype = Object.create( Texture.prototype ); +DataTexture.prototype.constructor = DataTexture; + + +export { DataTexture }; \ No newline at end of file diff --git a/src/textures/DepthTexture.js b/src/textures/DepthTexture.js index c368a70f2837a1..d89a7e38e5e325 100644 --- a/src/textures/DepthTexture.js +++ b/src/textures/DepthTexture.js @@ -1,22 +1,29 @@ +import { Texture } from './Texture'; +import { NearestFilter, UnsignedShortType, DepthFormat } from '../constants'; + /** * @author Matt DesLauriers / @mattdesl */ -THREE.DepthTexture = function ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { +function DepthTexture ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + this.isDepthTexture = this.isTexture = true; - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, THREE.DepthFormat, type, anisotropy ); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, DepthFormat, type, anisotropy ); this.image = { width: width, height: height }; - this.type = type !== undefined ? type : THREE.UnsignedShortType; + this.type = type !== undefined ? type : UnsignedShortType; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; }; -THREE.DepthTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DepthTexture.prototype.constructor = THREE.DepthTexture; +DepthTexture.prototype = Object.create( Texture.prototype ); +DepthTexture.prototype.constructor = DepthTexture; + + +export { DepthTexture }; \ No newline at end of file diff --git a/src/textures/Texture.js b/src/textures/Texture.js index 3d82dc013ca825..e5184760584617 100644 --- a/src/textures/Texture.js +++ b/src/textures/Texture.js @@ -1,36 +1,43 @@ +import { EventDispatcher } from '../core/EventDispatcher'; +import { UVMapping } from '../constants'; +import { MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter, LinearFilter } from '../constants'; +import { _Math } from '../math/Math'; +import { Vector2 } from '../math/Vector2'; + /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { +function Texture ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.isTexture = true; - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - this.uuid = THREE.Math.generateUUID(); + this.uuid = _Math.generateUUID(); this.name = ''; this.sourceFile = ''; - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; this.mipmaps = []; - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); this.generateMipmaps = true; this.premultiplyAlpha = false; @@ -42,19 +49,19 @@ THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, f // // Also changing the encoding after already used by a Material will not automatically make the Material // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding; + this.encoding = encoding !== undefined ? encoding : LinearEncoding; this.version = 0; this.onUpdate = null; }; -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; +Texture.DEFAULT_IMAGE = undefined; +Texture.DEFAULT_MAPPING = UVMapping; -THREE.Texture.prototype = { +Texture.prototype = { - constructor: THREE.Texture, + constructor: Texture, set needsUpdate( value ) { @@ -168,7 +175,7 @@ THREE.Texture.prototype = { if ( image.uuid === undefined ) { - image.uuid = THREE.Math.generateUUID(); // UGH + image.uuid = _Math.generateUUID(); // UGH } @@ -199,7 +206,7 @@ THREE.Texture.prototype = { transformUv: function ( uv ) { - if ( this.mapping !== THREE.UVMapping ) return; + if ( this.mapping !== UVMapping ) return; uv.multiply( this.repeat ); uv.add( this.offset ); @@ -208,17 +215,17 @@ THREE.Texture.prototype = { switch ( this.wrapS ) { - case THREE.RepeatWrapping: + case RepeatWrapping: uv.x = uv.x - Math.floor( uv.x ); break; - case THREE.ClampToEdgeWrapping: + case ClampToEdgeWrapping: uv.x = uv.x < 0 ? 0 : 1; break; - case THREE.MirroredRepeatWrapping: + case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { @@ -239,17 +246,17 @@ THREE.Texture.prototype = { switch ( this.wrapT ) { - case THREE.RepeatWrapping: + case RepeatWrapping: uv.y = uv.y - Math.floor( uv.y ); break; - case THREE.ClampToEdgeWrapping: + case ClampToEdgeWrapping: uv.y = uv.y < 0 ? 0 : 1; break; - case THREE.MirroredRepeatWrapping: + case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { @@ -276,6 +283,10 @@ THREE.Texture.prototype = { }; -Object.assign( THREE.Texture.prototype, THREE.EventDispatcher.prototype ); +Object.assign( Texture.prototype, EventDispatcher.prototype ); + +var count = 0; +function TextureIdCount () { return count++; }; + -THREE.TextureIdCount = 0; +export { TextureIdCount, Texture }; \ No newline at end of file diff --git a/src/textures/VideoTexture.js b/src/textures/VideoTexture.js index a0830777de7a54..49d87512c05ef9 100644 --- a/src/textures/VideoTexture.js +++ b/src/textures/VideoTexture.js @@ -1,10 +1,13 @@ +import { Texture } from './Texture'; + /** * @author mrdoob / http://mrdoob.com/ */ -THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { +function VideoTexture ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.isVideoTexture = this.isTexture = true; - THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.generateMipmaps = false; @@ -26,5 +29,8 @@ THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilt }; -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; +VideoTexture.prototype = Object.create( Texture.prototype ); +VideoTexture.prototype.constructor = VideoTexture; + + +export { VideoTexture }; \ No newline at end of file